forked from elkarte/Elkarte
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Subs.php
4375 lines (3816 loc) · 151 KB
/
Subs.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 all the main functions in it that relate to, well, everything.
*
* @name ElkArte Forum
* @copyright ElkArte Forum contributors
* @license BSD http://opensource.org/licenses/BSD-3-Clause
*
* This software is a derived product, based on:
*
* Simple Machines Forum (SMF)
* copyright: 2011 Simple Machines (http://www.simplemachines.org)
* license: BSD, See included LICENSE.TXT for terms and conditions.
*
* @version 1.0 Beta
*
*/
if (!defined('ELK'))
die('No access...');
/**
* Update some basic statistics.
*
* 'member' statistic updates the latest member, the total member
* count, and the number of unapproved members.
* 'member' also only counts approved members when approval is on, but
* is much more efficient with it off.
*
* 'message' changes the total number of messages, and the
* highest message id by id_msg - which can be parameters 1 and 2,
* respectively.
*
* 'topic' updates the total number of topics, or if parameter1 is true
* simply increments them.
*
* 'subject' updateds the log_search_subjects in the event of a topic being
* moved, removed or split. parameter1 is the topicid, parameter2 is the new subject
*
* 'postgroups' case updates those members who match condition's
* post-based membergroups in the database (restricted by parameter1).
*
* @param string $type Stat type - can be 'member', 'message', 'topic', 'subject' or 'postgroups'
* @param mixed $parameter1 = null
* @param mixed $parameter2 = null
*/
function updateStats($type, $parameter1 = null, $parameter2 = null)
{
switch ($type)
{
case 'member':
require_once(SUBSDIR . '/Members.subs.php');
updateMemberStats($parameter1, $parameter2);
break;
case 'message':
require_once(SUBSDIR . '/Messages.subs.php');
updateMessageStats($parameter1, $parameter2);
break;
case 'subject':
require_once(SUBSDIR . '/Messages.subs.php');
updateSubjectStats($parameter1, $parameter2);
break;
case 'topic':
require_once(SUBSDIR . '/Topic.subs.php');
updateTopicStats($parameter1, $parameter2);
break;
case 'postgroups':
require_once(SUBSDIR . '/Membergroups.subs.php');
updatePostGroupStats($parameter1, $parameter2);
break;
default:
trigger_error('updateStats(): Invalid statistic type \'' . $type . '\'', E_USER_NOTICE);
}
}
/**
* Updates the columns in the members table.
* Assumes the data has been htmlspecialchar'd.
* this function should be used whenever member data needs to be
* updated in place of an UPDATE query.
*
* id_member is either an int or an array of ints to be updated.
*
* data is an associative array of the columns to be updated and their respective values.
* any string values updated should be quoted and slashed.
*
* the value of any column can be '+' or '-', which mean 'increment'
* and decrement, respectively.
*
* if the member's post number is updated, updates their post groups.
*
* @param mixed $members An array of integers
* @param array $data
*/
function updateMemberData($members, $data)
{
global $modSettings, $user_info;
$db = database();
$parameters = array();
if (is_array($members))
{
$condition = 'id_member IN ({array_int:members})';
$parameters['members'] = $members;
}
elseif ($members === null)
$condition = '1=1';
else
{
$condition = 'id_member = {int:member}';
$parameters['member'] = $members;
}
// Everything is assumed to be a string unless it's in the below.
$knownInts = array(
'date_registered', 'posts', 'id_group', 'last_login', 'personal_messages', 'unread_messages', 'mentions',
'new_pm', 'pm_prefs', 'gender', 'hide_email', 'show_online', 'pm_email_notify', 'receive_from', 'karma_good', 'karma_bad',
'notify_announcements', 'notify_send_body', 'notify_regularity', 'notify_types',
'id_theme', 'is_activated', 'id_msg_last_visit', 'id_post_group', 'total_time_logged_in', 'warning', 'likes_given', 'likes_received',
);
$knownFloats = array(
'time_offset',
);
if (!empty($modSettings['integrate_change_member_data']))
{
// Only a few member variables are really interesting for integration.
$integration_vars = array(
'member_name',
'real_name',
'email_address',
'id_group',
'gender',
'birthdate',
'website_title',
'website_url',
'location',
'hide_email',
'time_format',
'time_offset',
'avatar',
'lngfile',
);
$vars_to_integrate = array_intersect($integration_vars, array_keys($data));
// Only proceed if there are any variables left to call the integration function.
if (count($vars_to_integrate) != 0)
{
// Fetch a list of member_names if necessary
if ((!is_array($members) && $members === $user_info['id']) || (is_array($members) && count($members) == 1 && in_array($user_info['id'], $members)))
$member_names = array($user_info['username']);
else
{
$member_names = array();
$request = $db->query('', '
SELECT member_name
FROM {db_prefix}members
WHERE ' . $condition,
$parameters
);
while ($row = $db->fetch_assoc($request))
$member_names[] = $row['member_name'];
$db->free_result($request);
}
if (!empty($member_names))
foreach ($vars_to_integrate as $var)
call_integration_hook('integrate_change_member_data', array($member_names, &$var, &$data[$var], &$knownInts, &$knownFloats));
}
}
$setString = '';
foreach ($data as $var => $val)
{
$type = 'string';
if (in_array($var, $knownInts))
$type = 'int';
elseif (in_array($var, $knownFloats))
$type = 'float';
elseif ($var == 'birthdate')
$type = 'date';
// Doing an increment?
if ($type == 'int' && ($val === '+' || $val === '-'))
{
$val = $var . ' ' . $val . ' 1';
$type = 'raw';
}
// Ensure posts, personal_messages, and unread_messages don't overflow or underflow.
if (in_array($var, array('posts', 'personal_messages', 'unread_messages')))
{
if (preg_match('~^' . $var . ' (\+ |- |\+ -)([\d]+)~', $val, $match))
{
if ($match[1] != '+ ')
$val = 'CASE WHEN ' . $var . ' <= ' . abs($match[2]) . ' THEN 0 ELSE ' . $val . ' END';
$type = 'raw';
}
}
$setString .= ' ' . $var . ' = {' . $type . ':p_' . $var . '},';
$parameters['p_' . $var] = $val;
}
$db->query('', '
UPDATE {db_prefix}members
SET' . substr($setString, 0, -1) . '
WHERE ' . $condition,
$parameters
);
updateStats('postgroups', $members, array_keys($data));
// Clear any caching?
if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2 && !empty($members))
{
if (!is_array($members))
$members = array($members);
foreach ($members as $member)
{
if ($modSettings['cache_enable'] >= 3)
{
cache_put_data('member_data-profile-' . $member, null, 120);
cache_put_data('member_data-normal-' . $member, null, 120);
cache_put_data('member_data-minimal-' . $member, null, 120);
}
cache_put_data('user_settings-' . $member, null, 60);
}
}
}
/**
* Updates the settings table as well as $modSettings... only does one at a time if $update is true.
*
* - updates both the settings table and $modSettings array.
* - all of changeArray's indexes and values are assumed to have escaped apostrophes (')!
* - if a variable is already set to what you want to change it to, that
* variable will be skipped over; it would be unnecessary to reset.
* - When update is true, UPDATEs will be used instead of REPLACE.
* - when update is true, the value can be true or false to increment
* or decrement it, respectively.
*
* @param array $changeArray
* @param bool $update = false
* @param bool $debug = false
* @todo: add debugging features, $debug isn't used
*/
function updateSettings($changeArray, $update = false, $debug = false)
{
global $modSettings;
$db = database();
if (empty($changeArray) || !is_array($changeArray))
return;
// In some cases, this may be better and faster, but for large sets we don't want so many UPDATEs.
if ($update)
{
foreach ($changeArray as $variable => $value)
{
$db->query('', '
UPDATE {db_prefix}settings
SET value = {' . ($value === false || $value === true ? 'raw' : 'string') . ':value}
WHERE variable = {string:variable}',
array(
'value' => $value === true ? 'value + 1' : ($value === false ? 'value - 1' : $value),
'variable' => $variable,
)
);
$modSettings[$variable] = $value === true ? $modSettings[$variable] + 1 : ($value === false ? $modSettings[$variable] - 1 : $value);
}
// Clean out the cache and make sure the cobwebs are gone too.
cache_put_data('modSettings', null, 90);
return;
}
$replaceArray = array();
foreach ($changeArray as $variable => $value)
{
// Don't bother if it's already like that ;).
if (isset($modSettings[$variable]) && $modSettings[$variable] == $value)
continue;
// If the variable isn't set, but would only be set to nothing'ness, then don't bother setting it.
elseif (!isset($modSettings[$variable]) && empty($value))
continue;
$replaceArray[] = array($variable, $value);
$modSettings[$variable] = $value;
}
if (empty($replaceArray))
return;
$db->insert('replace',
'{db_prefix}settings',
array('variable' => 'string-255', 'value' => 'string-65534'),
$replaceArray,
array('variable')
);
// Kill the cache - it needs redoing now, but we won't bother ourselves with that here.
cache_put_data('modSettings', null, 90);
}
/**
* Deletes one setting from the settings table and takes care of $modSettings as well
*
* @param mixed $toRemove the setting or the settings to be removed
*/
function removeSettings($toRemove)
{
global $modSettings;
$db = database();
if (empty($toRemove))
return;
$toRemove = is_array($toRemove) ? $toRemove : array($toRemove);
$db->query('', '
DELETE FROM {db_prefix}settings
WHERE variable IN ({array_string:setting_name})',
array(
'setting_name' => $toRemove,
)
);
foreach ($toRemove as $setting)
if (isset($modSettings[$setting]))
unset($modSettings[$setting]);
// Kill the cache - it needs redoing now, but we won't bother ourselves with that here.
cache_put_data('modSettings', null, 90);
}
/**
* Constructs a page list.
*
* - builds the page list, e.g. 1 ... 6 7 [8] 9 10 ... 15.
* - flexible_start causes it to use "url.page" instead of "url;start=page".
* - handles any wireless settings (adding special things to URLs.)
* - very importantly, cleans up the start value passed, and forces it to
* be a multiple of num_per_page.
* - checks that start is not more than max_value.
* - base_url should be the URL without any start parameter on it.
* - uses the compactTopicPagesEnable and compactTopicPagesContiguous
* settings to decide how to display the menu.
*
* an example is available near the function definition.
* $pageindex = constructPageIndex($scripturl . '?board=' . $board, $_REQUEST['start'], $num_messages, $maxindex, true);
*
* @param string $base_url
* @param int $start
* @param int $max_value
* @param int $num_per_page
* @param bool $flexible_start = false
* @param array $show
*/
function constructPageIndex($base_url, &$start, $max_value, $num_per_page, $flexible_start = false, $show = array())
{
global $modSettings, $context, $txt, $settings;
// Save whether $start was less than 0 or not.
$start = (int) $start;
$start_invalid = $start < 0;
$show_defaults = array(
'prev_next' => true,
'all' => false,
);
$show = array_merge($show_defaults, $show);
// Make sure $start is a proper variable - not less than 0.
if ($start_invalid)
$start = 0;
// Not greater than the upper bound.
elseif ($start >= $max_value)
$start = max(0, (int) $max_value - (((int) $max_value % (int) $num_per_page) == 0 ? $num_per_page : ((int) $max_value % (int) $num_per_page)));
// And it has to be a multiple of $num_per_page!
else
$start = max(0, (int) $start - ((int) $start % (int) $num_per_page));
$context['current_page'] = $start / $num_per_page;
$base_link = str_replace('{base_link}', ($flexible_start ? $base_url : strtr($base_url, array('%' => '%%')) . ';start=%1$d'), $settings['page_index_template']['base_link']);
// Compact pages is off or on?
if (empty($modSettings['compactTopicPagesEnable']))
{
// Show the left arrow.
$pageindex = $start == 0 ? ' ' : sprintf($base_link, $start - $num_per_page, str_replace('{prev_txt}', $txt['prev'], $settings['page_index_template']['previous_page']));
// Show all the pages.
$display_page = 1;
for ($counter = 0; $counter < $max_value; $counter += $num_per_page)
$pageindex .= $start == $counter && !$start_invalid ? sprintf($settings['page_index_template']['current_page'], $display_page++) : sprintf($base_link, $counter, $display_page++);
// Show the right arrow.
$display_page = ($start + $num_per_page) > $max_value ? $max_value : ($start + $num_per_page);
if ($start != $counter - $max_value && !$start_invalid)
$pageindex .= $display_page > $counter - $num_per_page ? ' ' : sprintf($base_link, $display_page, str_replace('{next_txt}', $txt['next'], $settings['page_index_template']['next_page']));
// The "all" button
if ($show['all'])
{
if ($show['all_selected'])
$pageindex .= sprintf($settings['page_index_template']['current_page'], $txt['all']);
else
$pageindex .= sprintf(str_replace('.%1$d', '.%1$s', $base_link), '0;all', str_replace('{all_txt}', $txt['all'], $settings['page_index_template']['all']));
}
}
else
{
// If they didn't enter an odd value, pretend they did.
$PageContiguous = (int) ($modSettings['compactTopicPagesContiguous'] - ($modSettings['compactTopicPagesContiguous'] % 2)) / 2;
// Show the "prev page" link. (>prev page< 1 ... 6 7 [8] 9 10 ... 15 next page)
if (!empty($start) && $show['prev_next'])
$pageindex = sprintf($base_link, $start - $num_per_page, str_replace('{prev_txt}', $txt['prev'], $settings['page_index_template']['previous_page']));
else
$pageindex = '';
// Show the first page. (prev page >1< ... 6 7 [8] 9 10 ... 15)
if ($start > $num_per_page * $PageContiguous)
$pageindex .= sprintf($base_link, 0, '1');
// Show the ... after the first page. (prev page 1 >...< 6 7 [8] 9 10 ... 15 next page)
if ($start > $num_per_page * ($PageContiguous + 1))
$pageindex .= str_replace('{custom}', 'data-baseurl="' . htmlspecialchars(JavaScriptEscape(($flexible_start ? $base_url : strtr($base_url, array('%' => '%%')) . ';start=%1$d')), ENT_COMPAT, 'UTF-8') . '" data-perpage="' . $num_per_page . '" data-firstpage="' . $num_per_page . '" data-lastpage="' . ($start - $num_per_page * $PageContiguous) . '"', $settings['page_index_template']['expand_pages']);
// Show the pages before the current one. (prev page 1 ... >6 7< [8] 9 10 ... 15 next page)
for ($nCont = $PageContiguous; $nCont >= 1; $nCont--)
if ($start >= $num_per_page * $nCont)
{
$tmpStart = $start - $num_per_page * $nCont;
$pageindex.= sprintf($base_link, $tmpStart, $tmpStart / $num_per_page + 1);
}
// Show the current page. (prev page 1 ... 6 7 >[8]< 9 10 ... 15 next page)
if (!$start_invalid)
$pageindex .= sprintf($settings['page_index_template']['current_page'], ($start / $num_per_page + 1));
else
$pageindex .= sprintf($base_link, $start, $start / $num_per_page + 1);
// Show the pages after the current one... (prev page 1 ... 6 7 [8] >9 10< ... 15 next page)
$tmpMaxPages = (int) (($max_value - 1) / $num_per_page) * $num_per_page;
for ($nCont = 1; $nCont <= $PageContiguous; $nCont++)
if ($start + $num_per_page * $nCont <= $tmpMaxPages)
{
$tmpStart = $start + $num_per_page * $nCont;
$pageindex .= sprintf($base_link, $tmpStart, $tmpStart / $num_per_page + 1);
}
// Show the '...' part near the end. (prev page 1 ... 6 7 [8] 9 10 >...< 15 next page)
if ($start + $num_per_page * ($PageContiguous + 1) < $tmpMaxPages)
$pageindex .= str_replace('{custom}', 'data-baseurl="' . htmlspecialchars(JavaScriptEscape(($flexible_start ? $base_url : strtr($base_url, array('%' => '%%')) . ';start=%1$d')), ENT_COMPAT, 'UTF-8') . '" data-perpage="' . $num_per_page . '" data-firstpage="' . ($start + $num_per_page * ($PageContiguous + 1)) . '" data-lastpage="' . $tmpMaxPages . '"', $settings['page_index_template']['expand_pages']);
// Show the last number in the list. (prev page 1 ... 6 7 [8] 9 10 ... >15< next page)
if ($start + $num_per_page * $PageContiguous < $tmpMaxPages)
$pageindex .= sprintf($base_link, $tmpMaxPages, $tmpMaxPages / $num_per_page + 1);
// Show the "next page" link. (prev page 1 ... 6 7 [8] 9 10 ... 15 >next page<)
if ($start != $tmpMaxPages && $show['prev_next'])
$pageindex .= sprintf($base_link, $start + $num_per_page, str_replace('{next_txt}', $txt['next'], $settings['page_index_template']['next_page']));
// The "all" button
if ($show['all'])
{
if ($show['all_selected'])
$pageindex .= sprintf($settings['page_index_template']['current_page'], $txt['all']);
else
$pageindex .= sprintf(str_replace('.%1$d', '.%1$s', $base_link), '0;all', str_replace('{all_txt}', $txt['all'], $settings['page_index_template']['all']));
}
}
return $pageindex;
}
/**
* Formats a number.
* - uses the format of number_format to decide how to format the number.
* for example, it might display "1 234,50".
* - caches the formatting data from the setting for optimization.
*
* @param float $number
* @param bool $override_decimal_count = false
*/
function comma_format($number, $override_decimal_count = false)
{
global $txt;
static $thousands_separator = null, $decimal_separator = null, $decimal_count = null;
// Cache these values...
if ($decimal_separator === null)
{
// Not set for whatever reason?
if (empty($txt['number_format']) || preg_match('~^1([^\d]*)?234([^\d]*)(0*?)$~', $txt['number_format'], $matches) != 1)
return $number;
// Cache these each load...
$thousands_separator = $matches[1];
$decimal_separator = $matches[2];
$decimal_count = strlen($matches[3]);
}
// Format the string with our friend, number_format.
return number_format($number, (float) $number === $number ? ($override_decimal_count === false ? $decimal_count : $override_decimal_count) : 0, $decimal_separator, $thousands_separator);
}
/**
* Format a time to make it look purdy.
*
* - returns a pretty formated version of time based on the user's format in $user_info['time_format'].
* - applies all necessary time offsets to the timestamp, unless offset_type is set.
* - if todayMod is set and show_today was not not specified or true, an
* alternate format string is used to show the date with something to show it is "today" or "yesterday".
* - performs localization (more than just strftime would do alone.)
*
* @param int $log_time
* @param bool $show_today = true
* @param string $offset_type = false
*/
function standardTime($log_time, $show_today = true, $offset_type = false)
{
global $context, $user_info, $txt, $modSettings;
static $non_twelve_hour;
// Offset the time.
if (!$offset_type)
$time = $log_time + ($user_info['time_offset'] + $modSettings['time_offset']) * 3600;
// Just the forum offset?
elseif ($offset_type == 'forum')
$time = $log_time + $modSettings['time_offset'] * 3600;
else
$time = $log_time;
// We can't have a negative date (on Windows, at least.)
if ($log_time < 0)
$log_time = 0;
// Today and Yesterday?
if ($modSettings['todayMod'] >= 1 && $show_today === true)
{
// Get the current time.
$nowtime = forum_time();
$then = @getdate($time);
$now = @getdate($nowtime);
// Try to make something of a time format string...
$s = strpos($user_info['time_format'], '%S') === false ? '' : ':%S';
if (strpos($user_info['time_format'], '%H') === false && strpos($user_info['time_format'], '%T') === false)
{
$h = strpos($user_info['time_format'], '%l') === false ? '%I' : '%l';
$today_fmt = $h . ':%M' . $s . ' %p';
}
else
$today_fmt = '%H:%M' . $s;
// Same day of the year, same year.... Today!
if ($then['yday'] == $now['yday'] && $then['year'] == $now['year'])
return $txt['today'] . standardTime($log_time, $today_fmt, $offset_type);
// Day-of-year is one less and same year, or it's the first of the year and that's the last of the year...
if ($modSettings['todayMod'] == '2' && (($then['yday'] == $now['yday'] - 1 && $then['year'] == $now['year']) || ($now['yday'] == 0 && $then['year'] == $now['year'] - 1) && $then['mon'] == 12 && $then['mday'] == 31))
return $txt['yesterday'] . standardTime($log_time, $today_fmt, $offset_type);
}
$str = !is_bool($show_today) ? $show_today : $user_info['time_format'];
if (setlocale(LC_TIME, $txt['lang_locale']))
{
if (!isset($non_twelve_hour))
$non_twelve_hour = trim(strftime('%p')) === '';
if ($non_twelve_hour && strpos($str, '%p') !== false)
$str = str_replace('%p', (strftime('%H', $time) < 12 ? $txt['time_am'] : $txt['time_pm']), $str);
foreach (array('%a', '%A', '%b', '%B') as $token)
if (strpos($str, $token) !== false)
$str = str_replace($token, !empty($txt['lang_capitalize_dates']) ? Util::ucwords(strftime($token, $time)) : strftime($token, $time), $str);
}
else
{
// Do-it-yourself time localization. Fun.
foreach (array('%a' => 'days_short', '%A' => 'days', '%b' => 'months_short', '%B' => 'months') as $token => $text_label)
if (strpos($str, $token) !== false)
$str = str_replace($token, $txt[$text_label][(int) strftime($token === '%a' || $token === '%A' ? '%w' : '%m', $time)], $str);
if (strpos($str, '%p') !== false)
$str = str_replace('%p', (strftime('%H', $time) < 12 ? $txt['time_am'] : $txt['time_pm']), $str);
}
// Windows doesn't support %e; on some versions, strftime fails altogether if used, so let's prevent that.
if ($context['server']['is_windows'] && strpos($str, '%e') !== false)
$str = str_replace('%e', ltrim(strftime('%d', $time), '0'), $str);
// Format any other characters..
return strftime($str, $time);
}
/**
* Used to render a timestamp to html5 <time> tag format.
*
* @param int $timestamp
* @return string
*/
function htmlTime($timestamp)
{
global $modSettings, $user_info;
if (empty($timestamp))
return '';
$timestamp = forum_time(true, $timestamp);
$time = date('Y-m-d H:i', $timestamp);
$stdtime = standardTime($timestamp);
// @todo maybe htmlspecialchars on the title attribute?
return '<time title="' . $stdtime . '" datetime="' . $time . '" data-timestamp="' . $timestamp . '">' . $stdtime . '</time>';
}
/**
* Gets the current time with offset.
*
* - always applies the offset in the time_offset setting.
*
* @param bool $use_user_offset = true if use_user_offset is true, applies the user's offset as well
* @param int $timestamp = null
* @return int seconds since the unix epoch
*/
function forum_time($use_user_offset = true, $timestamp = null)
{
global $user_info, $modSettings;
if ($timestamp === null)
$timestamp = time();
elseif ($timestamp == 0)
return 0;
return $timestamp + ($modSettings['time_offset'] + ($use_user_offset ? $user_info['time_offset'] : 0)) * 3600;
}
/**
* Removes special entities from strings. Compatibility...
* Faster than html_entity_decode
*
* - removes the base entities ( & " ' < and >. ) from text with htmlspecialchars_decode
* - additionally converts   with str_replace
*
* @param string $string
* @return the string without entities
*/
function un_htmlspecialchars($string)
{
$string = htmlspecialchars_decode($string, ENT_QUOTES);
$string = str_replace(' ', ' ', $string);
return $string;
}
/**
* Shorten a string of text
*
* - shortens a text string so that it is either shorter than length, or that length plus an ellipsis.
* - optionally attempts to break the string on a word boundary approximately at the allowed length
* - if using cutword and the resulting length is > len plus buffer then it is truncated to length plus an ellipsis.
* - respects internationalization characters and entities as one character.
* - returns the shortened string.
*
* @param string $text
* @param int $len
* @param bool $cutword try to cut at a word boundary
* @param int $buffer maximum length overflow to allow when cutting on a word boundary
*/
function shorten_text($text, $len = 384, $cutword = false, $buffer = 12)
{
// If its to long, cut it down to size
if (Util::strlen($text) > $len)
{
$text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
if ($cutword)
{
// Look for len - buffer characters and cut on first word boundary after
preg_match('~(.{' . ($len - $buffer) . '}.*?)\b~su', $text, $matches);
// Always one clown in the audience who likes long words or not using the spacebar
if (Util::strlen($matches[1]) > $len + $buffer)
$matches[1] = Util::substr($matches[1], 0, $len);
$text = rtrim($matches[1]) . ' ...';
}
else
$text = Util::substr($text, 0, $len) . '...';
$text = Util::htmlspecialchars($text);
}
return $text;
}
/**
* Calculates all the possible permutations (orders) of array.
* should not be called on huge arrays (bigger than like 10 elements.)
* returns an array containing each permutation.
*
* @param array $array
* @return array
*/
function permute($array)
{
$orders = array($array);
$n = count($array);
$p = range(0, $n);
for ($i = 1; $i < $n; null)
{
$p[$i]--;
$j = $i % 2 != 0 ? $p[$i] : 0;
$temp = $array[$i];
$array[$i] = $array[$j];
$array[$j] = $temp;
for ($i = 1; $p[$i] == 0; $i++)
$p[$i] = 1;
$orders[] = $array;
}
return $orders;
}
/**
* Parse bulletin board code in a string, as well as smileys optionally.
*
* - only parses bbc tags which are not disabled in disabledBBC.
* - handles basic HTML, if enablePostHTML is on.
* - caches the from/to replace regular expressions so as not to reload them every time a string is parsed.
* - only parses smileys if smileys is true.
* - does nothing if the enableBBC setting is off.
* - uses the cache_id as a unique identifier to facilitate any caching it may do.
* -returns the modified message.
*
* @param string $message
* @param bool $smileys = true
* @param string $cache_id = ''
* @param array $parse_tags = null
* @return string
*/
function parse_bbc($message, $smileys = true, $cache_id = '', $parse_tags = array())
{
global $txt, $scripturl, $context, $modSettings, $user_info;
static $bbc_codes = array(), $itemcodes = array(), $no_autolink_tags = array();
static $disabled;
// Don't waste cycles
if ($message === '')
return '';
// Clean up any cut/paste issues we may have
$message = sanitizeMSCutPaste($message);
// If the load average is too high, don't parse the BBC.
if (!empty($modSettings['bbc']) && $modSettings['current_load'] >= $modSettings['bbc'])
{
$context['disabled_parse_bbc'] = true;
return $message;
}
if ($smileys !== null && ($smileys == '1' || $smileys == '0'))
$smileys = (bool) $smileys;
if (empty($modSettings['enableBBC']) && $message !== false)
{
if ($smileys === true)
parsesmileys($message);
return $message;
}
// If we are not doing every tag then we don't cache this run.
if (!empty($parse_tags) && !empty($bbc_codes))
{
$temp_bbc = $bbc_codes;
$bbc_codes = array();
}
// Allow addons access before entering the main parse_bbc loop
call_integration_hook('integrate_pre_parsebbc', array(&$message, &$smileys, &$cache_id, &$parse_tags));
// Sift out the bbc for a performance improvement.
if (empty($bbc_codes) || $message === false || !empty($parse_tags))
{
if (!empty($modSettings['disabledBBC']))
{
$temp = explode(',', strtolower($modSettings['disabledBBC']));
foreach ($temp as $tag)
$disabled[trim($tag)] = true;
}
if (empty($modSettings['enableEmbeddedFlash']))
$disabled['flash'] = true;
/* The following bbc are formatted as an array, with keys as follows:
tag: the tag's name - should be lowercase!
type: one of...
- (missing): [tag]parsed content[/tag]
- unparsed_equals: [tag=xyz]parsed content[/tag]
- parsed_equals: [tag=parsed data]parsed content[/tag]
- unparsed_content: [tag]unparsed content[/tag]
- closed: [tag], [tag/], [tag /]
- unparsed_commas: [tag=1,2,3]parsed content[/tag]
- unparsed_commas_content: [tag=1,2,3]unparsed content[/tag]
- unparsed_equals_content: [tag=...]unparsed content[/tag]
parameters: an optional array of parameters, for the form
[tag abc=123]content[/tag]. The array is an associative array
where the keys are the parameter names, and the values are an
array which may contain the following:
- match: a regular expression to validate and match the value.
- quoted: true if the value should be quoted.
- validate: callback to evaluate on the data, which is $data.
- value: a string in which to replace $1 with the data.
either it or validate may be used, not both.
- optional: true if the parameter is optional.
test: a regular expression to test immediately after the tag's
'=', ' ' or ']'. Typically, should have a \] at the end.
Optional.
content: only available for unparsed_content, closed,
unparsed_commas_content, and unparsed_equals_content.
$1 is replaced with the content of the tag. Parameters
are replaced in the form {param}. For unparsed_commas_content,
$2, $3, ..., $n are replaced.
before: only when content is not used, to go before any
content. For unparsed_equals, $1 is replaced with the value.
For unparsed_commas, $1, $2, ..., $n are replaced.
after: similar to before in every way, except that it is used
when the tag is closed.
disabled_content: used in place of content when the tag is
disabled. For closed, default is '', otherwise it is '$1' if
block_level is false, '<div>$1</div>' elsewise.
disabled_before: used in place of before when disabled. Defaults
to '<div>' if block_level, '' if not.
disabled_after: used in place of after when disabled. Defaults
to '</div>' if block_level, '' if not.
block_level: set to true the tag is a "block level" tag, similar
to HTML. Block level tags cannot be nested inside tags that are
not block level, and will not be implicitly closed as easily.
One break following a block level tag may also be removed.
trim: if set, and 'inside' whitespace after the begin tag will be
removed. If set to 'outside', whitespace after the end tag will
meet the same fate.
validate: except when type is missing or 'closed', a callback to
validate the data as $data. Depending on the tag's type, $data
may be a string or an array of strings (corresponding to the
replacement.)
quoted: when type is 'unparsed_equals' or 'parsed_equals' only,
may be not set, 'optional', or 'required' corresponding to if
the content may be quoted. This allows the parser to read
[tag="abc]def[esdf]"] properly.
require_parents: an array of tag names, or not set. If set, the
enclosing tag *must* be one of the listed tags, or parsing won't
occur.
require_children: similar to require_parents, if set children
won't be parsed if they are not in the list.
disallow_children: similar to, but very different from,
require_children, if it is set the listed tags will not be
parsed inside the tag.
disallow_parents: similar to, but very different from,
require_parents, if it is set the listed tags will not be
parsed inside the tag.
parsed_tags_allowed: an array restricting what BBC can be in the
parsed_equals parameter, if desired.
*/
$codes = array(
array(
'tag' => 'abbr',
'type' => 'unparsed_equals',
'before' => '<abbr title="$1">',
'after' => '</abbr>',
'quoted' => 'optional',
'disabled_after' => ' ($1)',
),
array(
'tag' => 'acronym',
'type' => 'unparsed_equals',
'before' => '<abbr title="$1">',
'after' => '</abbr>',
'quoted' => 'optional',
'disabled_after' => ' ($1)',
),
array(
'tag' => 'anchor',
'type' => 'unparsed_equals',
'test' => '[#]?([A-Za-z][A-Za-z0-9_\-]*)\]',
'before' => '<span id="post_$1">',
'after' => '</span>',
),
array(
'tag' => 'b',
'before' => '<strong class="bbc_strong">',
'after' => '</strong>',
),
array(
'tag' => 'bdo',
'type' => 'unparsed_equals',
'before' => '<bdo dir="$1">',
'after' => '</bdo>',
'test' => '(rtl|ltr)\]',
'block_level' => true,
),
array(
'tag' => 'black',
'before' => '<span style="color: black;" class="bbc_color">',
'after' => '</span>',
),
array(
'tag' => 'blue',
'before' => '<span style="color: blue;" class="bbc_color">',
'after' => '</span>',
),
array(
'tag' => 'br',
'type' => 'closed',
'content' => '<br />',
),
array(
'tag' => 'center',
'before' => '<div class="centertext">',
'after' => '</div>',
'block_level' => true,
),
array(
'tag' => 'code',
'type' => 'unparsed_content',
'content' => '<div class="codeheader">' . $txt['code'] . ': <a href="javascript:void(0);" onclick="return elkSelectText(this);" class="codeoperation">' . $txt['code_select'] . '</a></div><pre class="bbc_code prettyprint">$1</pre>',
'validate' => isset($disabled['code']) ? null : create_function('&$tag, &$data, $disabled', '
global $context;
if (!isset($disabled[\'code\']))
{
$data = str_replace("\t", "<span style=\"white-space: pre;\">\t</span>", $data);
// Recent Opera bug requiring temporary fix. &nsbp; is needed before </code> to avoid broken selection.
if ($context[\'browser\'][\'is_opera\'])
$data .= \' \';
}'),
'block_level' => true,
),
array(
'tag' => 'code',
'type' => 'unparsed_equals_content',
'content' => '<div class="codeheader">' . $txt['code'] . ': ($2) <a href="#" onclick="return elkSelectText(this);" class="codeoperation">' . $txt['code_select'] . '</a></div><pre class="bbc_code prettyprint">$1</pre>',
'validate' => isset($disabled['code']) ? null : create_function('&$tag, &$data, $disabled', '
global $context;
if (!isset($disabled[\'code\']))
{
$data[0] = str_replace("\t", "<span style=\"white-space: pre;\">\t</span>", $data[0]);
// Recent Opera bug requiring temporary fix. &nsbp; is needed before </code> to avoid broken selection.
if ($context[\'browser\'][\'is_opera\'])
$data[0] .= \' \';
}'),
'block_level' => true,
),
array(
'tag' => 'color',
'type' => 'unparsed_equals',