format.php 79.9 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
<?php
/*
	Question2Answer by Gideon Greenspan and contributors
	http://www.question2answer.org/

	Description: Common functions for creating theme-ready structures from data


	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
22
if (!defined('QA_VERSION')) { // don't allow this page to be requested directly from browser
23
	header('Location: ../../');
Scott committed
24 25 26 27 28 29 30 31 32
	exit;
}

define('QA_PAGE_FLAGS_EXTERNAL', 1);
define('QA_PAGE_FLAGS_NEW_WINDOW', 2);


/**
 * Return textual representation of $seconds
33 34
 * @param int $seconds
 * @return string
Scott committed
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
 */
function qa_time_to_string($seconds)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

	$seconds = max($seconds, 1);

	$scales = array(
		31557600 => array('main/1_year', 'main/x_years'),
		2629800 => array('main/1_month', 'main/x_months'),
		604800 => array('main/1_week', 'main/x_weeks'),
		86400 => array('main/1_day', 'main/x_days'),
		3600 => array('main/1_hour', 'main/x_hours'),
		60 => array('main/1_minute', 'main/x_minutes'),
		1 => array('main/1_second', 'main/x_seconds'),
	);

	foreach ($scales as $scale => $phrases) {
		if ($seconds >= $scale) {
			$count = floor($seconds / $scale);

			if ($count == 1)
				$string = qa_lang($phrases[0]);
			else
				$string = qa_lang_sub($phrases[1], $count);
Scott committed
60

Scott committed
61 62 63
			break;
		}
	}
Scott committed
64

Scott committed
65 66 67 68 69 70 71
	return $string;
}


/**
 * Check if $post is by user $userid, or if post is anonymous and $userid not specified, then
 * check if $post is by the anonymous user identified by $cookieid
72 73 74
 * @param array $post
 * @param mixed $userid
 * @param string $cookieid
Scott committed
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
 * @return bool
 */
function qa_post_is_by_user($post, $userid, $cookieid)
{
	// In theory we should only test against NULL here, i.e. use isset($post['userid'])
	// but the risk of doing so is so high (if a bug creeps in that allows userid=0)
	// that I'm doing a tougher test. This will break under a zero user or cookie id.

	if (@$post['userid'] || $userid)
		return @$post['userid'] == $userid;
	elseif (@$post['cookieid'])
		return strcmp($post['cookieid'], $cookieid) == 0;

	return false;
}


/**
 * Return array which maps the 'userid' and/or 'lastuserid' of each user to its HTML representation.
 * For internal user management, corresponding 'handle' and/or 'lasthandle' are required in each element.
 * @param array $useridhandles  User IDs or usernames.
 * @param bool $microdata  Whether to include microdata.
 * @return array  The HTML.
 */
function qa_userids_handles_html($useridhandles, $microdata = false)
{
	require_once QA_INCLUDE_DIR . 'app/users.php';

	if (QA_FINAL_EXTERNAL_USERS) {
		$keyuserids = array();

		foreach ($useridhandles as $useridhandle) {
			if (isset($useridhandle['userid']))
				$keyuserids[$useridhandle['userid']] = true;

			if (isset($useridhandle['lastuserid']))
				$keyuserids[$useridhandle['lastuserid']] = true;
		}
Scott committed
113

Scott committed
114 115
		if (count($keyuserids))
			return qa_get_users_html(array_keys($keyuserids), true, qa_path_to_root(), $microdata);
Scott committed
116

Scott committed
117 118 119 120
		return array();
	} else {
		$usershtml = array();
		$favoritemap = qa_get_favorite_non_qs_map();
Scott committed
121

Scott committed
122 123 124 125 126
		foreach ($useridhandles as $useridhandle) {
			// only add each user to the array once
			$uid = isset($useridhandle['userid']) ? $useridhandle['userid'] : null;
			if ($uid && !isset($usershtml[$uid])) {
				$usershtml[$uid] = qa_get_one_user_html($useridhandle['handle'], $microdata, @$favoritemap['user'][$uid]);
Scott committed
127 128
			}

Scott committed
129 130 131 132 133
			$luid = isset($useridhandle['lastuserid']) ? $useridhandle['lastuserid'] : null;
			if ($luid && !isset($usershtml[$luid])) {
				$usershtml[$luid] = qa_get_one_user_html($useridhandle['lasthandle'], $microdata, @$favoritemap['user'][$luid]);
			}
		}
Scott committed
134

Scott committed
135
		return $usershtml;
Scott committed
136
	}
Scott committed
137
}
Scott committed
138 139


Scott committed
140 141 142 143 144
/**
 * Get an array listing all of the logged in user's favorite items, except their favorited questions (these are excluded because
 * users tend to favorite many more questions than other things.) The top-level array can contain three keys - 'user' for favorited
 * users, 'tag' for tags, 'category' for categories. The next level down has the identifier for each favorited entity in the *key*
 * of the array, and true for its value. If no user is logged in the empty array is returned. The result is cached for future calls.
145
 * @return array
Scott committed
146 147 148 149
 */
function qa_get_favorite_non_qs_map()
{
	global $qa_favorite_non_qs_map;
Scott committed
150

Scott committed
151 152 153
	if (!isset($qa_favorite_non_qs_map)) {
		$qa_favorite_non_qs_map = array();
		$loginuserid = qa_get_logged_in_userid();
Scott committed
154

Scott committed
155 156 157
		if (isset($loginuserid)) {
			require_once QA_INCLUDE_DIR . 'db/selects.php';
			require_once QA_INCLUDE_DIR . 'util/string.php';
Scott committed
158

159
			$favoritenonqs = qa_service('dbselect')->getPendingResult('favoritenonqs', qa_db_user_favorite_non_qs_selectspec($loginuserid));
Scott committed
160

Scott committed
161 162 163 164 165
			foreach ($favoritenonqs as $favorite) {
				switch ($favorite['type']) {
					case QA_ENTITY_USER:
						$qa_favorite_non_qs_map['user'][$favorite['userid']] = true;
						break;
Scott committed
166

Scott committed
167 168 169
					case QA_ENTITY_TAG:
						$qa_favorite_non_qs_map['tag'][qa_strtolower($favorite['tags'])] = true;
						break;
170

Scott committed
171 172 173
					case QA_ENTITY_CATEGORY:
						$qa_favorite_non_qs_map['category'][$favorite['categorybackpath']] = true;
						break;
174
				}
Scott committed
175
			}
Scott committed
176 177
		}
	}
Scott committed
178

Scott committed
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
	return $qa_favorite_non_qs_map;
}


/**
 * Convert textual tag to HTML representation, linked to its tag page.
 * @param string $tag  The tag.
 * @param bool $microdata  Whether to include microdata.
 * @param bool $favorited  Show the tag as favorited.
 * @return string  The tag HTML.
 */
function qa_tag_html($tag, $microdata = false, $favorited = false)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

	$url = qa_path_html('tag/' . $tag);
	$attrs = $microdata ? ' rel="tag"' : '';
	$class = $favorited ? ' qa-tag-favorited' : '';

	return '<a href="' . $url . '"' . $attrs . ' class="qa-tag-link' . $class . '">' . qa_html($tag) . '</a>';
}


/**
 * Given $navcategories retrieved for $categoryid from the database (using qa_db_category_nav_selectspec(...)),
 * return an array of elements from $navcategories for the hierarchy down to $categoryid.
205 206
 * @param array $navcategories
 * @param int $categoryid
Scott committed
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
 * @return array
 */
function qa_category_path($navcategories, $categoryid)
{
	$upcategories = array();

	for ($upcategory = @$navcategories[$categoryid]; isset($upcategory); $upcategory = @$navcategories[$upcategory['parentid']])
		$upcategories[$upcategory['categoryid']] = $upcategory;

	return array_reverse($upcategories, true);
}


/**
 * Given $navcategories retrieved for $categoryid from the database (using qa_db_category_nav_selectspec(...)),
 * return some HTML that shows the category hierarchy down to $categoryid.
223 224
 * @param array $navcategories
 * @param int $categoryid
Scott committed
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
 * @return string
 */
function qa_category_path_html($navcategories, $categoryid)
{
	$categories = qa_category_path($navcategories, $categoryid);

	$html = '';
	foreach ($categories as $category)
		$html .= (strlen($html) ? ' / ' : '') . qa_html($category['title']);

	return $html;
}


/**
 * Given $navcategories retrieved for $categoryid from the database (using qa_db_category_nav_selectspec(...)),
 * return a Q2A request string that represents the category hierarchy down to $categoryid.
242 243
 * @param array $navcategories
 * @param int $categoryid
Scott committed
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
 * @return string
 */
function qa_category_path_request($navcategories, $categoryid)
{
	$categories = qa_category_path($navcategories, $categoryid);

	$request = '';
	foreach ($categories as $category)
		$request .= (strlen($request) ? '/' : '') . $category['tags'];

	return $request;
}


/**
 * Return HTML to use for $ip address, which links to appropriate page with $anchorhtml
260 261
 * @param string $ip
 * @param string|null $anchorhtml
Scott committed
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
 * @return mixed|string
 */
function qa_ip_anchor_html($ip, $anchorhtml = null)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

	if (!strlen($anchorhtml))
		$anchorhtml = qa_html($ip);

	return '<a href="' . qa_path_html('ip/' . $ip) . '" title="' . qa_lang_html_sub('main/ip_address_x', qa_html($ip)) . '" class="qa-ip-link">' . $anchorhtml . '</a>';
}


/**
 * Given $post retrieved from database, return array of mostly HTML to be passed to theme layer.
 * $userid and $cookieid refer to the user *viewing* the page.
 * $usershtml is an array of [user id] => [HTML representation of user] built ahead of time.
 * $dummy is a placeholder (used to be $categories parameter but that's no longer needed)
280
 * $options is an array which sets what is displayed (see qa_post_html_defaults() in /qa-include/app/options.php)
Scott committed
281
 * If something is missing from $post (e.g. ['content']), correponding HTML also omitted.
282 283 284 285 286
 * @param array $post
 * @param mixed $userid
 * @param string $cookieid
 * @param array $usershtml
 * @param null $dummy
Scott committed
287 288 289 290 291 292 293 294
 * @param array $options
 * @return array
 */
function qa_post_html_fields($post, $userid, $cookieid, $usershtml, $dummy, $options = array())
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

	require_once QA_INCLUDE_DIR . 'app/updates.php';
295
	require_once QA_INCLUDE_DIR . 'app/posts.php';
Scott committed
296 297 298 299 300 301 302 303 304

	if (isset($options['blockwordspreg']))
		require_once QA_INCLUDE_DIR . 'util/string.php';

	$fields = array('raw' => $post);

	// Useful stuff used throughout function

	$postid = $post['postid'];
Scott committed
305 306 307
	$isquestion = $post['basetype'] == 'Q';
	$isanswer = $post['basetype'] == 'A';
	$iscomment = $post['basetype'] == 'C';
Scott committed
308 309 310
	$isbyuser = qa_post_is_by_user($post, $userid, $cookieid);
	$anchor = urlencode(qa_anchor($post['basetype'], $postid));
	$elementid = isset($options['elementid']) ? $options['elementid'] : $anchor;
311
	$microdata = qa_opt('use_microdata') && !empty($options['contentview']);
Scott committed
312 313 314 315 316 317
	$isselected = @$options['isselected'];
	$favoritedview = @$options['favoritedview'];
	$favoritemap = $favoritedview ? qa_get_favorite_non_qs_map() : array();

	// High level information

318 319
	$fields['hidden'] = isset($post['hidden']) ? $post['hidden'] : null;
	$fields['queued'] = isset($post['queued']) ? $post['queued'] : null;
Scott committed
320 321 322
	$fields['tags'] = 'id="' . qa_html($elementid) . '"';

	$fields['classes'] = ($isquestion && $favoritedview && @$post['userfavoriteq']) ? 'qa-q-favorited' : '';
323
	if ($isquestion && qa_post_is_closed($post)) {
Scott committed
324
		$fields['classes'] = ltrim($fields['classes'] . ' qa-q-closed');
325
	}
Scott committed
326 327 328

	if ($microdata) {
		if ($isanswer) {
Scott committed
329
			$fields['tags'] .= ' itemprop="suggestedAnswer' . ($isselected ? ' acceptedAnswer' : '') . '" itemscope itemtype="https://schema.org/Answer"';
Scott committed
330 331
		}
		if ($iscomment) {
Scott committed
332
			$fields['tags'] .= ' itemscope itemtype="https://schema.org/Comment"';
Scott committed
333 334 335
		}
	}

Scott committed
336
	// Question-specific stuff (title, URL, tags, answer count, category)
Scott committed
337

Scott committed
338 339 340
	if ($isquestion) {
		if (isset($post['title'])) {
			$fields['url'] = qa_q_path_html($postid, $post['title']);
Scott committed
341

Scott committed
342 343
			if (isset($options['blockwordspreg']))
				$post['title'] = qa_block_words_replace($post['title'], $options['blockwordspreg']);
Scott committed
344

Scott committed
345 346 347 348
			$fields['title'] = qa_html($post['title']);
			if ($microdata) {
				$fields['title'] = '<span itemprop="name">' . $fields['title'] . '</span>';
			}
Scott committed
349

Scott committed
350 351 352
			/*if (isset($post['score'])) // useful for setting match thresholds
				$fields['title'].=' <small>('.$post['score'].')</small>';*/
		}
Scott committed
353

Scott committed
354 355
		if (@$options['tagsview'] && isset($post['tags'])) {
			$fields['q_tags'] = array();
Scott committed
356

Scott committed
357 358 359 360
			$tags = qa_tagstring_to_tags($post['tags']);
			foreach ($tags as $tag) {
				if (isset($options['blockwordspreg']) && count(qa_block_words_match_all($tag, $options['blockwordspreg']))) // skip censored tags
					continue;
Scott committed
361

Scott committed
362
				$fields['q_tags'][] = qa_tag_html($tag, $microdata, @$favoritemap['tag'][qa_strtolower($tag)]);
Scott committed
363 364 365
			}
		}

Scott committed
366 367
		if (@$options['answersview'] && isset($post['acount'])) {
			$fields['answers_raw'] = $post['acount'];
Scott committed
368

Scott committed
369 370
			$fields['answers'] = ($post['acount'] == 1) ? qa_lang_html_sub_split('main/1_answer', '1', '1')
				: qa_lang_html_sub_split('main/x_answers', qa_format_number($post['acount'], 0, true));
Scott committed
371

Scott committed
372 373
			$fields['answer_selected'] = isset($post['selchildid']);
		}
374

Scott committed
375 376
		if (@$options['viewsview'] && isset($post['views'])) {
			$fields['views_raw'] = $post['views'];
Scott committed
377

Scott committed
378 379 380
			$fields['views'] = ($post['views'] == 1) ? qa_lang_html_sub_split('main/1_view', '1', '1') :
				qa_lang_html_sub_split('main/x_views', qa_format_number($post['views'], 0, true));
		}
Scott committed
381

Scott committed
382 383
		if (@$options['categoryview'] && isset($post['categoryname']) && isset($post['categorybackpath'])) {
			$favoriteclass = '';
Scott committed
384

385 386
			if (isset($favoritemap['category']) && !empty($favoritemap['category'])) {
				if (isset($favoritemap['category'][$post['categorybackpath']])) {
Scott committed
387 388 389 390 391 392 393 394
					$favoriteclass = ' qa-cat-favorited';
				} else {
					foreach ($favoritemap['category'] as $categorybackpath => $dummy) {
						if (substr('/' . $post['categorybackpath'], -strlen($categorybackpath)) == $categorybackpath)
							$favoriteclass = ' qa-cat-parent-favorited';
					}
				}
			}
Scott committed
395

Scott committed
396 397 398 399
			$fields['where'] = qa_lang_html_sub_split('main/in_category_x',
				'<a href="' . qa_path_html(@$options['categorypathprefix'] . implode('/', array_reverse(explode('/', $post['categorybackpath'])))) .
				'" class="qa-category-link' . $favoriteclass . '">' . qa_html($post['categoryname']) . '</a>');
		}
Scott committed
400 401
	}

Scott committed
402
	// Answer-specific stuff (selection)
Scott committed
403

Scott committed
404 405
	if ($isanswer) {
		$fields['selected'] = $isselected;
Scott committed
406

Scott committed
407 408
		if ($isselected)
			$fields['select_text'] = qa_lang_html('question/select_text');
Scott committed
409 410
	}

Scott committed
411
	// Post content
Scott committed
412

Scott committed
413 414 415 416 417 418 419 420
	if (@$options['contentview'] && isset($post['content'])) {
		$viewer = qa_load_viewer($post['content'], $post['format']);

		$fields['content'] = $viewer->get_html($post['content'], $post['format'], array(
			'blockwordspreg' => @$options['blockwordspreg'],
			'showurllinks' => @$options['showurllinks'],
			'linksnewwindow' => @$options['linksnewwindow'],
		));
Scott committed
421

Scott committed
422 423 424
		if ($microdata) {
			$fields['content'] = '<div itemprop="text">' . $fields['content'] . '</div>';
		}
Scott committed
425

Scott committed
426 427 428
		// this is for backwards compatibility with any existing links using the old style of anchor
		// that contained the post id only (changed to be valid under W3C specifications)
		$fields['content'] = '<a name="' . qa_html($postid) . '"></a>' . $fields['content'];
Scott committed
429 430
	}

Scott committed
431
	// Voting stuff
Scott committed
432

Scott committed
433 434
	if (@$options['voteview']) {
		$voteview = $options['voteview'];
Scott committed
435

Scott committed
436
		// Calculate raw values and pass through
Scott committed
437

Scott committed
438 439 440 441 442 443 444 445
		if (@$options['ovoteview'] && isset($post['opostid'])) {
			$upvotes = (int)@$post['oupvotes'];
			$downvotes = (int)@$post['odownvotes'];
			$fields['vote_opostid'] = true; // for voters/flaggers layer
		} else {
			$upvotes = (int)@$post['upvotes'];
			$downvotes = (int)@$post['downvotes'];
		}
Scott committed
446

Scott committed
447
		$netvotes = $upvotes - $downvotes;
Scott committed
448

Scott committed
449 450 451
		$fields['upvotes_raw'] = $upvotes;
		$fields['downvotes_raw'] = $downvotes;
		$fields['netvotes_raw'] = $netvotes;
Scott committed
452

Scott committed
453
		// Create HTML versions...
Scott committed
454

Scott committed
455 456
		$upvoteshtml = qa_html(qa_format_number($upvotes, 0, true));
		$downvoteshtml = qa_html(qa_format_number($downvotes, 0, true));
Scott committed
457

Scott committed
458 459 460 461 462 463
		if ($netvotes >= 1)
			$netvotesPrefix = '+';
		elseif ($netvotes <= -1)
			$netvotesPrefix = '&ndash;';
		else
			$netvotesPrefix = '';
Scott committed
464

Scott committed
465 466
		$netvotes = abs($netvotes);
		$netvoteshtml = $netvotesPrefix . qa_html(qa_format_number($netvotes, 0, true));
Scott committed
467

Scott committed
468
		// Pass information on vote viewing
Scott committed
469

Scott committed
470 471 472
		// $voteview will be one of:
		// updown, updown-disabled-page, updown-disabled-level, updown-uponly-level, updown-disabled-approve, updown-uponly-approve
		// net, net-disabled-page, net-disabled-level, net-uponly-level, net-disabled-approve, net-uponly-approve
Scott committed
473

Scott committed
474
		$fields['vote_view'] = (substr($voteview, 0, 6) == 'updown') ? 'updown' : 'net';
Scott committed
475

Scott committed
476
		$fields['vote_on_page'] = strpos($voteview, '-disabled-page') ? 'disabled' : 'enabled';
Scott committed
477

478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
		if ($iscomment) {
			// for comments just show number, no additional text
			$fields['upvotes_view'] = array('prefix' => '', 'data' => $upvoteshtml, 'suffix' => '');
			$fields['downvotes_view'] = array('prefix' => '', 'data' => $downvoteshtml, 'suffix' => '');
			$fields['netvotes_view'] = array('prefix' => '', 'data' => $netvoteshtml, 'suffix' => '');
		} else {
			$fields['upvotes_view'] = $upvotes == 1
				? qa_lang_html_sub_split('main/1_liked', $upvoteshtml, '1')
				: qa_lang_html_sub_split('main/x_liked', $upvoteshtml);
			$fields['downvotes_view'] = $downvotes == 1
				? qa_lang_html_sub_split('main/1_disliked', $downvoteshtml, '1')
				: qa_lang_html_sub_split('main/x_disliked', $downvoteshtml);
			$fields['netvotes_view'] = $netvotes == 1
				? qa_lang_html_sub_split('main/1_vote', $netvoteshtml, '1')
				: qa_lang_html_sub_split('main/x_votes', $netvoteshtml);
		}
Scott committed
494

Scott committed
495 496
		// schema.org microdata - vote display might be formatted (e.g. '2k') so we use meta tag for true count
		if ($microdata) {
497
			$fields['netvotes_view']['suffix'] .= ' <meta itemprop="upvoteCount" content="' . qa_html($upvotes - $downvotes) . '"/>';
Scott committed
498 499 500
			$fields['upvotes_view']['suffix'] .= ' <meta itemprop="upvoteCount" content="' . qa_html($upvotes) . '"/>';
		}

Scott committed
501
		// Voting buttons
Scott committed
502

Scott committed
503 504
		$fields['vote_tags'] = 'id="voting_' . qa_html($postid) . '"';
		$onclick = 'onclick="return qa_vote_click(this);"';
Scott committed
505

Scott committed
506 507
		if ($fields['hidden']) {
			$fields['vote_state'] = 'disabled';
508
			$fields['vote_up_tags'] = 'title="' . qa_lang_html('main/vote_disabled_hidden_post') . '"';
509 510 511 512 513
			$fields['vote_down_tags'] = $fields['vote_up_tags'];

		} elseif ($fields['queued']) {
			$fields['vote_state'] = 'disabled';
			$fields['vote_up_tags'] = 'title="' . qa_lang_html('main/vote_disabled_queued') . '"';
Scott committed
514
			$fields['vote_down_tags'] = $fields['vote_up_tags'];
Scott committed
515

Scott committed
516 517
		} elseif ($isbyuser) {
			$fields['vote_state'] = 'disabled';
518
			$fields['vote_up_tags'] = 'title="' . qa_lang_html('main/vote_disabled_my_post') . '"';
Scott committed
519
			$fields['vote_down_tags'] = $fields['vote_up_tags'];
Scott committed
520

Scott committed
521 522
		} elseif (strpos($voteview, '-disabled-')) {
			$fields['vote_state'] = (@$post['uservote'] > 0) ? 'voted_up_disabled' : ((@$post['uservote'] < 0) ? 'voted_down_disabled' : 'disabled');
Scott committed
523

Scott committed
524 525 526 527 528 529
			if (strpos($voteview, '-disabled-page'))
				$fields['vote_up_tags'] = 'title="' . qa_lang_html('main/vote_disabled_q_page_only') . '"';
			elseif (strpos($voteview, '-disabled-approve'))
				$fields['vote_up_tags'] = 'title="' . qa_lang_html('main/vote_disabled_approve') . '"';
			else
				$fields['vote_up_tags'] = 'title="' . qa_lang_html('main/vote_disabled_level') . '"';
Scott committed
530

Scott committed
531
			$fields['vote_down_tags'] = $fields['vote_up_tags'];
Scott committed
532

Scott committed
533 534 535 536
		} elseif (@$post['uservote'] > 0) {
			$fields['vote_state'] = 'voted_up';
			$fields['vote_up_tags'] = 'title="' . qa_lang_html('main/voted_up_popup') . '" name="' . qa_html('vote_' . $postid . '_0_' . $elementid) . '" ' . $onclick;
			$fields['vote_down_tags'] = ' ';
Scott committed
537

Scott committed
538 539 540 541
		} elseif (@$post['uservote'] < 0) {
			$fields['vote_state'] = 'voted_down';
			$fields['vote_up_tags'] = ' ';
			$fields['vote_down_tags'] = 'title="' . qa_lang_html('main/voted_down_popup') . '" name="' . qa_html('vote_' . $postid . '_0_' . $elementid) . '" ' . $onclick;
Scott committed
542

Scott committed
543 544
		} else {
			$fields['vote_up_tags'] = 'title="' . qa_lang_html('main/vote_up_popup') . '" name="' . qa_html('vote_' . $postid . '_1_' . $elementid) . '" ' . $onclick;
Scott committed
545

Scott committed
546 547 548
			if (strpos($voteview, '-uponly-level')) {
				$fields['vote_state'] = 'up_only';
				$fields['vote_down_tags'] = 'title="' . qa_lang_html('main/vote_disabled_down') . '"';
Scott committed
549

Scott committed
550 551 552
			} elseif (strpos($voteview, '-uponly-approve')) {
				$fields['vote_state'] = 'up_only';
				$fields['vote_down_tags'] = 'title="' . qa_lang_html('main/vote_disabled_down_approve') . '"';
Scott committed
553

Scott committed
554 555 556
			} else {
				$fields['vote_state'] = 'enabled';
				$fields['vote_down_tags'] = 'title="' . qa_lang_html('main/vote_down_popup') . '" name="' . qa_html('vote_' . $postid . '_-1_' . $elementid) . '" ' . $onclick;
Scott committed
557 558
			}
		}
Scott committed
559
	}
Scott committed
560

Scott committed
561
	// Flag count
Scott committed
562

Scott committed
563 564 565 566 567 568 569 570
	if (@$options['flagsview'] && @$post['flagcount']) {
		$fields['flags'] = ($post['flagcount'] == 1) ? qa_lang_html_sub_split('main/1_flag', '1', '1')
			: qa_lang_html_sub_split('main/x_flags', $post['flagcount']);
	}

	// Created when and by whom

	$fields['meta_order'] = qa_lang_html('main/meta_order'); // sets ordering of meta elements which can be language-specific
Scott committed
571

Scott committed
572 573 574 575
	if (@$options['whatview']) {
		$fields['what'] = qa_lang_html($isquestion ? 'main/asked' : ($isanswer ? 'main/answered' : 'main/commented'));

		if (@$options['whatlink'] && strlen(@$options['q_request'])) {
Scott committed
576 577
			$fields['what_url'] = $post['basetype'] == 'Q'
				? qa_path_html($options['q_request'])
Scott committed
578
				: qa_path_html($options['q_request'], array('show' => $postid), null, null, qa_anchor($post['basetype'], $postid));
Scott committed
579 580 581
			if ($microdata) {
				$fields['what_url_tags'] = ' itemprop="url"';
			}
Scott committed
582
		}
Scott committed
583
	}
Scott committed
584

Scott committed
585 586
	if (isset($post['created']) && @$options['whenview']) {
		$fields['when'] = qa_when_to_html($post['created'], @$options['fulldatedays']);
Scott committed
587

Scott committed
588 589 590 591 592
		if ($microdata) {
			$gmdate = gmdate('Y-m-d\TH:i:sO', $post['created']);
			$fields['when']['data'] = '<time itemprop="dateCreated" datetime="' . $gmdate . '" title="' . $gmdate . '">' . $fields['when']['data'] . '</time>';
		}
	}
Scott committed
593

Scott committed
594 595
	if (@$options['whoview']) {
		$fields['who'] = qa_who_to_html($isbyuser, @$post['userid'], $usershtml, @$options['ipview'] ? @inet_ntop(@$post['createip']) : null, $microdata, $post['name']);
Scott committed
596

Scott committed
597 598 599 600
		if (isset($post['points'])) {
			if (@$options['pointsview'])
				$fields['who']['points'] = ($post['points'] == 1) ? qa_lang_html_sub_split('main/1_point', '1', '1')
					: qa_lang_html_sub_split('main/x_points', qa_format_number($post['points'], 0, true));
Scott committed
601

Scott committed
602 603
			if (isset($options['pointstitle']))
				$fields['who']['title'] = qa_get_points_title_html($post['points'], $options['pointstitle']);
Scott committed
604 605
		}

Scott committed
606 607 608
		if (isset($post['level']))
			$fields['who']['level'] = qa_html(qa_user_level_string($post['level']));
	}
Scott committed
609

Scott committed
610 611 612 613 614 615 616
	if (@$options['avatarsize'] > 0) {
		if (QA_FINAL_EXTERNAL_USERS)
			$fields['avatar'] = qa_get_external_avatar_html($post['userid'], $options['avatarsize'], false);
		else
			$fields['avatar'] = qa_get_user_avatar_html(@$post['flags'], @$post['email'], @$post['handle'],
				@$post['avatarblobid'], @$post['avatarwidth'], @$post['avatarheight'], $options['avatarsize']);
	}
Scott committed
617

Scott committed
618 619
	// Updated when and by whom

620 621
	if (@$options['updateview'] && isset($post['updated']) &&
		($post['updatetype'] != QA_UPDATE_SELECTED || $isselected) && // only show selected change if it's still selected
Scott committed
622 623 624
		( // otherwise check if one of these conditions is fulfilled...
			(!isset($post['created'])) || // ... we didn't show the created time (should never happen in practice)
			($post['hidden'] && ($post['updatetype'] == QA_UPDATE_VISIBLE)) || // ... the post was hidden as the last action
625
			(qa_post_is_closed($post) && $post['updatetype'] == QA_UPDATE_CLOSED) || // ... the post was closed as the last action
Scott committed
626 627 628 629 630 631 632 633 634
			(abs($post['updated'] - $post['created']) > 300) || // ... or over 5 minutes passed between create and update times
			($post['lastuserid'] != $post['userid']) // ... or it was updated by a different user
		)
	) {
		switch ($post['updatetype']) {
			case QA_UPDATE_TYPE:
			case QA_UPDATE_PARENT:
				$langstring = 'main/moved';
				break;
Scott committed
635

Scott committed
636 637 638
			case QA_UPDATE_CATEGORY:
				$langstring = 'main/recategorized';
				break;
Scott committed
639

Scott committed
640 641 642
			case QA_UPDATE_VISIBLE:
				$langstring = $post['hidden'] ? 'main/hidden' : 'main/reshown';
				break;
Scott committed
643

Scott committed
644
			case QA_UPDATE_CLOSED:
645
				$langstring = qa_post_is_closed($post) ? 'main/closed' : 'main/reopened';
Scott committed
646
				break;
Scott committed
647

Scott committed
648 649 650
			case QA_UPDATE_TAGS:
				$langstring = 'main/retagged';
				break;
Scott committed
651

Scott committed
652 653 654
			case QA_UPDATE_SELECTED:
				$langstring = 'main/selected';
				break;
Scott committed
655

Scott committed
656 657 658 659
			default:
				$langstring = 'main/edited';
				break;
		}
660

Scott committed
661
		$fields['what_2'] = qa_lang_html($langstring);
Scott committed
662

Scott committed
663 664
		if (@$options['whenview']) {
			$fields['when_2'] = qa_when_to_html($post['updated'], @$options['fulldatedays']);
Scott committed
665

Scott committed
666
			if ($microdata) {
Scott committed
667 668
				$gmdate = gmdate('Y-m-d\TH:i:sO', $post['updated']);
				$fields['when_2']['data'] = '<time itemprop="dateModified" datetime="' . $gmdate . '" title="' . $gmdate . '">' . $fields['when_2']['data'] . '</time>';
Scott committed
669
			}
Scott committed
670
		}
Scott committed
671

Scott committed
672 673 674
		if (isset($post['lastuserid']) && @$options['whoview'])
			$fields['who_2'] = qa_who_to_html(isset($userid) && ($post['lastuserid'] == $userid), $post['lastuserid'], $usershtml, @$options['ipview'] ? @inet_ntop($post['lastip']) : null, false);
	}
Scott committed
675 676


Scott committed
677
	// That's it!
Scott committed
678

Scott committed
679 680
	return $fields;
}
Scott committed
681 682


Scott committed
683 684 685
/**
 * Generate array of mostly HTML representing a message, to be passed to theme layer.
 * @param array $message  The message object (as retrieved from database).
686
 * @param array $options  Viewing options (see qa_message_html_defaults() in /qa-include/app/options.php).
Scott committed
687 688 689 690 691
 * @return array  The HTML.
 */
function qa_message_html_fields($message, $options = array())
{
	require_once QA_INCLUDE_DIR . 'app/users.php';
Scott committed
692

Scott committed
693
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
694

Scott committed
695 696
	$fields = array('raw' => $message);
	$fields['tags'] = 'id="m' . qa_html($message['messageid']) . '"';
Scott committed
697

Scott committed
698 699
	// message content
	$viewer = qa_load_viewer($message['content'], $message['format']);
Scott committed
700

Scott committed
701 702 703 704 705
	$fields['content'] = $viewer->get_html($message['content'], $message['format'], array(
		'blockwordspreg' => @$options['blockwordspreg'],
		'showurllinks' => @$options['showurllinks'],
		'linksnewwindow' => @$options['linksnewwindow'],
	));
Scott committed
706

Scott committed
707 708
	// set ordering of meta elements which can be language-specific
	$fields['meta_order'] = qa_lang_html('main/meta_order');
Scott committed
709

Scott committed
710
	$fields['what'] = qa_lang_html('main/written');
Scott committed
711

Scott committed
712 713 714
	// when it was written
	if (@$options['whenview'])
		$fields['when'] = qa_when_to_html($message['created'], @$options['fulldatedays']);
Scott committed
715

Scott committed
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
	// who wrote it, and their avatar
	if (@$options['towhomview']) {
		// for sent private messages page (i.e. show who message was sent to)
		$fields['who'] = qa_lang_html_sub_split('main/to_x', qa_get_one_user_html($message['tohandle'], false));
		$fields['avatar'] = qa_get_user_avatar_html(@$message['toflags'], @$message['toemail'], @$message['tohandle'],
			@$message['toavatarblobid'], @$message['toavatarwidth'], @$message['toavatarheight'], $options['avatarsize']);
	} else {
		// for everything else (received private messages, wall messages)
		if (@$options['whoview']) {
			$fields['who'] = qa_lang_html_sub_split('main/by_x', qa_get_one_user_html($message['fromhandle'], false));
		}
		if (@$options['avatarsize'] > 0) {
			$fields['avatar'] = qa_get_user_avatar_html(@$message['fromflags'], @$message['fromemail'], @$message['fromhandle'],
				@$message['fromavatarblobid'], @$message['fromavatarwidth'], @$message['fromavatarheight'], $options['avatarsize']);
		}
	}
Scott committed
732

Scott committed
733 734 735 736 737 738 739
	return $fields;
}


/**
 * Generate array of split HTML (prefix, data, suffix) to represent author of post.
 * @param bool $isbyuser True if the current user made the post.
740
 * @param int|null $postuserid The post user's ID.
Scott committed
741 742
 * @param array $usershtml Array of HTML representing usernames.
 * @param string $ip The post user's IP.
Scott committed
743
 * @param bool|string $microdata Whether to include microdata.
Scott committed
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
 * @param string $name The author's username.
 * @return array The HTML.
 */
function qa_who_to_html($isbyuser, $postuserid, $usershtml, $ip = null, $microdata = false, $name = null)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

	if (isset($postuserid) && isset($usershtml[$postuserid])) {
		$whohtml = $usershtml[$postuserid];
	} else {
		if (strlen($name))
			$whohtml = qa_html($name);
		elseif ($isbyuser)
			$whohtml = qa_lang_html('main/me');
		else
			$whohtml = qa_lang_html('main/anonymous');
Scott committed
760

761 762
		if ($microdata) {
			// duplicate HTML from qa_get_one_user_html()
Scott committed
763
			$whohtml = '<span itemprop="author" itemscope itemtype="https://schema.org/Person"><span itemprop="name">' . $whohtml . '</span></span>';
764 765
		}

Scott committed
766 767 768
		if (isset($ip))
			$whohtml = qa_ip_anchor_html($ip, $whohtml);
	}
Scott committed
769

Scott committed
770 771 772 773 774 775 776
	return qa_lang_html_sub_split('main/by_x', $whohtml);
}


/**
 * Generate array of split HTML (prefix, data, suffix) to represent a timestamp, optionally with the full date.
 * @param int $timestamp  Unix timestamp.
777
 * @param int|null $fulldatedays  Number of days after which to show the full date.
Scott committed
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
 * @return array  The HTML.
 */
function qa_when_to_html($timestamp, $fulldatedays)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

	$interval = qa_opt('db_time') - $timestamp;

	if ($interval < 0 || (isset($fulldatedays) && $interval > 86400 * $fulldatedays)) {
		// full style date
		$stampyear = date('Y', $timestamp);
		$thisyear = date('Y', qa_opt('db_time'));

		$dateFormat = qa_lang($stampyear == $thisyear ? 'main/date_format_this_year' : 'main/date_format_other_years');
		$replaceData = array(
			'^day' => date(qa_lang('main/date_day_min_digits') == 2 ? 'd' : 'j', $timestamp),
			'^month' => qa_lang('main/date_month_' . date('n', $timestamp)),
			'^year' => date(qa_lang('main/date_year_digits') == 2 ? 'y' : 'Y', $timestamp),
		);
Scott committed
797

Scott committed
798 799 800
		return array(
			'data' => qa_html(strtr($dateFormat, $replaceData)),
		);
Scott committed
801

Scott committed
802 803 804 805 806 807 808 809 810 811 812 813
	} else {
		// ago-style date
		return qa_lang_html_sub_split('main/x_ago', qa_html(qa_time_to_string($interval)));
	}
}


/**
 * Return array of mostly HTML to be passed to theme layer, to *link* to an answer, comment or edit on
 * $question, as retrieved from database, with fields prefixed 'o' for the answer, comment or edit.
 * $userid, $cookieid, $usershtml, $options are passed through to qa_post_html_fields(). If $question['opersonal']
 * is set and true then the item is displayed with its personal relevance to the user (for user updates page).
814 815 816 817 818 819
 * @param array $question
 * @param mixed $userid
 * @param string $cookieid
 * @param array $usershtml
 * @param null $dummy
 * @param array $options
Scott committed
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
 * @return array
 */
function qa_other_to_q_html_fields($question, $userid, $cookieid, $usershtml, $dummy, $options)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

	require_once QA_INCLUDE_DIR . 'app/updates.php';

	$fields = qa_post_html_fields($question, $userid, $cookieid, $usershtml, null, $options);

	switch ($question['obasetype'] . '-' . @$question['oupdatetype']) {
		case 'Q-':
			$langstring = 'main/asked';
			break;

		case 'Q-' . QA_UPDATE_VISIBLE:
			if (@$question['opersonal'])
				$langstring = $question['hidden'] ? 'misc/your_q_hidden' : 'misc/your_q_reshown';
			else
				$langstring = $question['hidden'] ? 'main/hidden' : 'main/reshown';
			break;
Scott committed
841

Scott committed
842
		case 'Q-' . QA_UPDATE_CLOSED:
843
			$isClosed = qa_post_is_closed($question);
Scott committed
844
			if (@$question['opersonal'])
845
				$langstring = $isClosed ? 'misc/your_q_closed' : 'misc/your_q_reopened';
Scott committed
846
			else
847
				$langstring = $isClosed ? 'main/closed' : 'main/reopened';
Scott committed
848
			break;
Scott committed
849

Scott committed
850 851 852
		case 'Q-' . QA_UPDATE_TAGS:
			$langstring = @$question['opersonal'] ? 'misc/your_q_retagged' : 'main/retagged';
			break;
Scott committed
853

Scott committed
854 855 856
		case 'Q-' . QA_UPDATE_CATEGORY:
			$langstring = @$question['opersonal'] ? 'misc/your_q_recategorized' : 'main/recategorized';
			break;
Scott committed
857

Scott committed
858 859 860
		case 'A-':
			$langstring = @$question['opersonal'] ? 'misc/your_q_answered' : 'main/answered';
			break;
Scott committed
861

Scott committed
862 863 864
		case 'A-' . QA_UPDATE_SELECTED:
			$langstring = @$question['opersonal'] ? 'misc/your_a_selected' : 'main/answer_selected';
			break;
Scott committed
865

Scott committed
866 867 868 869 870 871
		case 'A-' . QA_UPDATE_VISIBLE:
			if (@$question['opersonal'])
				$langstring = $question['ohidden'] ? 'misc/your_a_hidden' : 'misc/your_a_reshown';
			else
				$langstring = $question['ohidden'] ? 'main/hidden' : 'main/answer_reshown';
			break;
Scott committed
872

Scott committed
873 874 875
		case 'A-' . QA_UPDATE_CONTENT:
			$langstring = @$question['opersonal'] ? 'misc/your_a_edited' : 'main/answer_edited';
			break;
Scott committed
876

Scott committed
877 878 879
		case 'Q-' . QA_UPDATE_FOLLOWS:
			$langstring = @$question['opersonal'] ? 'misc/your_a_questioned' : 'main/asked_related_q';
			break;
Scott committed
880

Scott committed
881 882 883
		case 'C-':
			$langstring = 'main/commented';
			break;
Scott committed
884

Scott committed
885 886 887
		case 'C-' . QA_UPDATE_C_FOR_Q:
			$langstring = @$question['opersonal'] ? 'misc/your_q_commented' : 'main/commented';
			break;
Scott committed
888

Scott committed
889 890 891
		case 'C-' . QA_UPDATE_C_FOR_A:
			$langstring = @$question['opersonal'] ? 'misc/your_a_commented' : 'main/commented';
			break;
Scott committed
892

Scott committed
893 894 895
		case 'C-' . QA_UPDATE_FOLLOWS:
			$langstring = @$question['opersonal'] ? 'misc/your_c_followed' : 'main/commented';
			break;
Scott committed
896

Scott committed
897 898 899
		case 'C-' . QA_UPDATE_TYPE:
			$langstring = @$question['opersonal'] ? 'misc/your_c_moved' : 'main/comment_moved';
			break;
Scott committed
900

Scott committed
901 902 903
		case 'C-' . QA_UPDATE_VISIBLE:
			if (@$question['opersonal'])
				$langstring = $question['ohidden'] ? 'misc/your_c_hidden' : 'misc/your_c_reshown';
Scott committed
904
			else
Scott committed
905 906
				$langstring = $question['ohidden'] ? 'main/hidden' : 'main/comment_reshown';
			break;
Scott committed
907

Scott committed
908 909 910
		case 'C-' . QA_UPDATE_CONTENT:
			$langstring = @$question['opersonal'] ? 'misc/your_c_edited' : 'main/comment_edited';
			break;
Scott committed
911

Scott committed
912 913 914 915 916
		case 'Q-' . QA_UPDATE_CONTENT:
		default:
			$langstring = @$question['opersonal'] ? 'misc/your_q_edited' : 'main/edited';
			break;
	}
Scott committed
917

Scott committed
918
	$fields['what'] = qa_lang_html($langstring);
Scott committed
919

Scott committed
920 921
	if (@$question['opersonal'])
		$fields['what_your'] = true;
Scott committed
922

Scott committed
923
	if ($question['obasetype'] != 'Q' || @$question['oupdatetype'] == QA_UPDATE_FOLLOWS)
Scott committed
924
		$fields['what_url'] = qa_q_path_html($question['postid'], $question['title'], false, $question['obasetype'], $question['opostid']);
Scott committed
925

Scott committed
926 927
	if (@$options['contentview'] && !empty($question['ocontent'])) {
		$viewer = qa_load_viewer($question['ocontent'], $question['oformat']);
Scott committed
928

Scott committed
929 930 931 932 933 934
		$fields['content'] = $viewer->get_html($question['ocontent'], $question['oformat'], array(
			'blockwordspreg' => @$options['blockwordspreg'],
			'showurllinks' => @$options['showurllinks'],
			'linksnewwindow' => @$options['linksnewwindow'],
		));
	}
Scott committed
935

Scott committed
936 937
	if (@$options['whenview'])
		$fields['when'] = qa_when_to_html($question['otime'], @$options['fulldatedays']);
Scott committed
938

Scott committed
939 940
	if (@$options['whoview']) {
		$isbyuser = qa_post_is_by_user(array('userid' => $question['ouserid'], 'cookieid' => @$question['ocookieid']), $userid, $cookieid);
Scott committed
941

Scott committed
942 943 944 945 946
		$fields['who'] = qa_who_to_html($isbyuser, $question['ouserid'], $usershtml, @$options['ipview'] ? @inet_ntop(@$question['oip']) : null, false, @$question['oname']);
		if (isset($question['opoints'])) {
			if (@$options['pointsview'])
				$fields['who']['points'] = ($question['opoints'] == 1) ? qa_lang_html_sub_split('main/1_point', '1', '1')
					: qa_lang_html_sub_split('main/x_points', qa_format_number($question['opoints'], 0, true));
Scott committed
947

Scott committed
948 949
			if (isset($options['pointstitle']))
				$fields['who']['title'] = qa_get_points_title_html($question['opoints'], $options['pointstitle']);
Scott committed
950
		}
951

Scott committed
952 953
		if (isset($question['olevel']))
			$fields['who']['level'] = qa_html(qa_user_level_string($question['olevel']));
Scott committed
954 955
	}

Scott committed
956 957 958 959 960
	unset($fields['flags']);
	if (@$options['flagsview'] && @$question['oflagcount']) {
		$fields['flags'] = ($question['oflagcount'] == 1) ? qa_lang_html_sub_split('main/1_flag', '1', '1')
			: qa_lang_html_sub_split('main/x_flags', $question['oflagcount']);
	}
Scott committed
961

Scott committed
962 963 964 965 966 967 968 969
	unset($fields['avatar']);
	if (@$options['avatarsize'] > 0) {
		if (QA_FINAL_EXTERNAL_USERS)
			$fields['avatar'] = qa_get_external_avatar_html($question['ouserid'], $options['avatarsize'], false);
		else
			$fields['avatar'] = qa_get_user_avatar_html($question['oflags'], $question['oemail'], $question['ohandle'],
				$question['oavatarblobid'], $question['oavatarwidth'], $question['oavatarheight'], $options['avatarsize']);
	}
Scott committed
970

Scott committed
971 972 973 974 975 976 977
	return $fields;
}


/**
 * Based on the elements in $question, return HTML to be passed to theme layer to link
 * to the question, or to an associated answer, comment or edit.
978 979 980 981 982 983
 * @param array $question
 * @param mixed $userid
 * @param string $cookieid
 * @param array $usershtml
 * @param null $dummy
 * @param array $options
Scott committed
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
 * @return array
 */
function qa_any_to_q_html_fields($question, $userid, $cookieid, $usershtml, $dummy, $options)
{
	if (isset($question['opostid']))
		$fields = qa_other_to_q_html_fields($question, $userid, $cookieid, $usershtml, null, $options);
	else
		$fields = qa_post_html_fields($question, $userid, $cookieid, $usershtml, null, $options);

	return $fields;
}


/**
 * Each element in $questions represents a question and optional associated answer, comment or edit, as retrieved from database.
 * Return it sorted by the date appropriate for each element, without removing duplicate references to the same question.
1000 1001
 * @param array $questions
 * @return array
Scott committed
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
 */
function qa_any_sort_by_date($questions)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

	require_once QA_INCLUDE_DIR . 'util/sort.php';

	foreach ($questions as $key => $question) // collect information about action referenced by each $question
		$questions[$key]['sort'] = -(isset($question['opostid']) ? $question['otime'] : $question['created']);

	qa_sort_by($questions, 'sort');

	return $questions;
}


/**
 * Each element in $questions represents a question and optional associated answer, comment or edit, as retrieved from database.
 * Return it sorted by the date appropriate for each element, and keep only the first item related to each question.
1021
 * @param array $questions
Scott committed
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
 * @return array
 */
function qa_any_sort_and_dedupe($questions)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

	require_once QA_INCLUDE_DIR . 'util/sort.php';

	foreach ($questions as $key => $question) { // collect information about action referenced by each $question
		if (isset($question['opostid'])) {
			$questions[$key]['_time'] = $question['otime'];
			$questions[$key]['_type'] = $question['obasetype'];
			$questions[$key]['_userid'] = @$question['ouserid'];
		} else {
			$questions[$key]['_time'] = $question['created'];
			$questions[$key]['_type'] = 'Q';
			$questions[$key]['_userid'] = $question['userid'];
		}
Scott committed
1040

Scott committed
1041 1042 1043
		$questions[$key]['sort'] = -$questions[$key]['_time'];
	}
	qa_sort_by($questions, 'sort');
Scott committed
1044

Scott committed
1045 1046 1047
	$keepquestions = array(); // now remove duplicate references to same question
	foreach ($questions as $question) { // going in order from most recent to oldest
		$laterquestion = @$keepquestions[$question['postid']];
Scott committed
1048

Scott committed
1049 1050 1051
		if (isset($laterquestion)) {
			// the two events were within 5 minutes of each other
			$close_events = abs($laterquestion['_time'] - $question['_time']) < 300;
Scott committed
1052

Scott committed
1053 1054 1055 1056 1057
			$later_edit =
				@$laterquestion['oupdatetype'] &&  // the more recent reference was an edit
				!@$question['oupdatetype'] &&  // this is not an edit
				$laterquestion['_type'] == $question['_type'] &&  // the same part (Q/A/C) is referenced here
				$laterquestion['_userid'] == $question['_userid'];  // the same user made the later edit
Scott committed
1058

Scott committed
1059 1060
			// this question (in an update list) is personal to the user, but the other one was not
			$this_personal = @$question['opersonal'] && !@$laterquestion['opersonal'];
Scott committed
1061

Scott committed
1062 1063 1064 1065
			if ($close_events && ($later_edit || $this_personal)) {
				// Remove any previous instance of the post to force a new position
				unset($keepquestions[$question['postid']]);
				$keepquestions[$question['postid']] = $question;
Scott committed
1066
			}
Scott committed
1067 1068 1069
		} else  // keep this reference if there is no more recent one
			$keepquestions[$question['postid']] = $question;
	}
Scott committed
1070

Scott committed
1071 1072 1073 1074 1075 1076 1077
	return $keepquestions;
}


/**
 * Each element in $questions represents a question and optional associated answer, comment or edit, as retrieved from database.
 * Return an array of elements (userid,handle) for the appropriate user for each element.
1078
 * @param array $questions
Scott committed
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
 * @return array
 */
function qa_any_get_userids_handles($questions)
{
	$userids_handles = array();

	foreach ($questions as $question) {
		if (isset($question['opostid'])) {
			$userids_handles[] = array(
				'userid' => @$question['ouserid'],
				'handle' => @$question['ohandle'],
			);
		} else {
			$userids_handles[] = array(
				'userid' => @$question['userid'],
				'handle' => @$question['handle'],
			);
		}
Scott committed
1097 1098
	}

Scott committed
1099 1100 1101 1102 1103 1104 1105 1106
	return $userids_handles;
}


/**
 * Return $html with any URLs converted into links (with nofollow and in a new window if $newwindow).
 * Closing parentheses/brackets are removed from the link if they don't have a matching opening one. This avoids creating
 * incorrect URLs from (http://www.question2answer.org) but allow URLs such as http://www.wikipedia.org/Computers_(Software)
1107
 * @param string $html
Scott committed
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
 * @param bool $newwindow
 * @return mixed
 */
function qa_html_convert_urls($html, $newwindow = false)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

	$uc = 'a-z\x{00a1}-\x{ffff}';
	$url_regex = '#\b((?:https?|ftp)://(?:[0-9' . $uc . '][0-9' . $uc . '-]*\.)+[' . $uc . ']{2,}(?::\d{2,5})?(?:/(?:[^\s<>]*[^\s<>\.])?)?)#iu';

	// get matches and their positions
	if (preg_match_all($url_regex, $html, $matches, PREG_OFFSET_CAPTURE)) {
		$brackets = array(
			')' => '(',
			'}' => '{',
			']' => '[',
		);
Scott committed
1125

Scott committed
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
		// loop backwards so we substitute correctly
		for ($i = count($matches[1]) - 1; $i >= 0; $i--) {
			$match = $matches[1][$i];
			$text_url = $match[0];
			$removed = '';
			$lastch = substr($text_url, -1);

			// exclude bracket from link if no matching bracket
			while (array_key_exists($lastch, $brackets)) {
				$open_char = $brackets[$lastch];
				$num_open = substr_count($text_url, $open_char);
				$num_close = substr_count($text_url, $lastch);

				if ($num_close == $num_open + 1) {
					$text_url = substr($text_url, 0, -1);
					$removed = $lastch . $removed;
					$lastch = substr($text_url, -1);
				} else
					break;
			}
Scott committed
1146

Scott committed
1147 1148 1149
			$target = $newwindow ? ' target="_blank"' : '';
			$replace = '<a href="' . $text_url . '" rel="nofollow"' . $target . '>' . $text_url . '</a>' . $removed;
			$html = substr_replace($html, $replace, $match[1], strlen($match[0]));
Scott committed
1150 1151 1152
		}
	}

Scott committed
1153 1154 1155 1156 1157 1158
	return $html;
}


/**
 * Return HTML representation of $url (if it appears to be an URL), linked with nofollow and in a new window if $newwindow
1159
 * @param string $url
Scott committed
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
 * @param bool $newwindow
 * @return mixed|string
 */
function qa_url_to_html_link($url, $newwindow = false)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

	if (is_numeric(strpos($url, '.'))) {
		$linkurl = $url;
		if (!is_numeric(strpos($linkurl, ':/')))
			$linkurl = 'http://' . $linkurl;

		return '<a href="' . qa_html($linkurl) . '" rel="nofollow"' . ($newwindow ? ' target="_blank"' : '') . '>' . qa_html($url) . '</a>';

	} else
		return qa_html($url);
}


/**
 * Return $htmlmessage with ^1...^6 substituted for links to log in or register or confirm email and come back to $topage with $params
1181 1182 1183
 * @param string $htmlmessage
 * @param string|null $topage
 * @param string|null $params
Scott committed
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
 * @return string
 */
function qa_insert_login_links($htmlmessage, $topage = null, $params = null)
{
	require_once QA_INCLUDE_DIR . 'app/users.php';

	$userlinks = qa_get_login_links(qa_path_to_root(), isset($topage) ? qa_path($topage, $params, '') : null);

	return strtr(
		$htmlmessage,

		array(
			'^1' => empty($userlinks['login']) ? '' : '<a href="' . qa_html($userlinks['login']) . '">',
			'^2' => empty($userlinks['login']) ? '' : '</a>',
			'^3' => empty($userlinks['register']) ? '' : '<a href="' . qa_html($userlinks['register']) . '">',
			'^4' => empty($userlinks['register']) ? '' : '</a>',
			'^5' => empty($userlinks['confirm']) ? '' : '<a href="' . qa_html($userlinks['confirm']) . '">',
			'^6' => empty($userlinks['confirm']) ? '' : '</a>',
		)
	);
}


/**
 * Return structure to pass through to theme layer to show linked page numbers for $request.
 * Q2A uses offset-based paging, i.e. pages are referenced in the URL by a 'start' parameter.
 * $start is current offset, there are $pagesize items per page and $count items in total
 * (unless $hasmore is true in which case there are at least $count items).
 * Show links to $prevnext pages before and after this one and include $params in the URLs.
1213 1214 1215 1216 1217
 * @param string $request
 * @param int $start
 * @param int $pagesize
 * @param int $count
 * @param int $prevnext
Scott committed
1218 1219
 * @param array $params
 * @param bool $hasmore
1220
 * @param string|null $anchor
Scott committed
1221 1222 1223 1224 1225 1226 1227
 * @return array|null
 */
function qa_html_page_links($request, $start, $pagesize, $count, $prevnext, $params = array(), $hasmore = false, $anchor = null)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

	$thispage = 1 + floor($start / $pagesize);
1228
	$lastpage = ceil(min((int)$count, 1 + QA_MAX_LIMIT_START) / $pagesize);
Scott committed
1229

Scott committed
1230
	if ($thispage > 1 || $lastpage > $thispage) {
Scott committed
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
		$links = array('label' => qa_lang_html('main/page_label'), 'items' => array());

		$keypages[1] = true;

		for ($page = max(2, min($thispage, $lastpage) - $prevnext); $page <= min($thispage + $prevnext, $lastpage); $page++)
			$keypages[$page] = true;

		$keypages[$lastpage] = true;

		if ($thispage > 1) {
			$links['items'][] = array(
				'type' => 'prev',
				'label' => qa_lang_html('main/page_prev'),
				'page' => $thispage - 1,
				'ellipsis' => false,
1246
			);
Scott committed
1247
		}
Scott committed
1248

Scott committed
1249 1250 1251 1252 1253 1254
		foreach (array_keys($keypages) as $page) {
			$links['items'][] = array(
				'type' => ($page == $thispage) ? 'this' : 'jump',
				'label' => $page,
				'page' => $page,
				'ellipsis' => (($page < $lastpage) || $hasmore) && (!isset($keypages[$page + 1])),
Scott committed
1255
			);
Scott committed
1256
		}
Scott committed
1257

Scott committed
1258 1259 1260 1261 1262 1263 1264
		if ($thispage < $lastpage) {
			$links['items'][] = array(
				'type' => 'next',
				'label' => qa_lang_html('main/page_next'),
				'page' => $thispage + 1,
				'ellipsis' => false,
			);
1265
		}
Scott committed
1266 1267 1268 1269 1270 1271

		foreach ($links['items'] as $key => $link) {
			if ($link['page'] != $thispage) {
				$params['start'] = $pagesize * ($link['page'] - 1);
				$links['items'][$key]['url'] = qa_path_html($request, $params, null, null, $anchor);
			}
1272
		}
Scott committed
1273

Scott committed
1274 1275
	} else
		$links = null;
Scott committed
1276

Scott committed
1277 1278
	return $links;
}
Scott committed
1279 1280


Scott committed
1281 1282 1283 1284
/**
 * Return HTML that suggests browsing all questions (in the category specified by $categoryrequest, if
 * it's not null) and also popular tags if $usingtags is true
 * @param bool $usingtags
1285 1286
 * @param string|null $categoryrequest
 * @return string
Scott committed
1287 1288 1289 1290
 */
function qa_html_suggest_qs_tags($usingtags = false, $categoryrequest = null)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1291

Scott committed
1292
	$hascategory = strlen($categoryrequest);
Scott committed
1293

Scott committed
1294 1295
	$htmlmessage = $hascategory ? qa_lang_html('main/suggest_category_qs') :
		($usingtags ? qa_lang_html('main/suggest_qs_tags') : qa_lang_html('main/suggest_qs'));
Scott committed
1296

Scott committed
1297 1298
	return strtr(
		$htmlmessage,
Scott committed
1299

Scott committed
1300 1301 1302 1303 1304 1305 1306 1307
		array(
			'^1' => '<a href="' . qa_path_html('questions' . ($hascategory ? ('/' . $categoryrequest) : '')) . '">',
			'^2' => '</a>',
			'^3' => '<a href="' . qa_path_html('tags') . '">',
			'^4' => '</a>',
		)
	);
}
Scott committed
1308 1309


Scott committed
1310 1311
/**
 * Return HTML that suggest getting things started by asking a question, in $categoryid if not null
1312 1313
 * @param int|null $categoryid
 * @return string
Scott committed
1314
 */
Félicie committed
1315 1316 1317
// function qa_html_suggest_ask($categoryid = null)
// {
// 	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1318

Félicie committed
1319
// 	$htmlmessage = qa_lang_html('main/suggest_ask');
Scott committed
1320

Félicie committed
1321 1322
// 	return strtr(
// 		$htmlmessage,
Scott committed
1323

Félicie committed
1324 1325 1326 1327 1328 1329
// 		array(
// 			'^1' => '<a href="' . qa_path_html('ask', strlen($categoryid) ? array('cat' => $categoryid) : null) . '">',
// 			'^2' => '</a>',
// 		)
// 	);
// }
Scott committed
1330 1331 1332 1333 1334


/**
 * Return the navigation structure for the category hierarchical menu, with $selectedid selected,
 * and links beginning with $pathprefix, and showing question counts if $showqcount
1335 1336
 * @param array $categories
 * @param int|null $selectedid
Scott committed
1337 1338
 * @param string $pathprefix
 * @param bool $showqcount
1339 1340
 * @param array|null $pathparams
 * @return array
Scott committed
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
 */
function qa_category_navigation($categories, $selectedid = null, $pathprefix = '', $showqcount = true, $pathparams = null)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

	$parentcategories = array();

	foreach ($categories as $category)
		$parentcategories[$category['parentid']][] = $category;

	$selecteds = qa_category_path($categories, $selectedid);
	$favoritemap = qa_get_favorite_non_qs_map();

	return qa_category_navigation_sub($parentcategories, null, $selecteds, $pathprefix, $showqcount, $pathparams, $favoritemap);
}


/**
 * Recursion function used by qa_category_navigation(...) to build hierarchical category menu.
1360 1361 1362 1363 1364 1365 1366 1367
 * @param array $parentcategories
 * @param int|null $parentid
 * @param array $selecteds
 * @param string $pathprefix
 * @param bool $showqcount
 * @param array $pathparams
 * @param array|null $favoritemap
 * @return array
Scott committed
1368 1369 1370 1371 1372 1373 1374
 */
function qa_category_navigation_sub($parentcategories, $parentid, $selecteds, $pathprefix, $showqcount, $pathparams, $favoritemap = null)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

	$navigation = array();

1375 1376 1377 1378 1379 1380 1381 1382
	// if (!isset($parentid)) {
	// 	$navigation['all'] = array(
	// 		'url' => qa_path_html($pathprefix, $pathparams),
	// 		'label' => qa_lang_html('main/all_categories'),
	// 		'selected' => !count($selecteds),
	// 		'categoryid' => null,
	// 	);
	// }
Scott committed
1383

Scott committed
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
	if (isset($parentcategories[$parentid])) {
		foreach ($parentcategories[$parentid] as $category) {
			$navigation[qa_html($category['tags'])] = array(
				'url' => qa_path_html($pathprefix . $category['tags'], $pathparams),
				'label' => qa_html($category['title']),
				'popup' => qa_html(@$category['content']),
				'selected' => isset($selecteds[$category['categoryid']]),
				'note' => $showqcount ? ('(' . qa_html(qa_format_number($category['qcount'], 0, true)) . ')') : null,
				'subnav' => qa_category_navigation_sub($parentcategories, $category['categoryid'], $selecteds,
					$pathprefix . $category['tags'] . '/', $showqcount, $pathparams, $favoritemap),
				'categoryid' => $category['categoryid'],
				'favorited' => @$favoritemap['category'][$category['backpath']],
			);
		}
	}
Scott committed
1399

Scott committed
1400 1401
	return $navigation;
}
Scott committed
1402 1403


Scott committed
1404 1405
/**
 * Return the sub navigation structure for user listing pages
1406
 * @return array|null
Scott committed
1407 1408 1409 1410 1411 1412
 */
function qa_users_sub_navigation()
{
	if (QA_FINAL_EXTERNAL_USERS) {
		return null;
	}
Scott committed
1413

Scott committed
1414
	$menuItems = array();
Scott committed
1415

Scott committed
1416 1417 1418
	$moderatorPlus = qa_get_logged_in_level() >= QA_USER_LEVEL_MODERATOR;
	$showNewUsersPage = !qa_user_permit_error('permit_view_new_users_page');
	$showSpecialUsersPage = !qa_user_permit_error('permit_view_special_users_page');
Scott committed
1419

Scott committed
1420 1421 1422 1423 1424 1425 1426
	if ($moderatorPlus || $showNewUsersPage || $showSpecialUsersPage) {
		// We want to show this item when more than one item should be displayed
		$menuItems['users$'] = array(
			'label' => qa_lang_html('main/highest_users'),
			'url' => qa_path_html('users'),
		);
	}
Scott committed
1427

1428 1429 1430 1431 1432 1433
	if ($showNewUsersPage) {
		$menuItems['users/new'] = array(
			'label' => qa_lang_html('main/newest_users'),
			'url' => qa_path_html('users/new'),
		);
	}
Scott committed
1434

Scott committed
1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
	if ($showSpecialUsersPage) {
		$menuItems['users/special'] = array(
			'label' => qa_lang('users/special_users'),
			'url' => qa_path_html('users/special'),
		);
	}

	if ($moderatorPlus) {
		$menuItems['users/blocked'] = array(
			'label' => qa_lang('users/blocked_users'),
			'url' => qa_path_html('users/blocked'),
		);
	}

	return $menuItems;
}


/**
 * Return the sub navigation structure for navigating between the different pages relating to a user
1455 1456
 * @param string $handle
 * @param string $selected
Scott committed
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524
 * @param bool $ismyuser
 * @return array
 */
function qa_user_sub_navigation($handle, $selected, $ismyuser = false)
{
	$navigation = array(
		'profile' => array(
			'label' => qa_lang_html_sub('profile/user_x', qa_html($handle)),
			'url' => qa_path_html('user/' . $handle),
		),

		'account' => array(
			'label' => qa_lang_html('misc/nav_my_details'),
			'url' => qa_path_html('account'),
		),

		'favorites' => array(
			'label' => qa_lang_html('misc/nav_my_favorites'),
			'url' => qa_path_html('favorites'),
		),

		'wall' => array(
			'label' => qa_lang_html('misc/nav_user_wall'),
			'url' => qa_path_html('user/' . $handle . '/wall'),
		),

		'messages' => array(
			'label' => qa_lang_html('misc/nav_user_pms'),
			'url' => qa_path_html('messages'),
		),

		'activity' => array(
			'label' => qa_lang_html('misc/nav_user_activity'),
			'url' => qa_path_html('user/' . $handle . '/activity'),
		),

		'questions' => array(
			'label' => qa_lang_html('misc/nav_user_qs'),
			'url' => qa_path_html('user/' . $handle . '/questions'),
		),

		'answers' => array(
			'label' => qa_lang_html('misc/nav_user_as'),
			'url' => qa_path_html('user/' . $handle . '/answers'),
		),
	);

	if (isset($navigation[$selected]))
		$navigation[$selected]['selected'] = true;

	if (QA_FINAL_EXTERNAL_USERS || !qa_opt('allow_user_walls'))
		unset($navigation['wall']);

	if (QA_FINAL_EXTERNAL_USERS || !$ismyuser)
		unset($navigation['account']);

	if (!$ismyuser)
		unset($navigation['favorites']);

	if (QA_FINAL_EXTERNAL_USERS || !$ismyuser || !qa_opt('allow_private_messages') || !qa_opt('show_message_history'))
		unset($navigation['messages']);

	return $navigation;
}


/**
 * Return the sub navigation structure for private message pages
1525
 * @deprecated 1.8.0 This menu is no longer used.
1526
 * @param string|null $selected
Scott committed
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
 * @return array
 */
function qa_messages_sub_navigation($selected = null)
{
	$navigation = array(
		'inbox' => array(
			'label' => qa_lang_html('misc/inbox'),
			'url' => qa_path_html('messages'),
		),

		'outbox' => array(
			'label' => qa_lang_html('misc/outbox'),
			'url' => qa_path_html('messages/sent'),
		),
	);

	if (isset($navigation[$selected]))
		$navigation[$selected]['selected'] = true;

	return $navigation;
}


/**
 * Return the sub navigation structure for user account pages.
 * @deprecated Deprecated from 1.6.3; use `qa_user_sub_navigation()` instead.
 */
function qa_account_sub_navigation()
{
	return array(
		'account' => array(
			'label' => qa_lang_html('misc/nav_my_details'),
			'url' => qa_path_html('account'),
		),

		'favorites' => array(
			'label' => qa_lang_html('misc/nav_my_favorites'),
			'url' => qa_path_html('favorites'),
		),
	);
}


/**
 * Return the url for $page retrieved from the database
1572
 * @param array $page
Scott committed
1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
 * @return string
 */
function qa_custom_page_url($page)
{
	return ($page['flags'] & QA_PAGE_FLAGS_EXTERNAL)
		? (is_numeric(strpos($page['tags'], '://')) ? $page['tags'] : qa_path_to_root() . $page['tags'])
		: qa_path($page['tags']);
}


/**
 * Add an element to the $navigation array corresponding to $page retrieved from the database
1585 1586
 * @param array $navigation
 * @param array $page
Scott committed
1587 1588 1589
 */
function qa_navigation_add_page(&$navigation, $page)
{
1590
	if (!isset($page['permit']) || !qa_permit_value_error($page['permit'], qa_get_logged_in_userid(), qa_get_logged_in_level(), qa_get_logged_in_flags())) {
Scott committed
1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605
		$url = qa_custom_page_url($page);

		$navigation[($page['flags'] & QA_PAGE_FLAGS_EXTERNAL) ? ('custom-' . $page['pageid']) : ($page['tags'] . '$')] = array(
			'url' => qa_html($url),
			'label' => qa_html($page['title']),
			'opposite' => ($page['nav'] == 'O'),
			'target' => ($page['flags'] & QA_PAGE_FLAGS_NEW_WINDOW) ? '_blank' : null,
			'selected' => ($page['flags'] & QA_PAGE_FLAGS_EXTERNAL) && (($url == qa_path(qa_request())) || ($url == qa_self_html())),
		);
	}
}


/**
 * Convert an admin option for matching into a threshold for the score given by database search
1606
 * @param int $match
Scott committed
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
 * @return int
 */
function qa_match_to_min_score($match)
{
	return 10 - 2 * $match;
}


/**
 * Adds JavaScript to the page to handle toggling of form fields based on other fields.
 * @param array $qa_content  Page content array.
 * @param array $effects  List of rules for element toggling, with the structure:
 *   array('target1' => 'source1', 'target2' => 'source2', ...)
 *   When the source expression is true, the DOM element ID represented by target is shown. The
 *   source can be a combination of ID as a JS expression.
 */
function qa_set_display_rules(&$qa_content, $effects)
{
	$keysourceids = array();
	$jsVarRegex = '/[A-Za-z_][A-Za-z0-9_]*/';

	// extract all JS variable names in all sources
	foreach ($effects as $target => $sources) {
		if (preg_match_all($jsVarRegex, $sources, $matches)) {
			foreach ($matches[0] as $element) {
				if (!in_array($element, $keysourceids))
					$keysourceids[] = $element;
			}
Scott committed
1635
		}
Scott committed
1636
	}
Scott committed
1637

Scott committed
1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
	$funcOrd = isset($qa_content['script_lines']) ? count($qa_content['script_lines']) : 0;
	$function = "qa_display_rule_$funcOrd";
	$optVar = "qa_optids_$funcOrd";

	// set up variables
	$funcscript = array("var $optVar = " . json_encode($keysourceids) . ";");

	// check and set all display rules
	$funcscript[] = "function {$function}(first) {";
	$funcscript[] = "\tvar opts = {};";
	$funcscript[] = "\tfor (var i = 0; i < {$optVar}.length; i++) {";
	$funcscript[] = "\t\tvar e = document.getElementById({$optVar}[i]);";
	$funcscript[] = "\t\topts[{$optVar}[i]] = e && (e.checked || (e.options && e.options[e.selectedIndex].value));";
	$funcscript[] = "\t}";
	foreach ($effects as $target => $sources) {
		$sourcesobj = preg_replace($jsVarRegex, 'opts.$0', $sources);
		$funcscript[] = "\tqa_display_rule_show(" . qa_js($target) . ", (" . $sourcesobj . "), first);";
	}
	$funcscript[] = "}";

	// set default state of options
	$loadscript = array(
		"for (var i = 0; i < {$optVar}.length; i++) {",
1661
		"\t$('#'+{$optVar}[i]).change(function() { " . $function . "(false); });",
Scott committed
1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
		"}",
		"{$function}(true);",
	);

	$qa_content['script_lines'][] = $funcscript;
	$qa_content['script_onloads'][] = $loadscript;
}


/**
 * Set up $qa_content and $field (with HTML name $fieldname) for tag auto-completion, where
 * $exampletags are suggestions and $completetags are simply the most popular ones. Show up to $maxtags.
1674 1675 1676 1677 1678 1679 1680
 * @param array $qa_content
 * @param array $field
 * @param string $fieldname
 * @param array $tags
 * @param array $exampletags
 * @param array $completetags
 * @param int $maxtags
Scott committed
1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713
 */
function qa_set_up_tag_field(&$qa_content, &$field, $fieldname, $tags, $exampletags, $completetags, $maxtags)
{
	$template = '<a href="#" class="qa-tag-link" onclick="return qa_tag_click(this);">^</a>';

	$qa_content['script_var']['qa_tag_template'] = $template;
	$qa_content['script_var']['qa_tag_onlycomma'] = (int)qa_opt('tag_separator_comma');
	$qa_content['script_var']['qa_tags_examples'] = qa_html(implode(',', $exampletags));
	$qa_content['script_var']['qa_tags_complete'] = qa_html(implode(',', $completetags));
	$qa_content['script_var']['qa_tags_max'] = (int)$maxtags;

	$separatorcomma = qa_opt('tag_separator_comma');

	$field['label'] = qa_lang_html($separatorcomma ? 'question/q_tags_comma_label' : 'question/q_tags_label');
	$field['value'] = qa_html(implode($separatorcomma ? ', ' : ' ', $tags));
	$field['tags'] = 'name="' . $fieldname . '" id="tags" autocomplete="off" onkeyup="qa_tag_hints();" onmouseup="qa_tag_hints();"';

	$sdn = ' style="display:none;"';

	$field['note'] =
		'<span id="tag_examples_title"' . (count($exampletags) ? '' : $sdn) . '>' . qa_lang_html('question/example_tags') . '</span>' .
		'<span id="tag_complete_title"' . $sdn . '>' . qa_lang_html('question/matching_tags') . '</span><span id="tag_hints">';

	foreach ($exampletags as $tag)
		$field['note'] .= str_replace('^', qa_html($tag), $template) . ' ';

	$field['note'] .= '</span>';
	$field['note_force'] = true;
}


/**
 * Get a list of user-entered tags submitted from a field that was created with qa_set_up_tag_field(...)
1714
 * @param string $fieldname
Scott committed
1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735
 * @return array
 */
function qa_get_tags_field_value($fieldname)
{
	require_once QA_INCLUDE_DIR . 'util/string.php';

	$text = qa_remove_utf8mb4(qa_post_text($fieldname));

	if (qa_opt('tag_separator_comma'))
		return array_unique(preg_split('/\s*,\s*/', trim(qa_strtolower(strtr($text, '/', ' '))), -1, PREG_SPLIT_NO_EMPTY));
	else
		return array_unique(qa_string_to_words($text, true, false, false, false));
}


/**
 * Set up $qa_content and $field (with HTML name $fieldname) for hierarchical category navigation, with the initial value
 * set to $categoryid (and $navcategories retrieved for $categoryid using qa_db_category_nav_selectspec(...)).
 * If $allownone is true, it will allow selection of no category. If $allownosub is true, it will allow a category to be
 * selected without selecting a subcategory within. Set $maxdepth to the maximum depth of category that can be selected
 * (or null for no maximum) and $excludecategoryid to a category that should not be included.
1736 1737 1738 1739 1740 1741 1742 1743 1744
 * @param array $qa_content
 * @param array $field
 * @param string $fieldname
 * @param array $navcategories
 * @param int $categoryid
 * @param int $allownone
 * @param int $allownosub
 * @param int|null $maxdepth
 * @param int|null $excludecategoryid
Scott committed
1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784
 */
function qa_set_up_category_field(&$qa_content, &$field, $fieldname, $navcategories, $categoryid, $allownone, $allownosub, $maxdepth = null, $excludecategoryid = null)
{
	$pathcategories = qa_category_path($navcategories, $categoryid);

	$startpath = '';
	foreach ($pathcategories as $category)
		$startpath .= '/' . $category['categoryid'];

	if (isset($maxdepth))
		$maxdepth = min(QA_CATEGORY_DEPTH, $maxdepth);
	else
		$maxdepth = QA_CATEGORY_DEPTH;

	$qa_content['script_onloads'][] = sprintf('qa_category_select(%s, %s);', qa_js($fieldname), qa_js($startpath));

	$qa_content['script_var']['qa_cat_exclude'] = $excludecategoryid;
	$qa_content['script_var']['qa_cat_allownone'] = (int)$allownone;
	$qa_content['script_var']['qa_cat_allownosub'] = (int)$allownosub;
	$qa_content['script_var']['qa_cat_maxdepth'] = $maxdepth;

	$field['type'] = 'select';
	$field['tags'] = sprintf('name="%s_0" id="%s_0" onchange="qa_category_select(%s);"', $fieldname, $fieldname, qa_js($fieldname));
	$field['options'] = array();

	// create the menu that will be shown if Javascript is disabled

	if ($allownone)
		$field['options'][''] = qa_lang_html('main/no_category'); // this is also copied to first menu created by Javascript

	$keycategoryids = array();

	if ($allownosub) {
		$category = @$navcategories[$categoryid];

		$upcategory = @$navcategories[$category['parentid']]; // first get supercategories
		while (isset($upcategory)) {
			$keycategoryids[$upcategory['categoryid']] = true;
			$upcategory = @$navcategories[$upcategory['parentid']];
		}
Scott committed
1785

Scott committed
1786
		$keycategoryids = array_reverse($keycategoryids, true);
Scott committed
1787

Scott committed
1788
		$depth = count($keycategoryids); // number of levels above
Scott committed
1789

Scott committed
1790 1791
		if (isset($category)) {
			$depth++; // to count category itself
Scott committed
1792

Scott committed
1793 1794 1795
			foreach ($navcategories as $navcategory) // now get siblings and self
				if (!strcmp($navcategory['parentid'], $category['parentid']))
					$keycategoryids[$navcategory['categoryid']] = true;
Scott committed
1796 1797
		}

Scott committed
1798 1799 1800 1801
		if ($depth < $maxdepth)
			foreach ($navcategories as $navcategory) // now get children, if not too deep
				if (!strcmp($navcategory['parentid'], $categoryid))
					$keycategoryids[$navcategory['categoryid']] = true;
Scott committed
1802

Scott committed
1803 1804
	} else {
		$haschildren = false;
Scott committed
1805

1806 1807
		foreach ($navcategories as $navcategory) {
			// check if it has any children
Scott committed
1808 1809 1810
			if (!strcmp($navcategory['parentid'], $categoryid)) {
				$haschildren = true;
				break;
Scott committed
1811
			}
1812
		}
Scott committed
1813

Scott committed
1814 1815 1816
		if (!$haschildren)
			$keycategoryids[$categoryid] = true; // show this category if it has no children
	}
Scott committed
1817

Scott committed
1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
	foreach ($keycategoryids as $keycategoryid => $dummy)
		if (strcmp($keycategoryid, $excludecategoryid))
			$field['options'][$keycategoryid] = qa_category_path_html($navcategories, $keycategoryid);

	$field['value'] = @$field['options'][$categoryid];
	$field['note'] =
		'<div id="' . $fieldname . '_note">' .
		'<noscript style="color:red;">' . qa_lang_html('question/category_js_note') . '</noscript>' .
		'</div>';
}


/**
 * Get the user-entered category id submitted from a field that was created with qa_set_up_category_field(...)
1832 1833
 * @param string $fieldname
 * @return string|null
Scott committed
1834 1835 1836 1837 1838 1839 1840 1841
 */
function qa_get_category_field_value($fieldname)
{
	for ($level = QA_CATEGORY_DEPTH; $level >= 1; $level--) {
		$levelid = qa_post_text($fieldname . '_' . $level);
		if (strlen($levelid))
			return $levelid;
	}
Scott committed
1842

Scott committed
1843 1844 1845 1846 1847
	if (!isset($levelid)) { // no Javascript-generated menu was present so take original menu
		$levelid = qa_post_text($fieldname . '_0');
		if (strlen($levelid))
			return $levelid;
	}
Scott committed
1848

Scott committed
1849 1850 1851 1852 1853 1854 1855
	return null;
}


/**
 * Set up $qa_content and add to $fields to allow the user to enter their name for a post if they are not logged in
 * $inname is from previous submission/validation. Pass $fieldprefix to add a prefix to the form field name used.
1856 1857 1858
 * @param array $qa_content
 * @param array $fields
 * @param string $inname
Scott committed
1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873
 * @param string $fieldprefix
 */
function qa_set_up_name_field(&$qa_content, &$fields, $inname, $fieldprefix = '')
{
	$fields['name'] = array(
		'label' => qa_lang_html('question/anon_name_label'),
		'tags' => 'name="' . $fieldprefix . 'name"',
		'value' => qa_html($inname),
	);
}


/**
 * Set up $qa_content and add to $fields to allow user to set if they want to be notified regarding their post.
 * $basetype is 'Q', 'A' or 'C' for question, answer or comment. $login_email is the email of logged in user,
1874
 * or null if this is an anonymous post. $inemail and $errors_email are from previous submission/validation.
Scott committed
1875
 * Pass $fieldprefix to add a prefix to the form field names and IDs used.
1876 1877 1878 1879 1880 1881
 * @param array $qa_content
 * @param array $fields
 * @param string $basetype
 * @param string|null $login_email
 * @param string $inemail
 * @param string $errors_email
Scott committed
1882 1883
 * @param string $fieldprefix
 */
1884
function qa_set_up_notify_fields(&$qa_content, &$fields, $basetype, $login_email, $inemail, $errors_email, $fieldprefix = '')
Scott committed
1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908
{
	$fields['notify'] = array(
		'tags' => 'name="' . $fieldprefix . 'notify"',
		'type' => 'checkbox',
	);

	switch ($basetype) {
		case 'Q':
			$labelaskemail = qa_lang_html('question/q_notify_email');
			$labelonly = qa_lang_html('question/q_notify_label');
			$labelgotemail = qa_lang_html('question/q_notify_x_label');
			break;

		case 'A':
			$labelaskemail = qa_lang_html('question/a_notify_email');
			$labelonly = qa_lang_html('question/a_notify_label');
			$labelgotemail = qa_lang_html('question/a_notify_x_label');
			break;

		case 'C':
			$labelaskemail = qa_lang_html('question/c_notify_email');
			$labelonly = qa_lang_html('question/c_notify_label');
			$labelgotemail = qa_lang_html('question/c_notify_x_label');
			break;
Scott committed
1909 1910
	}

Scott committed
1911 1912 1913 1914
	if (empty($login_email)) {
		$fields['notify']['label'] =
			'<span id="' . $fieldprefix . 'email_shown">' . $labelaskemail . '</span>' .
			'<span id="' . $fieldprefix . 'email_hidden" style="display:none;">' . $labelonly . '</span>';
Scott committed
1915

Scott committed
1916 1917 1918 1919
		$fields['notify']['tags'] .= ' id="' . $fieldprefix . 'notify" onclick="if (document.getElementById(\'' . $fieldprefix . 'notify\').checked) document.getElementById(\'' . $fieldprefix . 'email\').focus();"';
		$fields['notify']['tight'] = true;

		$fields['email'] = array(
1920
			'type' => 'email',
Scott committed
1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932
			'id' => $fieldprefix . 'email_display',
			'tags' => 'name="' . $fieldprefix . 'email" id="' . $fieldprefix . 'email"',
			'value' => qa_html($inemail),
			'note' => qa_lang_html('question/notify_email_note'),
			'error' => qa_html($errors_email),
		);

		qa_set_display_rules($qa_content, array(
			$fieldprefix . 'email_display' => $fieldprefix . 'notify',
			$fieldprefix . 'email_shown' => $fieldprefix . 'notify',
			$fieldprefix . 'email_hidden' => '!' . $fieldprefix . 'notify',
		));
Scott committed
1933

Scott committed
1934 1935
	} else {
		$fields['notify']['label'] = str_replace('^', qa_html($login_email), $labelgotemail);
Scott committed
1936
	}
Scott committed
1937
}
Scott committed
1938 1939


Scott committed
1940 1941 1942 1943 1944 1945 1946
/**
 * Return the theme that should be used for displaying the page
 * @return string
 */
function qa_get_site_theme()
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1947

Scott committed
1948 1949
	return qa_opt(qa_is_mobile_probably() ? 'site_theme_mobile' : 'site_theme');
}
Scott committed
1950 1951


Scott committed
1952 1953 1954
/**
 * Return the initialized class for $theme (or the default if it's gone), passing $template, $content and $request.
 * Also applies any registered plugin layers.
1955 1956 1957 1958
 * @param string $theme
 * @param string $template
 * @param array $content
 * @param string $request
Scott committed
1959 1960 1961 1962 1963
 * @return qa_html_theme_base
 */
function qa_load_theme_class($theme, $template, $content, $request)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
1964

Scott committed
1965
	global $qa_layers;
Scott committed
1966

Scott committed
1967
	// First load the default class
Scott committed
1968

Scott committed
1969
	require_once QA_INCLUDE_DIR . 'qa-theme-base.php';
Scott committed
1970

Scott committed
1971
	$classname = 'qa_html_theme_base';
Scott committed
1972

1973
	// Then load the selected theme if valid, otherwise load the Cagette theme
Scott committed
1974

Scott committed
1975
	if (!file_exists(QA_THEME_DIR . $theme . '/qa-styles.css'))
1976
		$theme = 'Cagette';
Scott committed
1977

Scott committed
1978
	$themeroothtml = qa_html(qa_path_to_root() . 'qa-theme/' . $theme . '/');
Scott committed
1979

Scott committed
1980 1981
	if (file_exists(QA_THEME_DIR . $theme . '/qa-theme.php')) {
		require_once QA_THEME_DIR . $theme . '/qa-theme.php';
Scott committed
1982

Scott committed
1983 1984
		if (class_exists('qa_html_theme'))
			$classname = 'qa_html_theme';
Scott committed
1985 1986
	}

Scott committed
1987
	// Create the list of layers to load
Scott committed
1988

Scott committed
1989
	$loadlayers = $qa_layers;
Scott committed
1990

Scott committed
1991 1992 1993 1994 1995
	if (!qa_user_maximum_permit_error('permit_view_voters_flaggers')) {
		$loadlayers[] = array(
			'directory' => QA_INCLUDE_DIR . 'plugins/',
			'include' => 'qa-layer-voters-flaggers.php',
			'urltoroot' => null,
Scott committed
1996 1997 1998
		);
	}

Scott committed
1999
	// Then load any theme layers using some class-munging magic (substitute class names)
Scott committed
2000

Scott committed
2001
	$layerindex = 0;
Scott committed
2002

Scott committed
2003 2004 2005
	foreach ($loadlayers as $layer) {
		$filename = $layer['directory'] . $layer['include'];
		$layerphp = file_get_contents($filename);
Scott committed
2006

Scott committed
2007 2008 2009
		if (strlen($layerphp)) {
			// include file name in layer class name to make debugging easier if there is an error
			$newclassname = 'qa_layer_' . (++$layerindex) . '_from_' . preg_replace('/[^A-Za-z0-9_]+/', '_', basename($layer['include']));
Scott committed
2010

Scott committed
2011 2012
			if (preg_match('/\s+class\s+qa_html_theme_layer\s+extends\s+qa_html_theme_base\s+/im', $layerphp) != 1)
				qa_fatal_error('Class for layer must be declared as "class qa_html_theme_layer extends qa_html_theme_base" in ' . $layer['directory'] . $layer['include']);
Scott committed
2013

Scott committed
2014 2015 2016 2017 2018 2019 2020
			$searchwordreplace = array(
				'qa_html_theme_base::qa_html_theme_base' => $classname . '::__construct', // PHP5 constructor fix
				'parent::qa_html_theme_base' => 'parent::__construct', // PHP5 constructor fix
				'qa_html_theme_layer' => $newclassname,
				'qa_html_theme_base' => $classname,
				'QA_HTML_THEME_LAYER_DIRECTORY' => "'" . $layer['directory'] . "'",
				'QA_HTML_THEME_LAYER_URLTOROOT' => "'" . qa_path_to_root() . $layer['urltoroot'] . "'",
Scott committed
2021 2022
			);

2023
			foreach ($searchwordreplace as $searchword => $replace) {
Scott committed
2024 2025
				if (preg_match_all('/\W(' . preg_quote($searchword, '/') . ')\W/im', $layerphp, $matches, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE)) {
					$searchmatches = array_reverse($matches[1]); // don't use preg_replace due to complication of escaping replacement phrase
2026

Scott committed
2027 2028
					foreach ($searchmatches as $searchmatch)
						$layerphp = substr_replace($layerphp, $replace, $searchmatch[1], strlen($searchmatch[0]));
2029
				}
2030
			}
Scott committed
2031

Scott committed
2032
			// echo '<pre style="text-align:left;">'.htmlspecialchars($layerphp).'</pre>'; // to debug munged code
Scott committed
2033

Scott committed
2034
			qa_eval_from_file($layerphp, $filename);
Scott committed
2035

Scott committed
2036
			$classname = $newclassname;
Scott committed
2037 2038 2039
		}
	}

Scott committed
2040
	// Finally, instantiate the object
Scott committed
2041

Scott committed
2042
	$themeclass = new $classname($template, $content, $themeroothtml, $request);
Scott committed
2043

Scott committed
2044 2045
	return $themeclass;
}
Scott committed
2046 2047


Scott committed
2048 2049 2050
/**
 * Return an instantiation of the appropriate editor module class, given $content in $format
 * Pass the preferred module name in $editorname, on return it will contain the name of the module used.
2051 2052 2053
 * @param string $content
 * @param string $format
 * @param string $editorname
Scott committed
2054 2055 2056 2057 2058
 * @return object
 */
function qa_load_editor($content, $format, &$editorname)
{
	$maxeditor = qa_load_module('editor', $editorname); // take preferred one first
Scott committed
2059

Scott committed
2060 2061 2062 2063
	if (isset($maxeditor) && method_exists($maxeditor, 'calc_quality')) {
		$maxquality = $maxeditor->calc_quality($content, $format);
		if ($maxquality >= 0.5)
			return $maxeditor;
Scott committed
2064

Scott committed
2065 2066
	} else
		$maxquality = 0;
Scott committed
2067

Scott committed
2068 2069 2070
	$editormodules = qa_load_modules_with('editor', 'calc_quality');
	foreach ($editormodules as $tryname => $tryeditor) {
		$tryquality = $tryeditor->calc_quality($content, $format);
Scott committed
2071

Scott committed
2072 2073 2074 2075
		if ($tryquality > $maxquality) {
			$maxeditor = $tryeditor;
			$maxquality = $tryquality;
			$editorname = $tryname;
Scott committed
2076 2077 2078
		}
	}

Scott committed
2079 2080 2081 2082 2083 2084 2085 2086 2087
	return $maxeditor;
}


/**
 * Return a form field from the $editor module while making necessary modifications to $qa_content. The parameters
 * $content, $format, $fieldname, $rows and $focusnow are passed through to the module's get_field() method. ($focusnow
 * is deprecated as a parameter to get_field() but it's still passed through for old editor modules.) Based on
 * $focusnow and $loadnow, also add the editor's load and/or focus scripts to $qa_content's onload handlers.
2088
 * @param object $editor
Scott committed
2089 2090 2091 2092 2093 2094 2095
 * @param array $qa_content
 * @param string $content
 * @param string $format
 * @param string $fieldname
 * @param int $rows
 * @param bool $focusnow
 * @param bool $loadnow
2096
 * @return array
Scott committed
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138
 */
function qa_editor_load_field($editor, &$qa_content, $content, $format, $fieldname, $rows, $focusnow = false, $loadnow = true)
{
	if (!isset($editor))
		qa_fatal_error('No editor found for format: ' . $format);

	$field = $editor->get_field($qa_content, $content, $format, $fieldname, $rows, $focusnow);

	$onloads = array();

	if ($loadnow && method_exists($editor, 'load_script'))
		$onloads[] = $editor->load_script($fieldname);

	if ($focusnow && method_exists($editor, 'focus_script'))
		$onloads[] = $editor->focus_script($fieldname);

	if (count($onloads))
		$qa_content['script_onloads'][] = $onloads;

	return $field;
}


/**
 * Return an instantiation of the appropriate viewer module class, given $content in $format
 * @param string $content
 * @param string $format
 * @return object
 */
function qa_load_viewer($content, $format)
{
	$maxviewer = null;
	$maxquality = 0;

	$viewermodules = qa_load_modules_with('viewer', 'calc_quality');

	foreach ($viewermodules as $tryviewer) {
		$tryquality = $tryviewer->calc_quality($content, $format);

		if ($tryquality > $maxquality) {
			$maxviewer = $tryviewer;
			$maxquality = $tryquality;
Scott committed
2139 2140 2141
		}
	}

Scott committed
2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187
	return $maxviewer;
}


/**
 * Return the plain text rendering of $content in $format, passing $options to the appropriate module
 * @param string $content
 * @param string $format
 * @param array $options
 * @return string
 */
function qa_viewer_text($content, $format, $options = array())
{
	$viewer = qa_load_viewer($content, $format);
	return $viewer->get_text($content, $format, $options);
}


/**
 * Return the HTML rendering of $content in $format, passing $options to the appropriate module
 * @param string $content
 * @param string $format
 * @param array $options
 * @return string
 */
function qa_viewer_html($content, $format, $options = array())
{
	$viewer = qa_load_viewer($content, $format);
	return $viewer->get_html($content, $format, $options);
}

/**
 * Retrieve title from HTTP POST, appropriately sanitised.
 * @param string $fieldname
 * @return string
 */
function qa_get_post_title($fieldname)
{
	require_once QA_INCLUDE_DIR . 'util/string.php';

	return qa_remove_utf8mb4(qa_post_text($fieldname));
}

/**
 * Retrieve the POST from an editor module's HTML field named $contentfield, where the editor's name was in HTML field $editorfield
 * Assigns the module's output to $incontent and $informat, editor's name in $ineditor, text rendering of content in $intext
2188 2189 2190 2191 2192 2193
 * @param string $editorfield
 * @param string $contentfield
 * @param string $ineditor
 * @param string $incontent
 * @param string $informat
 * @param string $intext
Scott committed
2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212
 */
function qa_get_post_content($editorfield, $contentfield, &$ineditor, &$incontent, &$informat, &$intext)
{
	require_once QA_INCLUDE_DIR . 'util/string.php';

	$ineditor = qa_post_text($editorfield);
	$editor = qa_load_module('editor', $ineditor);
	$readdata = $editor->read_post($contentfield);

	// sanitise 4-byte Unicode
	$incontent = qa_remove_utf8mb4($readdata['content']);
	$informat = $readdata['format'];
	$intext = qa_remove_utf8mb4(qa_viewer_text($incontent, $informat));
}


/**
 * Check if any of the 'content', 'format' or 'text' elements have changed between $oldfields and $fields
 * If so, recalculate $fields['text'] based on $fields['content'] and $fields['format']
2213 2214
 * @param array $fields
 * @param array $oldfields
Scott committed
2215 2216 2217
 */
function qa_update_post_text(&$fields, $oldfields)
{
2218
	if (strcmp($oldfields['content'], $fields['content']) ||
Scott committed
2219 2220 2221 2222
		strcmp($oldfields['format'], $fields['format']) ||
		strcmp($oldfields['text'], $fields['text'])
	) {
		$fields['text'] = qa_viewer_text($fields['content'], $fields['format']);
Scott committed
2223
	}
Scott committed
2224 2225 2226 2227 2228 2229
}


/**
 * Return the <img...> HTML to display avatar $blobid whose stored size is $width and $height
 * Constrain the image to $size (width AND height) and pad it to that size if $padding is true
2230 2231 2232 2233
 * @param string $blobId
 * @param int $width
 * @param int $height
 * @param int $size
Scott committed
2234
 * @param bool $padding
2235
 * @return string|null
Scott committed
2236 2237 2238 2239 2240 2241 2242 2243 2244 2245
 */
function qa_get_avatar_blob_html($blobId, $width, $height, $size, $padding = false)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

	require_once QA_INCLUDE_DIR . 'util/image.php';
	require_once QA_INCLUDE_DIR . 'app/users.php';

	if (strlen($blobId) == 0 || (int)$size <= 0) {
		return null;
Scott committed
2246 2247
	}

Scott committed
2248
	$avatarLink = qa_html(qa_get_avatar_blob_url($blobId, $size));
2249

Scott committed
2250
	qa_image_constrain($width, $height, $size);
Scott committed
2251

Scott committed
2252 2253 2254 2255
	$params = array(
		$avatarLink,
		$width && $height ? sprintf(' width="%d" height="%d"', $width, $height) : '',
	);
Scott committed
2256

Scott committed
2257
	$html = vsprintf('<img src="%s"%s class="qa-avatar-image" alt=""/>', $params);
2258

Scott committed
2259 2260 2261 2262 2263 2264
	if ($padding && $width && $height) {
		$padleft = floor(($size - $width) / 2);
		$padright = $size - $width - $padleft;
		$padtop = floor(($size - $height) / 2);
		$padbottom = $size - $height - $padtop;
		$html = sprintf('<span style="display:inline-block; padding:%dpx %dpx %dpx %dpx;">%s</span>', $padtop, $padright, $padbottom, $padleft, $html);
Scott committed
2265 2266
	}

Scott committed
2267 2268
	return $html;
}
Scott committed
2269 2270


2271 2272 2273 2274 2275 2276 2277 2278 2279
// /**
//  * Return the <img...> HTML to display the Gravatar for $email, constrained to $size
//  * @param string $email
//  * @param int|null $size
//  * @return string|null
//  */
// function qa_get_gravatar_html($email, $size)
// {
// 	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott committed
2280

2281
// 	require_once QA_INCLUDE_DIR . 'app/users.php';
Scott committed
2282

2283
// 	$avatarLink = qa_html(qa_get_gravatar_url($email, $size));
Scott committed
2284

2285 2286 2287 2288 2289 2290 2291
// 	$size = (int)$size;
// 	if ($size > 0) {
// 		return sprintf('<img src="%s" width="%d" height="%d" class="qa-avatar-image" alt="" />', $avatarLink, $size, $size);
// 	} else {
// 		return null;
// 	}
// }
Scott committed
2292 2293 2294 2295


/**
 * Retrieve the appropriate user title from $pointstitle for a user with $userpoints points, or null if none
2296 2297 2298
 * @param int $userpoints
 * @param array $pointstitle
 * @return string|null
Scott committed
2299 2300 2301 2302 2303 2304
 */
function qa_get_points_title_html($userpoints, $pointstitle)
{
	foreach ($pointstitle as $points => $title) {
		if ($userpoints >= $points)
			return $title;
Scott committed
2305 2306
	}

Scott committed
2307 2308 2309 2310 2311 2312 2313
	return null;
}


/**
 * Return an form to add to the $qa_content['notices'] array for displaying a user notice with id $noticeid
 * and $content. Pass the raw database information for the notice in $rawnotice.
2314 2315 2316
 * @param string $noticeid
 * @param string $content
 * @param array|null $rawnotice
Scott committed
2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336
 * @return array
 */
function qa_notice_form($noticeid, $content, $rawnotice = null)
{
	$elementid = 'notice_' . $noticeid;

	return array(
		'id' => qa_html($elementid),
		'raw' => $rawnotice,
		'form_tags' => 'method="post" action="' . qa_self_html() . '"',
		'form_hidden' => array('code' => qa_get_form_security_code('notice-' . $noticeid)),
		'close_tags' => 'name="' . qa_html($elementid) . '" onclick="return qa_notice_click(this);"',
		'content' => $content,
	);
}


/**
 * Return a form to set in $qa_content['favorite'] for the favoriting button for entity $entitytype with $entityid.
 * Set $favorite to whether the entity is currently a favorite and a description title for the button in $title.
2337 2338 2339 2340
 * @param string $entitytype
 * @param mixed $entityid
 * @param bool $favorite
 * @param string $title
Scott committed
2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355
 * @return array
 */
function qa_favorite_form($entitytype, $entityid, $favorite, $title)
{
	return array(
		'form_tags' => 'method="post" action="' . qa_self_html() . '"',
		'form_hidden' => array('code' => qa_get_form_security_code('favorite-' . $entitytype . '-' . $entityid)),
		'favorite_tags' => 'id="favoriting"',
		($favorite ? 'favorite_remove_tags' : 'favorite_add_tags') =>
			'title="' . qa_html($title) . '" name="' . qa_html('favorite_' . $entitytype . '_' . $entityid . '_' . (int)!$favorite) . '" onclick="return qa_favorite_click(this);"',
	);
}

/**
 * Format a number using the decimal point and thousand separator specified in the language files.
Scott committed
2356 2357
 * If the number is compacted it is turned into a string such as 17.3k (only the thousand/million
 * cases are currently supported).
Scott committed
2358
 *
2359
 * @since 1.8.0
Scott committed
2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371
 * @param integer $number Number to be formatted
 * @param integer $decimals Amount of decimals to use (ignored if number gets shortened)
 * @param bool $compact Whether the number can be shown as compact or not
 * @return string The formatted number as a string
 */
function qa_format_number($number, $decimals = 0, $compact = false)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

	$suffix = '';

	if ($compact && qa_opt('show_compact_numbers')) {
Scott committed
2372
		// when compacting we keep 2-3 significant figures (e.g. 9.1k, 234k)
Scott committed
2373 2374 2375
		if ($number >= 1000000) {
			$number /= 1000000;
			$suffix = qa_lang_html('main/_millions_suffix');
Scott committed
2376
			$decimals = $number < 100 ? 1 : 0;
Scott committed
2377 2378 2379
		} elseif ($number >= 1000) {
			$number /= 1000;
			$suffix = qa_lang_html('main/_thousands_suffix');
Scott committed
2380
			$decimals = $number < 100 ? 1 : 0;
Scott committed
2381
		}
2382 2383
	}

Scott committed
2384 2385 2386 2387 2388 2389 2390
	return number_format(
		$number,
		$decimals,
		qa_lang_html('main/_decimal_point'),
		qa_lang_html('main/_thousands_separator')
	) . $suffix;
}