forked from SimpleMachines/SMF
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLoad.php
3005 lines (2649 loc) · 121 KB
/
Load.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
/**
* This file has the hefty job of loading information for the forum.
*
* Simple Machines Forum (SMF)
*
* @package SMF
* @author Simple Machines http://www.simplemachines.org
* @copyright 2013 Simple Machines and individual contributors
* @license http://www.simplemachines.org/about/smf/license.php BSD
*
* @version 2.1 Alpha 1
*/
if (!defined('SMF'))
die('No direct access...');
/**
* Load the $modSettings array.
*
* @todo okay question of the day: why a function for loading settings is called reloadSettings()
*
* @global array $modSettings is a giant array of all of the forum-wide settings and statistics.
*/
function reloadSettings()
{
global $modSettings, $boarddir, $smcFunc, $txt, $db_character_set, $sourcedir;
// Most database systems have not set UTF-8 as their default input charset.
if (!empty($db_character_set))
$smcFunc['db_query']('set_character_set', '
SET NAMES ' . $db_character_set,
array(
)
);
// Try to load it from the cache first; it'll never get cached if the setting is off.
if (($modSettings = cache_get_data('modSettings', 90)) == null)
{
$request = $smcFunc['db_query']('', '
SELECT variable, value
FROM {db_prefix}settings',
array(
)
);
$modSettings = array();
if (!$request)
display_db_error();
while ($row = $smcFunc['db_fetch_row']($request))
$modSettings[$row[0]] = $row[1];
$smcFunc['db_free_result']($request);
// Do a few things to protect against missing settings or settings with invalid values...
if (empty($modSettings['defaultMaxTopics']) || $modSettings['defaultMaxTopics'] <= 0 || $modSettings['defaultMaxTopics'] > 999)
$modSettings['defaultMaxTopics'] = 20;
if (empty($modSettings['defaultMaxMessages']) || $modSettings['defaultMaxMessages'] <= 0 || $modSettings['defaultMaxMessages'] > 999)
$modSettings['defaultMaxMessages'] = 15;
if (empty($modSettings['defaultMaxMembers']) || $modSettings['defaultMaxMembers'] <= 0 || $modSettings['defaultMaxMembers'] > 999)
$modSettings['defaultMaxMembers'] = 30;
if (!empty($modSettings['cache_enable']))
cache_put_data('modSettings', $modSettings, 90);
}
// UTF-8 ?
$utf8 = (empty($modSettings['global_character_set']) ? $txt['lang_character_set'] : $modSettings['global_character_set']) === 'UTF-8';
// Set a list of common functions.
$ent_list = empty($modSettings['disableEntityCheck']) ? '&(#\d{1,7}|quot|amp|lt|gt|nbsp);' : '&(#021|quot|amp|lt|gt|nbsp);';
$ent_check = empty($modSettings['disableEntityCheck']) ? array('preg_replace_callback(\'~(&#(\d{1,7}|x[0-9a-fA-F]{1,6});)~\', \'entity_fix__callback\', ', ')') : array('', '');
// Preg_replace space characters depend on the character set in use
$space_chars = $utf8 ? '\x{A0}\x{AD}\x{2000}-\x{200F}\x{201F}\x{202F}\x{3000}\x{FEFF}' : '\x00-\x08\x0B\x0C\x0E-\x19\xA0';
// global array of anonymous helper functions, used mosly to properly handle multi byte strings
$smcFunc += array(
'entity_fix' => create_function('$string', '
$num = $string[0] === \'x\' ? hexdec(substr($string, 1)) : (int) $string;
return $num < 0x20 || $num > 0x10FFFF || ($num >= 0xD800 && $num <= 0xDFFF) || $num === 0x202E || $num === 0x202D ? \'\' : \'&#\' . $num . \';\';'),
'htmlspecialchars' => create_function('$string, $quote_style = ENT_COMPAT, $charset = \'ISO-8859-1\'', '
global $smcFunc;
return ' . strtr($ent_check[0], array('&' => '&')) . 'htmlspecialchars($string, $quote_style, ' . ($utf8 ? '\'UTF-8\'' : '$charset') . ')' . $ent_check[1] . ';'),
'htmltrim' => create_function('$string', '
global $smcFunc;
return preg_replace(\'~^(?:[ \t\n\r\x0B\x00' . $space_chars . ']| )+|(?:[ \t\n\r\x0B\x00' . $space_chars . ']| )+$~' . ($utf8 ? 'u' : '') . '\', \'\', ' . implode('$string', $ent_check) . ');'),
'strlen' => create_function('$string', '
global $smcFunc;
return strlen(preg_replace(\'~' . $ent_list . ($utf8 ? '|.~u' : '~') . '\', \'_\', ' . implode('$string', $ent_check) . '));'),
'strpos' => create_function('$haystack, $needle, $offset = 0', '
global $smcFunc;
$haystack_arr = preg_split(\'~(&#' . (empty($modSettings['disableEntityCheck']) ? '\d{1,7}' : '021') . ';|"|&|<|>| |.)~' . ($utf8 ? 'u' : '') . '\', ' . implode('$haystack', $ent_check) . ', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$haystack_size = count($haystack_arr);
if (strlen($needle) === 1)
{
$result = array_search($needle, array_slice($haystack_arr, $offset));
return is_int($result) ? $result + $offset : false;
}
else
{
$needle_arr = preg_split(\'~(&#' . (empty($modSettings['disableEntityCheck']) ? '\d{1,7}' : '021') . ';|"|&|<|>| |.)~' . ($utf8 ? 'u' : '') . '\', ' . implode('$needle', $ent_check) . ', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$needle_size = count($needle_arr);
$result = array_search($needle_arr[0], array_slice($haystack_arr, $offset));
while ((int) $result === $result)
{
$offset += $result;
if (array_slice($haystack_arr, $offset, $needle_size) === $needle_arr)
return $offset;
$result = array_search($needle_arr[0], array_slice($haystack_arr, ++$offset));
}
return false;
}'),
'substr' => create_function('$string, $start, $length = null', '
global $smcFunc;
$ent_arr = preg_split(\'~(&#' . (empty($modSettings['disableEntityCheck']) ? '\d{1,7}' : '021') . ';|"|&|<|>| |.)~' . ($utf8 ? 'u' : '') . '\', ' . implode('$string', $ent_check) . ', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
return $length === null ? implode(\'\', array_slice($ent_arr, $start)) : implode(\'\', array_slice($ent_arr, $start, $length));'),
'strtolower' => $utf8 ? (function_exists('mb_strtolower') ? create_function('$string', '
return mb_strtolower($string, \'UTF-8\');') : create_function('$string', '
global $sourcedir;
require_once($sourcedir . \'/Subs-Charset.php\');
return utf8_strtolower($string);')) : 'strtolower',
'strtoupper' => $utf8 ? (function_exists('mb_strtoupper') ? create_function('$string', '
return mb_strtoupper($string, \'UTF-8\');') : create_function('$string', '
global $sourcedir;
require_once($sourcedir . \'/Subs-Charset.php\');
return utf8_strtoupper($string);')) : 'strtoupper',
'truncate' => create_function('$string, $length', (empty($modSettings['disableEntityCheck']) ? '
global $smcFunc;
$string = ' . implode('$string', $ent_check) . ';' : '') . '
preg_match(\'~^(' . $ent_list . '|.){\' . $smcFunc[\'strlen\'](substr($string, 0, $length)) . \'}~'. ($utf8 ? 'u' : '') . '\', $string, $matches);
$string = $matches[0];
while (strlen($string) > $length)
$string = preg_replace(\'~(?:' . $ent_list . '|.)$~'. ($utf8 ? 'u' : '') . '\', \'\', $string);
return $string;'),
'ucfirst' => $utf8 ? create_function('$string', '
global $smcFunc;
return $smcFunc[\'strtoupper\']($smcFunc[\'substr\']($string, 0, 1)) . $smcFunc[\'substr\']($string, 1);') : 'ucfirst',
'ucwords' => $utf8 ? create_function('$string', '
global $smcFunc;
$words = preg_split(\'~([\s\r\n\t]+)~\', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
for ($i = 0, $n = count($words); $i < $n; $i += 2)
$words[$i] = $smcFunc[\'ucfirst\']($words[$i]);
return implode(\'\', $words);') : 'ucwords',
);
// Setting the timezone is a requirement for some functions in PHP >= 5.1.
if (isset($modSettings['default_timezone']) && function_exists('date_default_timezone_set'))
date_default_timezone_set($modSettings['default_timezone']);
// Check the load averages?
if (!empty($modSettings['loadavg_enable']))
{
if (($modSettings['load_average'] = cache_get_data('loadavg', 90)) == null)
{
$modSettings['load_average'] = @file_get_contents('/proc/loadavg');
if (!empty($modSettings['load_average']) && preg_match('~^([^ ]+?) ([^ ]+?) ([^ ]+)~', $modSettings['load_average'], $matches) != 0)
$modSettings['load_average'] = (float) $matches[1];
elseif (($modSettings['load_average'] = @`uptime`) != null && preg_match('~load average[s]?: (\d+\.\d+), (\d+\.\d+), (\d+\.\d+)~i', $modSettings['load_average'], $matches) != 0)
$modSettings['load_average'] = (float) $matches[1];
else
unset($modSettings['load_average']);
if (!empty($modSettings['load_average']))
cache_put_data('loadavg', $modSettings['load_average'], 90);
}
if (!empty($modSettings['load_average']))
call_integration_hook('integrate_load_average', array($modSettings['load_average']));
if (!empty($modSettings['loadavg_forum']) && !empty($modSettings['load_average']) && $modSettings['load_average'] >= $modSettings['loadavg_forum'])
display_loadavg_error();
}
// Is post moderation alive and well?
$modSettings['postmod_active'] = isset($modSettings['admin_features']) ? in_array('pm', explode(',', $modSettings['admin_features'])) : true;
// Here to justify the name of this function. :P
// It should be added to the install and upgrade scripts.
// But since the convertors need to be updated also. This is easier.
if (empty($modSettings['currentAttachmentUploadDir']))
{
updateSettings(array(
'attachmentUploadDir' => serialize(array(1 => $modSettings['attachmentUploadDir'])),
'currentAttachmentUploadDir' => 1,
));
}
// Integration is cool.
if (defined('SMF_INTEGRATION_SETTINGS'))
{
$integration_settings = unserialize(SMF_INTEGRATION_SETTINGS);
foreach ($integration_settings as $hook => $function)
add_integration_function($hook, $function, false);
}
// Any files to pre include?
if (!empty($modSettings['integrate_pre_include']))
{
$pre_includes = explode(',', $modSettings['integrate_pre_include']);
foreach ($pre_includes as $include)
{
$include = strtr(trim($include), array('$boarddir' => $boarddir, '$sourcedir' => $sourcedir));
if (file_exists($include))
require_once($include);
}
}
// Call pre load integration functions.
call_integration_hook('integrate_pre_load');
}
/**
* Load all the important user information.
* What it does:
* - sets up the $user_info array
* - assigns $user_info['query_wanna_see_board'] for what boards the user can see.
* - first checks for cookie or integration validation.
* - uses the current session if no integration function or cookie is found.
* - checks password length, if member is activated and the login span isn't over.
* - if validation fails for the user, $id_member is set to 0.
* - updates the last visit time when needed.
*/
function loadUserSettings()
{
global $modSettings, $user_settings, $sourcedir, $smcFunc;
global $cookiename, $user_info, $language, $context;
// Check first the integration, then the cookie, and last the session.
if (count($integration_ids = call_integration_hook('integrate_verify_user')) > 0)
{
$id_member = 0;
foreach ($integration_ids as $integration_id)
{
$integration_id = (int) $integration_id;
if ($integration_id > 0)
{
$id_member = $integration_id;
$already_verified = true;
break;
}
}
}
else
$id_member = 0;
if (empty($id_member) && isset($_COOKIE[$cookiename]))
{
// Fix a security hole in PHP 4.3.9 and below...
if (preg_match('~^a:[34]:\{i:0;(i:\d{1,6}|s:[1-8]:"\d{1,8}");i:1;s:(0|40):"([a-fA-F0-9]{40})?";i:2;[id]:\d{1,14};(i:3;i:\d;)?\}$~i', $_COOKIE[$cookiename]) == 1)
{
list ($id_member, $password) = @unserialize($_COOKIE[$cookiename]);
$id_member = !empty($id_member) && strlen($password) > 0 ? (int) $id_member : 0;
}
else
$id_member = 0;
}
elseif (empty($id_member) && isset($_SESSION['login_' . $cookiename]) && ($_SESSION['USER_AGENT'] == $_SERVER['HTTP_USER_AGENT'] || !empty($modSettings['disableCheckUA'])))
{
// @todo Perhaps we can do some more checking on this, such as on the first octet of the IP?
list ($id_member, $password, $login_span) = @unserialize($_SESSION['login_' . $cookiename]);
$id_member = !empty($id_member) && strlen($password) == 40 && $login_span > time() ? (int) $id_member : 0;
}
// Only load this stuff if the user isn't a guest.
if ($id_member != 0)
{
// Is the member data cached?
if (empty($modSettings['cache_enable']) || $modSettings['cache_enable'] < 2 || ($user_settings = cache_get_data('user_settings-' . $id_member, 60)) == null)
{
$request = $smcFunc['db_query']('', '
SELECT mem.*, IFNULL(a.id_attach, 0) AS id_attach, a.filename, a.attachment_type
FROM {db_prefix}members AS mem
LEFT JOIN {db_prefix}attachments AS a ON (a.id_member = {int:id_member})
WHERE mem.id_member = {int:id_member}
LIMIT 1',
array(
'id_member' => $id_member,
)
);
$user_settings = $smcFunc['db_fetch_assoc']($request);
$smcFunc['db_free_result']($request);
if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2)
cache_put_data('user_settings-' . $id_member, $user_settings, 60);
}
// Did we find 'im? If not, junk it.
if (!empty($user_settings))
{
// As much as the password should be right, we can assume the integration set things up.
if (!empty($already_verified) && $already_verified === true)
$check = true;
// SHA-1 passwords should be 40 characters long.
elseif (strlen($password) == 40)
$check = sha1($user_settings['passwd'] . $user_settings['password_salt']) == $password;
else
$check = false;
// Wrong password or not activated - either way, you're going nowhere.
$id_member = $check && ($user_settings['is_activated'] == 1 || $user_settings['is_activated'] == 11) ? $user_settings['id_member'] : 0;
}
else
$id_member = 0;
// If we no longer have the member maybe they're being all hackey, stop brute force!
if (!$id_member)
{
require_once($sourcedir . '/LogInOut.php');
validatePasswordFlood(!empty($user_settings['id_member']) ? $user_settings['id_member'] : $id_member, !empty($user_settings['passwd_flood']) ? $user_settings['passwd_flood'] : false, $id_member != 0);
}
}
// Found 'im, let's set up the variables.
if ($id_member != 0)
{
// Let's not update the last visit time in these cases...
// 1. SSI doesn't count as visiting the forum.
// 2. RSS feeds and XMLHTTP requests don't count either.
// 3. If it was set within this session, no need to set it again.
// 4. New session, yet updated < five hours ago? Maybe cache can help.
if (SMF != 'SSI' && !isset($_REQUEST['xml']) && (!isset($_REQUEST['action']) || $_REQUEST['action'] != '.xml') && empty($_SESSION['id_msg_last_visit']) && (empty($modSettings['cache_enable']) || ($_SESSION['id_msg_last_visit'] = cache_get_data('user_last_visit-' . $id_member, 5 * 3600)) === null))
{
// @todo can this be cached?
// Do a quick query to make sure this isn't a mistake.
$result = $smcFunc['db_query']('', '
SELECT poster_time
FROM {db_prefix}messages
WHERE id_msg = {int:id_msg}
LIMIT 1',
array(
'id_msg' => $user_settings['id_msg_last_visit'],
)
);
list ($visitTime) = $smcFunc['db_fetch_row']($result);
$smcFunc['db_free_result']($result);
$_SESSION['id_msg_last_visit'] = $user_settings['id_msg_last_visit'];
// If it was *at least* five hours ago...
if ($visitTime < time() - 5 * 3600)
{
updateMemberData($id_member, array('id_msg_last_visit' => (int) $modSettings['maxMsgID'], 'last_login' => time(), 'member_ip' => $_SERVER['REMOTE_ADDR'], 'member_ip2' => $_SERVER['BAN_CHECK_IP']));
$user_settings['last_login'] = time();
if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2)
cache_put_data('user_settings-' . $id_member, $user_settings, 60);
if (!empty($modSettings['cache_enable']))
cache_put_data('user_last_visit-' . $id_member, $_SESSION['id_msg_last_visit'], 5 * 3600);
}
}
elseif (empty($_SESSION['id_msg_last_visit']))
$_SESSION['id_msg_last_visit'] = $user_settings['id_msg_last_visit'];
$username = $user_settings['member_name'];
if (empty($user_settings['additional_groups']))
$user_info = array(
'groups' => array($user_settings['id_group'], $user_settings['id_post_group'])
);
else
$user_info = array(
'groups' => array_merge(
array($user_settings['id_group'], $user_settings['id_post_group']),
explode(',', $user_settings['additional_groups'])
)
);
// Because history has proven that it is possible for groups to go bad - clean up in case.
foreach ($user_info['groups'] as $k => $v)
$user_info['groups'][$k] = (int) $v;
// This is a logged in user, so definitely not a spider.
$user_info['possibly_robot'] = false;
}
// If the user is a guest, initialize all the critical user settings.
else
{
// This is what a guest's variables should be.
$username = '';
$user_info = array('groups' => array(-1));
$user_settings = array();
if (isset($_COOKIE[$cookiename]))
$_COOKIE[$cookiename] = '';
// Create a login token if it doesn't exist yet.
if (!isset($_SESSION['token']['post-login']))
createToken('login');
else
list ($context['login_token_var'],,, $context['login_token']) = $_SESSION['token']['post-login'];
// Do we perhaps think this is a search robot? Check every five minutes just in case...
if ((!empty($modSettings['spider_mode']) || !empty($modSettings['spider_group'])) && (!isset($_SESSION['robot_check']) || $_SESSION['robot_check'] < time() - 300))
{
require_once($sourcedir . '/ManageSearchEngines.php');
$user_info['possibly_robot'] = SpiderCheck();
}
elseif (!empty($modSettings['spider_mode']))
$user_info['possibly_robot'] = isset($_SESSION['id_robot']) ? $_SESSION['id_robot'] : 0;
// If we haven't turned on proper spider hunts then have a guess!
else
{
$ci_user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
$user_info['possibly_robot'] = (strpos($_SERVER['HTTP_USER_AGENT'], 'Mozilla') === false && strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') === false) || strpos($ci_user_agent, 'googlebot') !== false || strpos($ci_user_agent, 'slurp') !== false || strpos($ci_user_agent, 'crawl') !== false || strpos($ci_user_agent, 'msnbot') !== false;
}
}
// Set up the $user_info array.
$user_info += array(
'id' => $id_member,
'username' => $username,
'name' => isset($user_settings['real_name']) ? $user_settings['real_name'] : '',
'email' => isset($user_settings['email_address']) ? $user_settings['email_address'] : '',
'passwd' => isset($user_settings['passwd']) ? $user_settings['passwd'] : '',
'language' => empty($user_settings['lngfile']) || empty($modSettings['userLanguage']) ? $language : $user_settings['lngfile'],
'is_guest' => $id_member == 0,
'is_admin' => in_array(1, $user_info['groups']),
'theme' => empty($user_settings['id_theme']) ? 0 : $user_settings['id_theme'],
'last_login' => empty($user_settings['last_login']) ? 0 : $user_settings['last_login'],
'ip' => $_SERVER['REMOTE_ADDR'],
'ip2' => $_SERVER['BAN_CHECK_IP'],
'posts' => empty($user_settings['posts']) ? 0 : $user_settings['posts'],
'time_format' => empty($user_settings['time_format']) ? $modSettings['time_format'] : $user_settings['time_format'],
'time_offset' => empty($user_settings['time_offset']) ? 0 : $user_settings['time_offset'],
'avatar' => array(
'url' => isset($user_settings['avatar']) ? $user_settings['avatar'] : '',
'filename' => empty($user_settings['filename']) ? '' : $user_settings['filename'],
'custom_dir' => !empty($user_settings['attachment_type']) && $user_settings['attachment_type'] == 1,
'id_attach' => isset($user_settings['id_attach']) ? $user_settings['id_attach'] : 0
),
'smiley_set' => isset($user_settings['smiley_set']) ? $user_settings['smiley_set'] : '',
'messages' => empty($user_settings['instant_messages']) ? 0 : $user_settings['instant_messages'],
'unread_messages' => empty($user_settings['unread_messages']) ? 0 : $user_settings['unread_messages'],
'total_time_logged_in' => empty($user_settings['total_time_logged_in']) ? 0 : $user_settings['total_time_logged_in'],
'buddies' => !empty($modSettings['enable_buddylist']) && !empty($user_settings['buddy_list']) ? explode(',', $user_settings['buddy_list']) : array(),
'ignoreboards' => !empty($user_settings['ignore_boards']) && !empty($modSettings['allow_ignore_boards']) ? explode(',', $user_settings['ignore_boards']) : array(),
'ignoreusers' => !empty($user_settings['pm_ignore_list']) ? explode(',', $user_settings['pm_ignore_list']) : array(),
'warning' => isset($user_settings['warning']) ? $user_settings['warning'] : 0,
'permissions' => array(),
);
$user_info['groups'] = array_unique($user_info['groups']);
// Make sure that the last item in the ignore boards array is valid. If the list was too long it could have an ending comma that could cause problems.
if (!empty($user_info['ignoreboards']) && empty($user_info['ignoreboards'][$tmp = count($user_info['ignoreboards']) - 1]))
unset($user_info['ignoreboards'][$tmp]);
// Do we have any languages to validate this?
if (!empty($modSettings['userLanguage']) && (!empty($_GET['language']) || !empty($_SESSION['language'])))
$languages = getLanguages();
// Allow the user to change their language if its valid.
if (!empty($modSettings['userLanguage']) && !empty($_GET['language']) && isset($languages[strtr($_GET['language'], './\\:', '____')]))
{
$user_info['language'] = strtr($_GET['language'], './\\:', '____');
$_SESSION['language'] = $user_info['language'];
}
elseif (!empty($modSettings['userLanguage']) && !empty($_SESSION['language']) && isset($languages[strtr($_SESSION['language'], './\\:', '____')]))
$user_info['language'] = strtr($_SESSION['language'], './\\:', '____');
// Just build this here, it makes it easier to change/use - administrators can see all boards.
if ($user_info['is_admin'])
$user_info['query_see_board'] = '1=1';
// Otherwise just the groups in $user_info['groups'].
else
$user_info['query_see_board'] = '((FIND_IN_SET(' . implode(', b.member_groups) != 0 OR FIND_IN_SET(', $user_info['groups']) . ', b.member_groups) != 0)' . (!empty($modSettings['deny_boards_access']) ? ' AND (FIND_IN_SET(' . implode(', b.deny_member_groups) = 0 AND FIND_IN_SET(', $user_info['groups']) . ', b.deny_member_groups) = 0)' : '') . (isset($user_info['mod_cache']) ? ' OR ' . $user_info['mod_cache']['mq'] : '') . ')';
// Build the list of boards they WANT to see.
// This will take the place of query_see_boards in certain spots, so it better include the boards they can see also
// If they aren't ignoring any boards then they want to see all the boards they can see
if (empty($user_info['ignoreboards']))
$user_info['query_wanna_see_board'] = $user_info['query_see_board'];
// Ok I guess they don't want to see all the boards
else
$user_info['query_wanna_see_board'] = '(' . $user_info['query_see_board'] . ' AND b.id_board NOT IN (' . implode(',', $user_info['ignoreboards']) . '))';
call_integration_hook('integrate_user_info');
}
/**
* Check for moderators and see if they have access to the board.
* What it does:
* - sets up the $board_info array for current board information.
* - if cache is enabled, the $board_info array is stored in cache.
* - redirects to appropriate post if only message id is requested.
* - is only used when inside a topic or board.
* - determines the local moderators for the board.
* - adds group id 3 if the user is a local moderator for the board they are in.
* - prevents access if user is not in proper group nor a local moderator of the board.
*/
function loadBoard()
{
global $txt, $scripturl, $context, $modSettings;
global $board_info, $board, $topic, $user_info, $smcFunc;
// Assume they are not a moderator.
$user_info['is_mod'] = false;
$context['user']['is_mod'] = &$user_info['is_mod'];
// Start the linktree off empty..
$context['linktree'] = array();
// Have they by chance specified a message id but nothing else?
if (empty($_REQUEST['action']) && empty($topic) && empty($board) && !empty($_REQUEST['msg']))
{
// Make sure the message id is really an int.
$_REQUEST['msg'] = (int) $_REQUEST['msg'];
// Looking through the message table can be slow, so try using the cache first.
if (($topic = cache_get_data('msg_topic-' . $_REQUEST['msg'], 120)) === null)
{
$request = $smcFunc['db_query']('', '
SELECT id_topic
FROM {db_prefix}messages
WHERE id_msg = {int:id_msg}
LIMIT 1',
array(
'id_msg' => $_REQUEST['msg'],
)
);
// So did it find anything?
if ($smcFunc['db_num_rows']($request))
{
list ($topic) = $smcFunc['db_fetch_row']($request);
$smcFunc['db_free_result']($request);
// Save save save.
cache_put_data('msg_topic-' . $_REQUEST['msg'], $topic, 120);
}
}
// Remember redirection is the key to avoiding fallout from your bosses.
if (!empty($topic))
redirectexit('topic=' . $topic . '.msg' . $_REQUEST['msg'] . '#msg' . $_REQUEST['msg']);
else
{
loadPermissions();
loadTheme();
fatal_lang_error('topic_gone', false);
}
}
// Load this board only if it is specified.
if (empty($board) && empty($topic))
{
$board_info = array('moderators' => array(), 'moderator_groups' => array());
return;
}
if (!empty($modSettings['cache_enable']) && (empty($topic) || $modSettings['cache_enable'] >= 3))
{
// @todo SLOW?
if (!empty($topic))
$temp = cache_get_data('topic_board-' . $topic, 120);
else
$temp = cache_get_data('board-' . $board, 120);
if (!empty($temp))
{
$board_info = $temp;
$board = $board_info['id'];
}
}
if (empty($temp))
{
$request = $smcFunc['db_query']('', '
SELECT
c.id_cat, b.name AS bname, b.description, b.num_topics, b.member_groups, b.deny_member_groups,
b.id_parent, c.name AS cname, IFNULL(mg.id_group, 0) AS id_moderator_group, mg.group_name,
IFNULL(mem.id_member, 0) AS id_moderator,
mem.real_name' . (!empty($topic) ? ', b.id_board' : '') . ', b.child_level,
b.id_theme, b.override_theme, b.count_posts, b.id_profile, b.redirect,
b.unapproved_topics, b.unapproved_posts' . (!empty($topic) ? ', t.approved, t.id_member_started' : '') . '
FROM {db_prefix}boards AS b' . (!empty($topic) ? '
INNER JOIN {db_prefix}topics AS t ON (t.id_topic = {int:current_topic})' : '') . '
LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
LEFT JOIN {db_prefix}moderator_groups AS modgs ON (modgs.id_board = {raw:board_link})
LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = modgs.id_group)
LEFT JOIN {db_prefix}moderators AS mods ON (mods.id_board = {raw:board_link})
LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = mods.id_member)
WHERE b.id_board = {raw:board_link}',
array(
'current_topic' => $topic,
'board_link' => empty($topic) ? $smcFunc['db_quote']('{int:current_board}', array('current_board' => $board)) : 't.id_board',
)
);
// If there aren't any, skip.
if ($smcFunc['db_num_rows']($request) > 0)
{
$row = $smcFunc['db_fetch_assoc']($request);
// Set the current board.
if (!empty($row['id_board']))
$board = $row['id_board'];
// Basic operating information. (globals... :/)
$board_info = array(
'id' => $board,
'moderators' => array(),
'moderator_groups' => array(),
'cat' => array(
'id' => $row['id_cat'],
'name' => $row['cname']
),
'name' => $row['bname'],
'description' => $row['description'],
'num_topics' => $row['num_topics'],
'unapproved_topics' => $row['unapproved_topics'],
'unapproved_posts' => $row['unapproved_posts'],
'unapproved_user_topics' => 0,
'parent_boards' => getBoardParents($row['id_parent']),
'parent' => $row['id_parent'],
'child_level' => $row['child_level'],
'theme' => $row['id_theme'],
'override_theme' => !empty($row['override_theme']),
'profile' => $row['id_profile'],
'redirect' => $row['redirect'],
'posts_count' => empty($row['count_posts']),
'cur_topic_approved' => empty($topic) || $row['approved'],
'cur_topic_starter' => empty($topic) ? 0 : $row['id_member_started'],
);
// Load the membergroups allowed, and check permissions.
$board_info['groups'] = $row['member_groups'] == '' ? array() : explode(',', $row['member_groups']);
$board_info['deny_groups'] = $row['deny_member_groups'] == '' ? array() : explode(',', $row['deny_member_groups']);
do
{
if (!empty($row['id_moderator']))
$board_info['moderators'][$row['id_moderator']] = array(
'id' => $row['id_moderator'],
'name' => $row['real_name'],
'href' => $scripturl . '?action=profile;u=' . $row['id_moderator'],
'link' => '<a href="' . $scripturl . '?action=profile;u=' . $row['id_moderator'] . '">' . $row['real_name'] . '</a>'
);
if (!empty($row['id_moderator_group']))
$board_info['moderator_groups'][$row['id_moderator_group']] = array(
'id' => $row['id_moderator_group'],
'name' => $row['group_name'],
'href' => $scripturl . '?action=groups;sa=members;group=' . $row['id_moderator_group'],
'link' => '<a href="' . $scripturl . '?action=groups;sa=members;group=' . $row['id_moderator_group'] . '">' . $row['group_name'] . '</a>'
);
}
while ($row = $smcFunc['db_fetch_assoc']($request));
// If the board only contains unapproved posts and the user isn't an approver then they can't see any topics.
// If that is the case do an additional check to see if they have any topics waiting to be approved.
if ($board_info['num_topics'] == 0 && $modSettings['postmod_active'] && !allowedTo('approve_posts'))
{
// Free the previous result
$smcFunc['db_free_result']($request);
// @todo why is this using id_topic?
// @todo Can this get cached?
$request = $smcFunc['db_query']('', '
SELECT COUNT(id_topic)
FROM {db_prefix}topics
WHERE id_member_started={int:id_member}
AND approved = {int:unapproved}
AND id_board = {int:board}',
array(
'id_member' => $user_info['id'],
'unapproved' => 0,
'board' => $board,
)
);
list ($board_info['unapproved_user_topics']) = $smcFunc['db_fetch_row']($request);
}
if (!empty($modSettings['cache_enable']) && (empty($topic) || $modSettings['cache_enable'] >= 3))
{
// @todo SLOW?
if (!empty($topic))
cache_put_data('topic_board-' . $topic, $board_info, 120);
cache_put_data('board-' . $board, $board_info, 120);
}
}
else
{
// Otherwise the topic is invalid, there are no moderators, etc.
$board_info = array(
'moderators' => array(),
'moderator_groups' => array(),
'error' => 'exist'
);
$topic = null;
$board = 0;
}
$smcFunc['db_free_result']($request);
}
if (!empty($topic))
$_GET['board'] = (int) $board;
if (!empty($board))
{
// Get this into an array of keys for array_intersect
$moderator_groups = array_keys($board_info['moderator_groups']);
// Now check if the user is a moderator.
$user_info['is_mod'] = isset($board_info['moderators'][$user_info['id']]) || count(array_intersect($user_info['groups'], $moderator_groups)) != 0;
if (count(array_intersect($user_info['groups'], $board_info['groups'])) == 0 && !$user_info['is_admin'])
$board_info['error'] = 'access';
if (!empty($modSettings['deny_boards_access']) && count(array_intersect($user_info['groups'], $board_info['deny_groups'])) != 0 && !$user_info['is_admin'])
$board_info['error'] = 'access';
// Build up the linktree.
$context['linktree'] = array_merge(
$context['linktree'],
array(array(
'url' => $scripturl . '#c' . $board_info['cat']['id'],
'name' => $board_info['cat']['name']
)),
array_reverse($board_info['parent_boards']),
array(array(
'url' => $scripturl . '?board=' . $board . '.0',
'name' => $board_info['name']
))
);
}
// Set the template contextual information.
$context['user']['is_mod'] = &$user_info['is_mod'];
$context['current_topic'] = $topic;
$context['current_board'] = $board;
// Hacker... you can't see this topic, I'll tell you that. (but moderators can!)
if (!empty($board_info['error']) && (!empty($modSettings['deny_boards_access']) || $board_info['error'] != 'access' || !$user_info['is_mod']))
{
// The permissions and theme need loading, just to make sure everything goes smoothly.
loadPermissions();
loadTheme();
$_GET['board'] = '';
$_GET['topic'] = '';
// The linktree should not give the game away mate!
$context['linktree'] = array(
array(
'url' => $scripturl,
'name' => $context['forum_name_html_safe']
)
);
// If it's a prefetching agent or we're requesting an attachment.
if ((isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch') || (!empty($_REQUEST['action']) && $_REQUEST['action'] === 'dlattach'))
{
ob_end_clean();
header('HTTP/1.1 403 Forbidden');
die;
}
elseif ($user_info['is_guest'])
{
loadLanguage('Errors');
is_not_guest($txt['topic_gone']);
}
else
fatal_lang_error('topic_gone', false);
}
if ($user_info['is_mod'])
$user_info['groups'][] = 3;
}
/**
* Load this user's permissions.
*
*/
function loadPermissions()
{
global $user_info, $board, $board_info, $modSettings, $smcFunc, $sourcedir;
if ($user_info['is_admin'])
{
banPermissions();
return;
}
if (!empty($modSettings['cache_enable']))
{
$cache_groups = $user_info['groups'];
asort($cache_groups);
$cache_groups = implode(',', $cache_groups);
// If it's a spider then cache it different.
if ($user_info['possibly_robot'])
$cache_groups .= '-spider';
if ($modSettings['cache_enable'] >= 2 && !empty($board) && ($temp = cache_get_data('permissions:' . $cache_groups . ':' . $board, 240)) != null && time() - 240 > $modSettings['settings_updated'])
{
list ($user_info['permissions']) = $temp;
banPermissions();
return;
}
elseif (($temp = cache_get_data('permissions:' . $cache_groups, 240)) != null && time() - 240 > $modSettings['settings_updated'])
list ($user_info['permissions'], $removals) = $temp;
}
// If it is detected as a robot, and we are restricting permissions as a special group - then implement this.
$spider_restrict = $user_info['possibly_robot'] && !empty($modSettings['spider_group']) ? ' OR (id_group = {int:spider_group} AND add_deny = 0)' : '';
if (empty($user_info['permissions']))
{
// Get the general permissions.
$request = $smcFunc['db_query']('', '
SELECT permission, add_deny
FROM {db_prefix}permissions
WHERE id_group IN ({array_int:member_groups})
' . $spider_restrict,
array(
'member_groups' => $user_info['groups'],
'spider_group' => !empty($modSettings['spider_group']) ? $modSettings['spider_group'] : 0,
)
);
$removals = array();
while ($row = $smcFunc['db_fetch_assoc']($request))
{
if (empty($row['add_deny']))
$removals[] = $row['permission'];
else
$user_info['permissions'][] = $row['permission'];
}
$smcFunc['db_free_result']($request);
if (isset($cache_groups))
cache_put_data('permissions:' . $cache_groups, array($user_info['permissions'], $removals), 240);
}
// Get the board permissions.
if (!empty($board))
{
// Make sure the board (if any) has been loaded by loadBoard().
if (!isset($board_info['profile']))
fatal_lang_error('no_board');
$request = $smcFunc['db_query']('', '
SELECT permission, add_deny
FROM {db_prefix}board_permissions
WHERE (id_group IN ({array_int:member_groups})
' . $spider_restrict . ')
AND id_profile = {int:id_profile}',
array(
'member_groups' => $user_info['groups'],
'id_profile' => $board_info['profile'],
'spider_group' => !empty($modSettings['spider_group']) ? $modSettings['spider_group'] : 0,
)
);
while ($row = $smcFunc['db_fetch_assoc']($request))
{
if (empty($row['add_deny']))
$removals[] = $row['permission'];
else
$user_info['permissions'][] = $row['permission'];
}
$smcFunc['db_free_result']($request);
}
// Remove all the permissions they shouldn't have ;).
if (!empty($modSettings['permission_enable_deny']))
$user_info['permissions'] = array_diff($user_info['permissions'], $removals);
if (isset($cache_groups) && !empty($board) && $modSettings['cache_enable'] >= 2)
cache_put_data('permissions:' . $cache_groups . ':' . $board, array($user_info['permissions'], null), 240);
// Banned? Watch, don't touch..
banPermissions();
// Load the mod cache so we can know what additional boards they should see, but no sense in doing it for guests
if (!$user_info['is_guest'])
{
if (!isset($_SESSION['mc']) || $_SESSION['mc']['time'] <= $modSettings['settings_updated'])
{
require_once($sourcedir . '/Subs-Auth.php');
rebuildModCache();
}
else
$user_info['mod_cache'] = $_SESSION['mc'];
}
}
/**
* Loads an array of users' data by ID or member_name.
*
* @param mixed $users An array of users by id or name
* @param bool $is_name = false $users is by name or by id
* @param string $set = 'normal' What kind of data to load (normal, profile, minimal)
* @return array|bool The ids of the members loaded or false
*/
function loadMemberData($users, $is_name = false, $set = 'normal')
{
global $user_profile, $modSettings, $board_info, $smcFunc, $context;
// Can't just look for no users :P.
if (empty($users))
return false;
// Pass the set value
$context['loadMemberContext_set'] = $set;
// Make sure it's an array.
$users = !is_array($users) ? array($users) : array_unique($users);
$loaded_ids = array();
if (!$is_name && !empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 3)
{
$users = array_values($users);
for ($i = 0, $n = count($users); $i < $n; $i++)
{
$data = cache_get_data('member_data-' . $set . '-' . $users[$i], 240);
if ($data == null)
continue;
$loaded_ids[] = $data['id_member'];
$user_profile[$data['id_member']] = $data;
unset($users[$i]);
}
}
// Used by default
$select_columns = '
IFNULL(lo.log_time, 0) AS is_online, IFNULL(a.id_attach, 0) AS id_attach, a.filename, a.attachment_type,
mem.signature, mem.personal_text, mem.location, mem.gender, mem.avatar, mem.id_member, mem.member_name,
mem.real_name, mem.email_address, mem.hide_email, mem.date_registered, mem.website_title, mem.website_url,
mem.birthdate, mem.member_ip, mem.member_ip2, mem.icq, mem.aim, mem.yim, mem.skype, mem.posts, mem.last_login,
mem.karma_good, mem.id_post_group, mem.karma_bad, mem.lngfile, mem.id_group, mem.time_offset, mem.show_online,
mg.online_color AS member_group_color, IFNULL(mg.group_name, {string:blank_string}) AS member_group,
pg.online_color AS post_group_color, IFNULL(pg.group_name, {string:blank_string}) AS post_group,
mem.is_activated, mem.warning, ' . (!empty($modSettings['titlesEnable']) ? 'mem.usertitle, ' : '') . '
CASE WHEN mem.id_group = 0 OR mg.icons = {string:blank_string} THEN pg.icons ELSE mg.icons END AS icons';
$select_tables = '
LEFT JOIN {db_prefix}log_online AS lo ON (lo.id_member = mem.id_member)
LEFT JOIN {db_prefix}attachments AS a ON (a.id_member = mem.id_member)
LEFT JOIN {db_prefix}membergroups AS pg ON (pg.id_group = mem.id_post_group)
LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = mem.id_group)';
// We add or replace according the the set
switch ($set)
{
case 'normal':
$select_columns .= ', mem.buddy_list, mem.additional_groups';
break;
case 'profile':
$select_columns .= ', mem.additional_groups, mem.openid_uri, mem.id_theme, mem.pm_ignore_list, mem.pm_email_notify, mem.pm_receive_from,
mem.time_format, mem.secret_question, mem.smiley_set,
mem.total_time_logged_in, mem.notify_announcements, mem.notify_regularity, mem.notify_send_body,
mem.notify_types, lo.url, mem.ignore_boards, mem.password_salt, mem.pm_prefs, mem.buddy_list';
break;
case 'minimal':
$select_columns = '
mem.id_member, mem.member_name, mem.real_name, mem.email_address, mem.hide_email, mem.date_registered,
mem.posts, mem.last_login, mem.member_ip, mem.member_ip2, mem.lngfile, mem.id_group';
$select_tables = '';
break;
default:
trigger_error('loadMemberData(): Invalid member data set \'' . $set . '\'', E_USER_WARNING);
}
// Allow mods to easily add to the selected member data
call_integration_hook('integrate_load_member_data', array(&$select_columns, &$select_tables, &$set));
if (!empty($users))
{
// Load the member's data.
$request = $smcFunc['db_query']('', '
SELECT' . $select_columns . '
FROM {db_prefix}members AS mem' . $select_tables . '
WHERE mem.' . ($is_name ? 'member_name' : 'id_member') . ' IN ({' . ($is_name ? 'array_string' : 'array_int') . ':users})',
array(
'blank_string' => '',
'users' => $users,
)
);
$new_loaded_ids = array();
while ($row = $smcFunc['db_fetch_assoc']($request))
{
$new_loaded_ids[] = $row['id_member'];
$loaded_ids[] = $row['id_member'];
$row['options'] = array();
$user_profile[$row['id_member']] = $row;
}
$smcFunc['db_free_result']($request);
}
if (!empty($new_loaded_ids) && $set !== 'minimal')
{
$request = $smcFunc['db_query']('', '
SELECT *
FROM {db_prefix}themes
WHERE id_member IN ({array_int:loaded_ids})',
array(
'loaded_ids' => $new_loaded_ids,
)
);
while ($row = $smcFunc['db_fetch_assoc']($request))
$user_profile[$row['id_member']]['options'][$row['variable']] = $row['value'];
$smcFunc['db_free_result']($request);