-
Notifications
You must be signed in to change notification settings - Fork 85
/
_misc.funcs.php
8985 lines (7754 loc) · 253 KB
/
_misc.funcs.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 implements general purpose functions.
*
* This file is part of the evoCore framework - {@link http://evocore.net/}
* See also {@link https://github.com/b2evolution/b2evolution}.
*
* @license GNU GPL v2 - {@link http://b2evolution.net/about/gnu-gpl-license}
*
* @copyright (c)2003-2018 by Francois Planque - {@link http://fplanque.com/}
* Parts of this file are copyright (c)2004-2006 by Daniel HAHLER - {@link http://thequod.de/contact}.
* Parts of this file are copyright (c)2005-2006 by PROGIDISTRI - {@link http://progidistri.com/}.
*
* @package evocore
*/
if( !defined('EVO_MAIN_INIT') ) die( 'Please, do not access this page directly.' );
/**
* Dependencies
*/
load_funcs('antispam/model/_antispam.funcs.php');
load_funcs('tools/model/_email.funcs.php');
// @todo sam2kb> Move core functions get_admin_skins, get_filenames, cleardir_r, rmdir_r and some other
// to a separate file, and split files_Module from _core_Module
load_funcs('files/model/_file.funcs.php');
// Load utf8 support functions
load_funcs( '_ext/_portable_utf8.php' );
/**
* Call a method for all modules in a row
*
* @param string the name of the method which should be called
* @param array params
* @return array[module_name][return value], or NULL if the method doesn't have any return value
*/
function modules_call_method( $method_name, $params = NULL )
{
global $modules;
$result = NULL;
foreach( $modules as $module )
{
$Module = & $GLOBALS[$module.'_Module'];
if( $params == NULL )
{
$ret = $Module->{$method_name}();
}
else
{
$ret = $Module->{$method_name}( $params );
}
if( isset( $ret ) )
{
$result[$module] = $ret;
}
}
return $result;
}
/**
* Loads the b2evo database scheme.
*
* This gets updated through {@link db_delta()} which generates the queries needed to get
* to this scheme.
*
* @param boolean set true to load installed plugins table as well, leave it on false otherwise
* - currently used only on table normalization
*
* Please see {@link db_delta()} for things to take care of.
*/
function load_db_schema( $inlcude_plugins = false )
{
global $schema_queries;
global $modules, $inc_path;
global $db_storage_charset, $DB;
if( empty( $db_storage_charset ) )
{ // If no specific charset has been requested for datstorage, use the one of the current connection (optimize for speed - no conversions)
$db_storage_charset = $DB->connection_charset;
}
// Load modules:
foreach( $modules as $module )
{
echo get_install_format_text( 'Loading module: <code>'.$module.'/model/_'.$module.'.install.php</code><br />', 'br' );
require_once $inc_path.$module.'/model/_'.$module.'.install.php';
}
if( $inlcude_plugins )
{ // Load all plugins table into the schema queries
global $Plugins;
if( empty( $Plugins ) )
{
load_class( 'plugins/model/_plugins.class.php', 'Plugins' );
$Plugins = new Plugins();
}
$admin_Plugins = & get_Plugins_admin();
$admin_Plugins->restart();
while( $loop_Plugin = & $admin_Plugins->get_next() )
{ // loop through all installed plugins
$create_table_queries = $loop_Plugin->GetDbLayout();
foreach( $create_table_queries as $create_table_query )
{
if( ! preg_match( '|^\s*CREATE TABLE\s+(IF NOT EXISTS\s+)?([^\s(]+).*$|is', $create_table_query, $match) )
{ // Could not parse the CREATE TABLE command
continue;
}
$schema_queries[$match[2]] = array( 'Creating table for plugin', $create_table_query );
$DB->dbaliases[] = '#\b'.$match[2].'\b#';
$DB->dbreplaces[] = $match[2];
}
}
}
}
/**
* @deprecated kept only for plugin backward compatibility (core is being modified to call getters directly)
* To be removed, maybe in b2evo v5.
*
* @return DataObjectCache
*/
function & get_Cache( $objectName )
{
global $Plugins;
global $$objectName;
if( isset( $$objectName ) )
{ // Cache already exists:
return $$objectName;
}
$func_name = 'get_'.$objectName;
if( function_exists($func_name) )
{
return $func_name();
}
else
{
debug_die( 'getCache(): Unknown Cache type get function:'.$func_name.'()' );
}
}
/**
* Load functions file
*/
function load_funcs( $funcs_path )
{
global $inc_path;
require_once $inc_path.$funcs_path;
}
/**
* Shutdown function: save HIT and update session!
*
* This is registered in _main.inc.php with register_shutdown_function()
* This is called by PHP at the end of the script.
*
* NOTE: before PHP 4.1 nothing can be echoed here any more, but the minimum PHP requirement for b2evo is PHP 4.3
*/
function shutdown()
{
/**
* @var Hit
*/
global $Hit;
/**
* @var Session
*/
global $Session;
global $Settings;
global $Debuglog;
global $Timer;
// Try forking a background process and let the parent return as fast as possbile.
if( is_callable('pcntl_fork') && function_exists('posix_kill') && defined('STDIN') )
{
if( $pid = pcntl_fork() )
return; // Parent
function shutdown_kill()
{
posix_kill(posix_getpid(), SIGHUP);
}
if ( ob_get_level() )
{ // Discard the output buffer and close
ob_end_clean();
}
fclose(STDIN); // Close all of the standard
fclose(STDOUT); // file descriptors as we
fclose(STDERR); // are running as a daemon.
register_shutdown_function('shutdown_kill');
if( posix_setsid() < 0 )
return;
if( $pid = pcntl_fork() )
return; // Parent
// Now running as a daemon. This process will even survive
// an apachectl stop.
}
$Timer->resume('shutdown');
// echo '*** SHUTDOWN FUNC KICKING IN ***';
// fp> do we need special processing if we are in CLI mode? probably earlier actually
// if( ! $is_cli )
// Note: it might be useful at some point to do special processing if the script has been aborted or has timed out
// connection_aborted()
// connection_status()
// Save the current HIT, but set delayed since the hit ID will not be required here:
$Hit->log( true );
// Update the SESSION:
$Session->dbsave();
// Get updates here instead of slowing down normal display of the dashboard
load_funcs( 'dashboard/model/_dashboard.funcs.php' );
b2evonet_get_updates();
// Auto pruning of old HITS, old SESSIONS and potentially MORE analytics data:
if( $Settings->get( 'auto_prune_stats_mode' ) == 'page' )
{ // Autopruning is requested
load_class( 'sessions/model/_hitlist.class.php', 'Hitlist' );
Hitlist::dbprune(); // will prune once per day, according to Settings
}
// Calling debug_info() here will produce complete data but it will be after </html> hence invalid.
// Then again, it's for debug only, so it shouldn't matter that much.
debug_info();
// Update the SESSION again, at the very end:
// (e.g. "Debuglogs" may have been removed in debug_info())
$Session->dbsave();
$Timer->pause('shutdown');
}
/***** Formatting functions *****/
/**
* Format a string/content for being output
*
* @author fplanque
* @todo htmlspecialchars() takes a charset argument, which we could provide ($evo_charset?)
* @param string raw text
* @param string format, can be one of the following
* - raw: do nothing
* - htmlbody: display in HTML page body: allow full HTML
* - entityencoded: Special mode for RSS 0.92: allow full HTML but escape it
* - htmlhead: strips out HTML (mainly for use in Title)
* - htmlattr: use as an attribute: escapes quotes, strip tags
* - formvalue: use as a form value: escapes quotes and < > but leaves code alone
* - text: use as plain-text, e.g. for ascii-mails
* - xml: use in an XML file: strip HTML tags
* - xmlattr: use as an attribute: strips tags and escapes quotes
* @return string formatted text
*/
function format_to_output( $content, $format = 'htmlbody' )
{
global $Plugins, $evo_charset;
switch( $format )
{
case 'raw':
// do nothing!
break;
case 'htmlbody':
// display in HTML page body: allow full HTML
$content = convert_chars($content, 'html');
break;
case 'urlencoded':
// Encode string to be passed as part of an URL
$content = rawurlencode( $content );
break;
case 'entityencoded':
// Special mode for RSS 0.92: apply renders and allow full HTML but escape it
$content = convert_chars($content, 'html');
$content = htmlspecialchars( $content, ENT_QUOTES, $evo_charset );
break;
case 'htmlfeed':
// For use in RSS <content:encoded><![CDATA[ ... ]]></content:encoded>
// allow full HTML + absolute URLs...
$content = make_rel_links_abs($content);
$content = convert_chars($content, 'html');
$content = str_replace(']]>', ']]>', $content); // encode CDATA closing tag to prevent injection/breaking of the <![CDATA[ ... ]]>
break;
case 'htmlhead':
// Strips out HTML (mainly for use in Title)
$content = strip_tags($content);
$content = convert_chars($content, 'html');
break;
case 'htmlattr':
// use as an attribute: strips tags and escapes quotes
// TODO: dh> why not just htmlspecialchars?fp> because an attribute can never contain a tag? dh> well, "onclick='return 1<2;'" would get stripped, too. I'm just saying: why mess with it, when we can just use htmlspecialchars.. fp>ok
$content = strip_tags($content);
$content = convert_chars($content, 'html');
$content = str_replace( array('"', "'"), array('"', '''), $content );
break;
case 'htmlspecialchars':
case 'formvalue':
// Replace special chars to &, ", '|', < and > :
// Handles & " ' < > to & " ' < >
$content = htmlspecialchars( $content, ENT_QUOTES | ENT_HTML5, $evo_charset );
break;
case 'xml':
// use in an XML file: strip HTML tags
$content = strip_tags($content);
$content = convert_chars($content, 'xml');
break;
case 'xmlattr':
// use as an attribute: strips tags and escapes quotes
$content = strip_tags($content);
$content = convert_chars($content, 'xml');
$content = str_replace( array('"', "'"), array('"', '''), $content );
break;
case 'text':
// use as plain-text, e.g. for ascii-mails
$content = strip_tags( $content );
$trans_tbl = get_html_translation_table( HTML_ENTITIES );
$trans_tbl = array_flip( $trans_tbl );
$content = strtr( $content, $trans_tbl );
$content = preg_replace( '/[ \t]+/', ' ', $content);
$content = trim($content);
break;
case 'syslog':
// Replace special chars to &, ", '|', < and > :
// Handles & " ' < > to & " ' < >
$content = htmlspecialchars( $content, ENT_QUOTES | ENT_HTML5, $evo_charset );
$content = preg_replace( "/\[\[(.+?)]]/is", "<code>$1</code>", $content ); // Replaces [[...]] into <code>...</code>
break;
default:
debug_die( 'Output format ['.$format.'] not supported.' );
}
return $content;
}
/*
* autobrize(-)
*/
function autobrize($content) {
$content = callback_on_non_matching_blocks( $content, '~<code>.+?</code>~is', 'autobrize_callback' );
return $content;
}
/**
* Adds <br>'s to non code blocks
*
* @param string $content
* @return string content with <br>'s added
*/
function autobrize_callback( $content )
{
$content = preg_replace("/<br>\n/", "\n", $content);
$content = preg_replace("/<br \/>\n/", "\n", $content);
$content = preg_replace("/(\015\012)|(\015)|(\012)/", "<br />\n", $content);
return($content);
}
/*
* unautobrize(-)
*/
function unautobrize($content)
{
$content = callback_on_non_matching_blocks( $content, '~<code>.+?</code>~is', 'unautobrize_callback' );
return $content;
}
/**
* Removes <br>'s from non code blocks
*
* @param string $content
* @return string content with <br>'s removed
*/
function unautobrize_callback( $content )
{
$content = preg_replace("/<br>\n/", "\n", $content); //for PHP versions before 4.0.5
$content = preg_replace("/<br \/>\n/", "\n", $content);
return($content);
}
/**
* Add leading zeroes to a number when necessary.
*
* @param string The original number.
* @param integer How many digits shall the number have?
* @return string The padded number.
*/
function zeroise( $number, $threshold )
{
return str_pad( $number, $threshold, '0', STR_PAD_LEFT );
}
/**
* Get a limited text-only excerpt
*
* @param string
* @param int Maximum length
* @return string
*/
function excerpt( $str, $maxlen = 254, $tail = '…' )
{
// Add spaces
$str = str_replace( array( '<p>', '<br', '</tr><tr', '</th><th', '</td><td' ), array( ' <p>', ' <br', '</tr> <tr', '</th> <th', '</td> <td' ), $str );
// Remove <code>
$str = preg_replace( '#<code>(.+)</code>#is', '', $str );
// Strip tags:
$str = strip_tags( $str );
// Remove spaces:
$str = preg_replace( '/[ \t]+/', ' ', $str);
$str = trim( $str );
// Ger rid of all new lines and Display the html tags as source text:
$str = trim( preg_replace( '#[\r\n\t\s]+#', ' ', $str ) );
$str = strmaxlen( $str, $maxlen, $tail, 'raw', true );
return $str;
}
/**
* Get a limited text-only excerpt based on number of words
*
* @param string
* @param integer Maximum length
* @param array Params
* @return string
*/
function excerpt_words( $str, $maxwords = 50, $params = array() )
{
// Add spaces
$str = str_replace( array( '<p>', '<br' ), array( ' <p>', ' <br' ), $str );
// Remove <code>
$str = preg_replace( '#<code>(.+)</code>#is', '', $str );
// Strip tags:
$str = strip_tags( $str );
// Remove spaces:
$str = preg_replace( '/[ \t]+/', ' ', $str);
$str = trim( $str );
// Ger rid of all new lines and Display the html tags as source text:
$str = trim( preg_replace( '#[\r\n\t\s]+#', ' ', $str ) );
$str = strmaxwords( $str, $maxwords, $params );
return $str;
}
/**
* Crop string to maxlen with … (default tail) at the end if needed.
*
* If $format is not "raw", we make sure to not cut in the middle of an
* HTML entity, so that strmaxlen('1&2', 3, NULL, 'formvalue') will not
* become/stay '1&…'.
*
* @param string
* @param int Maximum length
* @param string Tail to use, when string gets cropped. Its length gets
* substracted from the total length (with HTML entities
* being decoded). Default is "…" (HTML entity)
* @param string Format, see {@link format_to_output()}
* @param boolean Crop at whitespace, if possible?
* (any word split at the end will get its head removed)
* @return string
*/
function strmaxlen( $str, $maxlen = 50, $tail = NULL, $format = 'raw', $cut_at_whitespace = false )
{
if( is_null($tail) )
{
$tail = '…';
}
$str = utf8_rtrim($str);
if( utf8_strlen( $str ) > $maxlen )
{
// Replace all HTML entities by a single char. html_entity_decode for example
// would not handle ….
$tail_for_length = preg_replace('~&\w+?;~', '.', $tail);
$tail_length = utf8_strlen( html_entity_decode($tail_for_length) );
$len = $maxlen-$tail_length;
if( $len < 1 )
{ // special case; $tail length is >= $maxlen
$len = 0;
}
$str_cropped = utf8_substr( $str, 0, $len );
if( $format != 'raw' )
{ // if the format isn't raw we make sure that we do not cut in the middle of an HTML entity
$maxlen_entity = 7; # "&" is 5, min 3!
$str_inspect = utf8_substr($str_cropped, 1-$maxlen_entity);
$pos_amp = utf8_strpos($str_inspect, '&');
if( $pos_amp !== false )
{ // there's an ampersand at the end of the cropped string
$look_until = $pos_amp;
$str_cropped_len = utf8_strlen($str_cropped);
if( $str_cropped_len < $maxlen_entity )
{ // we have to look at least for the length of an entity
$look_until += $maxlen_entity-$str_cropped_len;
}
if( strpos(utf8_substr($str, $len, $look_until), ';') !== false )
{
$str_cropped = utf8_substr( $str, 0, $len-utf8_strlen($str_inspect)+$pos_amp);
}
}
}
if( $cut_at_whitespace )
{
// Get the first character being cut off. Note: we can't use $str[index] in case of utf8 strings!
$first_cut_off_char = utf8_substr( $str, utf8_strlen( $str_cropped ), 1 );
if( ! ctype_space( $first_cut_off_char ) )
{ // first character being cut off is not whitespace
// Get the chars as an array from the cropped string to be able to get chars by position
$str_cropped_chars = preg_split('//u',$str_cropped, -1, PREG_SPLIT_NO_EMPTY);
$i = utf8_strlen($str_cropped);
while( $i && isset( $str_cropped_chars[ --$i ] ) && ! ctype_space( $str_cropped_chars[ $i ] ) )
{}
if( $i )
{
$str_cropped = utf8_substr($str_cropped, 0, $i);
}
}
}
$str = format_to_output(utf8_rtrim($str_cropped), $format);
$str .= $tail;
return $str;
}
else
{
return format_to_output($str, $format);
}
}
/**
* Crop string to maxwords preserving tags.
*
* @param string
* @param int Maximum number words
* @param mixed array Optional parameters
* @return string
*/
function strmaxwords( $str, $maxwords = 50, $params = array() )
{
$params = array_merge( array(
'cutting_mark' => '…',
'continued_link' => '',
'continued_text' => '…',
'continued_class' => '',
'always_continue' => false,
), $params );
// STATE MACHINE:
$in_tag = false;
$have_seen_non_whitespace = false;
$end = strlen( $str ); // If we use utf8_strlen here(), we also need to access UTF chars below
for( $i = 0; $i < $end; $i++ )
{
switch( $char = $str[$i] ) // This is NOT UTF-8
{
case '<' : // start of a tag
$in_tag = true;
break;
case '>' : // end of a tag
$in_tag = false;
break;
case ctype_space($char): // This is a whitespace char...
if( ! $in_tag )
{ // it's a word gap:
// Eat any additional whitespace:
while( isset($str[$i+1]) && ctype_space($str[$i+1]) )
{
$i++;
}
if( isset($str[$i+1]) && $have_seen_non_whitespace )
{ // only decrement words, if there's been at least one non-space char before.
--$maxwords;
}
}
// ignore white space in a tag...
break;
default:
$have_seen_non_whitespace = true;
break;
}
if( $maxwords < 1 )
{ // We have reached the cutting point:
break;
}
}
if( $maxwords < 1 )
{ // Cutting is necessary:
// restrict content to required number of words:
$str = utf8_substr( $str, 0, $i );
// Add a cutting mark:
$str .= $params['cutting_mark'];
// balance the tags out:
$str = balance_tags( $str );
// remove empty tags:
$str = preg_replace( '~<([\s]+?)[^>]*?></\1>~is', '', $str );
}
if( $params['always_continue'] || $maxwords < 1 )
{ // we want a continued text
$str .= ' <a href="'.$params['continued_link'].'" class="'.$params['continued_class'].'">'.$params['continued_text'].'</a>';
}
return $str;
}
/**
* Convert all non ASCII chars (except if UTF-8, GB2312 or CP1251) to &#nnnn; unicode references.
* Also convert entities to &#nnnn; unicode references if output is not HTML (eg XML)
*
* Preserves < > and quotes.
*
* fplanque: simplified
* sakichan: pregs instead of loop
*/
function convert_chars( $content, $flag = 'html' )
{
global $b2_htmltrans, $evo_charset;
/**
* Translation of invalid Unicode references range to valid range.
* These are Windows CP1252 specific characters.
* They would look weird on non-Windows browsers.
* If you've ever pasted text from MSWord, you'll understand.
*
* You should not have to change this.
*/
static $b2_htmltranswinuni = array(
'€' => '€', // the Euro sign
'‚' => '‚',
'ƒ' => 'ƒ',
'„' => '„',
'…' => '…',
'†' => '†',
'‡' => '‡',
'ˆ' => 'ˆ',
'‰' => '‰',
'Š' => 'Š',
'‹' => '‹',
'Œ' => 'Œ',
'Ž' => 'ž',
'‘' => '‘',
'’' => '’',
'“' => '“',
'”' => '”',
'•' => '•',
'–' => '–',
'—' => '—',
'˜' => '˜',
'™' => '™',
'š' => 'š',
'›' => '›',
'œ' => 'œ',
'ž' => 'ž',
'Ÿ' => 'Ÿ'
);
// Convert highbyte non ASCII/UTF-8 chars to urefs:
if( ! in_array(strtolower($evo_charset), array( 'utf8', 'utf-8', 'gb2312', 'windows-1251') ) )
{ // This is a single byte charset
// fp> why do we actually bother doing this:?
$content = preg_replace_callback(
'/[\x80-\xff]/',
'_convert_chars_callback',
$content);
}
// Convert Windows CP1252 => Unicode (valid HTML)
// TODO: should this go to input conversions instead (?)
$content = strtr( $content, $b2_htmltranswinuni );
if( $flag == 'html' )
{ // we can use entities
// Convert & chars that are not used in an entity
$content = preg_replace('/&(?![#A-Za-z0-9]{2,20};)/', '&', $content);
}
else
{ // unicode, xml...
// Convert & chars that are not used in an entity
$content = preg_replace('/&(?![#A-Za-z0-9]{2,20};)/', '&', $content);
// Convert HTML entities to urefs:
$content = strtr($content, $b2_htmltrans);
}
return( $content );
}
/**
* Callback for preg_replace_callback in convert_chars()
*/
function _convert_chars_callback( $matches )
{
return "&#".ord( $matches[0] ).";";
}
/**
* Get number of bytes in $string. This works around mbstring.func_overload, if
* activated for strlen/mb_strlen.
* @param string
* @return int
*/
function evo_bytes( $string )
{
$fo = ini_get('mbstring.func_overload');
if( $fo && $fo & 2 && function_exists('mb_strlen') )
{ // overloading of strlen is enabled
return mb_strlen( $string, 'ASCII' );
}
return strlen($string);
}
/**
* mbstring wrapper for strtolower function
*
* @deprecated by {@link utf8_strtolower()}
*
* fp> TODO: instead of those "when used" ifs, it would make more sense to redefine
* mb_strtolower beforehand if it doesn"t exist (it would then just be a fallback
* to the strtolower + a Debuglog->add() )
*
* @param string
* @return string
*/
function evo_strtolower( $string )
{
global $current_charset;
if( $current_charset != 'iso-8859-1' && $current_charset != '' && function_exists('mb_strtolower') )
{
return mb_strtolower( $string, $current_charset );
}
return strtolower($string);
}
/**
* mbstring wrapper for strlen function
*
* @deprecated by {@link utf8_strlen()}
*
* @param string
* @return string
*/
function evo_strlen( $string )
{
global $current_charset;
if( $current_charset != 'iso-8859-1' && $current_charset != '' && function_exists('mb_strlen') )
{
return mb_strlen( $string, $current_charset );
}
return strlen($string);
}
/**
* mbstring wrapper for strpos function
*
* @deprecated by {@link utf8_strpos()}
*
* @param string
* @param string
* @return int
*/
function evo_strpos( $string , $needle , $offset = null )
{
global $current_charset;
if( $current_charset != 'iso-8859-1' && $current_charset != '' && function_exists('mb_strpos') )
{
return mb_strpos( $string, $needle, $offset ,$current_charset );
}
return strpos( $string , $needle , $offset );
}
/**
* mbstring wrapper for substr function
*
* @deprecated by {@link utf8_substr()}
*
* @param string
* @param int start position
* @param int string length
* @return string
*/
function evo_substr( $string, $start = 0, $length = '#' )
{
global $current_charset;
if( ! $length )
{ // make mb_substr and substr behave consistently (mb_substr returns string for length=0)
return '';
}
if( $length == '#' )
{
$length = utf8_strlen($string);
}
if( $current_charset != 'iso-8859-1' && $current_charset != '' && function_exists('mb_substr') )
{
return mb_substr( $string, $start, $length, $current_charset );
}
return substr( $string, $start, $length );
}
/**
* Split $text into blocks by using $pattern and call $callback on the non-matching blocks.
*
* The non-matching block's text is the first param to $callback and additionally $params gets passed.
*
* This gets used to make links clickable or replace smilies.
*
* E.g., to replace only in non-HTML tags, call it like:
* <code>callback_on_non_matching_blocks( $text, '~<[^>]*>~s', 'your_callback' );</code>
*
* {@internal This function gets tested in misc.funcs.simpletest.php.}}
*
* @param string Text to handle
* @param string Regular expression pattern that defines blocks to exclude.
* @param callback Function name or object/method array to use as callback.
* Each non-matching block gets passed as first param, additional params may be
* passed with $params.
* @param array Of additional ("static") params to $callback.
* @return string
*/
function callback_on_non_matching_blocks( $text, $pattern, $callback, $params = array() )
{
if( preg_match_all( $pattern, $text, $matches, PREG_OFFSET_CAPTURE | PREG_PATTERN_ORDER ) )
{ // $pattern matches, call the callback method on full text except of matching blocks
// Create an unique string in order to replace all matching blocks temporarily
$unique_replacement = md5( time() + rand() );
$matches_search = array();
$matches_replace = array();
foreach( $matches[0] as $l => $l_matching )
{ // Build arrays with a source code of the matching blocks and with temporary replacement
$matches_source[] = $l_matching[0];
$matches_temp[] = '?'.$l.$unique_replacement.$l.'?';
}
// Replace all matching blocks with temporary text like '?X219a33da9c1b8f4e335bffc015df8c96X?'
// where X is index of match block in array $matches[0]
// It is used to avoid any changes in the matching blocks
$text = str_ireplace( $matches_source, $matches_temp, $text );
// Callback:
$callback_params = $params;
array_unshift( $callback_params, $text );
$text = call_user_func_array( $callback, $callback_params );
// Revert a source code of the matching blocks in content
$text = str_ireplace( $matches_temp, $matches_source, $text );
return $text;
}
$callback_params = $params;
array_unshift( $callback_params, $text );
return call_user_func_array( $callback, $callback_params );
}
/**
* Perform a global regular expression match outside blocks <code></code>, <pre></pre> and markdown codeblocks
*
* @param string Pattern to search for
* @param string Content
* @param array Array of all matches in multi-dimensional array
* @return integer|boolean Number of full pattern matches (which might be zero), or FALSE if an error occurred.
*/
function preg_match_outcode( $search, $content, & $matches )
{
if( stristr( $content, '<code' ) !== false || stristr( $content, '<pre' ) !== false || strstr( $content, '`' ) !== false )
{ // Call preg_match_all() on everything outside code/pre and markdown codeblocks:
return callback_on_non_matching_blocks( $content,
'~(`|<(code|pre)[^>]*>).*?(\1|</\2>)~is',
'preg_match_outcode_callback', array( $search, & $matches ) );
}
else
{ // No code/pre blocks, search in the whole thing:
return preg_match_all( $search, $content, $matches );
}
}
/**
* Used for function callback_on_non_matching_blocks(), because there is different order of params
*
* @param string Pattern to search for
* @param string Content
* @param array Array of all matches in multi-dimensional array
* @return integer|boolean Number of full pattern matches (which might be zero), or FALSE if an error occurred.
*/
function preg_match_outcode_callback( $content, $search, & $matches )
{
return preg_match_all( $search, $content, $matches );
}
/**
* Replace content outside blocks <code></code>, <pre></pre> and markdown codeblocks
*
* @param array|string Search list
* @param array|string Replace list or Callback function
* @param string Source content
* @param string Callback function name
* @param string Type of callback function: 'preg' -> preg_replace(), 'preg_callback' -> preg_replace_callback(), 'str' -> str_replace() (@see replace_content())
* @return string Replaced content
*/
function replace_content_outcode( $search, $replace, $content, $replace_function_callback = 'replace_content', $replace_function_type = 'preg' )
{
if( !empty( $search ) )
{
if( stristr( $content, '<code' ) !== false || stristr( $content, '<pre' ) !== false || strstr( $content, '`' ) !== false )
{ // Call replace_content() on everything outside code/pre and markdown codeblocks:
$content = callback_on_non_matching_blocks( $content,
'~(`|<(code|pre)[^>]*>).*?(\1|</\2>)~is',
$replace_function_callback, array( $search, $replace, $replace_function_type ) );
}
else
{ // No code/pre blocks, replace on the whole thing
$content = call_user_func( $replace_function_callback, $content, $search, $replace, $replace_function_type );
}
}
return $content;
}
/**