-
Notifications
You must be signed in to change notification settings - Fork 618
Expand file tree
/
Copy pathqa-base.php
More file actions
1950 lines (1552 loc) · 58 KB
/
Copy pathqa-base.php
File metadata and controls
1950 lines (1552 loc) · 58 KB
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
/*
Question2Answer by Gideon Greenspan and contributors
http://www.question2answer.org/
Description: Sets up Q2A environment, plus many globally useful functions
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
More about this license: http://www.question2answer.org/license.php
*/
define('QA_VERSION', '1.8.8'); // also used as suffix for .js and .css requests
define('QA_BUILD_DATE', '2023-07-25');
/**
* Autoloads some Q2A classes so it's possible to use them without adding a require_once first. From version 1.7 onwards.
* These loosely follow PHP-FIG's PSR-0 standard where faux namespaces are separated by underscores. This is being done
* slowly and carefully to maintain backwards compatibility, and does not apply to plugins, themes, nor most of the core
* for that matter.
*
* Classes are stored in the qa-include/Q2A folder, and then in subfolders depending on their categorization.
* Class names should be of the form Q2A_<Namespace>_<Class>, e.g. Q2A_Util_Debug. There may be multiple "namespaces".
* Classes are mapped to PHP files with the underscores converted to directory separators. The Q2A_Util_Debug class is in
* the file qa-include/Q2A/Util/Debug.php. A class named Q2A_Db_User_Messages would be in a file qa-include/Q2A/Db/User/Messages.php.
*
* @param $class
*/
function qa_autoload($class)
{
if (strpos($class, 'Q2A_') === 0)
require QA_INCLUDE_DIR . strtr($class, '_', '/') . '.php';
}
spl_autoload_register('qa_autoload');
// Execution section of this file - remainder contains function definitions
qa_initialize_php();
qa_initialize_constants_1();
if (defined('QA_WORDPRESS_LOAD_FILE')) {
// if relevant, load WordPress integration in global scope
require_once QA_WORDPRESS_LOAD_FILE;
} elseif (defined('QA_JOOMLA_LOAD_FILE')) {
// if relevant, load Joomla JConfig class into global scope
require_once QA_JOOMLA_LOAD_FILE;
}
qa_initialize_constants_2();
qa_initialize_modularity();
qa_register_core_modules();
qa_initialize_predb_plugins();
require_once QA_INCLUDE_DIR . 'qa-db.php';
qa_db_allow_connect();
// $qa_autoconnect defaults to true so that optional plugins will load for external code. Q2A core
// code sets $qa_autoconnect to false so that we can use custom fail handlers.
global $qa_autoconnect;
if (!isset($qa_autoconnect) || $qa_autoconnect !== false) {
qa_db_connect('qa_page_db_fail_handler');
qa_initialize_postdb_plugins();
}
// Version comparison functions
/**
* Converts the $version string (e.g. 1.6.2.2) to a floating point that can be used for greater/lesser comparisons
* (PHP's version_compare() function is not quite suitable for our needs)
* @deprecated 1.8.2 no longer used
* @param $version
* @return float
*/
function qa_version_to_float($version)
{
$value = 0.0;
if (preg_match('/[0-9\.]+/', $version, $matches)) {
$parts = explode('.', $matches[0]);
$units = 1.0;
foreach ($parts as $part) {
$value += min($part, 999) * $units;
$units /= 1000;
}
}
return $value;
}
/**
* Returns true if the current Q2A version is lower than $version
* @param $version
* @return bool
*/
function qa_qa_version_below($version)
{
return version_compare(QA_VERSION, $version) < 0;
}
/**
* Returns true if the current PHP version is lower than $version
* @param $version
* @return bool
*/
function qa_php_version_below($version)
{
return version_compare(phpversion(), $version) < 0;
}
// Initialization functions called above
/**
* Set up and verify the PHP environment for Q2A, including unregistering globals if necessary
*/
function qa_initialize_php()
{
if (qa_php_version_below('5.1.6'))
qa_fatal_error('Q2A requires PHP 5.1.6 or later');
error_reporting(E_ALL); // be ultra-strict about error checking
@ini_set('magic_quotes_runtime', 0);
@setlocale(LC_CTYPE, 'C'); // prevent strtolower() et al affecting non-ASCII characters (appears important for IIS)
if (function_exists('date_default_timezone_set') && function_exists('date_default_timezone_get'))
@date_default_timezone_set(@date_default_timezone_get()); // prevent PHP notices where default timezone not set
if (ini_get('register_globals')) {
$checkarrays = array('_ENV', '_GET', '_POST', '_COOKIE', '_SERVER', '_FILES', '_REQUEST', '_SESSION'); // unregister globals if they're registered
$keyprotect = array_flip(array_merge($checkarrays, array('GLOBALS')));
foreach ($checkarrays as $checkarray) {
if (isset(${$checkarray}) && is_array(${$checkarray})) {
foreach (${$checkarray} as $checkkey => $checkvalue) {
if (isset($keyprotect[$checkkey])) {
qa_fatal_error('My superglobals are not for overriding');
} else {
unset($GLOBALS[$checkkey]);
}
}
}
}
}
}
/**
* First stage of setting up Q2A constants, before (if necessary) loading WordPress or Joomla! integration
*/
function qa_initialize_constants_1()
{
global $qa_request_map;
define('QA_CATEGORY_DEPTH', 4); // you can't change this number!
if (!defined('QA_BASE_DIR'))
define('QA_BASE_DIR', dirname(dirname(__FILE__)) . '/'); // try out best if not set in index.php or qa-index.php - won't work with symbolic links
define('QA_EXTERNAL_DIR', QA_BASE_DIR . 'qa-external/');
define('QA_INCLUDE_DIR', QA_BASE_DIR . 'qa-include/');
define('QA_LANG_DIR', QA_BASE_DIR . 'qa-lang/');
define('QA_THEME_DIR', QA_BASE_DIR . 'qa-theme/');
define('QA_PLUGIN_DIR', QA_BASE_DIR . 'qa-plugin/');
if (!file_exists(QA_BASE_DIR . 'qa-config.php'))
qa_fatal_error('The config file could not be found. Please read the instructions in qa-config-example.php.');
require_once QA_BASE_DIR . 'qa-config.php';
$qa_request_map = isset($QA_CONST_PATH_MAP) && is_array($QA_CONST_PATH_MAP) ? $QA_CONST_PATH_MAP : array();
if (defined('QA_WORDPRESS_INTEGRATE_PATH') && strlen(QA_WORDPRESS_INTEGRATE_PATH)) {
define('QA_FINAL_WORDPRESS_INTEGRATE_PATH', QA_WORDPRESS_INTEGRATE_PATH . ((substr(QA_WORDPRESS_INTEGRATE_PATH, -1) == '/') ? '' : '/'));
define('QA_WORDPRESS_LOAD_FILE', QA_FINAL_WORDPRESS_INTEGRATE_PATH . 'wp-load.php');
if (!is_readable(QA_WORDPRESS_LOAD_FILE)) {
qa_fatal_error('Could not find wp-load.php file for WordPress integration - please check QA_WORDPRESS_INTEGRATE_PATH in qa-config.php');
}
} elseif (defined('QA_JOOMLA_INTEGRATE_PATH') && strlen(QA_JOOMLA_INTEGRATE_PATH)) {
define('QA_FINAL_JOOMLA_INTEGRATE_PATH', QA_JOOMLA_INTEGRATE_PATH . ((substr(QA_JOOMLA_INTEGRATE_PATH, -1) == '/') ? '' : '/'));
define('QA_JOOMLA_LOAD_FILE', QA_FINAL_JOOMLA_INTEGRATE_PATH . 'configuration.php');
if (!is_readable(QA_JOOMLA_LOAD_FILE)) {
qa_fatal_error('Could not find configuration.php file for Joomla integration - please check QA_JOOMLA_INTEGRATE_PATH in qa-config.php');
}
}
// Polyfills
// password_hash compatibility for 5.3-5.4
define('QA_PASSWORD_HASH', !qa_php_version_below('5.3.7'));
if (QA_PASSWORD_HASH) {
require_once QA_INCLUDE_DIR . 'vendor/password_compat.php';
}
// https://php.net/manual/en/function.hash-equals.php#115635
if (!function_exists('hash_equals')) {
function hash_equals($str1, $str2)
{
if (strlen((string)$str1) != strlen((string)$str2)) {
return false;
} else {
$res = $str1 ^ $str2;
$ret = 0;
for ($i = strlen($res) - 1; $i >= 0; $i--)
$ret |= ord($res[$i]);
return !$ret;
}
}
}
}
/**
* Second stage of setting up Q2A constants, after (if necessary) loading WordPress or Joomla! integration
*/
function qa_initialize_constants_2()
{
// Default values if not set in qa-config.php
$defaults = array(
'QA_COOKIE_DOMAIN' => '',
'QA_HTML_COMPRESSION' => true,
'QA_MAX_LIMIT_START' => 19999,
'QA_IGNORED_WORDS_FREQ' => 10000,
'QA_ALLOW_UNINDEXED_QUERIES' => false,
'QA_OPTIMIZE_LOCAL_DB' => true,
'QA_OPTIMIZE_DISTANT_DB' => false,
'QA_PERSISTENT_CONN_DB' => false,
'QA_DEBUG_PERFORMANCE' => false,
);
foreach ($defaults as $key => $def) {
if (!defined($key)) {
define($key, $def);
}
}
// Start performance monitoring
if (QA_DEBUG_PERFORMANCE) {
global $qa_usage;
$qa_usage = new Q2A_Util_Usage;
// ensure errors are displayed
@ini_set('display_errors', 'On');
}
// More for WordPress integration
if (defined('QA_FINAL_WORDPRESS_INTEGRATE_PATH')) {
define('QA_FINAL_MYSQL_HOSTNAME', DB_HOST);
define('QA_FINAL_MYSQL_USERNAME', DB_USER);
define('QA_FINAL_MYSQL_PASSWORD', DB_PASSWORD);
define('QA_FINAL_MYSQL_DATABASE', DB_NAME);
define('QA_FINAL_EXTERNAL_USERS', true);
// Undo WordPress's addition of magic quotes to various things (leave $_COOKIE as is since WP code might need that)
function qa_undo_wordpress_quoting($param, $isget)
{
if (is_array($param)) { //
foreach ($param as $key => $value)
$param[$key] = qa_undo_wordpress_quoting($value, $isget);
} else {
$param = stripslashes($param);
if ($isget)
$param = strtr($param, array('\\\'' => '\'', '\"' => '"')); // also compensate for WordPress's .htaccess file
}
return $param;
}
$_GET = qa_undo_wordpress_quoting($_GET, true);
$_POST = qa_undo_wordpress_quoting($_POST, false);
$_SERVER['PHP_SELF'] = stripslashes($_SERVER['PHP_SELF']);
} elseif (defined('QA_FINAL_JOOMLA_INTEGRATE_PATH')) {
// More for Joomla integration
$jconfig = new JConfig();
define('QA_FINAL_MYSQL_HOSTNAME', $jconfig->host);
define('QA_FINAL_MYSQL_USERNAME', $jconfig->user);
define('QA_FINAL_MYSQL_PASSWORD', $jconfig->password);
define('QA_FINAL_MYSQL_DATABASE', $jconfig->db);
define('QA_FINAL_EXTERNAL_USERS', true);
} else {
define('QA_FINAL_MYSQL_HOSTNAME', QA_MYSQL_HOSTNAME);
define('QA_FINAL_MYSQL_USERNAME', QA_MYSQL_USERNAME);
define('QA_FINAL_MYSQL_PASSWORD', QA_MYSQL_PASSWORD);
define('QA_FINAL_MYSQL_DATABASE', QA_MYSQL_DATABASE);
define('QA_FINAL_EXTERNAL_USERS', QA_EXTERNAL_USERS);
}
if (defined('QA_MYSQL_PORT')) {
define('QA_FINAL_MYSQL_PORT', QA_MYSQL_PORT);
}
if (!defined('QA_MYSQL_CHARSET')) {
define('QA_MYSQL_CHARSET', 'utf8'); // Use hardcoded default until v1.8.8
}
if (!defined('QA_MYSQL_COLLATION')) {
define('QA_MYSQL_COLLATION', null); // Use hardcoded default until v1.8.8
}
// Possible URL schemes for Q2A and the string used for url scheme testing
define('QA_URL_FORMAT_INDEX', 0); // http://...../index.php/123/why-is-the-sky-blue
define('QA_URL_FORMAT_NEAT', 1); // http://...../123/why-is-the-sky-blue [requires .htaccess]
define('QA_URL_FORMAT_PARAM', 3); // http://...../?qa=123/why-is-the-sky-blue
define('QA_URL_FORMAT_PARAMS', 4); // http://...../?qa=123&qa_1=why-is-the-sky-blue
define('QA_URL_FORMAT_SAFEST', 5); // http://...../index.php?qa=123&qa_1=why-is-the-sky-blue
define('QA_URL_TEST_STRING', '$&-_~#%\\@^*()][`\';=:|".{},!<>?# π§½Жש'); // tests escaping, spaces, quote slashing and unicode - but not + and /
}
/**
* Gets everything ready to start using modules, layers and overrides
*/
function qa_initialize_modularity()
{
global $qa_modules, $qa_layers, $qa_override_files, $qa_override_files_temp, $qa_overrides, $qa_direct;
$qa_modules = array();
$qa_layers = array();
$qa_override_files = array();
$qa_override_files_temp = array();
$qa_overrides = array();
$qa_direct = array();
}
/**
* Set up output buffering. Use gzip compression if option set and it's not an admin page (since some of these contain lengthy processes).
* @param $request
* @return bool whether buffering was used
*/
function qa_initialize_buffering($request = '')
{
if (headers_sent()) {
return false;
}
$useGzip = QA_HTML_COMPRESSION && substr($request, 0, 6) !== 'admin/' && extension_loaded('zlib');
ob_start($useGzip ? 'ob_gzhandler' : null);
return true;
}
/**
* Register all modules that come as part of the Q2A core (as opposed to plugins)
*/
function qa_register_core_modules()
{
qa_register_module('filter', 'plugins/qa-filter-basic.php', 'qa_filter_basic', '');
qa_register_module('editor', 'plugins/qa-editor-basic.php', 'qa_editor_basic', '');
qa_register_module('viewer', 'plugins/qa-viewer-basic.php', 'qa_viewer_basic', '');
qa_register_module('event', 'plugins/qa-event-limits.php', 'qa_event_limits', 'Q2A Event Limits');
qa_register_module('event', 'plugins/qa-event-notify.php', 'qa_event_notify', 'Q2A Event Notify');
qa_register_module('event', 'plugins/qa-event-updates.php', 'qa_event_updates', 'Q2A Event Updates');
qa_register_module('search', 'plugins/qa-search-basic.php', 'qa_search_basic', '');
qa_register_module('widget', 'plugins/qa-widget-activity-count.php', 'qa_activity_count', 'Activity Count');
qa_register_module('widget', 'plugins/qa-widget-ask-box.php', 'qa_ask_box', 'Ask Box');
qa_register_module('widget', 'plugins/qa-widget-related-qs.php', 'qa_related_qs', 'Related Questions');
qa_register_module('widget', 'plugins/qa-widget-category-list.php', 'qa_category_list', 'Categories');
}
/**
* Load plugins before database is available. Generally this includes database overrides and
* process plugins that run early in the request lifecycle.
*/
function qa_initialize_predb_plugins()
{
global $qa_pluginManager;
$qa_pluginManager = new Q2A_Plugin_PluginManager();
$qa_pluginManager->readAllPluginMetadatas();
$qa_pluginManager->loadPluginsBeforeDbInit();
qa_load_override_files();
}
/**
* Load plugins after database is available. Plugins loaded here are able to be disabled in admin.
*/
function qa_initialize_postdb_plugins()
{
global $qa_pluginManager;
require_once QA_INCLUDE_DIR . 'app/options.php';
qa_preload_options();
$qa_pluginManager->loadPluginsAfterDbInit();
qa_load_override_files();
qa_report_process_stage('plugins_loaded');
}
/**
* Standard database failure handler function which bring up the install/repair/upgrade page
* @param $type
* @param int $errno
* @param string $error
* @param string $query
* @return mixed
*/
function qa_page_db_fail_handler($type, $errno = null, $error = null, $query = null)
{
if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
$pass_failure_type = $type;
$pass_failure_errno = $errno;
$pass_failure_error = $error;
$pass_failure_query = $query;
require_once QA_INCLUDE_DIR . 'qa-install.php';
qa_exit('error');
}
/**
* Retrieve metadata information from the $contents of a qa-theme.php or qa-plugin.php file, specified by $type ('Plugin' or 'Theme').
* If $versiononly is true, only min version metadata is parsed.
* Name, Description, Min Q2A & Min PHP are not currently used by themes.
*
* @deprecated Deprecated from 1.7; Q2A_Util_Metadata class and metadata.json files should be used instead
* @param $contents
* @param $type
* @param bool $versiononly
* @return array
*/
function qa_addon_metadata($contents, $type, $versiononly = false)
{
$fields = array(
'min_q2a' => 'Minimum Question2Answer Version',
'min_php' => 'Minimum PHP Version',
);
if (!$versiononly) {
$fields = array_merge($fields, $fields = array(
'name' => 'Name',
'uri' => 'URI',
'description' => 'Description',
'version' => 'Version',
'date' => 'Date',
'author' => 'Author',
'author_uri' => 'Author URI',
'license' => 'License',
'update_uri' => 'Update Check URI',
));
}
$metadata = array();
foreach ($fields as $key => $field) {
// prepend 'Theme'/'Plugin' and search for key data
$fieldregex = str_replace(' ', '[ \t]*', preg_quote("$type $field", '/'));
if (preg_match('/' . $fieldregex . ':[ \t]*([^\n\f]*)[\n\f]/i', $contents, $matches))
$metadata[$key] = trim($matches[1]);
}
return $metadata;
}
/**
* Apply all the function overrides in override files that have been registered by plugins
*/
function qa_load_override_files()
{
global $qa_override_files, $qa_override_files_temp, $qa_overrides;
$functionindex = array();
foreach ($qa_override_files_temp as $override) {
$qa_override_files[] = $override;
$filename = $override['directory'] . $override['include'];
$functionsphp = file_get_contents($filename);
preg_match_all('/\Wfunction\s+(qa_[a-z_]+)\s*\(/im', $functionsphp, $rawmatches, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE);
$reversematches = array_reverse($rawmatches[1], true); // reverse so offsets remain correct as we step through
$postreplace = array();
// include file name in defined function names to make debugging easier if there is an error
$suffix = '_in_' . preg_replace('/[^A-Za-z0-9_]+/', '_', basename($override['include']));
foreach ($reversematches as $rawmatch) {
$function = strtolower($rawmatch[0]);
$position = $rawmatch[1];
if (isset($qa_overrides[$function]))
$postreplace[$function . '_base'] = $qa_overrides[$function];
$newname = $function . '_override_' . (@++$functionindex[$function]) . $suffix;
$functionsphp = substr_replace($functionsphp, $newname, $position, strlen($function));
$qa_overrides[$function] = $newname;
}
foreach ($postreplace as $oldname => $newname) {
if (preg_match_all('/\W(' . preg_quote($oldname) . ')\s*\(/im', $functionsphp, $matches, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE)) {
$searchmatches = array_reverse($matches[1]);
foreach ($searchmatches as $searchmatch) {
$functionsphp = substr_replace($functionsphp, $newname, $searchmatch[1], strlen($searchmatch[0]));
}
}
}
// echo '<pre style="text-align:left;">'.htmlspecialchars($functionsphp).'</pre>'; // to debug munged code
qa_eval_from_file($functionsphp, $filename);
}
$qa_override_files_temp = array();
}
// Functions for registering different varieties of Q2A modularity
/**
* Register a module of $type named $name, whose class named $class is defined in file $include (or null if no include necessary)
* If this module comes from a plugin, pass in the local plugin $directory and the $urltoroot relative url for that directory
* @param $type
* @param $include
* @param $class
* @param $name
* @param string $directory
* @param string $urltoroot
*/
function qa_register_module($type, $include, $class, $name, $directory = QA_INCLUDE_DIR, $urltoroot = null)
{
global $qa_modules;
$previous = @$qa_modules[$type][$name];
if (isset($previous)) {
qa_fatal_error('A ' . $type . ' module named ' . $name . ' already exists. Please check there are no duplicate plugins. ' .
"\n\nModule 1: " . $previous['directory'] . $previous['include'] . "\nModule 2: " . $directory . $include);
}
$qa_modules[$type][$name] = array(
'directory' => $directory,
'urltoroot' => $urltoroot,
'include' => $include,
'class' => $class,
);
}
/**
* Register a layer named $name, defined in file $include. If this layer comes from a plugin (as all currently do),
* pass in the local plugin $directory and the $urltoroot relative url for that directory
* @param $include
* @param $name
* @param string $directory
* @param string $urltoroot
*/
function qa_register_layer($include, $name, $directory = QA_INCLUDE_DIR, $urltoroot = null)
{
global $qa_layers;
$previous = @$qa_layers[$name];
if (isset($previous)) {
qa_fatal_error('A layer named ' . $name . ' already exists. Please check there are no duplicate plugins. ' .
"\n\nLayer 1: " . $previous['directory'] . $previous['include'] . "\nLayer 2: " . $directory . $include);
}
$qa_layers[$name] = array(
'directory' => $directory,
'urltoroot' => $urltoroot,
'include' => $include,
);
}
/**
* Register a file $include containing override functions. If this file comes from a plugin (as all currently do),
* pass in the local plugin $directory and the $urltoroot relative url for that directory
* @param $include
* @param string $directory
* @param string $urltoroot
*/
function qa_register_overrides($include, $directory = QA_INCLUDE_DIR, $urltoroot = null)
{
global $qa_override_files_temp;
$qa_override_files_temp[] = array(
'directory' => $directory,
'urltoroot' => $urltoroot,
'include' => $include,
);
}
/**
* Register a set of language phrases, which should be accessed by the prefix $name/ in the qa_lang_*() functions.
* Pass in the $pattern representing the PHP files that define these phrases, where * in the pattern is replaced with
* the language code (e.g. 'fr') and/or 'default'. These files should be formatted like Q2A's qa-lang-*.php files.
* @param $pattern
* @param $name
*/
function qa_register_phrases($pattern, $name)
{
global $qa_lang_file_pattern;
if (file_exists(QA_INCLUDE_DIR . 'lang/qa-lang-' . $name . '.php')) {
qa_fatal_error('The name "' . $name . '" for phrases is reserved and cannot be used by plugins.' . "\n\nPhrases: " . $pattern);
}
if (isset($qa_lang_file_pattern[$name])) {
qa_fatal_error('A set of phrases named ' . $name . ' already exists. Please check there are no duplicate plugins. ' .
"\n\nPhrases 1: " . $qa_lang_file_pattern[$name] . "\nPhrases 2: " . $pattern);
}
$qa_lang_file_pattern[$name] = $pattern;
}
// Function for registering varieties of Q2A modularity, which are (only) called from qa-plugin.php files
/**
* Register a plugin module of $type named $name, whose class named $class is defined in file $include (or null if no include necessary)
* This function relies on some global variable values and can only be called from a plugin's qa-plugin.php file
* @param $type
* @param $include
* @param $class
* @param $name
*/
function qa_register_plugin_module($type, $include, $class, $name)
{
global $qa_plugin_directory, $qa_plugin_urltoroot;
if (empty($qa_plugin_directory) || empty($qa_plugin_urltoroot)) {
qa_fatal_error('qa_register_plugin_module() can only be called from a plugin qa-plugin.php file');
}
qa_register_module($type, $include, $class, $name, $qa_plugin_directory, $qa_plugin_urltoroot);
}
/**
* Register a plugin layer named $name, defined in file $include. Can only be called from a plugin's qa-plugin.php file
* @param $include
* @param $name
*/
function qa_register_plugin_layer($include, $name)
{
global $qa_plugin_directory, $qa_plugin_urltoroot;
if (empty($qa_plugin_directory) || empty($qa_plugin_urltoroot)) {
qa_fatal_error('qa_register_plugin_layer() can only be called from a plugin qa-plugin.php file');
}
qa_register_layer($include, $name, $qa_plugin_directory, $qa_plugin_urltoroot);
}
/**
* Register a plugin file $include containing override functions. Can only be called from a plugin's qa-plugin.php file
* @param $include
*/
function qa_register_plugin_overrides($include)
{
global $qa_plugin_directory, $qa_plugin_urltoroot;
if (empty($qa_plugin_directory) || empty($qa_plugin_urltoroot)) {
qa_fatal_error('qa_register_plugin_overrides() can only be called from a plugin qa-plugin.php file');
}
qa_register_overrides($include, $qa_plugin_directory, $qa_plugin_urltoroot);
}
/**
* Register a file name $pattern within a plugin directory containing language phrases accessed by the prefix $name
* @param $pattern
* @param $name
*/
function qa_register_plugin_phrases($pattern, $name)
{
global $qa_plugin_directory, $qa_plugin_urltoroot;
if (empty($qa_plugin_directory) || empty($qa_plugin_urltoroot)) {
qa_fatal_error('qa_register_plugin_phrases() can only be called from a plugin qa-plugin.php file');
}
qa_register_phrases($qa_plugin_directory . $pattern, $name);
}
// Low-level functions used throughout Q2A
/**
* Calls eval() on the PHP code in $eval which came from the file $filename. It supplements PHP's regular error reporting by
* displaying/logging (as appropriate) the original source filename, if an error occurred when evaluating the code.
* @param $eval
* @param $filename
*/
function qa_eval_from_file($eval, $filename)
{
// could also use ini_set('error_append_string') but apparently it doesn't work for errors logged on disk
global $php_errormsg;
$oldtrackerrors = @ini_set('track_errors', 1);
$php_errormsg = null;
eval('?' . '>' . $eval);
if (isset($php_errormsg)) {
switch (strtolower(ini_get('display_errors') ?? '')) {
case 'on':
case '1':
case 'yes':
case 'true':
case 'stdout':
case 'stderr':
echo ' of ' . qa_html($filename) . "\n";
break;
}
@error_log('PHP Question2Answer more info: ' . $php_errormsg . " in eval()'d code from " . qa_html($filename));
}
@ini_set('track_errors', $oldtrackerrors);
}
/**
* Call $function with the arguments in the $args array (doesn't work with call-by-reference functions)
* @param $function
* @param $args
* @return mixed
*/
function qa_call($function, $args)
{
// call_user_func_array(...) is very slow, so we break out most common cases first
switch (count($args)) {
case 0:
return $function();
case 1:
return $function($args[0]);
case 2:
return $function($args[0], $args[1]);
case 3:
return $function($args[0], $args[1], $args[2]);
case 4:
return $function($args[0], $args[1], $args[2], $args[3]);
case 5:
return $function($args[0], $args[1], $args[2], $args[3], $args[4]);
}
return call_user_func_array($function, $args);
}
/**
* Determines whether a function is to be overridden by a plugin. But if the function is being called with
* the _base suffix, any override will be bypassed due to $qa_direct.
*
* @param string $function The function to override
* @return string|null The name of the overriding function (of the form `qa_functionname_override_1_in_filename`)
*/
function qa_to_override($function)
{
global $qa_overrides, $qa_direct;
// handle most common case first
if (!isset($qa_overrides[$function])) {
return null;
}
if (strpos($function, '_override_') !== false) {
qa_fatal_error('Override functions should not be calling qa_to_override()!');
}
if (@$qa_direct[$function]) {
unset($qa_direct[$function]); // bypass the override just this once
return null;
}
return $qa_overrides[$function];
}
/**
* Call the function which immediately overrides $function with the arguments in the $args array
* @param $function
* @param $args
* @return mixed
*/
function qa_call_override($function, $args)
{
global $qa_overrides;
if (strpos($function, '_override_') !== false) {
qa_fatal_error('Override functions should not be calling qa_call_override()!');
}
if (!function_exists($function . '_base')) {
// define the base function the first time that it's needed
eval('function ' . $function . '_base() { global $qa_direct; $qa_direct[\'' . $function . '\']=true; $args=func_get_args(); return qa_call(\'' . $function . '\', $args); }');
}
return qa_call($qa_overrides[$function], $args);
}
/**
* Exit PHP immediately after reporting a shutdown with $reason to any installed process modules
* @param string $reason
*/
function qa_exit($reason = null)
{
qa_report_process_stage('shutdown', $reason);
$code = $reason === 'error' ? 1 : 0;
exit($code);
}
/**
* Display $message in the browser, write it to server error log, and then stop abruptly
* @param $message
* @return mixed
*/
function qa_fatal_error($message)
{
if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
echo 'Question2Answer fatal error:<p style="color: red">' . qa_html($message, true) . '</p>';
@error_log('PHP Question2Answer fatal error: ' . $message);
echo '<p>Stack trace:<p>';
$backtrace = array_reverse(array_slice(debug_backtrace(), 1));
foreach ($backtrace as $trace) {
$color = strpos($trace['file'] ?? '', '/qa-plugin/') !== false ? 'red' : '#999';
echo sprintf(
'<code style="color: %s">%s() in %s:%s</code><br>',
$color, qa_html($trace['function'] ?? ''), basename($trace['file'] ?? ''), $trace['line'] ?? ''
);
}
qa_exit('error');
}
// Functions for listing, loading and getting info on modules
/**
* Return an array with all registered modules' information
*/
function qa_list_modules_info()
{
global $qa_modules;
return $qa_modules;
}
/**
* Return an array of all the module types for which at least one module has been registered
*/
function qa_list_module_types()
{
return array_keys(qa_list_modules_info());
}
/**
* Return a list of names of registered modules of $type
* @param $type
* @return array
*/
function qa_list_modules($type)
{
$modules = qa_list_modules_info();
return is_array(@$modules[$type]) ? array_keys($modules[$type]) : array();
}
/**
* Return an array containing information about the module of $type named $name
* @param $type
* @param $name
* @return array
*/
function qa_get_module_info($type, $name)
{
$modules = qa_list_modules_info();
return @$modules[$type][$name];
}
/**
* Return an instantiated class for module of $type named $name, whose functions can be called, or null if it doesn't exist
* @param $type
* @param $name
* @return mixed|null
*/
function qa_load_module($type, $name)
{
global $qa_modules;
$module = @$qa_modules[$type][$name];
if (is_array($module)) {
if (isset($module['object']))
return $module['object'];
if (strlen($module['include'] ?? ''))
require_once $module['directory'] . $module['include'];
if (strlen($module['class'] ?? '')) {
$object = new $module['class'];
if (method_exists($object, 'load_module'))
$object->load_module($module['directory'], qa_path_to_root() . $module['urltoroot'], $type, $name);
$qa_modules[$type][$name]['object'] = $object;
return $object;
}
}
return null;
}
/**
* Return an array of instantiated clases for modules which have defined $method
* (all modules are loaded but not included in the returned array)
* @param $method
* @return array
*/
function qa_load_all_modules_with($method)
{
$modules = array();
$regmodules = qa_list_modules_info();
foreach ($regmodules as $moduletype => $modulesinfo) {
foreach ($modulesinfo as $modulename => $moduleinfo) {
$module = qa_load_module($moduletype, $modulename);
if (method_exists($module, $method))
$modules[$modulename] = $module;
}
}
return $modules;
}
/**
* Return an array of instantiated clases for modules of $type which have defined $method
* (other modules of that type are also loaded but not included in the returned array)
* @param $type
* @param $method
* @return array
*/
function qa_load_modules_with($type, $method)
{
$modules = array();
$trynames = qa_list_modules($type);
foreach ($trynames as $tryname) {
$module = qa_load_module($type, $tryname);
if (method_exists($module, $method))
$modules[$tryname] = $module;
}
return $modules;
}
// HTML and Javascript escaping and sanitization
/**
* Return HTML representation of $string, work well with blocks of text if $multiline is true
* @param $string
* @param bool $multiline
* @return mixed|string
*/
function qa_html($string, $multiline = false)
{
$html = htmlspecialchars((string)$string);