/
Load.php
2392 lines (2101 loc) · 90.4 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 carries many useful functions for loading various general data from the database, often required on every page.
*
* Wedge (http://wedge.org)
* Copyright © 2010 René-Gilles Deberdt, wedge.org
* Portions are © 2011 Simple Machines.
* License: http://wedge.org/license/
*/
if (!defined('WEDGE'))
die('Hacking attempt...');
/**
* Loads the forum-wide settings into $settings as an array.
*
* - Ensure the database is using the same character set as the application thinks it is.
* - Attempt to load the settings from cache, failing that from the database, with some fallback/sanity values for a few common settings.
* - Save the value in cache for next time.
* - Fill up the list of known actions.
* - Set the timezone (mandatory in PHP)
* - Check the load average settings if available.
* - Check whether post moderation is enabled.
* - Run any functions specified in the pre_load hook.
*/
function loadSettings()
{
global $settings, $context, $pluginsdir, $pluginsurl, $action_list, $action_no_log;
// This is where it all began.
$context = array(
'pretty' => array('db_count' => 0),
'action' => '',
'subaction' => '',
'app_error_count' => 0,
);
// Try to load settings from the cache first; they'll never get cached if the setting is off.
if (($settings = cache_get_data('settings', 'forever')) === null)
{
$request = wesql::query('
SELECT variable, value
FROM {db_prefix}settings'
);
$settings = array();
if (!$request)
show_db_error();
while ($row = wesql::fetch_row($request))
$settings[$row[0]] = $row[1];
wesql::free_result($request);
if (empty($settings['language']))
$settings['language'] = 'english';
// Do a few things to protect against missing settings or settings with invalid values...
if (empty($settings['defaultMaxTopics']) || $settings['defaultMaxTopics'] <= 0 || $settings['defaultMaxTopics'] > 999)
$settings['defaultMaxTopics'] = 20;
if (empty($settings['defaultMaxMessages']) || $settings['defaultMaxMessages'] <= 0 || $settings['defaultMaxMessages'] > 999)
$settings['defaultMaxMessages'] = 15;
if (empty($settings['defaultMaxMembers']) || $settings['defaultMaxMembers'] <= 0 || $settings['defaultMaxMembers'] > 999)
$settings['defaultMaxMembers'] = 30;
$settings['js_lang'] = empty($settings['js_lang']) ? array() : unserialize($settings['js_lang']);
$settings['registered_hooks'] = empty($settings['registered_hooks']) ? array() : unserialize($settings['registered_hooks']);
$settings['hooks'] = $settings['registered_hooks'];
$settings['pretty_filters'] = unserialize($settings['pretty_filters']);
if (!empty($settings['cache_enable']))
cache_put_data('settings', $settings, 'forever');
}
/*
I am the Gatekeeper. Are you the Keymaster?
Here's the monstrous $action array - $action => array($file, [[$function], $plugin_id]).
If the function name is the same as the loadSource file name, e.g. Admin.php, to run Admin(), you can declare it as a string.
Only add $plugin_id if it's for a plugin, otherwise just have (one or) two items in the list.
Add custom actions to to the $action_list array this way:
'my-action' => array('MyFile.php', 'MyFunction'),
Then, the URL index.php?action=my-action will load call MyFile.php and call MyFunction().
*/
$action_list = array(
'activate' => 'Activate',
'admin' => 'Admin',
'ajax' => 'Ajax',
'announce' => 'Announce',
'boards' => 'Boards',
'buddy' => 'Buddy',
'collapse' => 'Collapse',
'coppa' => 'CoppaForm',
'credits' => 'Credits',
'deletemsg' => array('RemoveTopic', 'DeleteMessage'),
'display' => 'Display',
'dlattach' => 'Dlattach',
'emailuser' => 'Mailer',
'feed' => 'Feed',
'groups' => 'Groups',
'help' => 'Help',
'like' => 'Like',
'lock' => 'Lock',
'login' => 'Login',
'login2' => 'Login2',
'logout' => 'Logout',
'markasread' => array('Subs-Boards', 'MarkRead'),
'media' => array('media/Aeva-Gallery', 'aeva_initGallery'),
'mergeposts' => array('Merge', 'MergePosts'),
'mergetopics' => array('Merge', 'MergeTopics'),
'mlist' => 'Memberlist',
'moderate' => 'ModerationCenter',
'movetopic' => 'MoveTopic',
'movetopic2' => array('MoveTopic', 'MoveTopic2'),
'notify' => 'Notify',
'notifyboard' => array('Notify', 'BoardNotify'),
'notification' => array('Notifications', 'weNotif::action'),
'pin' => 'Pin',
'pm' => 'PersonalMessage',
'poll' => 'Poll',
'post' => 'Post',
'post2' => 'Post2',
'printpage' => 'PrintPage',
'profile' => array('Profile', 'ModifyProfile'),
'quickedit' => 'QuickEdit',
'quickmod' => array('QuickMod', 'QuickModeration'),
'quickmod2' => array('QuickMod', 'QuickInTopicModeration'),
'quotefast' => 'QuoteFast',
'recent' => 'Recent',
'register' => 'Register',
'register2' => array('Register', 'Register2'),
'reminder' => array('Reminder', 'RemindMe'),
'removetopic2' => array('RemoveTopic', 'RemoveTopic2'),
'report' => 'Report',
'restoretopic' => array('RemoveTopic', 'RestoreTopic'),
'search' => 'Search',
'search2' => 'Search2',
'sendtopic' => 'Mailer',
'skin' => array('Themes', 'PickTheme'),
'splittopics' => array('Split', 'SplitTopics'),
'stats' => 'Stats',
'suggest' => 'Suggest',
'theme' => 'Themes',
'thoughts' => 'Thoughts',
'trackip' => array('Profile-View', 'trackIP'),
'uncache' => array('Subs-Cache', 'uncache'),
'unread' => 'Unread',
'unreadreplies' => 'UnreadReplies',
'verification' => 'VerificationCode',
'viewquery' => 'ViewQuery',
'viewremote' => 'ViewRemote',
'who' => 'Who',
);
if (empty($settings['pm_enabled']))
unset($action_list['pm']);
// If an action should not influence the who's online list, please add it to the $action_no_log global from your own action.
$action_no_log = array('ajax', 'dlattach', 'feed', 'like', 'notification', 'verification', 'viewquery', 'viewremote');
// Set up path constants.
loadPaths();
// Deal with loading plugins.
$context['enabled_plugins'] = array();
if (!empty($settings['enabled_plugins']))
{
// Step through the list we think we have enabled.
$plugins = explode(',', $settings['enabled_plugins']);
$sane_path = str_replace('\\', '/', $pluginsdir);
$hook_stack = array();
foreach ($plugins as $plugin)
{
if (!empty($settings['plugin_' . $plugin]) && file_exists($sane_path . '/' . $plugin . '/plugin-info.xml'))
{
$plugin_details = @unserialize($settings['plugin_' . $plugin]);
$context['enabled_plugins'][$plugin_details['id']] = $plugin;
$context['plugins_dir'][$plugin_details['id']] = $sane_path . '/' . $plugin;
$context['plugins_url'][$plugin_details['id']] = $pluginsurl . '/' . $plugin;
if (isset($plugin_details['actions']))
foreach ($plugin_details['actions'] as $action)
{
if (strpos($action['function'], '::') !== false)
$action['function'] = explode('::', $action['function']);
$action_list[$action['action']] = array($action['filename'], $action['function'], $plugin_details['id']);
if (!empty($action['nolog']))
$action_no_log[] = $action['action'];
}
unset($plugin_details['id'], $plugin_details['provides'], $plugin_details['actions']);
foreach ($plugin_details as $hook => $functions)
foreach ($functions as $function)
{
$priority = (int) substr(strrchr($function, '|'), 1);
$hook_stack[$hook][$priority][] = strtr($function, array('$plugindir/' => ''));
}
}
else
$reset_plugins = true;
}
if (isset($reset_plugins))
updateSettings(array('enabled_plugins' => implode(',', $context['enabled_plugins'])));
// Having got all the hooks, figure out the priority ordering and commit to the master list.
foreach ($hook_stack as $hook => $hooks_by_priority)
{
krsort($hooks_by_priority);
if (!isset($settings['hooks'][$hook]))
$settings['hooks'][$hook] = array();
foreach ($hooks_by_priority as $priority => $hooks)
$settings['hooks'][$hook] = array_merge($settings['hooks'][$hook], $hooks);
}
}
// UTF8-aware string functions.
loadSource('Class-String');
westr::getInstance();
// Change the random generator seed, from time to time.
if (empty($settings['rand_seed']) || mt_rand(1, 250) == 42)
updateSettings(array('rand_seed' => mt_rand()));
// Setting the timezone is a requirement. At least use what the host has, to prevent errors.
date_default_timezone_set(isset($settings['default_timezone']) ? $settings['default_timezone'] : @date_default_timezone_get());
// Check the load averages?
if (!empty($settings['loadavg_enable']))
{
if (($settings['load_average'] = cache_get_data('loadavg', 90)) === null)
{
$settings['load_average'] = @file_get_contents('/proc/loadavg');
if (!empty($settings['load_average']) && preg_match('~^([^ ]+?) ([^ ]+?) ([^ ]+)~', $settings['load_average'], $matches) != 0)
$settings['load_average'] = (float) $matches[1];
elseif (can_shell_exec() && ($settings['load_average'] = `uptime`) != null && preg_match('~load average[s]?: (\d+\.\d+), (\d+\.\d+), (\d+\.\d+)~i', $settings['load_average'], $matches) != 0)
$settings['load_average'] = (float) $matches[1];
else
unset($settings['load_average']);
if (!empty($settings['load_average']))
cache_put_data('loadavg', $settings['load_average'], 90);
}
if (!empty($settings['loadavg_forum']) && !empty($settings['load_average']) && $settings['load_average'] >= $settings['loadavg_forum'])
show_db_error(true);
}
// Is post moderation alive and well?
$settings['postmod_active'] = !empty($settings['postmod_active']) || !empty($settings['postmod_rules']);
if (!empty($settings['imported_from']) && !isset($settings['imported_cleaned']))
importing_cleanup();
// Call pre-load hook functions.
call_hook('pre_load');
// Sanitize and normalize URL variables.
cleanRequest();
if (WEDGE == 'SSI')
return;
// Before we get carried away, are we doing a scheduled task? If so save CPU cycles by jumping out!
if (isset($_GET['scheduled']))
{
loadSource('ScheduledTasks');
AutoTask();
}
elseif (isset($_GET['imperative']))
{
loadSource('Subs-Scheduled');
ImperativeTask();
}
}
function can_shell_exec()
{
static $result = null;
if ($result !== null)
return $result;
$disable_functions = explode(',', ini_get('disable_functions') . ',' . ini_get('suhosin.executor.func.blacklist'));
return $result = (is_callable('shell_exec') && !ini_get('safe_mode') && !in_array('shell_exec', $disable_functions));
}
/**
* Validate whether we are dealing with a board, and whether the current user has access to that board.
*
* - Initialize the link tree (and later, populating it).
* - If only an individual msg is specified in the URL, identify the topic it belongs to, and redirect to that topic normally. (Assuming it exists; if not throw a fatal error that topic does not exist)
* - If no board or topic is applicable, return (we're not in a board, and there won't be board moderators)
* - See if we have checked this board or board+topic lately, and if so, grab from cache.
* - If we don't have this, load the board information into $board_info, including category id and name, board name and other details of this board
* - See if there are board moderators, and whether the current user is amongst them (which means possibly upgrading access if they did not have so before, as well as adding group id 3 to their groups)
* - If the user cannot see the topic (and isn't a local moderator), issue a fatal error.
*/
function loadBoard()
{
global $txt, $context, $settings;
global $board_info, $board, $topic, $user_settings;
// Start the linktree off empty..
$context['linktree'] = array();
// Have they by chance specified a message id but nothing else?
if (!$context['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 = wesql::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 (wesql::num_rows($request))
{
list ($topic) = wesql::fetch_row($request);
wesql::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(),
'skin' => '',
);
return;
}
// Is this a XML feed requesting a topic?
elseif (empty($board) && !empty($topic) && $context['action'] === 'feed')
return;
if (!empty($settings['cache_enable']) && (empty($topic) || $settings['cache_enable'] >= 3))
{
// !!! 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 = wesql::query('
SELECT
c.id_cat, b.name AS bname, b.url, b.id_owner, b.description, b.num_topics, b.member_groups,
b.num_posts, b.id_parent, c.name AS cname, IFNULL(mem.id_member, 0) AS id_moderator,
mem.real_name' . (!empty($topic) ? ', b.id_board' : '') . ', b.child_level, b.skin, b.skin_mobile,
b.override_skin, b.count_posts, b.id_profile, b.redirect, b.language, bm.permission = \'deny\' AS banned,
bm.permission = {literal:access} AS allowed, mco.real_name AS owner_name, mco.buddy_list AS contacts, b.board_type, b.sort_method,
b.sort_override, 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} AND {query_see_topic})' : '') . '
LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
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)
LEFT JOIN {db_prefix}members AS mco ON (mco.id_member = b.id_owner)
LEFT JOIN {db_prefix}board_members AS bm ON b.id_board = bm.id_board AND b.id_owner = {int:id_member}
WHERE b.id_board = {raw:board_link}',
array(
'current_topic' => $topic,
'board_link' => empty($topic) ? wesql::quote('{int:current_board}', array('current_board' => $board)) : 't.id_board',
'id_member' => MID,
)
);
// If there aren't any, skip.
if (wesql::num_rows($request) > 0)
{
$row = wesql::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,
'owner_id' => $row['id_owner'],
'owner_name' => $row['owner_name'],
'moderators' => array(),
'cat' => array(
'id' => $row['id_cat'],
'name' => $row['cname']
),
'name' => $row['bname'],
'description' => $row['description'],
'url' => $row['url'],
'num_posts' => $row['num_posts'],
'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'],
'skin' => $row['skin'],
'skin_mobile' => $row['skin_mobile'],
'override_skin' => !empty($row['override_skin']),
'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'],
'allowed_member' => $row['allowed'],
'banned_member' => $row['banned'],
'contacts' => $row['contacts'],
'language' => $row['language'],
'type' => $row['board_type'],
'sort_method' => $row['sort_method'],
'sort_override' => $row['sort_override'],
);
// Load privacy settings.
// !!! Are we still meant to be using this now we have query_see_topic..? It's going to be inaccurate!
// !!! @todo: update this code, with the new privacy system.
if ($row['member_groups'] === '0')
$board_info['privacy'] = 'members';
elseif ($row['member_groups'] === '-1,0')
$board_info['privacy'] = 'everyone';
elseif ($row['member_groups'] === 'contacts')
$board_info['privacy'] = 'contacts';
elseif ($row['member_groups'] === '')
{
$board_info['privacy'] = 'author';
$row['member_groups'] = '';
}
else
$board_info['privacy'] = 'everyone';
if (!empty($row['id_owner']))
$board_info['moderators'] = array(
$row['id_owner'] => array(
'id' => $row['id_owner'],
'name' => $row['owner_name'],
'href' => '<URL>?action=profile;u=' . $row['id_owner'],
'link' => '<a href="<URL>?action=profile;u=' . $row['id_owner'] . '">' . $row['owner_name'] . '</a>'
)
);
do
{
if (!empty($row['id_moderator']) && $row['id_moderator'] != $row['id_owner'])
$board_info['moderators'][$row['id_moderator']] = array(
'id' => $row['id_moderator'],
'name' => $row['real_name'],
'href' => '<URL>?action=profile;u=' . $row['id_moderator'],
'link' => '<a href="<URL>?action=profile;u=' . $row['id_moderator'] . '">' . $row['real_name'] . '</a>'
);
}
while ($row = wesql::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 && $settings['postmod_active'] && !allowedTo('approve_posts'))
{
wesql::free_result($request); // Free the previous result.
$request = wesql::query('
SELECT COUNT(id_topic)
FROM {db_prefix}topics
WHERE id_member_started = {int:id_member}
AND approved = {int:is_unapproved}
AND id_board = {int:board}',
array(
'id_member' => MID,
'is_unapproved' => 0,
'board' => $board,
)
);
list ($board_info['unapproved_user_topics']) = wesql::fetch_row($request);
}
if (!empty($settings['cache_enable']) && (empty($topic) || $settings['cache_enable'] >= 3))
{
// !!! 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(),
'skin' => '',
'error' => 'exist',
);
$topic = null;
$board = 0;
}
wesql::free_result($request);
}
if (isset($board_info['skin_mobile']) && we::is('mobile'))
$board_info['skin'] = $board_info['skin_mobile'];
if (!empty($topic))
$_GET['board'] = (int) $board;
if (!empty($board))
{
// Now tell the system class where we are, and whether we're a moderator.
we::$cache = array();
we::$is['mod'] |= isset($board_info['moderators'][MID]);
we::$is['b' . $board] = true;
we::$is['c' . $board_info['cat']['id']] = true;
if ($board_info['banned_member'] && !$board_info['allowed_member'])
$board_info['error'] = 'access';
if (!we::$is_admin && !in_array($board_info['id'], we::$user['qsb_boards']))
{
if (!we::$is['mod'] && (!empty($board_info['owner_id']) && MID != $board_info['owner_id']))
{
switch ($board_info['privacy'])
{
case 'contacts':
if (!in_array(MID, explode(',', $board_info['contacts'])))
$board_info['error'] = 'access';
break;
case 'members':
if (we::$is_guest)
$board_info['error'] = 'access';
break;
case 'author':
$board_info['error'] = 'access'; // We've already established that the user is not the owner
break;
case 'everyone':
$board_info['error'] = 'access'; // The fact we're here means there are some groups denying/not granting access which must be adhered to
break;
}
}
else
$board_info['error'] = 'access'; // You're not permitted here, not an admin or mod and there's no owner rights to allow you in either.
}
// Build up the linktree.
$context['linktree'] = array_merge(
$context['linktree'],
array(array(
'url' => '<URL>?category=' . $board_info['cat']['id'],
'name' => $board_info['cat']['name']
)),
array_reverse($board_info['parent_boards']),
array(array(
'url' => '<URL>?board=' . $board . '.0',
'name' => $board_info['name']
))
);
// Does this board have its own language setting? If so, does the user have their
// own personal language set? (User preference beats board, which beats forum default)
if (!empty($board_info['language']) && empty($user_settings['lngfile']))
{
we::$user['language'] = $board_info['language'];
$user_settings['lngfile'] = $board_info['language'];
}
}
// Set the template contextual information.
$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']) && ($board_info['error'] != 'access' || !we::$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! However, it WILL be available to admins etc. for Who's Online so they can see what's going on.
$context['linktree'] = array();
add_linktree($context['forum_name_html_safe'], '<URL>');
// If it's a prefetching agent or we're requesting an attachment.
preventPrefetch($context['action'] === 'dlattach');
if (we::$is_guest)
{
loadLanguage('Errors');
is_not_guest($txt['topic_gone']);
}
else
fatal_lang_error('topic_gone', false);
}
if (we::$is['mod'])
we::$user['groups'][] = 3;
}
/**
* Load the current user's permissions, to be stored in we::$user['permissions']
*
* - If the user is an admin, simply validate that they have not been banned then return.
* - Attempt to load from cache (level 2+ caching only); if matched, apply ban restrictions and return.
* - See if the user is possibly a spider, extend the user's "permissions" appropriately.
* - If we have not been able to establish permissions thus far (because caching failed us), query the general permissions table for our groups.
* - Then apply those permissions, both allow and denied.
* - If inside a board, identify the board profile, and load the permissions from that, following the same process.
* - If on caching level 2 or up, cache, then apply banned user permissions if banned.
* - If the user is not a guest, identify what other boards they may have access to through the moderator cache.
*/
function loadPermissions()
{
global $board, $board_info, $settings;
if (we::$is_admin)
{
banPermissions();
return;
}
if (!empty($settings['cache_enable']))
{
$cache_groups = we::$user['groups'];
asort($cache_groups);
$cache_groups = implode(',', $cache_groups);
// If it's a spider then cache it different.
if (we::$user['possibly_robot'])
$cache_groups .= '-spider';
if ($settings['cache_enable'] >= 2 && !empty($board) && ($temp = cache_get_data('permissions:' . $cache_groups . ':' . $board, 240)) !== null && time() - 240 > $settings['settings_updated'])
{
list (we::$user['permissions']) = $temp;
banPermissions();
return;
}
elseif (($temp = cache_get_data('permissions:' . $cache_groups, 240)) !== null && time() - 240 > $settings['settings_updated'])
list (we::$user['permissions'], $removals) = $temp;
}
// If it is detected as a robot, and we are restricting permissions as a special group - then implement this.
$spider_restrict = we::$user['possibly_robot'] && !empty($settings['spider_mode']) && !empty($settings['spider_group']) ? ' OR (id_group = {int:spider_group} AND add_deny = 0)' : '';
if (empty(we::$user['permissions']))
{
// Get the general permissions.
$request = wesql::query('
SELECT permission, add_deny
FROM {db_prefix}permissions
WHERE id_group IN ({array_int:member_groups})
' . $spider_restrict,
array(
'member_groups' => we::$user['groups'],
'spider_group' => !empty($settings['spider_group']) ? $settings['spider_group'] : 0,
)
);
$removals = array();
while ($row = wesql::fetch_assoc($request))
{
if (empty($row['add_deny']))
$removals[] = $row['permission'];
else
we::$user['permissions'][] = $row['permission'];
}
wesql::free_result($request);
if (isset($cache_groups))
cache_put_data('permissions:' . $cache_groups, array(we::$user['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 = wesql::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' => we::$user['groups'],
'id_profile' => $board_info['profile'],
'spider_group' => !empty($settings['spider_mode']) && !empty($settings['spider_group']) ? $settings['spider_group'] : 0,
)
);
while ($row = wesql::fetch_assoc($request))
{
if (empty($row['add_deny']))
$removals[] = $row['permission'];
else
we::$user['permissions'][] = $row['permission'];
}
wesql::free_result($request);
if (!empty($board_info['owner_id']) && $board_info['owner_id'] == MID)
we::$user['permissions'][] = 'moderate_board';
}
// Remove all the permissions they shouldn't have ;)
we::$user['permissions'] = array_diff(array_flip(array_flip(we::$user['permissions'])), $removals);
if (isset($cache_groups) && !empty($board) && $settings['cache_enable'] >= 2)
cache_put_data('permissions:' . $cache_groups . ':' . $board, array(we::$user['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 (we::$is_member)
{
if (!isset($_SESSION['mc']) || $_SESSION['mc']['time'] <= $settings['settings_updated'])
{
loadSource('Subs-Auth');
rebuildModCache();
}
else
we::$user['mod_cache'] = $_SESSION['mc'];
}
}
/**
* Loads user data, either by id or member_name, and can load one or many users' data together.
*
* User data, where successful, is loaded into the global $user_profiles array, keyed by user id. The exact data set is dependent on $set.
*
* @param mixed $users This can be either a single value or an array, representing a single user or multiple users.
* @param bool $is_name If this parameter is true, treat the value(s) in $users as denoting user names, otherwise they are numeric user ids.
* @param string $set Complexity of data to load, from 'minimal', 'normal', 'profile', each successively increasing in complexity.
* @return mixed Returns either an array of users whose data was matched, or false if no matches were made.
*/
function loadMemberData($users, $is_name = false, $set = 'normal')
{
global $user_profile, $settings, $board_info;
static $infraction_levels = null;
// Can't just look for no users. :P
if (empty($users))
return false;
if ($infraction_levels === null)
{
$infraction_levels = array();
$levels = !empty($settings['infraction_levels']) ? @unserialize($settings['infraction_levels']) : array();
foreach ($levels as $infraction => $details)
if (!empty($details['enabled']))
$infraction_levels[$infraction] = $details['points'];
}
// Make sure it's an array.
$users = !is_array($users) ? array($users) : array_flip(array_flip($users));
$loaded_ids = array();
if (!$is_name && !empty($settings['cache_enable']) && $settings['cache_enable'] >= 3)
{
$users = array_values($users);
for ($i = 0, $n = count($users); $i < $n; $i++)
{
if (($data = cache_get_data('member_data-' . $set . '-' . $users[$i], 240)) === null)
continue;
$loaded_ids[] = $data['id_member'];
$user_profile[$data['id_member']] = $data;
unset($users[$i]);
}
}
$select_columns = '
IFNULL(lo.log_time, 0) AS is_online,
IFNULL(a.id_attach, 0) AS id_attach, a.filename, a.attachment_type, a.transparency, a.id_folder,
mem.id_member, mem.member_name, mem.real_name, mem.signature, mem.personal_text, mem.location, mem.gender,
mem.avatar, mem.email_address, mem.hide_email, mem.website_title, mem.website_url, mem.birthdate,
mem.posts, mem.id_group, mem.id_post_group, mem.show_online, mem.warning, mem.is_activated, mem.data,
IFNULL(mg.group_name, {string:blank}) AS member_group,
IFNULL(pg.group_name, {string:blank}) AS post_group,'
. (!empty($settings['titlesEnable']) ? ' mem.usertitle,' : '');
$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)';
if ($set === 'normal')
{
$select_columns .= '
mem.last_login, mem.member_ip, mem.member_ip2, mem.lngfile,
mem.time_offset, mem.date_registered, mem.buddy_list,
mem.media_items, mem.media_comments';
}
elseif ($set === 'profile')
{
$select_columns .= '
mem.last_login, mem.member_ip, mem.member_ip2, mem.lngfile,
mem.time_offset, mem.date_registered, mem.buddy_list,
mem.media_items, mem.media_comments,
mem.additional_groups,
mem.pm_ignore_list, mem.pm_email_notify, mem.pm_receive_from,
mem.time_format, mem.timezone, mem.smiley_set, mem.total_time_logged_in,
mem.ignore_boards, mem.notify_announcements, mem.notify_regularity, mem.notify_send_body,
mem.notify_types, lo.url, mem.password_salt, mem.pm_prefs, mem.data';
$get_badges = true;
}
elseif ($set === 'userbox')
{
$select_columns .= '
mem.additional_groups';
$get_badges = true;
}
elseif ($set === '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 = '';
}
else
trigger_error('loadMemberData(): Invalid member data set \'' . $set . '\'', E_USER_WARNING);
if (isset($get_badges))
{
// Load cached membergroup badges (or rank images) and when to show them.
if (($mba = cache_get_data('member-badges', 5000)) === null)
{
$mba = array();
$request = wesql::query('
SELECT g.id_group, g.stars, g.show_when, g.display_order
FROM {db_prefix}membergroups AS g
WHERE g.show_when != {int:never}
ORDER BY g.display_order',
array(
'never' => 0,
)
);
while ($row = wesql::fetch_assoc($request))
if (!empty($row['stars']))
$mba[$row['id_group']] = array($row['show_when'], $row['stars'], $row['display_order']);
wesql::free_result($request);
cache_put_data('member-badges', $mba, 5000);
}
}
if (!empty($users))
{
// Load the member's data.
$request = wesql::query('
SELECT' . $select_columns . '
FROM {db_prefix}members AS mem' . $select_tables . '
WHERE mem.' . ($is_name ? 'member_name' : 'id_member') . (count($users) == 1 ? ' = {' . ($is_name ? 'string' : 'int') . ':users}' : ' IN ({' . ($is_name ? 'array_string' : 'array_int') . ':users})'),
array(
'blank' => '',
'users' => count($users) == 1 ? current($users) : $users,
)
);
$new_loaded_ids = array();
while ($row = wesql::fetch_assoc($request))
{
$new_loaded_ids[] = $row['id_member'];
$loaded_ids[] = $row['id_member'];
$row['options'] = array();
$row['set'] = $set;
if (!empty($row['member_ip']))
{
$row['member_ip'] = format_ip($row['member_ip']);
$row['member_ip2'] = format_ip($row['member_ip2']);
}
if (!empty($settings['signature_minposts']) && ((int) $row['posts'] < (int) $settings['signature_minposts']))
{
// Hide normally (e.g. topic view) except if user is an admin
if (($set === 'normal' || $set === 'userbox') && $row['id_group'] != 1)
$row['signature'] = '';
// Hide in profile unless it's the user's own profile and they have permission, or they have permission to modify anyone's.
elseif ($set === 'profile' && !(($row['id_member'] == MID && allowedTo('profile_signature_own')) || allowedTo('profile_signature_any')))
$row['signature'] = '';
}
// Maybe the user has some sanctions already?
if (!empty($row['data']))
{
$row['data'] = @unserialize($row['data']);
$row['sanctions'] = !empty($row['data']['sanctions']) ? $row['data']['sanctions'] : array();
}
else
$row['data'] = array();
// Maybe they've just been a generically bad individual?
// If they have, this overrides any other granting of it and makes it indefinitely long.
if (!empty($infraction_levels) && !empty($row['warning']))
foreach ($infraction_levels as $infraction => $points)
if ($row['warning'] >= $points)
$row['sanctions'][$infraction] = 1;
// OK, quick clean up.
if (!empty($row['sanctions']))
foreach ($row['sanctions'] as $infraction => $expiry)
if ($expiry != 1 && $expiry < time())
unset($row['sanctions'][$infraction]);
// No signature sanction?
if (!empty($row['sanctions']['no_sig']))
{
// It won't be shown in posts, but it will in the profile if the person is viewing their own, or someone with appropriate power is viewing their profile - so it can be edited etc.
if ($set === 'normal' || $set === 'userbox' || ($set === 'profile' && !(($row['id_member'] == MID && allowedTo('profile_signature_own')) || allowedTo('profile_signature_any'))))
$row['signature'] = '';
}
// This user is banned. We might need to fudge their group.
if (!empty($settings['ban_group']) && !empty($row['is_activated']) && ($row['is_activated'] >= 20 || isset($row['sanctions']['hard_ban'])))
{
$row['additional_groups'] = !empty($row['additional_groups']) ? $row['id_group'] . ',' . $row['additional_groups'] : $row['id_group'];
$row['id_group'] = $settings['ban_group'];
}
$user_profile[$row['id_member']] = $row;
}
wesql::free_result($request);
}
if (!empty($new_loaded_ids) && $set !== 'minimal')
{
$request = wesql::query('
SELECT *
FROM {db_prefix}themes
WHERE id_member' . (count($new_loaded_ids) == 1 ? ' = {int:loaded_ids}' : ' IN ({array_int:loaded_ids})'),
array(
'loaded_ids' => count($new_loaded_ids) == 1 ? $new_loaded_ids[0] : $new_loaded_ids,
)
);
while ($row = wesql::fetch_assoc($request))
$user_profile[$row['id_member']]['options'][$row['variable']] = $row['value'];
wesql::free_result($request);
}
if (!empty($new_loaded_ids) && !empty($settings['cache_enable']) && $settings['cache_enable'] >= 3)
for ($i = 0, $n = count($new_loaded_ids); $i < $n; $i++)
cache_put_data('member_data-' . $set . '-' . $new_loaded_ids[$i], $user_profile[$new_loaded_ids[$i]], 240);
// Are we loading any moderators? If so, fix their group data...
if (!empty($loaded_ids) && !empty($board_info['moderators']) && ($set === 'normal' || $set === 'userbox') && count($temp_mods = array_intersect($loaded_ids, array_keys($board_info['moderators']))) > 0)
{
if (($row = cache_get_data('moderator_group_info', 480)) === null)
{
$request = wesql::query('
SELECT group_name AS member_group, stars
FROM {db_prefix}membergroups
WHERE id_group = {int:moderator_group}
LIMIT 1',
array(
'moderator_group' => 3,
)
);
$row = wesql::fetch_assoc($request);
wesql::free_result($request);
cache_put_data('moderator_group_info', $row, 480);
}
foreach ($temp_mods as $id)
{
// Add the local moderator group to the list.
if (empty($user_profile[$id]['additional_groups']))
$user_profile[$id]['additional_groups'] = '3';