/
functions.php
3518 lines (2795 loc) · 116 KB
/
functions.php
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Loads common functions used throughout the site.
*
* @copyright (C) 2008-2016 PunBB, partially based on code (C) 2008-2009 FluxBB.org
* @license http://www.gnu.org/licenses/gpl.html GPL version 2 or higher
* @package PunBB
*/
//
// Common helpers and forum's wrappers for PHP functions
//
// Encodes the contents of $str so that they are safe to output on an (X)HTML page
function forum_htmlencode($str)
{
return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
}
// Trim whitespace including non-breaking space
function forum_trim($str, $charlist = " \t\n\r\0\x0B\xC2\xA0")
{
return utf8_trim($str, $charlist);
}
// Convert \r\n and \r to \n
function forum_linebreaks($str)
{
return str_replace(array("\r\n", "\r"), "\n", $str);
}
// Start PHP session
function forum_session_start() {
static $forum_session_started = FALSE;
$return = ($hook = get_hook('fn_forum_session_start_start')) ? eval($hook) : null;
if ($return !== null)
return;
// Check if session already started
if ($forum_session_started && session_id())
return;
session_cache_limiter(FALSE);
// Check session id
$forum_session_id = NULL;
if (isset($_COOKIE['PHPSESSID']))
$forum_session_id = $_COOKIE['PHPSESSID'];
else if (isset($_GET['PHPSESSID']))
$forum_session_id = $_GET['PHPSESSID'];
if (empty($forum_session_id) || !preg_match('/^[a-z0-9\-,]{16,32}$/i', $forum_session_id))
{
// Create new session id
$forum_session_id = random_key(32, FALSE, TRUE);
session_id($forum_session_id);
}
if (!isset($_SESSION))
{
session_start();
}
if (!isset($_SESSION['initiated']))
{
session_regenerate_id();
$_SESSION['initiated'] = TRUE;
}
$forum_session_started = TRUE;
}
// Converts the CDATA end sequence ]]> into ]]>
function escape_cdata($str)
{
return str_replace(']]>', ']]>', $str);
}
// Check the text is CAPSED
function check_is_all_caps($text)
{
return (bool)/**/(utf8_strtoupper($text) == $text && utf8_strtolower($text) != $text);
}
// Return current timestamp (with microseconds) as a float
function forum_microtime()
{
if (version_compare(PHP_VERSION, '5.0.0', '>='))
{
$mt = microtime(true);
}
else
{
list($usec, $sec) = explode(' ', microtime());
$mt = ((float)/**/$usec + (float)/**/$sec);
}
return $mt;
}
// Inserts $element into $input at $offset
// $offset can be either a numerical offset to insert at (eg: 0 inserts at the beginning of the array)
// or a string, which is the key that the new element should be inserted before
// $key is optional: it's used when inserting a new key/value pair into an associative array
function array_insert(&$input, $offset, $element, $key = null)
{
if ($key == null)
$key = $offset;
// Determine the proper offset if we're using a string
if (!is_int($offset))
$offset = array_search($offset, array_keys($input), true);
// Out of bounds checks
if ($offset > count($input))
$offset = count($input);
else if ($offset < 0)
$offset = 0;
$input = array_merge(array_slice($input, 0, $offset), array($key => $element), array_slice($input, $offset));
}
// Unset any variables instantiated as a result of register_globals being enabled
function forum_unregister_globals()
{
$register_globals = @ini_get('register_globals');
if ($register_globals === '' || $register_globals === '0' || strtolower($register_globals) === 'off')
return;
// Prevent script.php?GLOBALS[foo]=bar
if (isset($_REQUEST['GLOBALS']) || isset($_FILES['GLOBALS']))
exit('I\'ll have a steak sandwich and... a steak sandwich.');
// Variables that shouldn't be unset
$no_unset = array('GLOBALS', '_GET', '_POST', '_COOKIE', '_REQUEST', '_SERVER', '_ENV', '_FILES');
// Remove elements in $GLOBALS that are present in any of the superglobals
$input = array_merge($_GET, $_POST, $_COOKIE, $_SERVER, $_ENV, $_FILES, isset($_SESSION) && is_array($_SESSION) ? $_SESSION : array());
foreach ($input as $k => $v)
if (!in_array($k, $no_unset) && isset($GLOBALS[$k]))
{
unset($GLOBALS[$k]);
unset($GLOBALS[$k]); // Double unset to circumvent the zend_hash_del_key_or_index hole in PHP <4.4.3 and <5.1.4
}
}
// Removes any "bad" characters (characters which mess with the display of a page, are invisible, etc) from user input
function forum_remove_bad_characters()
{
global $bad_utf8_chars;
$bad_utf8_chars = array("\0", "\xc2\xad", "\xcc\xb7", "\xcc\xb8", "\xe1\x85\x9F", "\xe1\x85\xA0", "\xe2\x80\x80", "\xe2\x80\x81", "\xe2\x80\x82", "\xe2\x80\x83", "\xe2\x80\x84", "\xe2\x80\x85", "\xe2\x80\x86", "\xe2\x80\x87", "\xe2\x80\x88", "\xe2\x80\x89", "\xe2\x80\x8a", "\xe2\x80\x8b", "\xe2\x80\x8e", "\xe2\x80\x8f", "\xe2\x80\xaa", "\xe2\x80\xab", "\xe2\x80\xac", "\xe2\x80\xad", "\xe2\x80\xae", "\xe2\x80\xaf", "\xe2\x81\x9f", "\xe3\x80\x80", "\xe3\x85\xa4", "\xef\xbb\xbf", "\xef\xbe\xa0", "\xef\xbf\xb9", "\xef\xbf\xba", "\xef\xbf\xbb", "\xE2\x80\x8D");
($hook = get_hook('fn_remove_bad_characters_start')) ? eval($hook) : null;
if (!function_exists('_forum_remove_bad_characters'))
{
function _forum_remove_bad_characters($array)
{
global $bad_utf8_chars;
return is_array($array) ? array_map('_forum_remove_bad_characters', $array) : str_replace($bad_utf8_chars, '', $array);
}
}
$_GET = _forum_remove_bad_characters($_GET);
$_POST = _forum_remove_bad_characters($_POST);
$_COOKIE = _forum_remove_bad_characters($_COOKIE);
$_REQUEST = _forum_remove_bad_characters($_REQUEST);
}
// Fix the REQUEST_URI if we can, since both IIS6 and IIS7 break it
function forum_fix_request_uri()
{
if (defined('FORUM_IGNORE_REQUEST_URI'))
return;
global $forum_config;
if (!isset($_SERVER['REQUEST_URI']) || (isset($_SERVER['QUERY_STRING']) && !empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['REQUEST_URI'], '?') === false))
{
// Workaround for a bug in IIS7
if (isset($_SERVER['HTTP_X_ORIGINAL_URL']))
$_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_ORIGINAL_URL'];
// IIS6 also doesn't set REQUEST_URI, If we are using the default SEF URL scheme then we can work around it
else if (!isset($forum_config) || $forum_config['o_sef'] == 'Default')
{
$requested_page = str_replace(array('%26', '%3D', '%2F', '%3F'), array('&', '=', '/', '?'), rawurlencode($_SERVER['PHP_SELF']));
$_SERVER['REQUEST_URI'] = $requested_page.(isset($_SERVER['QUERY_STRING']) && !empty($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : '');
}
// Otherwise I am not aware of a work around...
else
error('The web server you are using is not correctly setting the REQUEST_URI variable.<br />This usually means you are using IIS6, or an unpatched IIS7. Please either disable SEF URLs, upgrade to IIS7 and install any available patches or try a different web server.');
}
}
// Set a cookie, PunBB style!
// Like other headers, cookies must be sent before any output from your script.
// Use headers_sent() to ckeck wether HTTP headers has been sent already.
function forum_setcookie($name, $value, $expire)
{
global $cookie_path, $cookie_domain, $cookie_secure;
$return = ($hook = get_hook('fn_forum_setcookie_start')) ? eval($hook) : null;
if ($return !== null)
return;
// Enable sending of a P3P header
header('P3P: CP="CUR ADM"');
if (version_compare(PHP_VERSION, '5.2.0', '>='))
setcookie($name, $value, $expire, $cookie_path, $cookie_domain, $cookie_secure, true);
else
setcookie($name, $value, $expire, $cookie_path.'; HttpOnly', $cookie_domain, $cookie_secure);
}
// Attempts to fetch the provided URL using any available means
function get_remote_file($url, $timeout, $head_only = false, $max_redirects = 10)
{
$result = null;
$parsed_url = parse_url($url);
$allow_url_fopen = strtolower(@ini_get('allow_url_fopen'));
// Quite unlikely that this will be allowed on a shared host, but it can't hurt
if (function_exists('ini_set'))
@ini_set('default_socket_timeout', $timeout);
// If we have cURL, we might as well use it
if (function_exists('curl_init'))
{
// Setup the transfer
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, $head_only);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_USERAGENT, 'PunBB');
// Grab the page
$content = @curl_exec($ch);
$responce_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Process 301/302 redirect
if ($content !== false && ($responce_code == '301' || $responce_code == '302') && $max_redirects > 0)
{
$headers = explode("\r\n", trim($content));
foreach ($headers as $header)
if (substr($header, 0, 10) == 'Location: ')
{
$responce = get_remote_file(substr($header, 10), $timeout, $head_only, $max_redirects - 1);
if ($responce !== null)
$responce['headers'] = array_merge($headers, $responce['headers']);
return $responce;
}
}
// Ignore everything except a 200 response code
if ($content !== false && $responce_code == '200')
{
if ($head_only)
$result['headers'] = explode("\r\n", str_replace("\r\n\r\n", "\r\n", trim($content)));
else
{
preg_match('#HTTP/1.[01] 200 OK#', $content, $match, PREG_OFFSET_CAPTURE);
$last_content = substr($content, $match[0][1]);
$content_start = strpos($last_content, "\r\n\r\n");
if ($content_start !== false)
{
$result['headers'] = explode("\r\n", str_replace("\r\n\r\n", "\r\n", substr($content, 0, $match[0][1] + $content_start)));
$result['content'] = substr($last_content, $content_start + 4);
}
}
}
}
// fsockopen() is the second best thing
else if (function_exists('fsockopen'))
{
$remote = @fsockopen($parsed_url['host'], !empty($parsed_url['port']) ? intval($parsed_url['port']) : 80, $errno, $errstr, $timeout);
if ($remote)
{
// Send a standard HTTP 1.0 request for the page
fwrite($remote, ($head_only ? 'HEAD' : 'GET').' '.(!empty($parsed_url['path']) ? $parsed_url['path'] : '/').(!empty($parsed_url['query']) ? '?'.$parsed_url['query'] : '').' HTTP/1.0'."\r\n");
fwrite($remote, 'Host: '.$parsed_url['host']."\r\n");
fwrite($remote, 'User-Agent: PunBB'."\r\n");
fwrite($remote, 'Connection: Close'."\r\n\r\n");
stream_set_timeout($remote, $timeout);
$stream_meta = stream_get_meta_data($remote);
// Fetch the response 1024 bytes at a time and watch out for a timeout
$content = false;
while (!feof($remote) && !$stream_meta['timed_out'])
{
$content .= fgets($remote, 1024);
$stream_meta = stream_get_meta_data($remote);
}
fclose($remote);
// Process 301/302 redirect
if ($content !== false && $max_redirects > 0 && preg_match('#^HTTP/1.[01] 30[12]#', $content))
{
$headers = explode("\r\n", trim($content));
foreach ($headers as $header)
if (substr($header, 0, 10) == 'Location: ')
{
$responce = get_remote_file(substr($header, 10), $timeout, $head_only, $max_redirects - 1);
if ($responce !== null)
$responce['headers'] = array_merge($headers, $responce['headers']);
return $responce;
}
}
// Ignore everything except a 200 response code
if ($content !== false && preg_match('#^HTTP/1.[01] 200 OK#', $content))
{
if ($head_only)
$result['headers'] = explode("\r\n", trim($content));
else
{
$content_start = strpos($content, "\r\n\r\n");
if ($content_start !== false)
{
$result['headers'] = explode("\r\n", substr($content, 0, $content_start));
$result['content'] = substr($content, $content_start + 4);
}
}
}
}
}
// Last case scenario, we use file_get_contents provided allow_url_fopen is enabled (any non 200 response results in a failure)
else if (in_array($allow_url_fopen, array('on', 'true', '1')))
{
// PHP5's version of file_get_contents() supports stream options
if (version_compare(PHP_VERSION, '5.0.0', '>='))
{
// Setup a stream context
$stream_context = stream_context_create(
array(
'http' => array(
'method' => $head_only ? 'HEAD' : 'GET',
'user_agent' => 'PunBB',
'max_redirects' => $max_redirects + 1, // PHP >=5.1.0 only
'timeout' => $timeout // PHP >=5.2.1 only
)
)
);
$content = @file_get_contents($url, false, $stream_context);
}
else
$content = @file_get_contents($url);
// Did we get anything?
if ($content !== false)
{
// Gotta love the fact that $http_response_header just appears in the global scope (*cough* hack! *cough*)
$result['headers'] = $http_response_header;
if (!$head_only)
$result['content'] = $content;
}
}
return $result;
}
// Clean version string from trailing '.0's
function clean_version($version)
{
return preg_replace('/(\.0)+(?!\.)|(\.0+$)/', '$2', $version);
}
// Dump contents of variable(s) for debug
function forum_dump()
{
echo '<pre>';
$num_args = func_num_args();
for ($i = 0; $i < $num_args; ++$i)
{
print_r(func_get_arg($i));
echo "\n\n";
}
echo '</pre>';
exit;
}
//
// Markup helpers
//
// A wrapper for PHP's number_format function
function forum_number_format($number, $decimals = 0)
{
global $lang_common;
$return = ($hook = get_hook('fn_forum_number_format_start')) ? eval($hook) : null;
if ($return !== null)
return $return;
return number_format($number, $decimals, $lang_common['lang_decimal_point'], $lang_common['lang_thousands_sep']);
}
// Format a time string according to $date_format, $time_format, and timezones
define('FORUM_FT_DATETIME', 0);
define('FORUM_FT_DATE', 1);
define('FORUM_FT_TIME', 2);
function format_time($timestamp, $type = FORUM_FT_DATETIME, $date_format = null, $time_format = null, $no_text = false)
{
global $forum_config, $lang_common, $forum_user, $forum_time_formats, $forum_date_formats;
$return = ($hook = get_hook('fn_format_time_start')) ? eval($hook) : null;
if ($return !== null)
return $return;
if ($timestamp == '')
return ($no_text ? '' : $lang_common['Never']);
if ($date_format === null)
$date_format = $forum_date_formats[$forum_user['date_format']];
if ($time_format === null)
$time_format = $forum_time_formats[$forum_user['time_format']];
$diff = ($forum_user['timezone'] + $forum_user['dst']) * 3600;
$timestamp += $diff;
$now = time();
$formatted_time = '';
if ($type == FORUM_FT_DATETIME || $type == FORUM_FT_DATE)
{
$formatted_time = gmdate($date_format, $timestamp);
if (!$no_text)
{
$base = gmdate('Y-m-d', $timestamp);
$today = gmdate('Y-m-d', $now + $diff);
$yesterday = gmdate('Y-m-d', $now + $diff - 86400);
if ($base == $today)
$formatted_time = $lang_common['Today'];
else if ($base == $yesterday)
$formatted_time = $lang_common['Yesterday'];
}
}
if ($type == FORUM_FT_DATETIME)
$formatted_time .= ' ';
if ($type == FORUM_FT_DATETIME || $type == FORUM_FT_TIME)
$formatted_time .= gmdate($time_format, $timestamp);
($hook = get_hook('fn_format_time_end')) ? eval($hook) : null;
return $formatted_time;
}
// Generate the "navigator" that appears at the top of every page
function generate_navlinks()
{
global $forum_config, $lang_common, $forum_url, $forum_user;
$return = ($hook = get_hook('fn_generate_navlinks_start')) ? eval($hook) : null;
if ($return !== null)
return $return;
// Index should always be displayed
$links['index'] = '<li id="navindex"'.((FORUM_PAGE == 'index') ? ' class="isactive"' : '').'><a href="'.forum_link($forum_url['index']).'">'.$lang_common['Index'].'</a></li>';
if ($forum_user['g_read_board'] == '1' && $forum_user['g_view_users'] == '1')
$links['userlist'] = '<li id="navuserlist"'.((FORUM_PAGE == 'userlist') ? ' class="isactive"' : '').'><a href="'.forum_link($forum_url['users']).'">'.$lang_common['User list'].'</a></li>';
if ($forum_config['o_rules'] == '1' && (!$forum_user['is_guest'] || $forum_user['g_read_board'] == '1' || $forum_config['o_regs_allow'] == '1'))
$links['rules'] = '<li id="navrules"'.((FORUM_PAGE == 'rules') ? ' class="isactive"' : '').'><a href="'.forum_link($forum_url['rules']).'">'.$lang_common['Rules'].'</a></li>';
if ($forum_user['is_guest'])
{
if ($forum_user['g_read_board'] == '1' && $forum_user['g_search'] == '1')
$links['search'] = '<li id="navsearch"'.((FORUM_PAGE == 'search') ? ' class="isactive"' : '').'><a href="'.forum_link($forum_url['search']).'">'.$lang_common['Search'].'</a></li>';
$links['register'] = '<li id="navregister"'.((FORUM_PAGE == 'register') ? ' class="isactive"' : '').'><a href="'.forum_link($forum_url['register']).'">'.$lang_common['Register'].'</a></li>';
$links['login'] = '<li id="navlogin"'.((FORUM_PAGE == 'login') ? ' class="isactive"' : '').'><a href="'.forum_link($forum_url['login']).'">'.$lang_common['Login'].'</a></li>';
}
else
{
if (!$forum_user['is_admmod'])
{
if ($forum_user['g_read_board'] == '1' && $forum_user['g_search'] == '1')
$links['search'] = '<li id="navsearch"'.((FORUM_PAGE == 'search') ? ' class="isactive"' : '').'><a href="'.forum_link($forum_url['search']).'">'.$lang_common['Search'].'</a></li>';
$links['profile'] = '<li id="navprofile"'.((substr(FORUM_PAGE, 0, 7) == 'profile') ? ' class="isactive"' : '').'><a href="'.forum_link($forum_url['user'], $forum_user['id']).'">'.$lang_common['Profile'].'</a></li>';
$links['logout'] = '<li id="navlogout"><a href="'.forum_link($forum_url['logout'], array($forum_user['id'], generate_form_token('logout'.$forum_user['id']))).'">'.$lang_common['Logout'].'</a></li>';
}
else
{
$links['search'] = '<li id="navsearch"'.((FORUM_PAGE == 'search') ? ' class="isactive"' : '').'><a href="'.forum_link($forum_url['search']).'">'.$lang_common['Search'].'</a></li>';
$links['profile'] = '<li id="navprofile"'.((substr(FORUM_PAGE, 0, 7) == 'profile') ? ' class="isactive"' : '').'><a href="'.forum_link($forum_url['user'], $forum_user['id']).'">'.$lang_common['Profile'].'</a></li>';
$links['admin'] = '<li id="navadmin"'.((substr(FORUM_PAGE, 0, 5) == 'admin') ? ' class="isactive"' : '').'><a href="'.forum_link($forum_url['admin_index']).'">'.$lang_common['Admin'].'</a></li>';
$links['logout'] = '<li id="navlogout"><a href="'.forum_link($forum_url['logout'], array($forum_user['id'], generate_form_token('logout'.$forum_user['id']))).'">'.$lang_common['Logout'].'</a></li>';
}
}
// Are there any additional navlinks we should insert into the array before imploding it?
if ($forum_config['o_additional_navlinks'] != '' && preg_match_all('#([0-9]+)\s*=\s*(.*?)\n#s', $forum_config['o_additional_navlinks']."\n", $extra_links))
{
// Insert any additional links into the $links array (at the correct index)
$num_links = count($extra_links[1]);
for ($i = 0; $i < $num_links; ++$i)
array_insert($links, (int)$extra_links[1][$i], '<li id="navextra'.($i + 1).'">'.$extra_links[2][$i].'</li>');
}
($hook = get_hook('fn_generate_navlinks_end')) ? eval($hook) : null;
return implode("\n\t\t", $links);
}
// Outputs markup to display a user's avatar
function generate_avatar_markup($user_id, $avatar_type, $avatar_width, $avatar_height, $username = NULL, $drop_cache = FALSE)
{
global $forum_config, $base_url;
$avatar_markup = $avatar_filename = '';
$return = ($hook = get_hook('fn_generate_avatar_markup_start')) ? eval($hook) : null;
if ($return !== null)
return $return;
// Create avatar filename
switch ($avatar_type)
{
case FORUM_AVATAR_GIF:
$avatar_filename = $user_id.'.gif';
break;
case FORUM_AVATAR_JPG:
$avatar_filename = $user_id.'.jpg';
break;
case FORUM_AVATAR_PNG:
$avatar_filename = $user_id.'.png';
break;
case FORUM_AVATAR_NONE:
default:
break;
}
// Create markup
if ($avatar_filename && $avatar_width > 0 && $avatar_height > 0)
{
$path = $forum_config['o_avatars_dir'].'/'.$avatar_filename;
//
if ($drop_cache)
{
$path .= '?no_cache='.random_key(8, TRUE);
}
$alt_attr = '';
if (is_string($username) && utf8_strlen($username) > 0) {
$alt_attr = forum_htmlencode($username);
}
$avatar_markup = '<img src="'.$base_url.'/'.$path.'" width="'.$avatar_width.'" height="'.$avatar_height.'" alt="'.$alt_attr.'" />';
}
($hook = get_hook('fn_generate_avatar_markup_end')) ? eval($hook) : null;
return $avatar_markup;
}
// Generate breadcrumb navigation
function generate_crumbs($reverse)
{
global $lang_common, $forum_url, $forum_config, $forum_page;
$return = ($hook = get_hook('fn_generate_crumbs_start')) ? eval($hook) : null;
if ($return !== null)
return $return;
if (empty($forum_page['crumbs']))
$forum_page['crumbs'][0] = $forum_config['o_board_title'];
$crumbs = '';
$num_crumbs = count($forum_page['crumbs']);
if ($reverse)
{
for ($i = ($num_crumbs - 1); $i >= 0; --$i)
$crumbs .= (is_array($forum_page['crumbs'][$i]) ? forum_htmlencode($forum_page['crumbs'][$i][0]) : forum_htmlencode($forum_page['crumbs'][$i])).((isset($forum_page['page']) && $i == ($num_crumbs - 1)) ? ' ('.$lang_common['Page'].' '.forum_number_format($forum_page['page']).')' : '').($i > 0 ? $lang_common['Title separator'] : '');
}
else
for ($i = 0; $i < $num_crumbs; ++$i)
{
if ($i < ($num_crumbs - 1))
$crumbs .= '<span class="crumb'.(($i == 0) ? ' crumbfirst' : '').'">'.(($i >= 1) ? '<span>'.$lang_common['Crumb separator'].'</span>' : '').(is_array($forum_page['crumbs'][$i]) ? '<a href="'.$forum_page['crumbs'][$i][1].'">'.forum_htmlencode($forum_page['crumbs'][$i][0]).'</a>' : forum_htmlencode($forum_page['crumbs'][$i])).'</span> ';
else
$crumbs .= '<span class="crumb crumblast'.(($i == 0) ? ' crumbfirst' : '').'">'.(($i >= 1) ? '<span>'.$lang_common['Crumb separator'].'</span>' : '').(is_array($forum_page['crumbs'][$i]) ? '<a href="'.$forum_page['crumbs'][$i][1].'">'.forum_htmlencode($forum_page['crumbs'][$i][0]).'</a>' : forum_htmlencode($forum_page['crumbs'][$i])).'</span> ';
}
($hook = get_hook('fn_generate_crumbs_end')) ? eval($hook) : null;
return $crumbs;
}
// Generate a string with page and item information for multipage headings
function generate_items_info($label, $first, $total)
{
global $forum_page, $lang_common;
$return = ($hook = get_hook('fn_generate_page_info_start')) ? eval($hook) : null;
if ($return !== null)
return $return;
if ($forum_page['num_pages'] == 1)
$item_info = '<span class="item-info">'.sprintf($lang_common['Item info single'], $label, forum_number_format($total)).'</span>';
else
$item_info = '<span class="item-info">'.sprintf($lang_common['Item info plural'], $label, forum_number_format($first), forum_number_format($forum_page['finish_at']), forum_number_format($total)).'</span>';
($hook = get_hook('fn_generate_page_info_end')) ? eval($hook) : null;
return $item_info;
}
// Generate a string with numbered links (for multipage scripts)
function paginate($num_pages, $cur_page, $link, $separator, $args = null, $is_default_scheme = null)
{
global $forum_url, $lang_common;
if ($is_default_scheme === null)
$forum_url_page = $forum_url['page'];
else
{
$forum_url_page = '&p=$1';
unset($forum_url['insertion_find']);
}
$pages = array();
$link_to_all = false;
$return = ($hook = get_hook('fn_paginate_start')) ? eval($hook) : null;
if ($return !== null)
return $return;
// If $cur_page == -1, we link to all pages (used in viewforum.php)
if ($cur_page == -1)
{
$cur_page = 1;
$link_to_all = true;
}
if ($num_pages <= 1)
$pages = array('<strong class="first-item">'.forum_number_format(1).'</strong>');
else
{
// Add a previous page link
if ($num_pages > 1 && $cur_page > 1)
$pages[] = '<a'.(empty($pages) ? ' class="first-item"' : '').' href="'.forum_sublink($link, $forum_url_page, ($cur_page - 1), $args).'">'.$lang_common['Previous'].'</a>';
if ($cur_page > 3)
{
$pages[] = '<a'.(empty($pages) ? ' class="first-item"' : '').' href="'.forum_sublink($link, $forum_url_page, 1, $args).'">'.forum_number_format(1).'</a>';
if ($cur_page > 5)
$pages[] = '<span>'.$lang_common['Spacer'].'</span>';
}
// Don't ask me how the following works. It just does, OK? :-)
for ($current = ($cur_page == 5) ? $cur_page - 3 : $cur_page - 2, $stop = ($cur_page + 4 == $num_pages) ? $cur_page + 4 : $cur_page + 3; $current < $stop; ++$current)
if ($current < 1 || $current > $num_pages)
continue;
else if ($current != $cur_page || $link_to_all)
$pages[] = '<a'.(empty($pages) ? ' class="first-item"' : '').' href="'.forum_sublink($link, $forum_url_page, $current, $args).'">'.forum_number_format($current).'</a>';
else
$pages[] = '<strong'.(empty($pages) ? ' class="first-item"' : '').'>'.forum_number_format($current).'</strong>';
if ($cur_page <= ($num_pages-3))
{
if ($cur_page != ($num_pages-3) && $cur_page != ($num_pages-4))
$pages[] = '<span>'.$lang_common['Spacer'].'</span>';
$pages[] = '<a'.(empty($pages) ? ' class="first-item"' : '').' href="'.forum_sublink($link, $forum_url_page, $num_pages, $args).'">'.forum_number_format($num_pages).'</a>';
}
// Add a next page link
if ($num_pages > 1 && !$link_to_all && $cur_page < $num_pages)
$pages[] = '<a'.(empty($pages) ? ' class="first-item"' : '').' href="'.forum_sublink($link, $forum_url_page, ($cur_page + 1), $args).'">'.$lang_common['Next'].'</a>';
}
($hook = get_hook('fn_paginate_end')) ? eval($hook) : null;
return implode($separator, $pages);
}
// Display executed queries (if enabled) for debug
function get_saved_queries()
{
global $forum_db, $lang_common;
// Get the queries so that we can print them out
$saved_queries = $forum_db->get_saved_queries();
ob_start();
?>
<div id="brd-debug" class="main">
<div class="debug">
<table>
<caption><?php echo $lang_common['Debug summary'] ?></caption>
<thead>
<tr>
<th class="tcl" scope="col"><?php echo $lang_common['Query times'] ?></th>
<th class="tcr" scope="col"><?php echo $lang_common['Query'] ?></th>
</tr>
</thead>
<tbody>
<?php
$query_time_total = 0.0;
foreach ($saved_queries as $cur_query)
{
$query_time_total += $cur_query[1];
?>
<tr>
<td class="tcl"><?php echo (($cur_query[1] != 0) ? forum_number_format($cur_query[1], 5) : ' ') ?></td>
<td class="tcr"><?php echo forum_htmlencode($cur_query[0]) ?></td>
</tr>
<?php
}
?>
<tr>
<td class="tcl border-less"><?php echo forum_number_format($query_time_total, 5) ?></td>
<td class="tcr border-less"><?php echo $lang_common['Total query time'] ?></td>
</tr>
</tbody>
</table>
</div>
</div>
<?php
return ob_get_clean();
}
//
// Other special helpers
//
// Return all code blocks that hook into $hook_id
function get_hook($hook_id)
{
global $forum_hooks;
return !defined('FORUM_DISABLE_HOOKS') && isset($forum_hooks[$hook_id]) ? implode("\n", $forum_hooks[$hook_id]) : false;
}
// Generate a hyperlink with parameters and anchor
function forum_link($link, $args = null)
{
global $forum_config, $base_url;
$return = ($hook = get_hook('fn_forum_link_start')) ? eval($hook) : null;
if ($return !== null)
return $return;
$gen_link = $link;
if ($args === null)
$gen_link = $base_url.'/'.$link;
else if (!is_array($args))
$gen_link = $base_url.'/'.str_replace('$1', $args, $link);
else
{
for ($i = 0; isset($args[$i]); ++$i)
$gen_link = str_replace('$'.($i + 1), $args[$i], $gen_link);
$gen_link = $base_url.'/'.$gen_link;
}
($hook = get_hook('fn_forum_link_end')) ? eval($hook) : null;
return $gen_link;
}
// Generate a hyperlink with parameters and anchor and a subsection such as a subpage
function forum_sublink($link, $sublink, $subarg, $args = null)
{
global $forum_config, $forum_url, $base_url;
$return = ($hook = get_hook('fn_forum_sublink_start')) ? eval($hook) : null;
if ($return !== null)
return $return;
if ($sublink == $forum_url['page'] && $subarg == 1)
return forum_link($link, $args);
$gen_link = $link;
if (!is_array($args) && $args !== null)
$gen_link = str_replace('$1', $args, $link);
else
{
for ($i = 0; isset($args[$i]); ++$i)
$gen_link = str_replace('$'.($i + 1), $args[$i], $gen_link);
}
if (isset($forum_url['insertion_find']))
$gen_link = $base_url.'/'.str_replace($forum_url['insertion_find'], str_replace('$1', str_replace('$1', $subarg, $sublink), $forum_url['insertion_replace']), $gen_link);
else
$gen_link = $base_url.'/'.$gen_link.str_replace('$1', $subarg, $sublink);
($hook = get_hook('fn_forum_sublink_end')) ? eval($hook) : null;
return $gen_link;
}
// Make a string safe to use in a URL
function sef_friendly($str)
{
global $forum_config, $forum_user;
static $lang_url_replace, $forum_reserved_strings;
if (!isset($lang_url_replace))
require FORUM_ROOT.'lang/'.$forum_user['language'].'/url_replace.php';
if (!isset($forum_reserved_strings))
{
// Bring in any reserved strings
if (file_exists(FORUM_ROOT.'include/url/'.$forum_config['o_sef'].'/reserved_strings.php'))
require FORUM_ROOT.'include/url/'.$forum_config['o_sef'].'/reserved_strings.php';
else
require FORUM_ROOT.'include/url/Default/reserved_strings.php';
}
$return = ($hook = get_hook('fn_sef_friendly_start')) ? eval($hook) : null;
if ($return !== null)
return $return;
$str = strtr($str, $lang_url_replace);
$str = strtolower(utf8_decode($str));
$str = forum_trim(preg_replace(array('/[^a-z0-9\s]/', '/[\s]+/'), array('', '-'), $str), '-');
foreach ($forum_reserved_strings as $match => $replace)
if ($str == $match)
return $replace;
else if ($match != '')
$str = str_replace($match, $replace, $str);
return $str;
}
// Replace censored words in $text loader
function censor_words($text)
{
global $forum_db, $forum_censors;
$return = ($hook = get_hook('fn_censor_words_start')) ? eval($hook) : null;
if ($return !== null)
return $return;
// If not already loaded in a previous call, load the cached censors
if (!defined('FORUM_CENSORS_LOADED'))
{
if (file_exists(FORUM_CACHE_DIR.'cache_censors.php'))
include FORUM_CACHE_DIR.'cache_censors.php';
if (!defined('FORUM_CENSORS_LOADED'))
{
if (!defined('FORUM_CACHE_FUNCTIONS_LOADED'))
require FORUM_ROOT.'include/cache.php';
generate_censors_cache();
require FORUM_CACHE_DIR.'cache_censors.php';
}
}
// Check Unicode support
$unicode = defined('FORUM_SUPPORT_PCRE_UNICODE');
return (isset($forum_censors)) ? censor_words_do($forum_censors, $text, $unicode) : $text;
}
// Replace censored words in $text
function censor_words_do($forum_censors, $text, $unicode)
{
static $search_for = NULL;
static $replace_with = NULL;
if (is_null($search_for))
$search_for = array();
if (is_null($replace_with))
$replace_with = array();
if (!empty($forum_censors))
{
// Generate regexp`s
foreach ($forum_censors as $censor_key => $cur_word)
{
if ($unicode)
{
// Unescape *
$replace = str_replace('\*', '*', preg_quote($cur_word['search_for'], '#'));
$replace = preg_replace(array('#(?<=[\p{Nd}\p{L}_])\*(?=[\p{Nd}\p{L}_])#iu', '#^\*#', '#\*$#'), array('([\x20]*?|[\p{Nd}\p{L}_-]*?)', '[\p{Nd}\p{L}_-]*?', '[\p{Nd}\p{L}_-]*?'), $replace);
// Generate the final substitution
$search_for[$censor_key] = '#(?<![\p{Nd}\p{L}_-])('.$replace.')(?![\p{Nd}\p{L}_-])#iu';
}
else
{
// Unescape *
$replace = str_replace('\*', '\w*?', preg_quote($cur_word['search_for'], '#'));
$search_for[$censor_key] = '#(?<=\W)('.$replace.')(?=\W)#iu'; // This better for ASCII than (?!</S)
}
$replace_with[$censor_key] = $cur_word['replace_with'];
($hook = get_hook('fn_censor_words_setup_regex')) ? eval($hook) : null;
}
// Replace
if (!empty($search_for))
{
$text = utf8_substr(preg_replace($search_for, $replace_with, ' '.$text.' '), 1, -1);
}
}
return $text;
}
// Verifies that the provided username is OK for insertion into the database
function validate_username($username, $exclude_id = null)
{
global $lang_common, $lang_register, $lang_profile, $forum_config;
$errors = array();
$return = ($hook = get_hook('fn_validate_username_start')) ? eval($hook) : null;
if ($return !== null)
return $return;
// Convert multiple whitespace characters into one (to prevent people from registering with indistinguishable usernames)
$username = preg_replace('#\s+#s', ' ', $username);
// Validate username
if (utf8_strlen($username) < 2)
$errors[] = $lang_profile['Username too short'];
else if (utf8_strlen($username) > 25)
$errors[] = $lang_profile['Username too long'];
else if (strtolower($username) == 'guest' || utf8_strtolower($username) == utf8_strtolower($lang_common['Guest']))
$errors[] = $lang_profile['Username guest'];
else if (preg_match('/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/', $username) || preg_match('/((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(([0-9A-Fa-f]{1,4}:){0,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))/', $username))
$errors[] = $lang_profile['Username IP'];
else if ((strpos($username, '[') !== false || strpos($username, ']') !== false) && strpos($username, '\'') !== false && strpos($username, '"') !== false)
$errors[] = $lang_profile['Username reserved chars'];
else if (preg_match('/(?:\[\/?(?:b|u|i|h|colou?r|quote|code|img|url|email|list)\]|\[(?:code|quote|list)=)/i', $username))
$errors[] = $lang_profile['Username BBCode'];
// Check username for any censored words