-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathUtils.php
More file actions
507 lines (441 loc) · 14.7 KB
/
Utils.php
File metadata and controls
507 lines (441 loc) · 14.7 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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
<?php
/**
* Copyright (C) 2015-2019 FeatherBB
* based on code by (C) 2008-2015 FluxBB
* and Rickard Andersson (C) 2002-2008 PunBB
* License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher
*/
namespace FeatherBB\Core;
use FeatherBB\Core\Interfaces\Cache as CacheInterface;
use FeatherBB\Core\Interfaces\Container;
use FeatherBB\Core\Interfaces\ForumEnv;
use FeatherBB\Core\Interfaces\ForumSettings;
use FeatherBB\Core\Interfaces\Request;
use FeatherBB\Core\Interfaces\User;
use FeatherBB\Core\Interfaces\View as ViewInterface;
use FeatherBB\Model\Cache;
class Utils
{
/**
* Return current timestamp (with microseconds) as a float
* @return float
*/
public static function getMicrotime()
{
list($usec, $sec) = explode(' ', microtime());
return ((float)$usec + (float)$sec);
}
/**
* Replace four-byte characters with a question mark
*
* As MySQL cannot properly handle four-byte characters with the default utf-8
* charset up until version 5.5.3 (where a special charset has to be used), they
* need to be replaced, by question marks in this case.
* @param $str
* @return string
*/
public static function stripBadMultibyteChars($str)
{
$result = '';
$length = strlen($str);
for ($i = 0; $i < $length; $i++) {
// Replace four-byte characters (11110www 10zzzzzz 10yyyyyy 10xxxxxx)
$ord = ord($str[$i]);
if ($ord >= 240 && $ord <= 244) {
$result .= '?';
$i += 3;
} else {
$result .= $str[$i];
}
}
return $result;
}
/**
* A wrapper for PHP's number_format function
* @param $number
* @param int $decimals
* @return string
*/
public static function forumNumberFormat($number, $decimals = 0)
{
return is_numeric($number) ? number_format($number, $decimals, __('lang_decimal_point'), __('lang_thousands_sep')) : $number;
}
/**
* Format a time string according to $timeFormat and time zones
* @param $timestamp
* @param bool $dateOnly
* @param null $dateFormat
* @param null $timeFormat
* @param bool $timeOnly
* @param bool $noText
* @return false|string
*/
public static function formatTime($timestamp, $dateOnly = false, $dateFormat = null, $timeFormat = null, $timeOnly = false, $noText = false)
{
if ($timestamp == '') {
return __('Never');
}
$diff = (User::getPref('timezone') + User::getPref('dst')) * 3600;
$timestamp += $diff;
$now = time();
if (is_null($dateFormat)) {
$availableDateFormats = Container::get('forum_date_formats');
$userFormat = User::getPref('date_format');
$dateFormat = isset($availableDateFormats[$userFormat]) ? $availableDateFormats[$userFormat] : $userFormat;
}
if (is_null($timeFormat)) {
$availableTimeFormats = Container::get('forum_time_formats');
$userFormat = User::getPref('time_format');
$timeFormat = isset($availableTimeFormats[$userFormat]) ? $availableTimeFormats[$userFormat] : $userFormat;
}
$date = gmdate($dateFormat, $timestamp);
$today = gmdate($dateFormat, $now+$diff);
$yesterday = gmdate($dateFormat, $now+$diff-86400);
if (!$noText) {
if ($date == $today) {
$date = __('Today');
} elseif ($date == $yesterday) {
$date = __('Yesterday');
}
}
if ($dateOnly) {
return $date;
} elseif ($timeOnly) {
return gmdate($timeFormat, $timestamp);
} else {
return $date.' '.gmdate($timeFormat, $timestamp);
}
}
/**
* Calls htmlspecialchars with a few options already set
* @param $str
* @return string
*/
public static function escape($str)
{
return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
}
/**
* A wrapper for utf8_strlen for compatibility
* @param $str
* @return int
*/
public static function strlen($str)
{
return \utf8\len($str);
}
/**
* Convert \r\n and \r to \n
* @param $str
* @return mixed
*/
public static function linebreaks($str)
{
return str_replace(["\r\n", "\r"], "\n", $str);
}
/**
* A wrapper for utf8_trim for compatibility
* @param $str
* @param bool $charlist
* @return string
*/
public static function trim($str, $charlist = false)
{
return is_string($str) ? \utf8\trim($str, $charlist) : '';
}
/**
* Checks if a string is in all uppercase
* @param $string
* @return bool
*/
public static function isAllUppercase($string)
{
return \utf8\to_upper($string) == $string && \utf8\to_lower($string) != $string;
}
/**
* Replace string matching regular expression
*
* This function takes care of possibly disabled unicode properties in PCRE builds
* @param $pattern
* @param $replace
* @param $subject
* @param bool $callback
* @return string|string[]|null
*/
public static function ucpPregReplace($pattern, $replace, $subject, $callback = false)
{
if ($callback) {
$replaced = preg_replace_callback($pattern, $replace, $subject);
} else {
$replaced = preg_replace($pattern, $replace, $subject);
}
// If preg_replace() returns false, this probably means unicode support is not built-in, so we need to modify the pattern a little
if ($replaced === false) {
if (is_array($pattern)) {
foreach ($pattern as $curKey => $curPattern) {
$pattern[$curKey] = str_replace('\p{L}\p{N}', '\w', $curPattern);
}
$replaced = preg_replace($pattern, $replace, $subject);
} else {
$replaced = preg_replace(str_replace('\p{L}\p{N}', '\w', $pattern), $replace, $subject);
}
}
return $replaced;
}
/**
* Converts the file size in bytes to a human readable file size
* @param $size
* @return string
*/
public static function fileSize($size)
{
$units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB'];
for ($i = 0; $size > 1024; $i++) {
$size /= 1024;
}
return sprintf(__('Size unit '.$units[$i]), round($size, 2));
}
/**
* Generate browser's title
* @param $pageTitle
* @param null $p
* @return string
*/
public static function generatePageTitle($pageTitle, $p = null)
{
if (!is_array($pageTitle)) {
$pageTitle = [$pageTitle];
}
$pageTitle = array_reverse($pageTitle);
if ($p > 1) {
$pageTitle[0] .= ' ('.sprintf(__('Page'), self::forumNumberFormat($p)).')';
}
$crumbs = implode(__('Title separator'), $pageTitle);
return $crumbs;
}
/**
* Generate breadcrumbs on top of page
* @var $crumbs: array('optionnal/url' => 'Text displayed')
* @var $rightCrumb: array('link' => 'url/of/action', 'text' => 'Text displayed')
*
* @return string
*/
public static function generateBreadcrumbs(array $crumbs = [], array $rightCrumb = [])
{
ViewInterface::setPageInfo([
'rightCrumb' => $rightCrumb,
'crumbs' => $crumbs,
], 1
)->addTemplate('breadcrumbs.php');
}
/**
* Determines the correct title for $user
* $user must contain the elements 'username', 'title', 'posts', 'g_id' and 'g_user_title'
* @param $user
* @return string
*/
public static function getTitle($user)
{
static $banList;
// If not already built in a previous call, build an array of lowercase banned usernames
if (empty($banList)) {
$banList = [];
foreach (Container::get('bans') as $curBan) {
$banList[] = \utf8\to_lower($curBan['username']);
}
}
// If the user has a custom title
if ($user['title'] != '') {
$userTitle = self::escape($user['title']);
}
// If the user is banned
elseif (in_array(\utf8\to_lower($user['username']), $banList)) {
$userTitle = __('Banned');
}
// If the user group has a default user title
elseif ($user['g_user_title'] != '') {
$userTitle = self::escape($user['g_user_title']);
}
// If the user is a guest
elseif ($user['g_id'] == ForumEnv::get('FEATHER_GUEST')) {
$userTitle = __('Guest');
}
// If nothing else helps, we assign the default
else {
$userTitle = __('Member');
}
return $userTitle;
}
/**
* Determines the correct user title
*
* @param string $title
* @param string $name
* @param string $groupTitle
* @param int $gid
* @return string
*/
public static function getTitleTwig($title = '', $name = '', $groupTitle = '', $gid = 0)
{
static $ban_list;
// If not already built in a previous call, build an array of lowercase banned usernames
if (empty($ban_list)) {
$ban_list = [];
foreach (Container::get('bans') as $cur_ban) {
$ban_list[] = \utf8\to_lower($cur_ban['username']);
}
}
// If the user has a custom title
if ($title != '') {
$user_title = self::escape($title);
} // If the user is banned
elseif (in_array(\utf8\to_lower($name), $ban_list)) {
$user_title = __('Banned');
} // If the user group has a default user title
elseif ($groupTitle != '') {
$user_title = self::escape($groupTitle);
} // If the user is a guest
elseif ($gid == ForumEnv::get('FEATHER_GUEST')) {
$user_title = __('Guest');
} // If nothing else helps, we assign the default
else {
$user_title = __('Member');
}
return $user_title;
}
/**
* Replace censored words in $text
* @param $text
* @return bool|string
*/
public static function censor($text)
{
if (!CacheInterface::isCached('search_for')) {
CacheInterface::store('search_for', Cache::getCensoring('search_for'));
}
$searchFor = CacheInterface::retrieve('search_for');
if (!CacheInterface::isCached('replace_with')) {
CacheInterface::store('replace_with', Cache::getCensoring('replace_with'));
}
$replaceWith = CacheInterface::retrieve('replace_with');
if (!empty($searchFor) && !empty($replaceWith)) {
return substr(self::ucpPregReplace($searchFor, $replaceWith, ' '.$text.' '), 1, -1);
} else {
return $text;
}
}
/**
* Fetch admin IDs
* @return string
*/
public static function getAdminIds()
{
// Get Slim current session
if (!CacheInterface::isCached('admin_ids')) {
CacheInterface::store('admin_ids', Cache::getAdminIds());
}
return CacheInterface::retrieve('admin_ids');
}
/**
* Outputs markup to display a user's avatar
* @param $userId
* @return string
*/
public static function generateAvatarMarkup($userId)
{
$filetypes = ['jpg', 'gif', 'png'];
$avatarMarkup = '';
foreach ($filetypes as $curType) {
$path = ForumSettings::get('o_avatars_dir').'/'.$userId.'.'.$curType;
if (file_exists(ForumEnv::get('FEATHER_ROOT').$path) && $imgSize = getimagesize(ForumEnv::get('FEATHER_ROOT').$path)) {
$avatarMarkup = '<img src="'.self::escape(Container::get('url')->base(true).'/'.$path.'?m='.filemtime(ForumEnv::get('FEATHER_ROOT').$path)).'" '.$imgSize[3].' alt="" />';
break;
}
}
return $avatarMarkup;
}
/**
* Get IP Address
* @return mixed\
*/
public static function getIp()
{
if (isset(Request::getServerParams()['HTTP_CLIENT_IP'])) {
$client = Request::getServerParams()['HTTP_CLIENT_IP'];
}
if (isset(Request::getServerParams()['HTTP_X_FORWARDED_FOR'])) {
$forward = Request::getServerParams()['HTTP_X_FORWARDED_FOR'];
}
$remote = Request::getServerParams()['REMOTE_ADDR'];
if (isset($client) && filter_var($client, FILTER_VALIDATE_IP)) {
return $client;
} elseif (isset($forward) && filter_var($forward, FILTER_VALIDATE_IP)) {
return $forward;
}
return $remote;
}
/**
* Timing attack safe string comparison
*
* Compares two strings using the same time whether they're equal or not.
*
* This function was added in PHP 5.6.
*
* Note: It can leak the length of a string when arguments of differing length are supplied.
*
* @param string $a Expected string.
* @param string $b Actual, user supplied, string.
* @return bool Whether strings are equal.
*
* Sourcecode from WordPress
*/
public static function hashEquals($a, $b)
{
if (function_exists('hash_equals')) {
return hash_equals((string)$a, (string)$b);
}
$aLength = strlen($a);
if ($aLength !== strlen($b)) {
return false;
}
$result = 0;
// Do not attempt to "optimize" this.
for ($i = 0; $i < $aLength; $i++) {
$result |= ord($a[ $i ]) ^ ord($b[ $i ]);
}
return $result === 0;
}
/**
* Hash a user password using BCRYPT
* Replaces old sha1 password hashing verification
* Requires PHP >= 5.5
*
* @param string $password User password
* @return string Hashed password
*/
public static function passwordHash($password)
{
return password_hash($password, PASSWORD_DEFAULT);
}
/**
* Compare an inputed password with the one in database for a user
* Requires PHP >= 5.5
*
* @param string $password Inputed password
* @param string $hash Password stored in database
* @return bool Do the passwords match ?
*/
public static function passwordVerify($password, $hash)
{
return password_verify($password, $hash);
}
/**
* Check if the password needs rehash because PHP's default algorithm has changed
* @param $hash
* @return bool
*/
public static function passwordNeedsRehash($hash)
{
return password_needs_rehash($hash, PASSWORD_DEFAULT);
}
}