-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbmCustomApplication.php
More file actions
454 lines (404 loc) · 12.2 KB
/
bmCustomApplication.php
File metadata and controls
454 lines (404 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
<?php
/*
* Copyright (c) 2009, "The Blind Mice Studio"
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of the "The Blind Mice Studio" nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY "The Blind Mice Studio" ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL "The Blind Mice Studio" BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/**
* Операция завершилась успешно
* @name E_SUCCESS
*/
define('E_SUCCESS', 0);
define('E_DATA_OBJECT_NOT_EXISTS', 106);
define('E_DATAOBJECTMAP_NOT_FOUND', 107);
define('E_DATAOBJECTFIELDS_NOT_FOUND', 108);
define('E_REFERENCEMAP_NOT_EXISTS', 109);
define('E_REFERENCEMAP_NOT_FOUND', 110);
define('E_REFERENCEFIELDS_NOT_FOUND', 111);
define('E_OBJECTS_NOT_FOUND', 112);
define('BM_VT_ANY', 0);
/**
* Строка
*/
define('BM_VT_STRING', 1);
/**
* Целое число
*/
define('BM_VT_INTEGER', 2);
/**
* Число с плавающей точкой
*/
define('BM_VT_FLOAT', 3);
/**
* Дата
*/
define('BM_VT_DATETIME', 4);
/**
* Объект
*/
define('BM_VT_OBJECT', 5);
/**
* Пароль
*/
define('BM_VT_PASSWORD', 6);
/**
* Изображение
*/
define('BM_VT_IMAGE', 7);
/**
*
* Файл
*/
define('BM_VT_FILE', 8);
/**
* Длинный текст
*/
define('BM_VT_TEXT', 9);
/**
* Базовый класс приложений
*/
abstract class bmCustomApplication extends bmFFObject
{
public $templatecache = array();
public $doctype = '<DOCTYPE html>';
public $action = '';
/**
* @var bmMySQLLink|null
*/
public $dataLink = null;
public $dataLinkWrite = null;
public $user = null;
public $session = null;
public $debug = BM_C_DEBUG;
public $locale = '';
/**
* Конструктор класса
*
* @param bmApplication $application указатель на приложение. должен быть null
* @param array $parameters параметры, необходимые для инициализации экземпляра приложения
*
*/
public function __construct($application, $parameters = array())
{
$this->locale = C_LOCALE;
parent::__construct($application, $parameters);
$this->action = $this->cgi->getGPC('action', '');
$this->dataLink = new bmMySQLLink($this);
if(defined('USE_SEPARATE_DB_FOR_WRITE') && USE_SEPARATE_DB_FOR_WRITE == 1)
{
$this->dataLinkWrite = new bmMySQLLink($this, array('database' => 'write'));
}
register_shutdown_function(array($this, 'save'));
}
/**
* Выполняет авторизацию пользователя.
* В случае, если проверка пары email/пароль прошла успешно, то функция обновляет $this->user и сохраняет информацию о пользователе в $this->session
* -
*
* @param string $email e-mail пользователя
* @param string $password пароль пользователя в открытом виде
* @param bool $isMD5 флаг, указывающий на тип параметра $password - plaintext или md5
*
* @return bool флаг успеха авторизации
*/
public function login($email, $password, $isMD5 = false)
{
$result = false;
if (($this->session->userId != C_DEFAULT_USER_ID) && ($this->session->userId != 0))
{
$this->user->identifier = $this->session->userId;
$this->user->lastVisit = $this->session->createTime;
$this->timeOnline = time() - $this->session->createTime;
$this->user->store();
}
$dataLink = $this->dataLink;
/*$password = $dataLink->formatInput($password);
if (!$isMD5)
{
$password = md5($password);
}*/
$sql = "SELECT
`id` AS `id`, `password` AS `password`
FROM
`user`
WHERE
`email` = '" . $dataLink->formatInput($email) . "'
LIMIT 1;";
$user = $dataLink->getObject($sql);
if (password_verify($password, $user->password))
{
$result = true;
$this->session->userId = $user->id;
$this->session->createTime = time();
$this->session->store();
$this->user->identifier = $user->id;
$this->user->load();
}
return $result;
}
/**
* Выполняет деавторизацию пользователя.
* Сбрасывает $this->user в гостя
*
* @return bool флаг успеха: false, если пользователь является гостем, иначе true
*/
public function logout()
{
$result = false;
if ($this->session->userId != C_DEFAULT_USER_ID)
{
$result = true;
$this->user->lastVisit = $this->session->createTime;
$this->user->timeOnline = time() - $this->session->createTime;
$dataLink = $this->dataLink;
$this->session->userId = C_DEFAULT_USER_ID;
$this->session->createTime = time();
$this->session->save();
$this->user->identifier = C_DEFAULT_USER_ID;
$this->user->load();
}
return $result;
}
public function __get($propertyName)
{
switch ($propertyName)
{
case 'dataObjectMapIds':
if (!array_key_exists('dataObjectMapIds', $this->properties))
{
$this->properties['dataObjectMapIds'] = $this->data->getDataObjectMaps($this, false);
}
return $this->properties['dataObjectMapIds'];
break;
case 'dataObjectMaps':
return $this->data->getDataObjectMaps($this);
break;
case 'referenceMapIds':
if (!array_key_exists('referenceMapIds', $this->properties))
{
$this->properties['referenceMapIds'] = $this->data->getReferenceMaps($this, false);
}
return $this->properties['referenceMapIds'];
break;
case 'referenceMaps':
return $this->data->getReferenceMaps($this);
break;
default:
$className = 'bm' . ucfirst($propertyName);
if (class_exists($className))
{
if (!$this->propertyExists($propertyName))
{
$this->addProperty($propertyName, new $className($this));
}
}
return parent::__get($propertyName);
break;
}
}
/**
* Сохраняет состояние объекта. Не реализована.
* @todo определить необходимость присутствия этой функции
*/
public function save()
{
}
/**
* Выполняет конвертацию переданной строки в UTF-8
*
* @param string $string исходная строка
*
* @return string результат конвертации переданной строки
*/
public function decodeUrl($string)
{
$encoding = mb_detect_encoding($string, 'UTF-8, CP1251');
if ($encoding != 'UTF-8')
{
$string = mb_convert_encoding($string, 'UTF-8', $encoding);
}
return $string;
}
/**
* Возвращает содержимое шаблона
* Функция пытается прочесть шаблон из кеша, если невозможно, то (если это разрешено параметром $read), читает с диска
*
* @param string $templateName имя шаблона
* @param bool $escape необходимо ли выполнить экранирование. по умолчанию - true
* @param bool $read разрешено ли чтение шаблона с диска. по умолчанию - false
* @param string $path путь к корню проекта. по умолчанию - значение константы projectRoot
*
* @todo проверить логику функции
*/
public function getTemplate($templateName, $escape = true, $read = false, $path = projectRoot)
{
$template = $this->debug ? false : $this->cacheLink->get(C_TEMPLATE_PREFIX . $templateName);
if ($template === false || $read !== false)
{
$template = trim(file_get_contents($path . '/templates/' . $templateName . '.html'));
$this->cacheLink->set(C_TEMPLATE_PREFIX . $templateName, $template);
}
if ($escape)
{
$template = addcslashes(trim($template), '"');
}
return $template;
}
/**
* Создает stdObject по переданному ассоциативному массиву
*
* @param array $parameters
*
* @return stdClass
*/
public function createObject($parameters)
{
$result = new stdClass();
foreach ($parameters as $parameterName => $parameterValue)
{
$result->$parameterName = $parameterValue;
}
return $result;
}
/**
* Выполняет фильтрацию(валидацию) переданного значения в соответствии с его типом
*
* @param string $value значение, подлежащее конвертации
* @param mixed $type код типа значения
*
* @return string
*/
public function validateValue($value, $type = BM_VT_ANY)
{
switch ($type)
{
case BM_VT_INTEGER:
$value = intval($value);
break;
case BM_VT_FLOAT:
$value = floatval($value);
break;
case BM_VT_STRING:
case BM_VT_TEXT:
$value = trim($value);
break;
}
return $value;
}
public function declineNumber($value, $strings)
{
if ($value > 100)
{
$value = $value % 100;
}
$firstDigit = $value % 10;
$secondDigit = floor($value / 10);
if ($secondDigit != 1)
{
if ($firstDigit == 1)
{
return $strings[0];
}
else
{
if ($firstDigit > 1 && $firstDigit < 5)
{
return $strings[1];
}
else
{
return $strings[2];
}
}
}
else
{
return $strings[2];
}
}
public function getObjectIdByFieldName($objectName, $fieldName, $value)
{
$sql = "SELECT `id` AS `identifier` FROM `" . $objectName . "` WHERE `" . $fieldName . "` = '" . $this->dataLink->formatInput($value, BM_VT_STRING) . "';";
$result = $this->dataLink->getValue($sql);
return ($result != null) ? $result : 0;
}
public function getObjectIdByFieldNames($objectName, $arrayFieldsValues)
{
$result = null;
$where = '';
if (is_array($arrayFieldsValues))
{
foreach ($arrayFieldsValues as $fieldName => $fieldValue)
{
if (mb_strlen($where) > 0)
{
$where .= ' AND ';
}
$where .= " (`" . $fieldName . "` = '" . $this->dataLink->formatInput(
$fieldValue,
BM_VT_STRING
) . "') ";
}
}
if (mb_strlen($where) > 0)
{
$sql = "SELECT `id` AS `identifier` FROM `" . $objectName . "` WHERE " . $where . ";";
$result = $this->dataLink->getValue($sql);
}
return ($result != null) ? $result : 0;
}
public function getObjectIdBySynonym($objectName, $synonym)
{
$sql = "SELECT `" . $objectName . "Id` AS `identifier` FROM `" . $objectName . "_synonym` WHERE `synonym` = '" . $this->dataLink->formatInput($synonym, BM_VT_STRING) . "';";
$result = $this->dataLink->getValue($sql);
return ($result != null) ? $result : 0;
}
public function isEmailCorrect($email)
{
$emailParts = explode('@', $email);
if (count($emailParts) == 2)
{
$hostname = $emailParts[1];
if (getmxrr($hostname, $mxhosts) && filter_var($email, FILTER_VALIDATE_EMAIL))
{
return true;
}
}
return false;
}
public function formatNumber($number)
{
if ($number >= 10000)
{
$number = number_format($number, 0, ',', '~');
$number = str_replace('~', ' ', $number);
return $number;
}
else
{
return $number;
}
}
}
?>