qa-base.php 59.4 KB
Newer Older
Scott committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
<?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
*/


Scott committed
23 24
define('QA_VERSION', '1.8.5'); // also used as suffix for .js and .css requests
define('QA_BUILD_DATE', '2020-07-15');
Scott committed
25 26


Scott committed
27
/**
28 29 30
 * Autoloads some Q2A classes so it's possible to use them without adding a require_once first. From
 * version 1.9 onwards we follow PSR-4. Classes are stored in qa-src/ which maps to the 'Q2A' namespace.
 * So for example \Q2A\Storage\CacheFactory maps to qa-src/Storage/CacheFactory.php.
Scott committed
31
 *
32
 * @param string $class
Scott committed
33 34 35
 */
function qa_autoload($class)
{
Scott committed
36 37 38
	if (strpos($class, 'Q2A\\') === 0) {
		require QA_BASE_DIR . 'qa-src/' . strtr(substr($class, 4), '\\', '/') . '.php';
	}
Scott committed
39 40
}
spl_autoload_register('qa_autoload');
Scott committed
41

42
use Q2A\App\Application;
Scott committed
43

Scott committed
44
// Execution section of this file - remainder contains function definitions
45

Scott committed
46 47
qa_initialize_php();
qa_initialize_constants_1();
Scott committed
48

Scott committed
49 50 51 52 53 54 55
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;
}
Scott committed
56

Scott committed
57 58 59
qa_initialize_constants_2();
qa_initialize_modularity();
qa_register_core_modules();
60

61
qa_initialize_predb_plugins();
Scott committed
62
require_once QA_INCLUDE_DIR . 'qa-db.php';
63 64
$qa_db = qa_service('database');
$qa_db->allowConnect();
Scott committed
65

66 67 68
// $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.
if (!isset($qa_autoconnect) || $qa_autoconnect !== false) {
69
	$qa_db->connect('qa_page_db_fail_handler');
70 71
	qa_initialize_postdb_plugins();
}
72

Scott committed
73

Scott committed
74
// Version comparison functions
Scott committed
75

Scott committed
76 77 78
/**
 * 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)
Scott committed
79
 * @deprecated 1.8.2 no longer used
80
 * @param string $version
Scott committed
81
 * @return float
Scott committed
82 83 84 85
 */
function qa_version_to_float($version)
{
	$value = 0.0;
Scott committed
86

Scott committed
87 88 89
	if (preg_match('/[0-9\.]+/', $version, $matches)) {
		$parts = explode('.', $matches[0]);
		$units = 1.0;
Scott committed
90

Scott committed
91 92 93
		foreach ($parts as $part) {
			$value += min($part, 999) * $units;
			$units /= 1000;
Scott committed
94 95 96
		}
	}

Scott committed
97 98
	return $value;
}
Scott committed
99 100


Scott committed
101
/**
Scott committed
102
 * Returns true if the current Q2A version is lower than $version
103
 * @param string $version
Scott committed
104
 * @return bool
Scott committed
105 106 107
 */
function qa_qa_version_below($version)
{
Scott committed
108
	return version_compare(QA_VERSION, $version) < 0;
Scott committed
109
}
Scott committed
110 111


Scott committed
112
/**
Scott committed
113
 * Returns true if the current PHP version is lower than $version
114
 * @param string $version
Scott committed
115
 * @return bool
Scott committed
116 117 118
 */
function qa_php_version_below($version)
{
Scott committed
119
	return version_compare(phpversion(), $version) < 0;
Scott committed
120
}
Scott committed
121 122


Scott committed
123
// Initialization functions called above
Scott committed
124

Scott committed
125 126 127 128 129 130 131
/**
 * 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');
Scott committed
132

Scott committed
133
	error_reporting(E_ALL); // be ultra-strict about error checking
Scott committed
134

Scott committed
135
	@ini_set('magic_quotes_runtime', 0);
Scott committed
136

Scott committed
137
	@setlocale(LC_CTYPE, 'C'); // prevent strtolower() et al affecting non-ASCII characters (appears important for IIS)
Scott committed
138

Scott committed
139 140
	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
Scott committed
141

Scott committed
142 143 144
	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')));
Scott committed
145

Scott committed
146 147 148 149 150 151 152 153 154 155
		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]);
					}
				}
			}
Scott committed
156 157
		}
	}
Scott committed
158
}
Scott committed
159 160


Scott committed
161 162 163 164 165 166
/**
 * First stage of setting up Q2A constants, before (if necessary) loading WordPress or Joomla! integration
 */
function qa_initialize_constants_1()
{
	global $qa_request_map;
Scott committed
167

Scott committed
168
	define('QA_CATEGORY_DEPTH', 4); // you can't change this number!
Scott committed
169

Scott committed
170
	if (!defined('QA_BASE_DIR'))
171
		define('QA_BASE_DIR', dirname(dirname(__FILE__)) . '/'); // try our best if not set in index.php or qa-index.php - won't work with symbolic links
Scott committed
172

Scott committed
173 174 175 176 177
	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/');
Scott committed
178

Scott committed
179 180
	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.');
Scott committed
181

Scott committed
182
	require_once QA_BASE_DIR . 'qa-config.php';
Scott committed
183

Scott committed
184
	$qa_request_map = isset($QA_CONST_PATH_MAP) && is_array($QA_CONST_PATH_MAP) ? $QA_CONST_PATH_MAP : array();
Scott committed
185

Scott committed
186 187 188
	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');
Scott committed
189

Scott committed
190 191
		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');
Scott committed
192
		}
Scott committed
193 194 195
	} 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');
196

Scott committed
197 198
		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');
199
		}
Scott committed
200
	}
201

202 203
	require_once QA_INCLUDE_DIR . 'vendor/PHPMailer/PHPMailerAutoload.php';

Scott committed
204
	// Polyfills
205

Scott committed
206 207 208 209 210
	// 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';
	}
Scott committed
211

Scott committed
212 213 214 215 216 217 218 219 220
	// http://php.net/manual/en/function.hash-equals.php#115635
	if (!function_exists('hash_equals')) {
		function hash_equals($str1, $str2)
		{
			if (strlen($str1) != strlen($str2)) {
				return false;
			} else {
				$res = $str1 ^ $str2;
				$ret = 0;
221 222
				for ($i = strlen($res) - 1; $i >= 0; $i--)
					$ret |= ord($res[$i]);
Scott committed
223
				return !$ret;
224 225
			}
		}
Scott committed
226
	}
Scott committed
227
}
Scott committed
228 229


Scott committed
230 231 232 233 234 235
/**
 * 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
Scott committed
236

237 238 239 240 241 242 243 244 245 246 247 248
	$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,
	);

Scott committed
249
	foreach ($defaults as $key => $def) {
250 251 252 253
		if (!defined($key)) {
			define($key, $def);
		}
	}
Scott committed
254

Scott committed
255
	// Start performance monitoring
Scott committed
256

Scott committed
257 258
	if (QA_DEBUG_PERFORMANCE) {
		global $qa_usage;
Scott committed
259
		$qa_usage = new \Q2A\Util\Usage;
Scott committed
260 261 262
		// ensure errors are displayed
		@ini_set('display_errors', 'On');
	}
Scott committed
263

Scott committed
264
	// More for WordPress integration
Scott committed
265

Scott committed
266 267 268 269 270 271
	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);
Scott committed
272

Scott committed
273
		// Undo WordPress's addition of magic quotes to various things (leave $_COOKIE as is since WP code might need that)
Scott committed
274

Scott committed
275 276 277 278 279
		function qa_undo_wordpress_quoting($param, $isget)
		{
			if (is_array($param)) { //
				foreach ($param as $key => $value)
					$param[$key] = qa_undo_wordpress_quoting($value, $isget);
Scott committed
280

Scott committed
281 282 283 284
			} else {
				$param = stripslashes($param);
				if ($isget)
					$param = strtr($param, array('\\\'' => '\'', '\"' => '"')); // also compensate for WordPress's .htaccess file
Scott committed
285 286
			}

Scott committed
287
			return $param;
288 289
		}

Scott committed
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
		$_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);
	}

	// 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).
344
 * @param string $request
Scott committed
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
 * @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');
}


/**
379 380
 * Load plugins before database is available. Generally this includes database overrides and
 * process plugins that run early in the request lifecycle.
Scott committed
381
 */
382
function qa_initialize_predb_plugins()
Scott committed
383
{
384
	global $qa_pluginManager;
Scott committed
385
	$qa_pluginManager = new \Q2A\Plugin\PluginManager();
386
	$qa_pluginManager->readAllPluginMetadatas();
Scott committed
387

388
	$qa_pluginManager->loadPluginsBeforeDbInit();
Scott committed
389
	qa_load_override_files();
390 391
}

392

393 394 395 396 397 398
/**
 * Load plugins after database is available. Plugins loaded here are able to be disabled in admin.
 */
function qa_initialize_postdb_plugins()
{
	global $qa_pluginManager;
Scott committed
399

400 401
	require_once QA_INCLUDE_DIR . 'app/options.php';
	qa_preload_options();
Scott committed
402

403
	$qa_pluginManager->loadPluginsAfterDbInit();
Scott committed
404
	qa_load_override_files();
405 406

	qa_report_process_stage('plugins_loaded');
Scott committed
407 408 409
}


410 411
/**
 * Standard database failure handler function which bring up the install/repair/upgrade page
412 413 414 415
 * @param string $type
 * @param int|null $errno
 * @param string|null $error
 * @param string|null $query
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
 * @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');
}


Scott committed
433 434 435 436 437
/**
 * 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.
 *
Scott committed
438
 * @deprecated Deprecated from 1.7; \Q2A\Util\Metadata class and metadata.json files should be used instead
439 440 441
 * @param string $contents
 * @param string $type
 * @param bool|null $versiononly
Scott committed
442
 * @return array
Scott committed
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
 */
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',
		));
462 463
	}

Scott committed
464 465 466 467 468 469
	$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]);
Scott committed
470 471
	}

Scott committed
472 473
	return $metadata;
}
Scott committed
474 475


Scott committed
476 477 478 479 480 481
/**
 * 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;
Scott committed
482

Scott committed
483
	$functionindex = array();
Scott committed
484

Scott committed
485 486 487 488
	foreach ($qa_override_files_temp as $override) {
		$qa_override_files[] = $override;
		$filename = $override['directory'] . $override['include'];
		$functionsphp = file_get_contents($filename);
Scott committed
489

Scott committed
490
		preg_match_all('/\Wfunction\s+(qa_[a-z_]+)\s*\(/im', $functionsphp, $rawmatches, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE);
Scott committed
491

Scott committed
492 493 494 495
		$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']));
Scott committed
496

Scott committed
497 498 499
		foreach ($reversematches as $rawmatch) {
			$function = strtolower($rawmatch[0]);
			$position = $rawmatch[1];
Scott committed
500

Scott committed
501 502
			if (isset($qa_overrides[$function]))
				$postreplace[$function . '_base'] = $qa_overrides[$function];
Scott committed
503

Scott committed
504 505 506 507
			$newname = $function . '_override_' . (@++$functionindex[$function]) . $suffix;
			$functionsphp = substr_replace($functionsphp, $newname, $position, strlen($function));
			$qa_overrides[$function] = $newname;
		}
Scott committed
508

Scott committed
509 510 511 512 513
		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]));
Scott committed
514
				}
Scott committed
515
			}
Scott committed
516
		}
517

Scott committed
518 519 520
		// echo '<pre style="text-align:left;">'.htmlspecialchars($functionsphp).'</pre>'; // to debug munged code

		qa_eval_from_file($functionsphp, $filename);
Scott committed
521 522
	}

Scott committed
523 524
	$qa_override_files_temp = array();
}
Scott committed
525 526


Scott committed
527
// Functions for registering different varieties of Q2A modularity
Scott committed
528

Scott committed
529 530 531
/**
 * 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
532 533 534 535
 * @param string $type
 * @param string $include
 * @param string $class
 * @param string $name
Scott committed
536
 * @param string $directory
537
 * @param string|null $urltoroot
Scott committed
538 539 540 541
 */
function qa_register_module($type, $include, $class, $name, $directory = QA_INCLUDE_DIR, $urltoroot = null)
{
	global $qa_modules;
Scott committed
542

Scott committed
543
	$previous = @$qa_modules[$type][$name];
Scott committed
544

Scott committed
545 546 547
	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);
Scott committed
548 549
	}

Scott committed
550 551 552 553 554 555 556
	$qa_modules[$type][$name] = array(
		'directory' => $directory,
		'urltoroot' => $urltoroot,
		'include' => $include,
		'class' => $class,
	);
}
Scott committed
557 558


Scott committed
559 560 561
/**
 * 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
562 563
 * @param string $include
 * @param string $name
Scott committed
564
 * @param string $directory
565
 * @param string|null $urltoroot
Scott committed
566 567 568 569
 */
function qa_register_layer($include, $name, $directory = QA_INCLUDE_DIR, $urltoroot = null)
{
	global $qa_layers;
Scott committed
570

Scott committed
571
	$previous = @$qa_layers[$name];
Scott committed
572

Scott committed
573 574 575
	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);
Scott committed
576 577
	}

Scott committed
578 579 580 581 582 583
	$qa_layers[$name] = array(
		'directory' => $directory,
		'urltoroot' => $urltoroot,
		'include' => $include,
	);
}
Scott committed
584 585


Scott committed
586 587 588
/**
 * 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
589
 * @param string $include
Scott committed
590
 * @param string $directory
591
 * @param string|null $urltoroot
Scott committed
592 593 594 595
 */
function qa_register_overrides($include, $directory = QA_INCLUDE_DIR, $urltoroot = null)
{
	global $qa_override_files_temp;
Scott committed
596

Scott committed
597 598 599 600 601 602
	$qa_override_files_temp[] = array(
		'directory' => $directory,
		'urltoroot' => $urltoroot,
		'include' => $include,
	);
}
Scott committed
603 604


Scott committed
605 606 607 608
/**
 * 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.
609 610
 * @param string $pattern
 * @param string $name
Scott committed
611 612 613 614
 */
function qa_register_phrases($pattern, $name)
{
	global $qa_lang_file_pattern;
Scott committed
615

Scott committed
616 617 618
	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);
	}
Scott committed
619

Scott committed
620 621 622
	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);
Scott committed
623 624
	}

Scott committed
625 626
	$qa_lang_file_pattern[$name] = $pattern;
}
Scott committed
627 628


Scott committed
629
// Function for registering varieties of Q2A modularity, which are (only) called from qa-plugin.php files
Scott committed
630

Scott committed
631 632 633
/**
 * 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
634 635 636 637
 * @param string $type
 * @param string $include
 * @param string $class
 * @param string $name
Scott committed
638 639 640 641
 */
function qa_register_plugin_module($type, $include, $class, $name)
{
	global $qa_plugin_directory, $qa_plugin_urltoroot;
Scott committed
642

Scott committed
643 644
	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');
Scott committed
645 646
	}

Scott committed
647 648
	qa_register_module($type, $include, $class, $name, $qa_plugin_directory, $qa_plugin_urltoroot);
}
Scott committed
649 650


Scott committed
651 652
/**
 * Register a plugin layer named $name, defined in file $include. Can only be called from a plugin's qa-plugin.php file
653 654
 * @param string $include
 * @param string $name
Scott committed
655 656 657 658
 */
function qa_register_plugin_layer($include, $name)
{
	global $qa_plugin_directory, $qa_plugin_urltoroot;
Scott committed
659

Scott committed
660 661
	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');
Scott committed
662 663
	}

Scott committed
664 665
	qa_register_layer($include, $name, $qa_plugin_directory, $qa_plugin_urltoroot);
}
Scott committed
666 667


Scott committed
668 669
/**
 * Register a plugin file $include containing override functions. Can only be called from a plugin's qa-plugin.php file
670
 * @param string $include
Scott committed
671 672 673 674
 */
function qa_register_plugin_overrides($include)
{
	global $qa_plugin_directory, $qa_plugin_urltoroot;
Scott committed
675

Scott committed
676 677
	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');
Scott committed
678 679
	}

Scott committed
680 681
	qa_register_overrides($include, $qa_plugin_directory, $qa_plugin_urltoroot);
}
Scott committed
682 683


Scott committed
684 685
/**
 * Register a file name $pattern within a plugin directory containing language phrases accessed by the prefix $name
686 687
 * @param string $pattern
 * @param string $name
Scott committed
688 689 690 691
 */
function qa_register_plugin_phrases($pattern, $name)
{
	global $qa_plugin_directory, $qa_plugin_urltoroot;
Scott committed
692

Scott committed
693 694
	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');
Scott committed
695 696
	}

Scott committed
697 698
	qa_register_phrases($qa_plugin_directory . $pattern, $name);
}
Scott committed
699 700


Scott committed
701
// Low-level functions used throughout Q2A
Scott committed
702

Scott committed
703 704 705
/**
 * 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.
706 707
 * @param string $eval
 * @param string $filename
Scott committed
708 709 710 711
 */
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
Scott committed
712

Scott committed
713
	global $php_errormsg;
Scott committed
714

Scott committed
715 716
	$oldtrackerrors = @ini_set('track_errors', 1);
	$php_errormsg = null;
Scott committed
717

Scott committed
718
	eval('?' . '>' . $eval);
Scott committed
719

Scott committed
720 721 722 723 724 725 726 727 728 729
	if (strlen($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;
Scott committed
730 731
		}

Scott committed
732 733 734 735 736 737 738 739 740
		@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)
741 742
 * @param string $function
 * @param array $args
Scott committed
743
 * @return mixed
Scott committed
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
 */
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;
Scott committed
780 781
	}

Scott committed
782 783
	if (strpos($function, '_override_') !== false) {
		qa_fatal_error('Override functions should not be calling qa_to_override()!');
Scott committed
784 785
	}

Scott committed
786 787 788
	if (@$qa_direct[$function]) {
		unset($qa_direct[$function]); // bypass the override just this once
		return null;
Scott committed
789 790
	}

Scott committed
791 792
	return $qa_overrides[$function];
}
Scott committed
793 794


Scott committed
795 796
/**
 * Call the function which immediately overrides $function with the arguments in the $args array
797 798
 * @param string $function
 * @param array $args
Scott committed
799
 * @return mixed
Scott committed
800 801 802 803
 */
function qa_call_override($function, $args)
{
	global $qa_overrides;
Scott committed
804

Scott committed
805 806
	if (strpos($function, '_override_') !== false) {
		qa_fatal_error('Override functions should not be calling qa_call_override()!');
Scott committed
807 808
	}

Scott committed
809 810 811
	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); }');
Scott committed
812 813
	}

Scott committed
814 815
	return qa_call($qa_overrides[$function], $args);
}
Scott committed
816 817


Scott committed
818 819
/**
 * Exit PHP immediately after reporting a shutdown with $reason to any installed process modules
820
 * @param string|null $reason
Scott committed
821 822 823 824
 */
function qa_exit($reason = null)
{
	qa_report_process_stage('shutdown', $reason);
Scott committed
825

Scott committed
826 827 828
	$code = $reason === 'error' ? 1 : 0;
	exit($code);
}
Scott committed
829 830


Scott committed
831 832
/**
 * Display $message in the browser, write it to server error log, and then stop abruptly
833
 * @param string $message
Scott committed
834
 * @return mixed
Scott committed
835 836 837 838
 */
function qa_fatal_error($message)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
839

Scott committed
840 841 842
	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>';
Scott committed
843

Scott committed
844 845 846 847 848 849 850
	$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']
		);
Scott committed
851 852
	}

Scott committed
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
	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
878
 * @param string $type
Scott committed
879
 * @return array
Scott committed
880 881 882 883 884 885 886 887 888
 */
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
889 890
 * @param string $type
 * @param string $name
891
 * @return array
Scott committed
892 893 894 895 896 897 898 899 900
 */
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
901 902
 * @param string $type
 * @param string $name
Scott committed
903
 * @return mixed|null
Scott committed
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
 */
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;
		}
Scott committed
927 928
	}

Scott committed
929 930
	return null;
}
Scott committed
931

Scott committed
932 933 934
/**
 * Return an array of instantiated clases for modules which have defined $method
 * (all modules are loaded but not included in the returned array)
935
 * @param string $method
Scott committed
936
 * @return array
Scott committed
937 938 939 940
 */
function qa_load_all_modules_with($method)
{
	$modules = array();
Scott committed
941

Scott committed
942
	$regmodules = qa_list_modules_info();
Scott committed
943

Scott committed
944 945 946
	foreach ($regmodules as $moduletype => $modulesinfo) {
		foreach ($modulesinfo as $modulename => $moduleinfo) {
			$module = qa_load_module($moduletype, $modulename);
Scott committed
947

Scott committed
948 949
			if (method_exists($module, $method))
				$modules[$modulename] = $module;
Scott committed
950 951 952
		}
	}

Scott committed
953 954
	return $modules;
}
Scott committed
955

Scott committed
956 957 958
/**
 * 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)
959 960
 * @param string $type
 * @param string $method
Scott committed
961
 * @return array
Scott committed
962 963 964 965
 */
function qa_load_modules_with($type, $method)
{
	$modules = array();
Scott committed
966

Scott committed
967
	$trynames = qa_list_modules($type);
Scott committed
968

Scott committed
969 970
	foreach ($trynames as $tryname) {
		$module = qa_load_module($type, $tryname);
Scott committed
971

Scott committed
972 973
		if (method_exists($module, $method))
			$modules[$tryname] = $module;
Scott committed
974 975
	}

Scott committed
976 977
	return $modules;
}
Scott committed
978 979


Scott committed
980
// HTML and Javascript escaping and sanitization
Scott committed
981

Scott committed
982 983
/**
 * Return HTML representation of $string, work well with blocks of text if $multiline is true
984
 * @param string $string
Scott committed
985
 * @param bool $multiline
986
 * @return string
Scott committed
987 988 989
 */
function qa_html($string, $multiline = false)
{
990
	$html = htmlspecialchars($string);
Scott committed
991

Scott committed
992 993 994 995 996
	if ($multiline) {
		$html = preg_replace('/\r\n?/', "\n", $html);
		$html = preg_replace('/(?<=\s) /', '&nbsp;', $html);
		$html = str_replace("\t", '&nbsp; &nbsp; ', $html);
		$html = nl2br($html);
Scott committed
997 998
	}

Scott committed
999 1000
	return $html;
}
Scott committed
1001 1002


Scott committed
1003 1004 1005 1006
/**
 * Return $html after ensuring it is safe, i.e. removing Javascripts and the like - uses htmLawed library
 * Links open in a new window if $linksnewwindow is true. Set $storage to true if sanitization is for
 * storing in the database, rather than immediate display to user - some think this should be less strict.
1007
 * @param string $html
Scott committed
1008 1009
 * @param bool $linksnewwindow
 * @param bool $storage
1010
 * @return string
Scott committed
1011
 */
Scott committed
1012
function qa_sanitize_html($html, $linksnewwindow = false, $storage = false)
Scott committed
1013 1014
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1015

Scott committed
1016
	require_once 'vendor/htmLawed.php';
Scott committed
1017

Scott committed
1018
	global $qa_sanitize_html_newwindow;
Scott committed
1019

Scott committed
1020
	$qa_sanitize_html_newwindow = $linksnewwindow;
Scott committed
1021

Scott committed
1022 1023
	$safe = htmLawed($html, array(
		'safe' => 1,
1024
		'elements' => '*-form-style',
Scott committed
1025 1026 1027 1028 1029
		'schemes' => 'href: aim, feed, file, ftp, gopher, http, https, irc, mailto, news, nntp, sftp, ssh, telnet; *:file, http, https; style: !; classid:clsid',
		'keep_bad' => 0,
		'anti_link_spam' => array('/.*/', ''),
		'hook_tag' => 'qa_sanitize_html_hook_tag',
	));
Scott committed
1030

Scott committed
1031 1032
	return $safe;
}
Scott committed
1033 1034


Scott committed
1035 1036
/**
 * htmLawed hook function used to process tags in qa_sanitize_html(...)
1037
 * @param string $element
Scott committed
1038 1039
 * @param array $attributes
 * @return string
Scott committed
1040 1041 1042 1043
 */
function qa_sanitize_html_hook_tag($element, $attributes = null)
{
	global $qa_sanitize_html_newwindow;
Scott committed
1044

Scott committed
1045 1046
	if (!isset($attributes)) // it's a closing tag
		return '</' . $element . '>';
Scott committed
1047

Scott committed
1048
	if ($element == 'param' && trim(strtolower(@$attributes['name'])) == 'allowscriptaccess')
Scott committed
1049
		$attributes['name'] = 'allowscriptaccess_denied';
Scott committed
1050

Scott committed
1051 1052
	if ($element == 'embed')
		unset($attributes['allowscriptaccess']);
Scott committed
1053

Scott committed
1054
	if ($element == 'a' && isset($attributes['href']) && $qa_sanitize_html_newwindow)
Scott committed
1055
		$attributes['target'] = '_blank';
Scott committed
1056

Scott committed
1057 1058 1059
	$html = '<' . $element;
	foreach ($attributes as $key => $value)
		$html .= ' ' . $key . '="' . $value . '"';
Scott committed
1060

Scott committed
1061 1062
	return $html . '>';
}
Scott committed
1063 1064


Scott committed
1065 1066
/**
 * Return XML representation of $string, which is similar to HTML but ASCII control characters are also disallowed
1067
 * @param string $string
Scott committed
1068
 * @return string
Scott committed
1069 1070 1071
 */
function qa_xml($string)
{
1072
	return htmlspecialchars(preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', '', $string));
Scott committed
1073
}
Scott committed
1074 1075


Scott committed
1076 1077 1078
/**
 * Return JavaScript representation of $value, putting in quotes if non-numeric or if $forcequotes is true. In the
 * case of boolean values they are returned as the appropriate true or false string
1079
 * @param mixed $value
Scott committed
1080 1081
 * @param bool $forcequotes
 * @return string
Scott committed
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
 */
function qa_js($value, $forcequotes = false)
{
	$boolean = is_bool($value);
	if ($boolean)
		$value = $value ? 'true' : 'false';
	if ((is_numeric($value) || $boolean) && !$forcequotes)
		return $value;
	else
		return "'" . strtr($value, array(
Scott committed
1092 1093 1094 1095 1096
				"'" => "\\'",
				'/' => '\\/',
				'\\' => '\\\\',
				"\n" => "\\n",
				"\r" => "\\n",
Scott committed
1097 1098
			)) . "'";
}
Scott committed
1099 1100


Scott committed
1101 1102 1103 1104 1105
// Finding out more about the current request

/**
 * Inform Q2A that the current request is $request (slash-separated, independent of the url scheme chosen),
 * that the relative path to the Q2A root apperas to be $relativeroot, and the url scheme appears to be $usedformat
1106 1107 1108
 * @param string $request
 * @param string $relativeroot
 * @param int|null $usedformat
Scott committed
1109
 * @return mixed
Scott committed
1110
 */
Scott committed
1111
function qa_set_request($request, $relativeroot, $usedformat = null)
Scott committed
1112 1113
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1114

Scott committed
1115
	global $qa_request, $qa_root_url_relative, $qa_used_url_format;
Scott committed
1116

Scott committed
1117 1118 1119 1120
	$qa_request = $request;
	$qa_root_url_relative = $relativeroot;
	$qa_used_url_format = $usedformat;
}
Scott committed
1121 1122


Scott committed
1123 1124
/**
 * Returns the current Q2A request (slash-separated, independent of the url scheme chosen)
1125
 * @return string
Scott committed
1126 1127 1128 1129
 */
function qa_request()
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1130

Scott committed
1131 1132 1133
	global $qa_request;
	return $qa_request;
}
Scott committed
1134 1135


Scott committed
1136 1137
/**
 * Returns the indexed $part (as separated by slashes) of the current Q2A request, or null if it doesn't exist
1138 1139
 * @param int $part
 * @return string
Scott committed
1140 1141 1142 1143 1144 1145
 */
function qa_request_part($part)
{
	$parts = explode('/', qa_request());
	return @$parts[$part];
}
Scott committed
1146 1147


Scott committed
1148 1149
/**
 * Returns an array of parts (as separated by slashes) of the current Q2A request, starting at part $start
Scott committed
1150 1151
 * @param int $start
 * @return array
Scott committed
1152 1153 1154 1155 1156
 */
function qa_request_parts($start = 0)
{
	return array_slice(explode('/', qa_request()), $start);
}
Scott committed
1157 1158


Scott committed
1159 1160
/**
 * Return string for incoming GET/POST/COOKIE value, stripping slashes if appropriate
1161 1162
 * @param string $string
 * @return string
Scott committed
1163 1164 1165 1166
 */
function qa_gpc_to_string($string)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1167

1168 1169 1170 1171 1172
	// get_magic_quotes_gpc always returns false from PHP 5.4; this avoids deprecation notice on PHP 7.4+
	if (qa_php_version_below('5.4.0'))
		return get_magic_quotes_gpc() ? stripslashes($string) : $string;
	else
		return $string;
Scott committed
1173
}
Scott committed
1174 1175


Scott committed
1176 1177
/**
 * Return string with slashes added, if appropriate for later removal by qa_gpc_to_string()
1178 1179
 * @param string $string
 * @return string
Scott committed
1180 1181 1182 1183
 */
function qa_string_to_gpc($string)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1184

1185 1186 1187 1188 1189
	// get_magic_quotes_gpc always returns false from PHP 5.4; this avoids deprecation notice on PHP 7.4+
	if (qa_php_version_below('5.4.0'))
		return get_magic_quotes_gpc() ? addslashes($string) : $string;
	else
		return $string;
Scott committed
1190
}
Scott committed
1191 1192


Scott committed
1193 1194
/**
 * Return string for incoming GET field, or null if it's not defined
1195 1196
 * @param string $field
 * @return mixed|null
Scott committed
1197 1198 1199 1200
 */
function qa_get($field)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1201

Scott committed
1202 1203
	return isset($_GET[$field]) ? qa_gpc_to_string($_GET[$field]) : null;
}
Scott committed
1204 1205


Scott committed
1206 1207 1208
/**
 * Return string for incoming POST field, or null if it's not defined.
 * While we're at it, trim() surrounding white space and converted to Unix line endings.
1209
 * @param string $field
Scott committed
1210
 * @return mixed|null
Scott committed
1211 1212 1213 1214
 */
function qa_post_text($field)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1215

Scott committed
1216 1217
	return isset($_POST[$field]) ? preg_replace('/\r\n?/', "\n", trim(qa_gpc_to_string($_POST[$field]))) : null;
}
Scott committed
1218

Scott committed
1219 1220 1221
/**
 * Return an array for incoming POST field, or null if it's not an array or not defined.
 * While we're at it, trim() surrounding white space for each value and convert them to Unix line endings.
1222 1223
 * @param string $field
 * @return mixed|null
Scott committed
1224 1225 1226 1227 1228 1229 1230
 */
function qa_post_array($field)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

	if (!isset($_POST[$field]) || !is_array($_POST[$field])) {
		return null;
Scott committed
1231 1232
	}

Scott committed
1233 1234 1235
	$result = array();
	foreach ($_POST[$field] as $key => $value)
		$result[$key] = preg_replace('/\r\n?/', "\n", trim(qa_gpc_to_string($value)));
Scott committed
1236

Scott committed
1237 1238
	return $result;
}
Scott committed
1239 1240


Scott committed
1241 1242 1243
/**
 * Return true if form button $name was clicked (as type=submit/image) to create this page request, or if a
 * simulated click was sent for the button (via 'qa_click' POST field)
1244 1245
 * @param string $name
 * @return bool
Scott committed
1246 1247 1248 1249
 */
function qa_clicked($name)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1250

Scott committed
1251 1252
	return isset($_POST[$name]) || isset($_POST[$name . '_x']) || (qa_post_text('qa_click') == $name);
}
Scott committed
1253 1254


Scott committed
1255 1256
/**
 * Determine the remote IP address of the user accessing the site.
1257
 * @return string|null  String representing IP if it's available, or null otherwise.
Scott committed
1258 1259 1260 1261
 */
function qa_remote_ip_address()
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1262

Scott committed
1263 1264
	return isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
}
Scott committed
1265 1266


Scott committed
1267 1268 1269 1270 1271
/**
 * Checks whether an HTTP request has exceeded the post_max_size PHP variable. This happens whenever an HTTP request
 * is too big to be properly processed by PHP, usually because there is an attachment in the HTTP request. A warning
 * is added to the server's log displaying the size of the file that triggered this situation. It is important to note
 * that whenever this happens the $_POST and $_FILES superglobals are empty.
1272
 * @return bool
Scott committed
1273 1274 1275 1276 1277 1278 1279 1280
 */
function qa_post_limit_exceeded()
{
	if (in_array($_SERVER['REQUEST_METHOD'], array('POST', 'PUT')) && empty($_POST) && empty($_FILES)) {
		$postmaxsize = ini_get('post_max_size');  // Gets the current post_max_size configuration
		$unit = substr($postmaxsize, -1);
		if (!is_numeric($unit)) {
			$postmaxsize = substr($postmaxsize, 0, -1);
Scott committed
1281
		}
Scott committed
1282 1283 1284
		// Gets an integer value that can be compared against the size of the HTTP request
		$postmaxsize = convert_to_bytes($unit, $postmaxsize);
		return $_SERVER['CONTENT_LENGTH'] > $postmaxsize;
Scott committed
1285
	}
1286 1287

	return false;
Scott committed
1288
}
Scott committed
1289 1290


Scott committed
1291
/**
1292 1293 1294 1295 1296 1297
 * Turns a numeric value and a unit (g/m/k) into bytes
 * @param string $unit One of 'g', 'm', 'k'. It is case insensitive
 * @param int $value The value to turn into bytes
 * @return int The amount of bytes the unit and the value represent. If the unit is not one of 'g', 'm' or 'k' then the
 * original value is returned
 */
Scott committed
1298 1299
function convert_to_bytes($unit, $value)
{
1300 1301
	$value = (int) $value;

Scott committed
1302 1303
	switch (strtolower($unit)) {
		case 'g':
1304
			return $value * pow(1024, 3);
Scott committed
1305
		case 'm':
1306
			return $value * pow(1024, 2);
Scott committed
1307 1308 1309 1310
		case 'k':
			return $value * 1024;
		default:
			return $value;
1311
	}
Scott committed
1312
}
1313 1314


1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
/**
 * Issue a HTTP status code header.
 * @param int $code
 * @param string $message
 * @return void
 */
function qa_http_error($code, $message)
{
	$protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1';
	$code = (int) $code;

	header("$protocol $code $message");
}


/**
 * Issue a HTTP 404 header.
 * @return void
 */
function qa_404()
{
	qa_http_error('404', 'Not Found');
}


/**
 * Issue a HTTP 500 header.
 * @return void
 */
function qa_500()
{
	qa_http_error('500', 'Internal Server Error');
}


Scott committed
1350
/**
1351
 * Return true if we are responding to an HTTP GET request
Scott committed
1352 1353 1354 1355 1356
 * @return bool True if the request is GET
 */
function qa_is_http_get()
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1357

Scott committed
1358 1359
	return $_SERVER['REQUEST_METHOD'] === 'GET';
}
Scott committed
1360

Scott committed
1361 1362
/**
 * Return true if we are responding to an HTTP POST request
1363
 * @return bool True if the request is POST
Scott committed
1364 1365 1366 1367
 */
function qa_is_http_post()
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1368

Scott committed
1369 1370
	return $_SERVER['REQUEST_METHOD'] === 'POST' || !empty($_POST);
}
Scott committed
1371 1372


Scott committed
1373 1374
/**
 * Return true if we appear to be responding to a secure HTTP request (but hard to be sure)
1375
 * @return bool
Scott committed
1376 1377 1378 1379
 */
function qa_is_https_probably()
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1380

Scott committed
1381 1382
	return (@$_SERVER['HTTPS'] && ($_SERVER['HTTPS'] != 'off')) || (@$_SERVER['SERVER_PORT'] == 443);
}
Scott committed
1383 1384


Scott committed
1385 1386 1387
/**
 * Return true if it appears the page request is coming from a human using a web browser, rather than a search engine
 * or other bot. Based on a whitelist of terms in user agents, this can easily be tricked by a scraper or bad bot.
1388
 * @return bool
Scott committed
1389 1390 1391 1392
 */
function qa_is_human_probably()
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1393

Scott committed
1394
	require_once QA_INCLUDE_DIR . 'util/string.php';
Scott committed
1395

Scott committed
1396
	$useragent = @$_SERVER['HTTP_USER_AGENT'];
Scott committed
1397

Scott committed
1398 1399 1400 1401 1402
	return (strlen($useragent) == 0) || qa_string_matches_one($useragent, array(
		'MSIE', 'Firefox', 'Chrome', 'Safari', 'Opera', 'Gecko', 'MIDP', 'PLAYSTATION', 'Teleca',
		'BlackBerry', 'UP.Browser', 'Polaris', 'MAUI_WAP_Browser', 'iPad', 'iPhone', 'iPod',
	));
}
Scott committed
1403 1404


Scott committed
1405
/**
1406 1407 1408
 * Return true if it appears that the page request is coming from a mobile client rather than a desktop/laptop web
 * browser
 * @return bool
Scott committed
1409 1410 1411 1412
 */
function qa_is_mobile_probably()
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1413

Scott committed
1414
	require_once QA_INCLUDE_DIR . 'util/string.php';
Scott committed
1415

Scott committed
1416
	// inspired by: http://dangerousprototypes.com/docs/PhpBB3_MOD:_Replacement_mobile_browser_detection_for_mobile_themes
Scott committed
1417

Scott committed
1418
	$loweragent = strtolower(@$_SERVER['HTTP_USER_AGENT']);
Scott committed
1419

Scott committed
1420 1421
	if (strpos($loweragent, 'ipad') !== false) // consider iPad as desktop
		return false;
Scott committed
1422

Scott committed
1423
	$mobileheaders = array('HTTP_X_OPERAMINI_PHONE', 'HTTP_X_WAP_PROFILE', 'HTTP_PROFILE');
Scott committed
1424

Scott committed
1425 1426
	foreach ($mobileheaders as $header)
		if (isset($_SERVER[$header]))
Scott committed
1427 1428
			return true;

Scott committed
1429 1430 1431 1432 1433 1434
	if (qa_string_matches_one($loweragent, array(
		'android', 'phone', 'mobile', 'windows ce', 'palm', ' mobi', 'wireless', 'blackberry', 'opera mini', 'symbian',
		'nokia', 'samsung', 'ericsson,', 'vodafone/', 'kindle', 'ipod', 'wap1.', 'wap2.', 'sony', 'sanyo', 'sharp',
		'panasonic', 'philips', 'pocketpc', 'avantgo', 'blazer', 'ipaq', 'up.browser', 'up.link', 'mmp', 'smartphone', 'midp',
	)))
		return true;
Scott committed
1435

Scott committed
1436 1437 1438 1439
	return qa_string_matches_one(strtolower(@$_SERVER['HTTP_ACCEPT']), array(
		'application/vnd.wap.xhtml+xml', 'text/vnd.wap.wml',
	));
}
Scott committed
1440 1441


Scott committed
1442
// Language phrase support
Scott committed
1443

Scott committed
1444 1445 1446 1447 1448 1449
/**
 * Return the translated string for $identifier, unless we're using external translation logic.
 * This will retrieve the 'site_language' option so make sure you've already loaded/set that if
 * loading an option now will cause a problem (see issue in qa_default_option()). The part of
 * $identifier before the slash (/) replaces the * in the qa-lang-*.php file references, and the
 * part after the / is the key of the array element to be taken from that file's returned result.
1450
 * @param string $identifier
Scott committed
1451
 * @return string
Scott committed
1452 1453 1454 1455
 */
function qa_lang($identifier)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1456

Scott committed
1457
	global $qa_lang_file_pattern, $qa_phrases_full;
Scott committed
1458

Scott committed
1459
	list($group, $label) = explode('/', $identifier, 2);
Scott committed
1460

Scott committed
1461 1462
	if (isset($qa_phrases_full[$group][$label]))
		return $qa_phrases_full[$group][$label];
Scott committed
1463

Scott committed
1464 1465 1466 1467 1468 1469
	if (!isset($qa_phrases_full[$group])) {
		// load the default language files
		if (isset($qa_lang_file_pattern[$group]))
			$include = str_replace('*', 'default', $qa_lang_file_pattern[$group]);
		else
			$include = QA_INCLUDE_DIR . 'lang/qa-lang-' . $group . '.php';
Scott committed
1470

Scott committed
1471
		$qa_phrases_full[$group] = is_file($include) ? (array)(include_once $include) : array();
Scott committed
1472

Scott committed
1473 1474 1475 1476 1477 1478 1479
		// look for a localized file in qa-lang/<lang>/
		$languagecode = qa_opt('site_language');
		if (strlen($languagecode)) {
			if (isset($qa_lang_file_pattern[$group]))
				$include = str_replace('*', $languagecode, $qa_lang_file_pattern[$group]);
			else
				$include = QA_LANG_DIR . $languagecode . '/qa-lang-' . $group . '.php';
Scott committed
1480

Scott committed
1481 1482
			$phrases = is_file($include) ? (array)(include $include) : array();
			$qa_phrases_full[$group] = array_merge($qa_phrases_full[$group], $phrases);
Scott committed
1483 1484
		}

Scott committed
1485 1486 1487 1488
		// add any custom phrases from qa-lang/custom/
		$include = QA_LANG_DIR . 'custom/qa-lang-' . $group . '.php';
		$phrases = is_file($include) ? (array)(include $include) : array();
		$qa_phrases_full[$group] = array_merge($qa_phrases_full[$group], $phrases);
Scott committed
1489

Scott committed
1490 1491
		if (isset($qa_phrases_full[$group][$label]))
			return $qa_phrases_full[$group][$label];
Scott committed
1492 1493
	}

Scott committed
1494 1495
	return '[' . $identifier . ']'; // as a last resort, return the identifier to help in development
}
Scott committed
1496 1497


Scott committed
1498 1499
/**
 * Return the translated string for $identifier, with $symbol substituted for $textparam
1500 1501
 * @param string $identifier
 * @param string $textparam
Scott committed
1502 1503
 * @param string $symbol
 * @return mixed
Scott committed
1504 1505 1506 1507 1508
 */
function qa_lang_sub($identifier, $textparam, $symbol = '^')
{
	return str_replace($symbol, $textparam, qa_lang($identifier));
}
Scott committed
1509 1510


Scott committed
1511 1512
/**
 * Return the translated string for $identifier, converted to HTML
1513 1514
 * @param string $identifier
 * @return string
Scott committed
1515 1516 1517 1518 1519
 */
function qa_lang_html($identifier)
{
	return qa_html(qa_lang($identifier));
}
Scott committed
1520 1521


Scott committed
1522 1523
/**
 * Return the translated string for $identifier converted to HTML, with $symbol *then* substituted for $htmlparam
1524 1525
 * @param string $identifier
 * @param string $htmlparam
Scott committed
1526 1527
 * @param string $symbol
 * @return mixed
Scott committed
1528 1529 1530 1531 1532
 */
function qa_lang_html_sub($identifier, $htmlparam, $symbol = '^')
{
	return str_replace($symbol, $htmlparam, qa_lang_html($identifier));
}
Scott committed
1533 1534


Scott committed
1535 1536 1537
/**
 * Return an array containing the translated string for $identifier converted to HTML, then split into three,
 * with $symbol substituted for $htmlparam in the 'data' element, and obvious 'prefix' and 'suffix' elements
1538 1539
 * @param string $identifier
 * @param string $htmlparam
Scott committed
1540 1541
 * @param string $symbol
 * @return array
Scott committed
1542 1543 1544 1545
 */
function qa_lang_html_sub_split($identifier, $htmlparam, $symbol = '^')
{
	$html = qa_lang_html($identifier);
Scott committed
1546

Scott committed
1547 1548 1549
	$symbolpos = strpos($html, $symbol);
	if (!is_numeric($symbolpos))
		qa_fatal_error('Missing ' . $symbol . ' in language string ' . $identifier);
Scott committed
1550

Scott committed
1551 1552 1553 1554 1555 1556
	return array(
		'prefix' => substr($html, 0, $symbolpos),
		'data' => $htmlparam,
		'suffix' => substr($html, $symbolpos + 1),
	);
}
Scott committed
1557 1558


Scott committed
1559
// Request and path generation
Scott committed
1560

Scott committed
1561 1562
/**
 * Return the relative path to the Q2A root (if it was previously set by qa_set_request())
1563
 * @return string
Scott committed
1564 1565 1566 1567
 */
function qa_path_to_root()
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1568

Scott committed
1569 1570 1571
	global $qa_root_url_relative;
	return $qa_root_url_relative;
}
Scott committed
1572 1573


Scott committed
1574 1575
/**
 * Return an array of mappings of Q2A requests, as defined in the qa-config.php file
1576
 * @return array
Scott committed
1577 1578 1579 1580
 */
function qa_get_request_map()
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1581

Scott committed
1582 1583 1584
	global $qa_request_map;
	return $qa_request_map;
}
Scott committed
1585 1586


Scott committed
1587 1588 1589 1590 1591
/**
 * Return the relative URI path for $request, with optional parameters $params and $anchor.
 * Slashes in $request will not be urlencoded, but any other characters will.
 * If $neaturls is set, use that, otherwise retrieve the option. If $rooturl is set, take
 * that as the root of the Q2A site, otherwise use path to root which was set elsewhere.
1592 1593 1594 1595 1596
 * @param string $request
 * @param array|null $params
 * @param string|null $rooturl
 * @param int|null $neaturls
 * @param string|null $anchor
Scott committed
1597
 * @return string
Scott committed
1598
 */
Scott committed
1599
function qa_path($request, $params = null, $rooturl = null, $neaturls = null, $anchor = null)
Scott committed
1600 1601
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1602

Scott committed
1603 1604 1605 1606
	if (!isset($neaturls)) {
		require_once QA_INCLUDE_DIR . 'app/options.php';
		$neaturls = qa_opt('neat_urls');
	}
Scott committed
1607

Scott committed
1608 1609
	if (!isset($rooturl))
		$rooturl = qa_path_to_root();
Scott committed
1610

Scott committed
1611 1612
	$url = $rooturl . ((empty($rooturl) || (substr($rooturl, -1) == '/')) ? '' : '/');
	$paramsextra = '';
Scott committed
1613

Scott committed
1614 1615
	$requestparts = explode('/', $request);
	$pathmap = qa_get_request_map();
Scott committed
1616

Scott committed
1617 1618
	if (isset($pathmap[$requestparts[0]])) {
		$newpart = $pathmap[$requestparts[0]];
Scott committed
1619

Scott committed
1620 1621 1622 1623 1624
		if (strlen($newpart))
			$requestparts[0] = $newpart;
		elseif (count($requestparts) == 1)
			array_shift($requestparts);
	}
Scott committed
1625

Scott committed
1626 1627 1628 1629
	foreach ($requestparts as $index => $requestpart) {
		$requestparts[$index] = urlencode($requestpart);
	}
	$requestpath = implode('/', $requestparts);
Scott committed
1630

Scott committed
1631 1632 1633 1634 1635
	switch ($neaturls) {
		case QA_URL_FORMAT_INDEX:
			if (!empty($request))
				$url .= 'index.php/' . $requestpath;
			break;
Scott committed
1636

Scott committed
1637 1638 1639 1640 1641 1642 1643 1644
		case QA_URL_FORMAT_NEAT:
			$url .= $requestpath;
			break;

		case QA_URL_FORMAT_PARAM:
			if (!empty($request))
				$paramsextra = '?qa=' . $requestpath;
			break;
Scott committed
1645

Scott committed
1646 1647
		default:
			$url .= 'index.php';
Scott committed
1648

Scott committed
1649 1650 1651 1652 1653 1654
		case QA_URL_FORMAT_PARAMS:
			if (!empty($request)) {
				foreach ($requestparts as $partindex => $requestpart)
					$paramsextra .= (strlen($paramsextra) ? '&' : '?') . 'qa' . ($partindex ? ('_' . $partindex) : '') . '=' . $requestpart;
			}
			break;
Scott committed
1655 1656
	}

1657 1658 1659 1660 1661 1662
	if (is_array($params)) {
		foreach ($params as $key => $value) {
			$value = is_array($value) ? '' : (string) $value;
			$paramsextra .= (strlen($paramsextra) ? '&' : '?') . urlencode($key) . '=' . urlencode($value);
		}
	}
Scott committed
1663

Scott committed
1664 1665
	return $url . $paramsextra . (empty($anchor) ? '' : '#' . urlencode($anchor));
}
Scott committed
1666 1667


Scott committed
1668 1669
/**
 * Return HTML representation of relative URI path for $request - see qa_path() for other parameters
1670 1671 1672 1673 1674
 * @param string $request
 * @param array|null $params
 * @param string|null $rooturl
 * @param int|null $neaturls
 * @param string|null $anchor
Scott committed
1675
 * @return mixed|string
Scott committed
1676 1677 1678 1679 1680
 */
function qa_path_html($request, $params = null, $rooturl = null, $neaturls = null, $anchor = null)
{
	return qa_html(qa_path($request, $params, $rooturl, $neaturls, $anchor));
}
Scott committed
1681 1682


Scott committed
1683 1684
/**
 * Return the absolute URI for $request - see qa_path() for other parameters
1685 1686 1687
 * @param string $request
 * @param array|null $params
 * @param string|null $anchor
Scott committed
1688
 * @return string
Scott committed
1689 1690 1691 1692 1693
 */
function qa_path_absolute($request, $params = null, $anchor = null)
{
	return qa_path($request, $params, qa_opt('site_url'), null, $anchor);
}
Scott committed
1694 1695


Scott committed
1696 1697 1698
/**
 * Get Q2A request for a question, and make it search-engine friendly, shortening it if necessary
 * by removing shorter words which are generally less meaningful.
Scott committed
1699
 * @param int $questionid The question ID
Scott committed
1700
 * @param string $title The question title
Scott committed
1701
 * @return string
Scott committed
1702 1703 1704 1705
 */
function qa_q_request($questionid, $title)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1706

Scott committed
1707 1708
	require_once QA_INCLUDE_DIR . 'app/options.php';
	require_once QA_INCLUDE_DIR . 'util/string.php';
Scott committed
1709

Scott committed
1710 1711
	$title = qa_block_words_replace($title, qa_get_block_words_preg());
	$slug = qa_slugify($title, qa_opt('q_urls_remove_accents'), qa_opt('q_urls_title_length'));
Scott committed
1712

Scott committed
1713 1714
	return (int)$questionid . '/' . $slug;
}
Scott committed
1715 1716


Scott committed
1717 1718
/**
 * Return the HTML anchor that should be used for post $postid with $basetype (Q/A/C)
1719 1720 1721
 * @param string $basetype
 * @param int $postid
 * @return string
Scott committed
1722 1723 1724 1725
 */
function qa_anchor($basetype, $postid)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1726

Scott committed
1727 1728
	return strtolower($basetype) . $postid; // used to be $postid only but this violated HTML spec
}
Scott committed
1729 1730


Scott committed
1731 1732 1733
/**
 * Return the URL for question $questionid with $title, possibly using $absolute URLs.
 * To link to a specific answer or comment in a question, set $showtype and $showid accordingly.
1734 1735
 * @param int $questionid
 * @param string $title
Scott committed
1736
 * @param bool $absolute
1737 1738 1739
 * @param string|null $showtype
 * @param int|null $showid
 * @return string
Scott committed
1740 1741 1742 1743 1744
 */
function qa_q_path($questionid, $title, $absolute = false, $showtype = null, $showid = null)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

Scott committed
1745
	if (($showtype == 'Q' || $showtype == 'A' || $showtype == 'C') && isset($showid)) {
Scott committed
1746 1747
		$params = array('show' => $showid); // due to pagination
		$anchor = qa_anchor($showtype, $showid);
Scott committed
1748

Scott committed
1749 1750 1751
	} else {
		$params = null;
		$anchor = null;
Scott committed
1752 1753
	}

Scott committed
1754 1755
	return qa_path(qa_q_request($questionid, $title), $params, $absolute ? qa_opt('site_url') : null, null, $anchor);
}
Scott committed
1756 1757


Scott committed
1758 1759
/**
 * Return the HTML representation of the URL for $questionid - other parameters as for qa_q_path()
1760 1761 1762 1763 1764
 * @param int $questionid
 * @param string $title
 * @param bool|null $absolute
 * @param string|null $showtype
 * @param int|null $showid
Scott committed
1765
 * @return mixed|string
Scott committed
1766 1767 1768 1769 1770
 */
function qa_q_path_html($questionid, $title, $absolute = false, $showtype = null, $showid = null)
{
	return qa_html(qa_q_path($questionid, $title, $absolute, $showtype, $showid));
}
Scott committed
1771 1772


Scott committed
1773 1774
/**
 * Return the request for the specified $feed
1775 1776
 * @param string $feed
 * @return string
Scott committed
1777 1778 1779 1780
 */
function qa_feed_request($feed)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1781

Scott committed
1782 1783
	return 'feed/' . $feed . '.rss';
}
Scott committed
1784 1785


Scott committed
1786 1787
/**
 * Return an HTML-ready relative URL for the current page, preserving GET parameters - this is useful for action="..." in HTML forms
1788
 * @return string
Scott committed
1789 1790 1791 1792
 */
function qa_self_html()
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1793

Scott committed
1794
	global $qa_used_url_format;
Scott committed
1795

Scott committed
1796 1797
	return qa_path_html(qa_request(), $_GET, null, $qa_used_url_format);
}
Scott committed
1798 1799


Scott committed
1800 1801 1802
/**
 * Return HTML for hidden fields to insert into a <form method="get"...> on the page.
 * This is needed because any parameters on the URL will be lost when the form is submitted.
1803 1804 1805 1806 1807 1808
 * @param string $request
 * @param array|null $params
 * @param string|null $rooturl
 * @param int|null $neaturls
 * @param string|null $anchor
 * @return string
Scott committed
1809
 */
Scott committed
1810
function qa_path_form_html($request, $params = null, $rooturl = null, $neaturls = null, $anchor = null)
Scott committed
1811 1812
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1813

Scott committed
1814 1815
	$path = qa_path($request, $params, $rooturl, $neaturls, $anchor);
	$formhtml = '';
Scott committed
1816

Scott committed
1817 1818 1819
	$questionpos = strpos($path, '?');
	if (is_numeric($questionpos)) {
		$params = explode('&', substr($path, $questionpos + 1));
Scott committed
1820

Scott committed
1821 1822 1823
		foreach ($params as $param)
			if (preg_match('/^([^\=]*)(\=(.*))?$/', $param, $matches))
				$formhtml .= '<input type="hidden" name="' . qa_html(urldecode($matches[1])) . '" value="' . qa_html(urldecode(@$matches[3])) . '"/>';
Scott committed
1824 1825
	}

Scott committed
1826 1827
	return $formhtml;
}
Scott committed
1828 1829


Scott committed
1830 1831
/**
 * Redirect the user's web browser to $request and then we're done - see qa_path() for other parameters
1832 1833 1834 1835 1836
 * @param string $request
 * @param array|null $params
 * @param string|null $rooturl
 * @param int|null $neaturls
 * @param string|null $anchor
Scott committed
1837
 * @return mixed
Scott committed
1838
 */
Scott committed
1839
function qa_redirect($request, $params = null, $rooturl = null, $neaturls = null, $anchor = null)
Scott committed
1840 1841
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1842

Scott committed
1843 1844
	qa_redirect_raw(qa_path($request, $params, $rooturl, $neaturls, $anchor));
}
Scott committed
1845 1846


Scott committed
1847 1848
/**
 * Redirect the user's web browser to page $path which is already a URL
1849
 * @param string $url
Scott committed
1850
 * @return mixed
Scott committed
1851 1852 1853 1854
 */
function qa_redirect_raw($url)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1855

Scott committed
1856 1857 1858
	header('Location: ' . $url);
	qa_exit('redirect');
}
Scott committed
1859 1860


Scott committed
1861
// General utilities
Scott committed
1862

Scott committed
1863 1864
/**
 * Return the contents of remote $url, using file_get_contents() if possible, otherwise curl functions
1865 1866
 * @param string $url
 * @return bool|string
Scott committed
1867 1868 1869 1870
 */
function qa_retrieve_url($url)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
1871

Scott committed
1872 1873 1874 1875
	// ensure we're fetching a remote URL
	if (!preg_match('#^https?://#', $url)) {
		return '';
	}
Scott committed
1876

Scott committed
1877
	$contents = '';
Scott committed
1878

1879
	// Due to the design of the file_get_contents function, sometimes getting external content will be very slow.
Scott committed
1880 1881
	// So we try curl first, if possible. https://stackoverflow.com/q/3629504
	if (function_exists('curl_exec')) {
Scott committed
1882 1883 1884 1885
		$curl = curl_init($url);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		$contents = @curl_exec($curl);
		curl_close($curl);
Scott committed
1886 1887
	}

Scott committed
1888 1889 1890
	if (!strlen($contents)) {
		$contents = @file_get_contents($url);
	}
1891

Scott committed
1892 1893
	return $contents;
}
Scott committed
1894 1895


1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
/**
 * Helper function to access the Application object.
 * @return Application
 */
function qa_app()
{
	return Application::getInstance();
}


/**
1907
 * Helper function to get/set services.
1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918
 * If the $key parameter is set and the $object parameter is null the container is called to resolve the $key.
 * If the $key and the $object parameters are null the container is called to bind the $object to the $key.
 * @param mixed $key Identifier for the object to get/set.
 * @param mixed $object Object to set in the $key (if null, a stored object is returned)
 * @return mixed
 */
function qa_service($key, $object = null)
{
	$app = Application::getInstance();

	if ($object === null) {
1919
		return $app->getService($key);
1920 1921
	}

1922
	$app->registerService($key, $object);
1923 1924 1925
}


Scott committed
1926 1927
/**
 * Shortcut to get or set an option value without specifying database
1928 1929 1930
 * @param string $name
 * @param mixed|null $value
 * @return string
Scott committed
1931 1932 1933 1934
 */
function qa_opt($name, $value = null)
{
	global $qa_options_cache;
Scott committed
1935

Scott committed
1936
	if (!isset($value) && isset($qa_options_cache[$name]))
Scott committed
1937
		return $qa_options_cache[$name]; // quick shortcut to reduce calls to qa_get_options()
Scott committed
1938

Scott committed
1939
	require_once QA_INCLUDE_DIR . 'app/options.php';
Scott committed
1940

Scott committed
1941 1942
	if (isset($value))
		qa_set_option($name, $value);
Scott committed
1943

Scott committed
1944
	$options = qa_get_options(array($name));
Scott committed
1945

Scott committed
1946 1947
	return $options[$name];
}
Scott committed
1948

Scott committed
1949 1950
/**
 * Simple method to output a preformatted variable
1951
 * @param mixed $var
Scott committed
1952 1953 1954
 */
function qa_debug($var)
{
1955
	echo "\n" . '<pre style="padding: 10px; background-color: #eee; color: #444; font-size: 12px; text-align: left; white-space: pre-wrap">';
Scott committed
1956
	echo $var === null ? 'NULL' : htmlspecialchars(print_r($var, true), ENT_COMPAT|ENT_SUBSTITUTE);
Scott committed
1957 1958
	echo '</pre>' . "\n";
}
Scott committed
1959 1960


Scott committed
1961
// Event and process stage reporting
Scott committed
1962

Scott committed
1963 1964 1965
/**
 * Suspend the reporting of events to event modules via qa_report_event(...) if $suspend is
 * true, otherwise reinstate it. A counter is kept to allow multiple calls.
Scott committed
1966
 * @param bool $suspend
Scott committed
1967 1968 1969 1970
 */
function qa_suspend_event_reports($suspend = true)
{
	global $qa_event_reports_suspended;
Scott committed
1971

Scott committed
1972 1973
	$qa_event_reports_suspended += ($suspend ? 1 : -1);
}
Scott committed
1974 1975


Scott committed
1976 1977
/**
 * Send a notification of event $event by $userid, $handle and $cookieid to all event modules, with extra $params
1978 1979 1980 1981
 * @param string $event
 * @param mixed $userid
 * @param string $handle
 * @param string $cookieid
Scott committed
1982
 * @param array $params
1983
 * @return mixed
Scott committed
1984
 */
Scott committed
1985
function qa_report_event($event, $userid, $handle, $cookieid, $params = array())
Scott committed
1986 1987
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1988

Scott committed
1989
	global $qa_event_reports_suspended;
Scott committed
1990

Scott committed
1991 1992
	if ($qa_event_reports_suspended > 0)
		return;
Scott committed
1993

Scott committed
1994 1995 1996 1997
	$eventmodules = qa_load_modules_with('event', 'process_event');
	foreach ($eventmodules as $eventmodule)
		$eventmodule->process_event($event, $userid, $handle, $cookieid, $params);
}
Scott committed
1998

1999 2000 2001 2002
/**
 * Execute the given $method in all process modules. Parameters can be sent as arguments.
 * @param string $method
 */
Scott committed
2003 2004 2005
function qa_report_process_stage($method) // can have extra params
{
	global $qa_process_reports_suspended;
Scott committed
2006

Scott committed
2007 2008
	if (@$qa_process_reports_suspended)
		return;
Scott committed
2009

Scott committed
2010
	$qa_process_reports_suspended = true; // prevent loop, e.g. because of an error
Scott committed
2011

Scott committed
2012 2013
	$args = func_get_args();
	$args = array_slice($args, 1);
Scott committed
2014

Scott committed
2015 2016 2017
	$processmodules = qa_load_modules_with('process', $method);
	foreach ($processmodules as $processmodule) {
		call_user_func_array(array($processmodule, $method), $args);
Scott committed
2018
	}
Scott committed
2019 2020 2021

	$qa_process_reports_suspended = null;
}