qa-app-format.php 72.3 KB
Newer Older
Gideon Greenspan committed
1 2 3 4 5 6 7
<?php

/*
	Question2Answer (c) Gideon Greenspan

	http://www.question2answer.org/

Scott Vivian committed
8

Gideon Greenspan committed
9 10 11 12 13 14 15 16 17
	File: qa-include/qa-app-format.php
	Version: See define()s at top of qa-include/qa-base.php
	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.
Scott Vivian committed
18

Gideon Greenspan committed
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
	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
*/

	if (!defined('QA_VERSION')) { // don't allow this page to be requested directly from browser
		header('Location: ../');
		exit;
	}

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

Scott Vivian committed
35

Gideon Greenspan committed
36 37 38 39 40
	function qa_time_to_string($seconds)
/*
	Return textual representation of $seconds
*/
	{
Gideon Greenspan committed
41
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott Vivian committed
42

Gideon Greenspan committed
43
		$seconds=max($seconds, 1);
Scott Vivian committed
44

Gideon Greenspan committed
45 46 47 48 49 50 51 52 53
		$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' ),
		);
Scott Vivian committed
54

Gideon Greenspan committed
55 56 57
		foreach ($scales as $scale => $phrases)
			if ($seconds>=$scale) {
				$count=floor($seconds/$scale);
Scott Vivian committed
58

Gideon Greenspan committed
59 60 61 62
				if ($count==1)
					$string=qa_lang($phrases[0]);
				else
					$string=qa_lang_sub($phrases[1], $count);
Scott Vivian committed
63

Gideon Greenspan committed
64 65
				break;
			}
Scott Vivian committed
66

Gideon Greenspan committed
67 68
		return $string;
	}
Scott Vivian committed
69 70


Gideon Greenspan committed
71 72 73 74 75 76 77 78 79
	function qa_post_is_by_user($post, $userid, $cookieid)
/*
	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
*/
	{
		// 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.
Scott Vivian committed
80

Gideon Greenspan committed
81 82 83 84
		if (@$post['userid'] || $userid)
			return @$post['userid']==$userid;
		elseif (@$post['cookieid'])
			return strcmp($post['cookieid'], $cookieid)==0;
Scott Vivian committed
85

Gideon Greenspan committed
86 87 88
		return false;
	}

Scott Vivian committed
89

Gideon Greenspan committed
90 91 92 93 94 95 96 97
	function qa_userids_handles_html($useridhandles, $microformats=false)
/*
	Return array which maps the ['userid'] and/or ['lastuserid'] in each element of
	$useridhandles to its HTML representation. For internal user management, corresponding
	['handle'] and/or ['lasthandle'] are required in each element.
*/
	{
		require_once QA_INCLUDE_DIR.'qa-app-users.php';
Scott Vivian committed
98

Gideon Greenspan committed
99 100
		if (QA_FINAL_EXTERNAL_USERS) {
			$keyuserids=array();
Scott Vivian committed
101

Gideon Greenspan committed
102 103 104 105 106 107 108
			foreach ($useridhandles as $useridhandle) {
				if (isset($useridhandle['userid']))
					$keyuserids[$useridhandle['userid']]=true;

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

Gideon Greenspan committed
110 111 112 113
			if (count($keyuserids))
				return qa_get_users_html(array_keys($keyuserids), true, qa_path_to_root(), $microformats);
			else
				return array();
Scott Vivian committed
114

Gideon Greenspan committed
115 116
		} else {
			$usershtml=array();
Gideon Greenspan committed
117
			$favoritemap=qa_get_favorite_non_qs_map();
Gideon Greenspan committed
118 119 120

			foreach ($useridhandles as $useridhandle) {
				if (isset($useridhandle['userid']) && $useridhandle['handle'])
Gideon Greenspan committed
121
					$usershtml[$useridhandle['userid']]=qa_get_one_user_html($useridhandle['handle'], $microformats, @$favoritemap['user'][$useridhandle['userid']]);
Gideon Greenspan committed
122 123

				if (isset($useridhandle['lastuserid']) && $useridhandle['lasthandle'])
Gideon Greenspan committed
124
					$usershtml[$useridhandle['lastuserid']]=qa_get_one_user_html($useridhandle['lasthandle'], $microformats, @$favoritemap['user'][$useridhandle['lastuserid']]);
Gideon Greenspan committed
125
			}
Scott Vivian committed
126

Gideon Greenspan committed
127 128 129
			return $usershtml;
		}
	}
Scott Vivian committed
130 131


Gideon Greenspan committed
132
	function qa_get_favorite_non_qs_map()
Gideon Greenspan committed
133 134 135 136 137 138
/*
	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.
*/
Gideon Greenspan committed
139 140
	{
		global $qa_favorite_non_qs_map;
Scott Vivian committed
141

Gideon Greenspan committed
142
		if (!isset($qa_favorite_non_qs_map)) {
Gideon Greenspan committed
143
			$qa_favorite_non_qs_map=array();
Gideon Greenspan committed
144
			$loginuserid=qa_get_logged_in_userid();
Scott Vivian committed
145

Gideon Greenspan committed
146 147 148
			if (isset($loginuserid)) {
				require_once QA_INCLUDE_DIR.'qa-db-selects.php';
				require_once QA_INCLUDE_DIR.'qa-util-string.php';
Scott Vivian committed
149

Gideon Greenspan committed
150
				$favoritenonqs=qa_db_get_pending_result('favoritenonqs', qa_db_user_favorite_non_qs_selectspec($loginuserid));
Scott Vivian committed
151

152
				foreach ($favoritenonqs as $favorite) {
Gideon Greenspan committed
153 154 155 156
					switch ($favorite['type']) {
						case QA_ENTITY_USER:
							$qa_favorite_non_qs_map['user'][$favorite['userid']]=true;
							break;
Scott Vivian committed
157

Gideon Greenspan committed
158 159 160
						case QA_ENTITY_TAG:
							$qa_favorite_non_qs_map['tag'][qa_strtolower($favorite['tags'])]=true;
							break;
Scott Vivian committed
161

Gideon Greenspan committed
162 163 164 165
						case QA_ENTITY_CATEGORY:
							$qa_favorite_non_qs_map['category'][$favorite['categorybackpath']]=true;
							break;
					}
166
				}
Gideon Greenspan committed
167
			}
Gideon Greenspan committed
168 169 170 171
		}

		return $qa_favorite_non_qs_map;
	}
Gideon Greenspan committed
172

Scott Vivian committed
173

Gideon Greenspan committed
174
	function qa_tag_html($tag, $microformats=false, $favorited=false)
Gideon Greenspan committed
175
/*
Gideon Greenspan committed
176
	Convert textual $tag to HTML representation, with microformats if $microformats is true. Set $favorited to true to show the tag as favorited.
Gideon Greenspan committed
177 178
*/
	{
Gideon Greenspan committed
179
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott Vivian committed
180

Gideon Greenspan committed
181 182
		return '<a href="'.qa_path_html('tag/'.$tag).'"'.($microformats ? ' rel="tag"' : '').' class="qa-tag-link'.
			($favorited ? ' qa-tag-favorited' : '').'">'.qa_html($tag).'</a>';
Gideon Greenspan committed
183 184
	}

Scott Vivian committed
185

Gideon Greenspan committed
186 187 188 189 190 191 192
	function qa_category_path($navcategories, $categoryid)
/*
	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.
*/
	{
		$upcategories=array();
Scott Vivian committed
193

Gideon Greenspan committed
194 195
		for ($upcategory=@$navcategories[$categoryid]; isset($upcategory); $upcategory=@$navcategories[$upcategory['parentid']])
			$upcategories[$upcategory['categoryid']]=$upcategory;
Scott Vivian committed
196

Gideon Greenspan committed
197 198
		return array_reverse($upcategories, true);
	}
Scott Vivian committed
199

Gideon Greenspan committed
200 201 202 203 204 205 206 207

	function qa_category_path_html($navcategories, $categoryid)
/*
	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.
*/
	{
		$categories=qa_category_path($navcategories, $categoryid);
Scott Vivian committed
208

Gideon Greenspan committed
209 210 211
		$html='';
		foreach ($categories as $category)
			$html.=(strlen($html) ? ' / ' : '').qa_html($category['title']);
Scott Vivian committed
212

Gideon Greenspan committed
213 214
		return $html;
	}
Scott Vivian committed
215 216


Gideon Greenspan committed
217 218 219 220 221 222 223 224 225 226 227
	function qa_category_path_request($navcategories, $categoryid)
/*
	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.
*/
	{
		$categories=qa_category_path($navcategories, $categoryid);

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

Gideon Greenspan committed
229 230
		return $request;
	}
Scott Vivian committed
231 232


Gideon Greenspan committed
233 234 235 236 237
	function qa_ip_anchor_html($ip, $anchorhtml=null)
/*
	Return HTML to use for $ip address, which links to appropriate page with $anchorhtml
*/
	{
Gideon Greenspan committed
238
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott Vivian committed
239

Gideon Greenspan committed
240 241
		if (!strlen($anchorhtml))
			$anchorhtml=qa_html($ip);
Scott Vivian committed
242

Gideon Greenspan committed
243
		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>';
Gideon Greenspan committed
244
	}
Scott Vivian committed
245 246


Gideon Greenspan committed
247 248 249 250 251
	function qa_post_html_fields($post, $userid, $cookieid, $usershtml, $dummy, $options=array())
/*
	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.
Gideon Greenspan committed
252
	$dummy is a placeholder (used to be $categories parameter but that's no longer needed)
Gideon Greenspan committed
253 254 255 256
	$options is an array which sets what is displayed (see qa_post_html_defaults() in qa-app-options.php)
	If something is missing from $post (e.g. ['content']), correponding HTML also omitted.
*/
	{
Gideon Greenspan committed
257
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott Vivian committed
258

Gideon Greenspan committed
259
		require_once QA_INCLUDE_DIR.'qa-app-updates.php';
Scott Vivian committed
260

Gideon Greenspan committed
261 262
		if (isset($options['blockwordspreg']))
			require_once QA_INCLUDE_DIR.'qa-util-string.php';
Scott Vivian committed
263

Gideon Greenspan committed
264
		$fields=array('raw' => $post);
Scott Vivian committed
265

Gideon Greenspan committed
266 267 268 269 270 271 272 273 274 275
	//	Useful stuff used throughout function

		$postid=$post['postid'];
		$isquestion=($post['basetype']=='Q');
		$isanswer=($post['basetype']=='A');
		$isbyuser=qa_post_is_by_user($post, $userid, $cookieid);
		$anchor=urlencode(qa_anchor($post['basetype'], $postid));
		$elementid=isset($options['elementid']) ? $options['elementid'] : $anchor;
		$microformats=@$options['microformats'];
		$isselected=@$options['isselected'];
Gideon Greenspan committed
276 277
		$favoritedview=@$options['favoritedview'];
		$favoritemap=$favoritedview ? qa_get_favorite_non_qs_map() : array();
Scott Vivian committed
278

Gideon Greenspan committed
279 280 281
	//	High level information

		$fields['hidden']=@$post['hidden'];
Gideon Greenspan committed
282
		$fields['tags']='id="'.qa_html($elementid).'"';
Scott Vivian committed
283

Gideon Greenspan committed
284 285 286
		$fields['classes']=($isquestion && $favoritedview && @$post['userfavoriteq']) ? 'qa-q-favorited' : '';
		if ($isquestion && isset($post['closedbyid']))
			$fields['classes']=ltrim($fields['classes'].' qa-q-closed');
Scott Vivian committed
287

Gideon Greenspan committed
288 289 290
		if ($microformats)
			$fields['classes'].=' hentry '.($isquestion ? 'question' : ($isanswer ? ($isselected ? 'answer answer-selected' : 'answer') : 'comment'));

Gideon Greenspan committed
291
	//	Question-specific stuff (title, URL, tags, answer count, category)
Scott Vivian committed
292

Gideon Greenspan committed
293 294 295
		if ($isquestion) {
			if (isset($post['title'])) {
				$fields['url']=qa_q_path_html($postid, $post['title']);
Scott Vivian committed
296

Gideon Greenspan committed
297 298
				if (isset($options['blockwordspreg']))
					$post['title']=qa_block_words_replace($post['title'], $options['blockwordspreg']);
Scott Vivian committed
299

Gideon Greenspan committed
300 301
				$fields['title']=qa_html($post['title']);
				if ($microformats)
Gideon Greenspan committed
302
					$fields['title']='<span class="entry-title">'.$fields['title'].'</span>';
Scott Vivian committed
303

Gideon Greenspan committed
304
				/*if (isset($post['score'])) // useful for setting match thresholds
Gideon Greenspan committed
305
					$fields['title'].=' <small>('.$post['score'].')</small>';*/
Gideon Greenspan committed
306
			}
Scott Vivian committed
307

Gideon Greenspan committed
308 309
			if (@$options['tagsview'] && isset($post['tags'])) {
				$fields['q_tags']=array();
Scott Vivian committed
310

Gideon Greenspan committed
311 312 313 314
				$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 Vivian committed
315

Gideon Greenspan committed
316
					$fields['q_tags'][]=qa_tag_html($tag, $microformats, @$favoritemap['tag'][qa_strtolower($tag)]);
Gideon Greenspan committed
317 318
				}
			}
Scott Vivian committed
319

Gideon Greenspan committed
320 321
			if (@$options['answersview'] && isset($post['acount'])) {
				$fields['answers_raw']=$post['acount'];
Scott Vivian committed
322

Gideon Greenspan committed
323 324
				$fields['answers']=($post['acount']==1) ? qa_lang_html_sub_split('main/1_answer', '1', '1')
					: qa_lang_html_sub_split('main/x_answers', number_format($post['acount']));
Scott Vivian committed
325

Gideon Greenspan committed
326 327
				$fields['answer_selected']=isset($post['selchildid']);
			}
Scott Vivian committed
328

Gideon Greenspan committed
329 330
			if (@$options['viewsview'] && isset($post['views'])) {
				$fields['views_raw']=$post['views'];
Scott Vivian committed
331

Gideon Greenspan committed
332 333 334 335
				$fields['views']=($post['views']==1) ? qa_lang_html_sub_split('main/1_view', '1', '1') :
					qa_lang_html_sub_split('main/x_views', number_format($post['views']));
			}

Gideon Greenspan committed
336 337
			if (@$options['categoryview'] && isset($post['categoryname']) && isset($post['categorybackpath'])) {
				$favoriteclass='';
Scott Vivian committed
338

Gideon Greenspan committed
339 340 341 342 343 344 345 346 347
				if (count(@$favoritemap['category'])) {
					if (@$favoritemap['category'][$post['categorybackpath']])
						$favoriteclass=' qa-cat-favorited';

					else
						foreach ($favoritemap['category'] as $categorybackpath => $dummy)
							if (substr('/'.$post['categorybackpath'], -strlen($categorybackpath))==$categorybackpath)
								$favoriteclass=' qa-cat-parent-favorited';
				}
Scott Vivian committed
348

Gideon Greenspan committed
349
				$fields['where']=qa_lang_html_sub_split('main/in_category_x',
Gideon Greenspan committed
350 351
					'<a href="'.qa_path_html(@$options['categorypathprefix'].implode('/', array_reverse(explode('/', $post['categorybackpath'])))).
					'" class="qa-category-link'.$favoriteclass.'">'.qa_html($post['categoryname']).'</a>');
Gideon Greenspan committed
352
			}
Gideon Greenspan committed
353
		}
Scott Vivian committed
354

Gideon Greenspan committed
355
	//	Answer-specific stuff (selection)
Scott Vivian committed
356

Gideon Greenspan committed
357 358
		if ($isanswer) {
			$fields['selected']=$isselected;
Scott Vivian committed
359

Gideon Greenspan committed
360 361 362 363 364
			if ($isselected)
				$fields['select_text']=qa_lang_html('question/select_text');
		}

	//	Post content
Scott Vivian committed
365

Gideon Greenspan committed
366 367
		if (@$options['contentview'] && !empty($post['content'])) {
			$viewer=qa_load_viewer($post['content'], $post['format']);
Scott Vivian committed
368

Gideon Greenspan committed
369 370 371 372 373
			$fields['content']=$viewer->get_html($post['content'], $post['format'], array(
				'blockwordspreg' => @$options['blockwordspreg'],
				'showurllinks' => @$options['showurllinks'],
				'linksnewwindow' => @$options['linksnewwindow'],
			));
Scott Vivian committed
374

Gideon Greenspan committed
375
			if ($microformats)
Gideon Greenspan committed
376
				$fields['content']='<div class="entry-content">'.$fields['content'].'</div>';
Scott Vivian committed
377

Gideon Greenspan committed
378
			$fields['content']='<a name="'.qa_html($postid).'"></a>'.$fields['content'];
Gideon Greenspan committed
379 380 381
				// 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)
		}
Scott Vivian committed
382

Gideon Greenspan committed
383
	//	Voting stuff
Scott Vivian committed
384

Gideon Greenspan committed
385 386
		if (@$options['voteview']) {
			$voteview=$options['voteview'];
Scott Vivian committed
387

Gideon Greenspan committed
388
		//	Calculate raw values and pass through
Scott Vivian committed
389

Gideon Greenspan committed
390 391 392 393 394 395 396 397 398
			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'];
			}

Gideon Greenspan committed
399
			$netvotes=(int)($upvotes-$downvotes);
Scott Vivian committed
400

Gideon Greenspan committed
401 402 403 404 405
			$fields['upvotes_raw']=$upvotes;
			$fields['downvotes_raw']=$downvotes;
			$fields['netvotes_raw']=$netvotes;

		//	Create HTML versions...
Scott Vivian committed
406

Gideon Greenspan committed
407 408 409 410 411 412 413 414 415
			$upvoteshtml=qa_html($upvotes);
			$downvoteshtml=qa_html($downvotes);

			if ($netvotes>=1)
				$netvoteshtml='+'.qa_html($netvotes);
			elseif ($netvotes<=-1)
				$netvoteshtml='&ndash;'.qa_html(-$netvotes);
			else
				$netvoteshtml='0';
Scott Vivian committed
416

Gideon Greenspan committed
417 418 419
		//	...with microformats if appropriate

			if ($microformats) {
Gideon Greenspan committed
420 421 422 423
				$netvoteshtml.='<span class="votes-up"><span class="value-title" title="'.$upvoteshtml.'"></span></span>'.
					'<span class="votes-down"><span class="value-title" title="'.$downvoteshtml.'"></span></span>';
				$upvoteshtml='<span class="votes-up">'.$upvoteshtml.'</span>';
				$downvoteshtml='<span class="votes-down">'.$downvoteshtml.'</span>';
Gideon Greenspan committed
424
			}
Scott Vivian committed
425

Gideon Greenspan committed
426
		//	Pass information on vote viewing
Scott Vivian committed
427

Gideon Greenspan committed
428
		//	$voteview will be one of:
Gideon Greenspan committed
429 430
		//	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 Vivian committed
431

Gideon Greenspan committed
432
			$fields['vote_view']=(substr($voteview, 0, 6)=='updown') ? 'updown' : 'net';
Scott Vivian committed
433

Gideon Greenspan committed
434
			$fields['vote_on_page']=strpos($voteview, '-disabled-page') ? 'disabled' : 'enabled';
Scott Vivian committed
435

Gideon Greenspan committed
436 437
			$fields['upvotes_view']=($upvotes==1) ? qa_lang_html_sub_split('main/1_liked', $upvoteshtml, '1')
				: qa_lang_html_sub_split('main/x_liked', $upvoteshtml);
Scott Vivian committed
438

Gideon Greenspan committed
439 440
			$fields['downvotes_view']=($downvotes==1) ? qa_lang_html_sub_split('main/1_disliked', $downvoteshtml, '1')
				: qa_lang_html_sub_split('main/x_disliked', $downvoteshtml);
Scott Vivian committed
441

Gideon Greenspan committed
442 443
			$fields['netvotes_view']=(abs($netvotes)==1) ? qa_lang_html_sub_split('main/1_vote', $netvoteshtml, '1')
				: qa_lang_html_sub_split('main/x_votes', $netvoteshtml);
Scott Vivian committed
444

Gideon Greenspan committed
445
		//	Voting buttons
Scott Vivian committed
446

Gideon Greenspan committed
447 448
			$fields['vote_tags']='id="voting_'.qa_html($postid).'"';
			$onclick='onclick="return qa_vote_click(this);"';
Scott Vivian committed
449

Gideon Greenspan committed
450 451
			if ($fields['hidden']) {
				$fields['vote_state']='disabled';
Gideon Greenspan committed
452
				$fields['vote_up_tags']='title="'.qa_lang_html($isanswer ? 'main/vote_disabled_hidden_a' : 'main/vote_disabled_hidden_q').'"';
Gideon Greenspan committed
453
				$fields['vote_down_tags']=$fields['vote_up_tags'];
Scott Vivian committed
454

Gideon Greenspan committed
455 456
			} elseif ($isbyuser) {
				$fields['vote_state']='disabled';
Gideon Greenspan committed
457
				$fields['vote_up_tags']='title="'.qa_lang_html($isanswer ? 'main/vote_disabled_my_a' : 'main/vote_disabled_my_q').'"';
Gideon Greenspan committed
458
				$fields['vote_down_tags']=$fields['vote_up_tags'];
Scott Vivian committed
459

Gideon Greenspan committed
460 461
			} elseif (strpos($voteview, '-disabled-')) {
				$fields['vote_state']=(@$post['uservote']>0) ? 'voted_up_disabled' : ((@$post['uservote']<0) ? 'voted_down_disabled' : 'disabled');
Scott Vivian committed
462

Gideon Greenspan committed
463
				if (strpos($voteview, '-disabled-page'))
Gideon Greenspan committed
464
					$fields['vote_up_tags']='title="'.qa_lang_html('main/vote_disabled_q_page_only').'"';
Gideon Greenspan committed
465
				elseif (strpos($voteview, '-disabled-approve'))
Gideon Greenspan committed
466
					$fields['vote_up_tags']='title="'.qa_lang_html('main/vote_disabled_approve').'"';
Gideon Greenspan committed
467
				else
Gideon Greenspan committed
468
					$fields['vote_up_tags']='title="'.qa_lang_html('main/vote_disabled_level').'"';
Scott Vivian committed
469

Gideon Greenspan committed
470 471 472 473
				$fields['vote_down_tags']=$fields['vote_up_tags'];

			} elseif (@$post['uservote']>0) {
				$fields['vote_state']='voted_up';
Gideon Greenspan committed
474
				$fields['vote_up_tags']='title="'.qa_lang_html('main/voted_up_popup').'" name="'.qa_html('vote_'.$postid.'_0_'.$elementid).'" '.$onclick;
Gideon Greenspan committed
475 476 477 478 479
				$fields['vote_down_tags']=' ';

			} elseif (@$post['uservote']<0) {
				$fields['vote_state']='voted_down';
				$fields['vote_up_tags']=' ';
Gideon Greenspan committed
480
				$fields['vote_down_tags']='title="'.qa_lang_html('main/voted_down_popup').'" name="'.qa_html('vote_'.$postid.'_0_'.$elementid).'" '.$onclick;
Scott Vivian committed
481

Gideon Greenspan committed
482
			} else {
Gideon Greenspan committed
483
				$fields['vote_up_tags']='title="'.qa_lang_html('main/vote_up_popup').'" name="'.qa_html('vote_'.$postid.'_1_'.$elementid).'" '.$onclick;
Scott Vivian committed
484

Gideon Greenspan committed
485 486
				if (strpos($voteview, '-uponly-level')) {
					$fields['vote_state']='up_only';
Gideon Greenspan committed
487
					$fields['vote_down_tags']='title="'.qa_lang_html('main/vote_disabled_down').'"';
Scott Vivian committed
488

Gideon Greenspan committed
489 490
				} elseif (strpos($voteview, '-uponly-approve')) {
					$fields['vote_state']='up_only';
Gideon Greenspan committed
491
					$fields['vote_down_tags']='title="'.qa_lang_html('main/vote_disabled_down_approve').'"';
Scott Vivian committed
492

Gideon Greenspan committed
493 494
				} else {
					$fields['vote_state']='enabled';
Gideon Greenspan committed
495
					$fields['vote_down_tags']='title="'.qa_lang_html('main/vote_down_popup').'" name="'.qa_html('vote_'.$postid.'_-1_'.$elementid).'" '.$onclick;
Gideon Greenspan committed
496 497 498
				}
			}
		}
Scott Vivian committed
499

Gideon Greenspan committed
500
	//	Flag count
Scott Vivian committed
501

Gideon Greenspan committed
502 503 504
		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']);
Scott Vivian committed
505

Gideon Greenspan committed
506
	//	Created when and by whom
Scott Vivian committed
507

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

Gideon Greenspan committed
510 511
		if (@$options['whatview'] ) {
			$fields['what']=qa_lang_html($isquestion ? 'main/asked' : ($isanswer ? 'main/answered' : 'main/commented'));
Scott Vivian committed
512

Gideon Greenspan committed
513
			if (@$options['whatlink'] && strlen(@$options['q_request']))
Gideon Greenspan committed
514 515
				$fields['what_url']=($post['basetype']=='Q') ? qa_path_html($options['q_request'])
					: qa_path_html($options['q_request'], array('show' => $postid), null, null, qa_anchor($post['basetype'], $postid));
Gideon Greenspan committed
516
		}
Scott Vivian committed
517

Gideon Greenspan committed
518 519
		if (isset($post['created']) && @$options['whenview']) {
			$fields['when']=qa_when_to_html($post['created'], @$options['fulldatedays']);
Scott Vivian committed
520

Gideon Greenspan committed
521
			if ($microformats)
Gideon Greenspan committed
522
				$fields['when']['data']='<span class="published"><span class="value-title" title="'.gmdate('Y-m-d\TH:i:sO', $post['created']).'"></span>'.$fields['when']['data'].'</span>';
Gideon Greenspan committed
523
		}
Scott Vivian committed
524

Gideon Greenspan committed
525
		if (@$options['whoview']) {
Gideon Greenspan committed
526
			$fields['who']=qa_who_to_html($isbyuser, @$post['userid'], $usershtml, @$options['ipview'] ? @$post['createip'] : null, $microformats, $post['name']);
Scott Vivian committed
527

Gideon Greenspan committed
528 529 530 531
			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_html(number_format($post['points'])));
Scott Vivian committed
532

Gideon Greenspan committed
533 534 535
				if (isset($options['pointstitle']))
					$fields['who']['title']=qa_get_points_title_html($post['points'], $options['pointstitle']);
			}
Scott Vivian committed
536

Gideon Greenspan committed
537 538 539 540
			if (isset($post['level']))
				$fields['who']['level']=qa_html(qa_user_level_string($post['level']));
		}

Gideon Greenspan committed
541 542 543 544 545 546 547
		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']);
		}
Gideon Greenspan committed
548 549

	//	Updated when and by whom
Scott Vivian committed
550

Gideon Greenspan committed
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
		if (
			@$options['updateview'] && isset($post['updated']) &&
			(($post['updatetype']!=QA_UPDATE_SELECTED) || $isselected) && // only show selected change if it's still selected
			( // 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
				(isset($post['closedbyid']) && ($post['updatetype']==QA_UPDATE_CLOSED)) || // ... the post was closed as the last action
				(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 Vivian committed
567

Gideon Greenspan committed
568 569 570 571 572 573 574
				case QA_UPDATE_CATEGORY:
					$langstring='main/recategorized';
					break;

				case QA_UPDATE_VISIBLE:
					$langstring=$post['hidden'] ? 'main/hidden' : 'main/reshown';
					break;
Scott Vivian committed
575

Gideon Greenspan committed
576 577 578
				case QA_UPDATE_CLOSED:
					$langstring=isset($post['closedbyid']) ? 'main/closed' : 'main/reopened';
					break;
Scott Vivian committed
579

Gideon Greenspan committed
580 581 582
				case QA_UPDATE_TAGS:
					$langstring='main/retagged';
					break;
Scott Vivian committed
583

Gideon Greenspan committed
584 585 586
				case QA_UPDATE_SELECTED:
					$langstring='main/selected';
					break;
Scott Vivian committed
587

Gideon Greenspan committed
588 589 590 591
				default:
					$langstring='main/edited';
					break;
			}
Scott Vivian committed
592

Gideon Greenspan committed
593
			$fields['what_2']=qa_lang_html($langstring);
Scott Vivian committed
594

Gideon Greenspan committed
595 596
			if (@$options['whenview']) {
				$fields['when_2']=qa_when_to_html($post['updated'], @$options['fulldatedays']);
Scott Vivian committed
597

Gideon Greenspan committed
598
				if ($microformats)
Gideon Greenspan committed
599
					$fields['when_2']['data']='<span class="updated"><span class="value-title" title="'.gmdate('Y-m-d\TH:i:sO', $post['updated']).'"></span>'.$fields['when_2']['data'].'</span>';
Gideon Greenspan committed
600
			}
Scott Vivian committed
601

Gideon Greenspan committed
602 603 604
			if (isset($post['lastuserid']) && @$options['whoview'])
				$fields['who_2']=qa_who_to_html(isset($userid) && ($post['lastuserid']==$userid), $post['lastuserid'], $usershtml, @$options['ipview'] ? $post['lastip'] : null, false);
		}
Scott Vivian committed
605

Gideon Greenspan committed
606 607 608 609
	//	That's it!

		return $fields;
	}
Scott Vivian committed
610

Gideon Greenspan committed
611

Gideon Greenspan committed
612 613 614 615 616
	function qa_message_html_fields($message, $options=array())
/*
	Given $message retrieved from database, return an array of mostly HTML to be passed to theme layer.
	Pass viewing options in $options (see qa_message_html_defaults() in qa-app-options.php)
*/
Gideon Greenspan committed
617 618
	{
		require_once QA_INCLUDE_DIR.'qa-app-users.php';
Scott Vivian committed
619

Gideon Greenspan committed
620
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott Vivian committed
621

Scott committed
622 623
		$fields = array('raw' => $message);
		$fields['tags'] = 'id="m'.qa_html($message['messageid']).'"';
Scott Vivian committed
624

Gideon Greenspan committed
625
	//	Message content
Scott Vivian committed
626

Scott committed
627
		$viewer = qa_load_viewer($message['content'], $message['format']);
Scott Vivian committed
628

Scott committed
629
		$fields['content'] = $viewer->get_html($message['content'], $message['format'], array(
Gideon Greenspan committed
630 631 632 633
			'blockwordspreg' => @$options['blockwordspreg'],
			'showurllinks' => @$options['showurllinks'],
			'linksnewwindow' => @$options['linksnewwindow'],
		));
Scott Vivian committed
634

Gideon Greenspan committed
635
	//	Set ordering of meta elements which can be language-specific
Scott Vivian committed
636

Scott committed
637
		$fields['meta_order'] = qa_lang_html('main/meta_order');
Scott Vivian committed
638

Scott committed
639
		$fields['what'] = qa_lang_html('main/written');
Gideon Greenspan committed
640 641

	//	When it was written
Scott Vivian committed
642

Gideon Greenspan committed
643
		if (@$options['whenview'])
Scott committed
644
			$fields['when'] = qa_when_to_html($message['created'], @$options['fulldatedays']);
Gideon Greenspan committed
645 646

	//	Who wrote it, and their avatar
Scott Vivian committed
647

Scott committed
648 649 650 651 652 653 654
		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 {
Scott committed
655
			// for everything else (received private messages, wall messages)
Scott committed
656 657 658 659 660 661 662
			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 Vivian committed
663

Gideon Greenspan committed
664
	//	That's it!
Scott Vivian committed
665

Gideon Greenspan committed
666 667
		return $fields;
	}
Scott Vivian committed
668 669


Gideon Greenspan committed
670
	function qa_who_to_html($isbyuser, $postuserid, $usershtml, $ip=null, $microformats=false, $name=null)
Gideon Greenspan committed
671 672 673 674
/*
	Return array of split HTML (prefix, data, suffix) to represent author of post
*/
	{
Gideon Greenspan committed
675
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott Vivian committed
676

Gideon Greenspan committed
677 678 679
		if (isset($postuserid) && isset($usershtml[$postuserid])) {
			$whohtml=$usershtml[$postuserid];
			if ($microformats)
Gideon Greenspan committed
680
				$whohtml='<span class="vcard author">'.$whohtml.'</span>';
Gideon Greenspan committed
681

Gideon Greenspan committed
682 683 684 685 686 687 688
		} else {
			if (strlen($name))
				$whohtml=qa_html($name);
			elseif ($isbyuser)
				$whohtml=qa_lang_html('main/me');
			else
				$whohtml=qa_lang_html('main/anonymous');
Scott Vivian committed
689

Gideon Greenspan committed
690 691 692
			if (isset($ip))
				$whohtml=qa_ip_anchor_html($ip, $whohtml);
		}
Scott Vivian committed
693

Gideon Greenspan committed
694 695
		return qa_lang_html_sub_split('main/by_x', $whohtml);
	}
Scott Vivian committed
696 697


Gideon Greenspan committed
698 699 700 701 702 703
	function qa_when_to_html($timestamp, $fulldatedays)
/*
	Return array of split HTML (prefix, data, suffix) to represent unix $timestamp, with the full date shown if it's
	more than $fulldatedays ago
*/
	{
Gideon Greenspan committed
704
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott Vivian committed
705

Gideon Greenspan committed
706
		$interval=qa_opt('db_time')-$timestamp;
Scott Vivian committed
707

Gideon Greenspan committed
708 709 710
		if ( ($interval<0) || (isset($fulldatedays) && ($interval>(86400*$fulldatedays))) ) { // full style date
			$stampyear=date('Y', $timestamp);
			$thisyear=date('Y', qa_opt('db_time'));
Scott Vivian committed
711

Gideon Greenspan committed
712 713 714 715 716 717 718 719 720 721 722 723
			return array(
				'data' => qa_html(strtr(qa_lang(($stampyear==$thisyear) ? 'main/date_format_this_year' : 'main/date_format_other_years'), 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),
				))),
			);

		} else // ago-style date
			return qa_lang_html_sub_split('main/x_ago', qa_html(qa_time_to_string($interval)));
	}

Scott Vivian committed
724

Gideon Greenspan committed
725 726 727 728
	function qa_other_to_q_html_fields($question, $userid, $cookieid, $usershtml, $dummy, $options)
/*
	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.
Gideon Greenspan committed
729 730
	$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).
Gideon Greenspan committed
731 732
*/
	{
Gideon Greenspan committed
733
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott Vivian committed
734

Gideon Greenspan committed
735
		require_once QA_INCLUDE_DIR.'qa-app-updates.php';
Scott Vivian committed
736

Gideon Greenspan committed
737
		$fields=qa_post_html_fields($question, $userid, $cookieid, $usershtml, null, $options);
Scott Vivian committed
738 739

		switch ($question['obasetype'].'-'.@$question['oupdatetype']) {
Gideon Greenspan committed
740 741 742
			case 'Q-':
				$langstring='main/asked';
				break;
Scott Vivian committed
743

Gideon Greenspan committed
744
			case 'Q-'.QA_UPDATE_VISIBLE:
Gideon Greenspan committed
745 746 747 748
				if (@$question['opersonal'])
					$langstring=$question['hidden'] ? 'misc/your_q_hidden' : 'misc/your_q_reshown';
				else
					$langstring=$question['hidden'] ? 'main/hidden' : 'main/reshown';
Gideon Greenspan committed
749
				break;
Scott Vivian committed
750

Gideon Greenspan committed
751
			case 'Q-'.QA_UPDATE_CLOSED:
Gideon Greenspan committed
752 753 754 755
				if (@$question['opersonal'])
					$langstring=isset($question['closedbyid']) ? 'misc/your_q_closed' : 'misc/your_q_reopened';
				else
					$langstring=isset($question['closedbyid']) ? 'main/closed' : 'main/reopened';
Gideon Greenspan committed
756
				break;
Scott Vivian committed
757

Gideon Greenspan committed
758
			case 'Q-'.QA_UPDATE_TAGS:
Gideon Greenspan committed
759
				$langstring=@$question['opersonal'] ? 'misc/your_q_retagged' : 'main/retagged';
Gideon Greenspan committed
760
				break;
Scott Vivian committed
761

Gideon Greenspan committed
762
			case 'Q-'.QA_UPDATE_CATEGORY:
Gideon Greenspan committed
763
				$langstring=@$question['opersonal'] ? 'misc/your_q_recategorized' : 'main/recategorized';
Gideon Greenspan committed
764 765 766
				break;

			case 'A-':
Gideon Greenspan committed
767
				$langstring=@$question['opersonal'] ? 'misc/your_q_answered' : 'main/answered';
Gideon Greenspan committed
768
				break;
Scott Vivian committed
769

Gideon Greenspan committed
770
			case 'A-'.QA_UPDATE_SELECTED:
Gideon Greenspan committed
771
				$langstring=@$question['opersonal'] ? 'misc/your_a_selected' : 'main/answer_selected';
Gideon Greenspan committed
772
				break;
Scott Vivian committed
773

Gideon Greenspan committed
774
			case 'A-'.QA_UPDATE_VISIBLE:
Gideon Greenspan committed
775 776 777 778
				if (@$question['opersonal'])
					$langstring=$question['ohidden'] ? 'misc/your_a_hidden' : 'misc/your_a_reshown';
				else
					$langstring=$question['ohidden'] ? 'main/hidden' : 'main/answer_reshown';
Gideon Greenspan committed
779
				break;
Scott Vivian committed
780

Gideon Greenspan committed
781
			case 'A-'.QA_UPDATE_CONTENT:
Gideon Greenspan committed
782
				$langstring=@$question['opersonal'] ? 'misc/your_a_edited' : 'main/answer_edited';
Gideon Greenspan committed
783
				break;
Scott Vivian committed
784

Gideon Greenspan committed
785
			case 'Q-'.QA_UPDATE_FOLLOWS:
Gideon Greenspan committed
786
				$langstring=@$question['opersonal'] ? 'misc/your_a_questioned' : 'main/asked_related_q';
Gideon Greenspan committed
787
				break;
Scott Vivian committed
788

Gideon Greenspan committed
789 790 791
			case 'C-':
				$langstring='main/commented';
				break;
Scott Vivian committed
792

Gideon Greenspan committed
793 794 795
			case 'C-'.QA_UPDATE_C_FOR_Q:
				$langstring=@$question['opersonal'] ? 'misc/your_q_commented' : 'main/commented';
				break;
Scott Vivian committed
796

Gideon Greenspan committed
797 798 799
			case 'C-'.QA_UPDATE_C_FOR_A:
				$langstring=@$question['opersonal'] ? 'misc/your_a_commented' : 'main/commented';
				break;
Scott Vivian committed
800

Gideon Greenspan committed
801 802 803
			case 'C-'.QA_UPDATE_FOLLOWS:
				$langstring=@$question['opersonal'] ? 'misc/your_c_followed' : 'main/commented';
				break;
Scott Vivian committed
804

Gideon Greenspan committed
805
			case 'C-'.QA_UPDATE_TYPE:
Gideon Greenspan committed
806
				$langstring=@$question['opersonal'] ? 'misc/your_c_moved' : 'main/comment_moved';
Gideon Greenspan committed
807
				break;
Scott Vivian committed
808

Gideon Greenspan committed
809
			case 'C-'.QA_UPDATE_VISIBLE:
Gideon Greenspan committed
810 811 812 813
				if (@$question['opersonal'])
					$langstring=$question['ohidden'] ? 'misc/your_c_hidden' : 'misc/your_c_reshown';
				else
					$langstring=$question['ohidden'] ? 'main/hidden' : 'main/comment_reshown';
Gideon Greenspan committed
814
				break;
Scott Vivian committed
815

Gideon Greenspan committed
816
			case 'C-'.QA_UPDATE_CONTENT:
Gideon Greenspan committed
817
				$langstring=@$question['opersonal'] ? 'misc/your_c_edited' : 'main/comment_edited';
Gideon Greenspan committed
818
				break;
Scott Vivian committed
819

Gideon Greenspan committed
820 821
			case 'Q-'.QA_UPDATE_CONTENT:
			default:
Gideon Greenspan committed
822
				$langstring=@$question['opersonal'] ? 'misc/your_q_edited' : 'main/edited';
Gideon Greenspan committed
823 824
				break;
		}
Scott Vivian committed
825

Gideon Greenspan committed
826
		$fields['what']=qa_lang_html($langstring);
Scott Vivian committed
827

Gideon Greenspan committed
828 829
		if (@$question['opersonal'])
			$fields['what_your']=true;
Scott Vivian committed
830

Gideon Greenspan committed
831 832 833 834 835
		if ( ($question['obasetype']!='Q') || (@$question['oupdatetype']==QA_UPDATE_FOLLOWS) )
			$fields['what_url']=qa_q_path_html($question['postid'], $question['title'], false, $question['obasetype'], $question['opostid']);

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

Gideon Greenspan committed
837 838 839 840 841 842
			$fields['content']=$viewer->get_html($question['ocontent'], $question['oformat'], array(
				'blockwordspreg' => @$options['blockwordspreg'],
				'showurllinks' => @$options['showurllinks'],
				'linksnewwindow' => @$options['linksnewwindow'],
			));
		}
Scott Vivian committed
843

Gideon Greenspan committed
844 845
		if (@$options['whenview'])
			$fields['when']=qa_when_to_html($question['otime'], @$options['fulldatedays']);
Scott Vivian committed
846

Gideon Greenspan committed
847 848
		if (@$options['whoview']) {
			$isbyuser=qa_post_is_by_user(array('userid' => $question['ouserid'], 'cookieid' => @$question['ocookieid']), $userid, $cookieid);
Scott Vivian committed
849

Gideon Greenspan committed
850
			$fields['who']=qa_who_to_html($isbyuser, $question['ouserid'], $usershtml, @$options['ipview'] ? @$question['oip'] : null, false, @$question['oname']);
Scott Vivian committed
851

Gideon Greenspan committed
852 853 854 855
			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_html(number_format($question['opoints'])));
Scott Vivian committed
856

Gideon Greenspan committed
857 858 859 860 861 862 863
				if (isset($options['pointstitle']))
					$fields['who']['title']=qa_get_points_title_html($question['opoints'], $options['pointstitle']);
			}

			if (isset($question['olevel']))
				$fields['who']['level']=qa_html(qa_user_level_string($question['olevel']));
		}
Scott Vivian committed
864

Gideon Greenspan committed
865 866 867 868 869 870
		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']);

		unset($fields['avatar']);
Gideon Greenspan committed
871 872
		if (@$options['avatarsize']>0) {
			if (QA_FINAL_EXTERNAL_USERS)
Gideon Greenspan committed
873
				$fields['avatar']=qa_get_external_avatar_html($question['ouserid'], $options['avatarsize'], false);
Gideon Greenspan committed
874 875 876 877
			else
				$fields['avatar']=qa_get_user_avatar_html($question['oflags'], $question['oemail'], $question['ohandle'],
					$question['oavatarblobid'], $question['oavatarwidth'], $question['oavatarheight'], $options['avatarsize']);
		}
Scott Vivian committed
878

Gideon Greenspan committed
879 880
		return $fields;
	}
Scott Vivian committed
881 882


Gideon Greenspan committed
883 884 885 886 887 888 889 890 891 892 893 894 895
	function qa_any_to_q_html_fields($question, $userid, $cookieid, $usershtml, $dummy, $options)
/*
	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.
*/
	{
		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;
	}
Scott Vivian committed
896

Gideon Greenspan committed
897 898 899 900 901 902 903

	function qa_any_sort_by_date($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, without removing duplicate references to the same question.
*/
	{
Gideon Greenspan committed
904
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott Vivian committed
905

Gideon Greenspan committed
906
		require_once QA_INCLUDE_DIR.'qa-util-sort.php';
Scott Vivian committed
907

Gideon Greenspan committed
908 909
		foreach ($questions as $key => $question) // collect information about action referenced by each $question
			$questions[$key]['sort']=-(isset($question['opostid']) ? $question['otime'] : $question['created']);
Scott Vivian committed
910

Gideon Greenspan committed
911
		qa_sort_by($questions, 'sort');
Scott Vivian committed
912

Gideon Greenspan committed
913 914
		return $questions;
	}
Scott Vivian committed
915 916


Gideon Greenspan committed
917 918 919 920 921 922
	function qa_any_sort_and_dedupe($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.
*/
	{
Gideon Greenspan committed
923
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott Vivian committed
924

Gideon Greenspan committed
925
		require_once QA_INCLUDE_DIR.'qa-util-sort.php';
Scott Vivian committed
926

Gideon Greenspan committed
927 928 929 930 931 932 933 934 935 936 937 938 939
		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'];
			}

			$questions[$key]['sort']=-$questions[$key]['_time'];
		}
Scott Vivian committed
940

Gideon Greenspan committed
941
		qa_sort_by($questions, 'sort');
Scott Vivian committed
942

Gideon Greenspan committed
943 944 945
		$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 Vivian committed
946

Gideon Greenspan committed
947 948 949
			if (
				(!isset($laterquestion)) // keep this reference if there is no more recent one
			|| // or ...
Gideon Greenspan committed
950 951 952
				(
					(@$laterquestion['oupdatetype']) && // the more recent reference was an edit
					(!@$question['oupdatetype']) && // this is not an edit
Scott Vivian committed
953
					($laterquestion['_type']==$question['_type']) && // the same part (Q/A/C) is referenced here
Gideon Greenspan committed
954 955 956
					($laterquestion['_userid']==$question['_userid']) && // the same user made the later edit
					(abs($laterquestion['_time']-$question['_time'])<300) // the edit was within 5 minutes of creation
				)
Gideon Greenspan committed
957 958 959 960 961 962
			|| // or ...
				(
					(@$question['opersonal']) && // this question (in an update list) is personal to the user
					(!@$laterquestion['opersonal']) && // the other one was not personal
					(abs($laterquestion['_time']-$question['_time'])<300) // the two events were within 5 minutes of each other
				)
Gideon Greenspan committed
963 964 965
			)
				$keepquestions[$question['postid']]=$question;
		}
Scott Vivian committed
966

Gideon Greenspan committed
967 968 969
		return $keepquestions;
	}

Scott Vivian committed
970

Gideon Greenspan committed
971 972 973 974 975 976 977
	function qa_any_get_userids_handles($questions)
/*
	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.
*/
	{
		$userids_handles=array();
Scott Vivian committed
978

Gideon Greenspan committed
979 980 981 982 983 984
		foreach ($questions as $question)
			if (isset($question['opostid']))
				$userids_handles[]=array(
					'userid' => @$question['ouserid'],
					'handle' => @$question['ohandle'],
				);
Scott Vivian committed
985

Gideon Greenspan committed
986 987 988 989 990
			else
				$userids_handles[]=array(
					'userid' => @$question['userid'],
					'handle' => @$question['handle'],
				);
Scott Vivian committed
991

Gideon Greenspan committed
992 993
		return $userids_handles;
	}
Scott Vivian committed
994 995


Scott committed
996
	function qa_html_convert_urls($html, $newwindow = false)
Gideon Greenspan committed
997
/*
Scott committed
998 999 1000
	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)
Gideon Greenspan committed
1001 1002
*/
	{
Gideon Greenspan committed
1003
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott Vivian committed
1004

Scott committed
1005
		$uc = 'a-z\x{00a1}-\x{ffff}';
1006
		$url_regex = '#\b((?:https?|ftp)://(?:[0-9'.$uc.'][0-9'.$uc.'-]*\.)+['.$uc.']{2,}(?::\d{2,5})?(?:/(?:[^\s<>]*[^\s<>\.])?)?)#iu';
Scott committed
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044

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

			// 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;
				}

				$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]));
			}
		}

		return $html;
Gideon Greenspan committed
1045 1046
	}

Scott Vivian committed
1047

Gideon Greenspan committed
1048 1049 1050 1051 1052
	function qa_url_to_html_link($url, $newwindow=false)
/*
	Return HTML representation of $url (if it appears to be an URL), linked with nofollow and in a new window if $newwindow
*/
	{
Gideon Greenspan committed
1053
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott Vivian committed
1054

Gideon Greenspan committed
1055 1056 1057 1058
		if (is_numeric(strpos($url, '.'))) {
			$linkurl=$url;
			if (!is_numeric(strpos($linkurl, ':/')))
				$linkurl='http://'.$linkurl;
Scott Vivian committed
1059

Gideon Greenspan committed
1060
			return '<a href="'.qa_html($linkurl).'" rel="nofollow"'.($newwindow ? ' target="_blank"' : '').'>'.qa_html($url).'</a>';
Scott Vivian committed
1061

Gideon Greenspan committed
1062 1063 1064 1065
		} else
			return qa_html($url);
	}

Scott Vivian committed
1066

Gideon Greenspan committed
1067 1068 1069 1070 1071 1072
	function qa_insert_login_links($htmlmessage, $topage=null, $params=null)
/*
	Return $htmlmessage with ^1...^6 substituted for links to log in or register or confirm email and come back to $topage with $params
*/
	{
		require_once QA_INCLUDE_DIR.'qa-app-users.php';
Scott Vivian committed
1073

Gideon Greenspan committed
1074
		$userlinks=qa_get_login_links(qa_path_to_root(), isset($topage) ? qa_path($topage, $params, '') : null);
Scott Vivian committed
1075

Gideon Greenspan committed
1076 1077
		return strtr(
			$htmlmessage,
Scott Vivian committed
1078

Gideon Greenspan committed
1079
			array(
Gideon Greenspan committed
1080 1081 1082 1083 1084 1085
				'^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>',
Gideon Greenspan committed
1086 1087 1088 1089
			)
		);
	}

Scott Vivian committed
1090

Gideon Greenspan committed
1091 1092 1093 1094 1095 1096 1097 1098 1099
	function qa_html_page_links($request, $start, $pagesize, $count, $prevnext, $params=array(), $hasmore=false, $anchor=null)
/*
	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.
*/
	{
Gideon Greenspan committed
1100
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott Vivian committed
1101

Gideon Greenspan committed
1102 1103
		$thispage=1+floor($start/$pagesize);
		$lastpage=ceil(min($count, 1+QA_MAX_LIMIT_START)/$pagesize);
Scott Vivian committed
1104

Gideon Greenspan committed
1105 1106
		if (($thispage>1) || ($lastpage>$thispage)) {
			$links=array('label' => qa_lang_html('main/page_label'), 'items' => array());
Scott Vivian committed
1107

Gideon Greenspan committed
1108
			$keypages[1]=true;
Scott Vivian committed
1109

Gideon Greenspan committed
1110 1111
			for ($page=max(2, min($thispage, $lastpage)-$prevnext); $page<=min($thispage+$prevnext, $lastpage); $page++)
				$keypages[$page]=true;
Scott Vivian committed
1112

Gideon Greenspan committed
1113
			$keypages[$lastpage]=true;
Scott Vivian committed
1114

Gideon Greenspan committed
1115 1116 1117 1118 1119 1120 1121
			if ($thispage>1)
				$links['items'][]=array(
					'type' => 'prev',
					'label' => qa_lang_html('main/page_prev'),
					'page' => $thispage-1,
					'ellipsis' => false,
				);
Scott Vivian committed
1122

Gideon Greenspan committed
1123 1124 1125 1126 1127 1128 1129
			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 Vivian committed
1130

Gideon Greenspan committed
1131 1132 1133 1134 1135 1136 1137
			if ($thispage<$lastpage)
				$links['items'][]=array(
					'type' => 'next',
					'label' => qa_lang_html('main/page_next'),
					'page' => $thispage+1,
					'ellipsis' => false,
				);
Scott Vivian committed
1138

Gideon Greenspan committed
1139 1140 1141 1142 1143
			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);
				}
Scott Vivian committed
1144

Gideon Greenspan committed
1145 1146
		} else
			$links=null;
Scott Vivian committed
1147

Gideon Greenspan committed
1148 1149 1150
		return $links;
	}

Scott Vivian committed
1151

Gideon Greenspan committed
1152 1153 1154 1155 1156 1157
	function qa_html_suggest_qs_tags($usingtags=false, $categoryrequest=null)
/*
	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
*/
	{
Gideon Greenspan committed
1158
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott Vivian committed
1159

Gideon Greenspan committed
1160
		$hascategory=strlen($categoryrequest);
Scott Vivian committed
1161

Gideon Greenspan committed
1162 1163
		$htmlmessage=$hascategory ? qa_lang_html('main/suggest_category_qs') :
			($usingtags ? qa_lang_html('main/suggest_qs_tags') : qa_lang_html('main/suggest_qs'));
Scott Vivian committed
1164

Gideon Greenspan committed
1165 1166
		return strtr(
			$htmlmessage,
Scott Vivian committed
1167

Gideon Greenspan committed
1168
			array(
Gideon Greenspan committed
1169 1170 1171 1172
				'^1' => '<a href="'.qa_path_html('questions'.($hascategory ? ('/'.$categoryrequest) : '')).'">',
				'^2' => '</a>',
				'^3' => '<a href="'.qa_path_html('tags').'">',
				'^4' => '</a>',
Gideon Greenspan committed
1173 1174 1175 1176
			)
		);
	}

Scott Vivian committed
1177

Gideon Greenspan committed
1178 1179 1180 1181 1182
	function qa_html_suggest_ask($categoryid=null)
/*
	Return HTML that suggest getting things started by asking a question, in $categoryid if not null
*/
	{
Gideon Greenspan committed
1183
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott Vivian committed
1184

Gideon Greenspan committed
1185
		$htmlmessage=qa_lang_html('main/suggest_ask');
Scott Vivian committed
1186

Gideon Greenspan committed
1187 1188
		return strtr(
			$htmlmessage,
Scott Vivian committed
1189

Gideon Greenspan committed
1190
			array(
Gideon Greenspan committed
1191 1192
				'^1' => '<a href="'.qa_path_html('ask', strlen($categoryid) ? array('cat' => $categoryid) : null).'">',
				'^2' => '</a>',
Gideon Greenspan committed
1193 1194 1195
			)
		);
	}
Scott Vivian committed
1196 1197


Gideon Greenspan committed
1198 1199 1200 1201 1202 1203
	function qa_category_navigation($categories, $selectedid=null, $pathprefix='', $showqcount=true, $pathparams=null)
/*
	Return the navigation structure for the category hierarchical menu, with $selectedid selected,
	and links beginning with $pathprefix, and showing question counts if $showqcount
*/
	{
Gideon Greenspan committed
1204
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott Vivian committed
1205

Gideon Greenspan committed
1206
		$parentcategories=array();
Scott Vivian committed
1207

Gideon Greenspan committed
1208 1209
		foreach ($categories as $category)
			$parentcategories[$category['parentid']][]=$category;
Scott Vivian committed
1210

Gideon Greenspan committed
1211
		$selecteds=qa_category_path($categories, $selectedid);
Gideon Greenspan committed
1212
		$favoritemap=qa_get_favorite_non_qs_map();
Scott Vivian committed
1213

Gideon Greenspan committed
1214
		return qa_category_navigation_sub($parentcategories, null, $selecteds, $pathprefix, $showqcount, $pathparams, $favoritemap);
Gideon Greenspan committed
1215
	}
Scott Vivian committed
1216 1217


Gideon Greenspan committed
1218
	function qa_category_navigation_sub($parentcategories, $parentid, $selecteds, $pathprefix, $showqcount, $pathparams, $favoritemap=null)
Gideon Greenspan committed
1219 1220 1221 1222
/*
	Recursion function used by qa_category_navigation(...) to build hierarchical category menu.
*/
	{
Gideon Greenspan committed
1223
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott Vivian committed
1224

Gideon Greenspan committed
1225
		$navigation=array();
Scott Vivian committed
1226

Gideon Greenspan committed
1227 1228 1229 1230 1231 1232 1233
		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 Vivian committed
1234

Gideon Greenspan committed
1235 1236 1237 1238 1239 1240 1241 1242
		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(number_format($category['qcount'])).')') : null,
Gideon Greenspan committed
1243 1244
					'subnav' => qa_category_navigation_sub($parentcategories, $category['categoryid'], $selecteds,
						$pathprefix.$category['tags'].'/', $showqcount, $pathparams, $favoritemap),
Gideon Greenspan committed
1245
					'categoryid' => $category['categoryid'],
Gideon Greenspan committed
1246
					'favorited' => @$favoritemap['category'][$category['backpath']],
Gideon Greenspan committed
1247
				);
Scott Vivian committed
1248

Gideon Greenspan committed
1249 1250
		return $navigation;
	}
Scott Vivian committed
1251 1252


Gideon Greenspan committed
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
	function qa_users_sub_navigation()
/*
	Return the sub navigation structure for user listing pages
*/
	{
		if ((!QA_FINAL_EXTERNAL_USERS) && (qa_get_logged_in_level()>=QA_USER_LEVEL_MODERATOR)) {
			return array(
				'users$' => array(
					'url' => qa_path_html('users'),
					'label' => qa_lang_html('main/highest_users'),
				),
Scott Vivian committed
1264

Gideon Greenspan committed
1265 1266 1267 1268
				'users/special' => array(
					'label' => qa_lang('users/special_users'),
					'url' => qa_path_html('users/special'),
				),
Scott Vivian committed
1269

Gideon Greenspan committed
1270 1271 1272 1273 1274
				'users/blocked' => array(
					'label' => qa_lang('users/blocked_users'),
					'url' => qa_path_html('users/blocked'),
				),
			);
Scott Vivian committed
1275

Gideon Greenspan committed
1276 1277 1278
		} else
			return null;
	}
Scott Vivian committed
1279 1280


Gideon Greenspan committed
1281
	function qa_user_sub_navigation($handle, $selected, $ismyuser=false)
Gideon Greenspan committed
1282 1283 1284
/*
	Return the sub navigation structure for navigating between the different pages relating to a user
*/
Gideon Greenspan committed
1285 1286 1287 1288 1289 1290
	{
		$navigation=array(
			'profile' => array(
				'label' => qa_lang_html_sub('profile/user_x', qa_html($handle)),
				'url' => qa_path_html('user/'.$handle),
			),
Scott Vivian committed
1291

Gideon Greenspan committed
1292 1293 1294 1295
			'account' => array(
				'label' => qa_lang_html('misc/nav_my_details'),
				'url' => qa_path_html('account'),
			),
Scott Vivian committed
1296

Gideon Greenspan committed
1297 1298 1299 1300
			'favorites' => array(
				'label' => qa_lang_html('misc/nav_my_favorites'),
				'url' => qa_path_html('favorites'),
			),
Scott Vivian committed
1301

Gideon Greenspan committed
1302 1303 1304 1305
			'wall' => array(
				'label' => qa_lang_html('misc/nav_user_wall'),
				'url' => qa_path_html('user/'.$handle.'/wall'),
			),
Scott Vivian committed
1306

Scott committed
1307 1308 1309 1310 1311
			'messages' => array(
				'label' => qa_lang_html('misc/nav_user_pms'),
				'url' => qa_path_html('messages'),
			),

Gideon Greenspan committed
1312 1313 1314 1315
			'activity' => array(
				'label' => qa_lang_html('misc/nav_user_activity'),
				'url' => qa_path_html('user/'.$handle.'/activity'),
			),
Scott Vivian committed
1316

Gideon Greenspan committed
1317 1318 1319 1320
			'questions' => array(
				'label' => qa_lang_html('misc/nav_user_qs'),
				'url' => qa_path_html('user/'.$handle.'/questions'),
			),
Scott Vivian committed
1321

Gideon Greenspan committed
1322 1323 1324 1325 1326
			'answers' => array(
				'label' => qa_lang_html('misc/nav_user_as'),
				'url' => qa_path_html('user/'.$handle.'/answers'),
			),
		);
Scott Vivian committed
1327

Gideon Greenspan committed
1328 1329
		if (isset($navigation[$selected]))
			$navigation[$selected]['selected']=true;
Scott Vivian committed
1330

Gideon Greenspan committed
1331
		if (QA_FINAL_EXTERNAL_USERS || !qa_opt('allow_user_walls'))
Gideon Greenspan committed
1332
			unset($navigation['wall']);
Scott Vivian committed
1333

Gideon Greenspan committed
1334 1335
		if (QA_FINAL_EXTERNAL_USERS || !$ismyuser)
			unset($navigation['account']);
Scott Vivian committed
1336

Gideon Greenspan committed
1337 1338
		if (!$ismyuser)
			unset($navigation['favorites']);
Scott Vivian committed
1339

Scott committed
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
		if (!$ismyuser || !qa_opt('allow_private_messages') || !qa_opt('show_message_history'))
			unset($navigation['messages']);

		return $navigation;
	}


	function qa_messages_sub_navigation($selected=null)
/*
	Return the sub navigation structure for private message pages
*/
	{
		$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;

Gideon Greenspan committed
1367 1368
		return $navigation;
	}
Scott Vivian committed
1369 1370


1371 1372 1373 1374 1375
	/**
	 * Return the sub navigation structure for user account pages.
	 *
	 * @deprecated Deprecated from 1.6.3; use `qa_user_sub_navigation()` instead.
	 */
Gideon Greenspan committed
1376 1377 1378 1379 1380 1381 1382
	function qa_account_sub_navigation()
	{
		return array(
			'account' => array(
				'label' => qa_lang_html('misc/nav_my_details'),
				'url' => qa_path_html('account'),
			),
Scott Vivian committed
1383

Gideon Greenspan committed
1384 1385 1386 1387 1388 1389
			'favorites' => array(
				'label' => qa_lang_html('misc/nav_my_favorites'),
				'url' => qa_path_html('favorites'),
			),
		);
	}
Scott Vivian committed
1390 1391


Gideon Greenspan committed
1392 1393 1394 1395 1396 1397 1398 1399 1400
	function qa_custom_page_url($page)
/*
	Return the url for $page retrieved from the database
*/
	{
		return ($page['flags'] & QA_PAGE_FLAGS_EXTERNAL)
			? (is_numeric(strpos($page['tags'], '://')) ? $page['tags'] : qa_path_to_root().$page['tags'])
			: qa_path($page['tags']);
	}
Scott Vivian committed
1401 1402


Gideon Greenspan committed
1403 1404 1405 1406 1407 1408 1409
	function qa_navigation_add_page(&$navigation, $page)
/*
	Add an element to the $navigation array corresponding to $page retrieved from the database
*/
	{
		if (
			(!qa_permit_value_error($page['permit'], qa_get_logged_in_userid(), qa_get_logged_in_level(), qa_get_logged_in_flags())) || !isset($page['permit'])
Gideon Greenspan committed
1410 1411
		) {
			$url=qa_custom_page_url($page);
Scott Vivian committed
1412

Gideon Greenspan committed
1413
			$navigation[($page['flags'] & QA_PAGE_FLAGS_EXTERNAL) ? ('custom-'.$page['pageid']) : ($page['tags'].'$')]=array(
Gideon Greenspan committed
1414
				'url' => qa_html($url),
Gideon Greenspan committed
1415 1416 1417
				'label' => qa_html($page['title']),
				'opposite' => ($page['nav']=='O'),
				'target' => ($page['flags'] & QA_PAGE_FLAGS_NEW_WINDOW) ? '_blank' : null,
Gideon Greenspan committed
1418
				'selected' => ($page['flags'] & QA_PAGE_FLAGS_EXTERNAL) && ( ($url==qa_path(qa_request())) || ($url==qa_self_html()) ),
Gideon Greenspan committed
1419
			);
Gideon Greenspan committed
1420
		}
Gideon Greenspan committed
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
	}


	function qa_match_to_min_score($match)
/*
	Convert an admin option for matching into a threshold for the score given by database search
*/
	{
		return 10-2*$match;
	}

Scott Vivian committed
1432

Gideon Greenspan committed
1433 1434 1435 1436 1437 1438 1439 1440
	function qa_set_display_rules(&$qa_content, $effects)
/*
	For each [target] => [source] in $effects, set up $qa_content so that the visibility of the DOM element ID
	target is equal to the checked state or boolean-casted value of the DOM element ID source. Each source can
	also combine multiple DOM IDs using JavaScript(=PHP) operators. This is twisted but rather convenient.
*/
	{
		$function='qa_display_rule_'.count(@$qa_content['script_lines']);
Scott Vivian committed
1441

Gideon Greenspan committed
1442
		$keysourceids=array();
Scott Vivian committed
1443

Gideon Greenspan committed
1444 1445 1446 1447
		foreach ($effects as $target => $sources)
			if (preg_match_all('/[A-Za-z_][A-Za-z0-9_]*/', $sources, $matches)) // element names must be legal JS variable names
				foreach ($matches[0] as $element)
					$keysourceids[$element]=true;
Scott Vivian committed
1448

Gideon Greenspan committed
1449 1450
		$funcscript=array("function ".$function."(first) {"); // build the Javascripts
		$loadscript=array();
Scott Vivian committed
1451

Gideon Greenspan committed
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461
		foreach ($keysourceids as $key => $dummy) {
			$funcscript[]="\tvar e=document.getElementById(".qa_js($key).");";
			$funcscript[]="\tvar ".$key."=e && (e.checked || (e.options && e.options[e.selectedIndex].value));";
			$loadscript[]="var e=document.getElementById(".qa_js($key).");";
			$loadscript[]="if (e) {";
			$loadscript[]="\t".$key."_oldonclick=e.onclick;";
			$loadscript[]="\te.onclick=function() {";
			$loadscript[]="\t\t".$function."(false);";
			$loadscript[]="\t\tif (typeof ".$key."_oldonclick=='function')";
			$loadscript[]="\t\t\t".$key."_oldonclick();";
Gideon Greenspan committed
1462
			$loadscript[]="\t};";
Gideon Greenspan committed
1463 1464
			$loadscript[]="}";
		}
Scott Vivian committed
1465

Gideon Greenspan committed
1466 1467 1468 1469
		foreach ($effects as $target => $sources) {
			$funcscript[]="\tvar e=document.getElementById(".qa_js($target).");";
			$funcscript[]="\tif (e) { var d=(".$sources."); if (first || (e.nodeName=='SPAN')) { e.style.display=d ? '' : 'none'; } else { if (d) { $(e).fadeIn(); } else { $(e).fadeOut(); } } }";
		}
Scott Vivian committed
1470

Gideon Greenspan committed
1471 1472
		$funcscript[]="}";
		$loadscript[]=$function."(true);";
Scott Vivian committed
1473

Gideon Greenspan committed
1474 1475 1476 1477
		$qa_content['script_lines'][]=$funcscript;
		$qa_content['script_onloads'][]=$loadscript;
	}

Scott Vivian committed
1478

Gideon Greenspan committed
1479 1480 1481 1482 1483 1484
	function qa_set_up_tag_field(&$qa_content, &$field, $fieldname, $tags, $exampletags, $completetags, $maxtags)
/*
	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.
*/
	{
Gideon Greenspan committed
1485
		$template='<a href="#" class="qa-tag-link" onclick="return qa_tag_click(this);">^</a>';
Gideon Greenspan committed
1486 1487 1488 1489 1490 1491 1492

		$qa_content['script_rel'][]='qa-content/qa-ask.js?'.QA_VERSION;
		$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;
Scott Vivian committed
1493

Gideon Greenspan committed
1494
		$separatorcomma=qa_opt('tag_separator_comma');
Scott Vivian committed
1495

Gideon Greenspan committed
1496 1497
		$field['label']=qa_lang_html($separatorcomma ? 'question/q_tags_comma_label' : 'question/q_tags_label');
		$field['value']=qa_html(implode($separatorcomma ? ', ' : ' ', $tags));
Gideon Greenspan committed
1498
		$field['tags']='name="'.$fieldname.'" id="tags" autocomplete="off" onkeyup="qa_tag_hints();" onmouseup="qa_tag_hints();"';
Scott Vivian committed
1499

Gideon Greenspan committed
1500
		$sdn=' style="display:none;"';
Scott Vivian committed
1501

Gideon Greenspan committed
1502
		$field['note']=
Gideon Greenspan committed
1503 1504
			'<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">';
Gideon Greenspan committed
1505 1506 1507 1508

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

Gideon Greenspan committed
1509
		$field['note'].='</span>';
Gideon Greenspan committed
1510 1511
		$field['note_force']=true;
	}
Scott Vivian committed
1512 1513


Gideon Greenspan committed
1514 1515 1516 1517 1518 1519
	function qa_get_tags_field_value($fieldname)
/*
	Get a list of user-entered tags submitted from a field that was created with qa_set_up_tag_field(...)
*/
	{
		require_once QA_INCLUDE_DIR.'qa-util-string.php';
Scott Vivian committed
1520

Gideon Greenspan committed
1521
		$text=qa_post_text($fieldname);
Scott Vivian committed
1522

Gideon Greenspan committed
1523 1524 1525 1526 1527
		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));
	}
Scott Vivian committed
1528 1529


Gideon Greenspan committed
1530 1531 1532 1533 1534 1535 1536 1537 1538
	function qa_set_up_category_field(&$qa_content, &$field, $fieldname, $navcategories, $categoryid, $allownone, $allownosub, $maxdepth=null, $excludecategoryid=null)
/*
	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.
*/
	{
1539
		$pathcategories = qa_category_path($navcategories, $categoryid);
Gideon Greenspan committed
1540

1541
		$startpath = '';
Gideon Greenspan committed
1542
		foreach ($pathcategories as $category)
1543
			$startpath .= '/' . $category['categoryid'];
Scott Vivian committed
1544

1545 1546 1547 1548
		if (isset($maxdepth))
			$maxdepth = min(QA_CATEGORY_DEPTH, $maxdepth);
		else
			$maxdepth = QA_CATEGORY_DEPTH;
Gideon Greenspan committed
1549

1550 1551
		$qa_content['script_rel'][] = 'qa-content/qa-ask.js?' . QA_VERSION;
		$qa_content['script_onloads'][] = sprintf('qa_category_select(%s, %s);', qa_js($fieldname), qa_js($startpath));
Scott Vivian committed
1552

1553 1554 1555 1556
		$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;
Gideon Greenspan committed
1557

1558 1559 1560
		$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();
Scott Vivian committed
1561

Gideon Greenspan committed
1562
		// create the menu that will be shown if Javascript is disabled
Scott Vivian committed
1563

Gideon Greenspan committed
1564
		if ($allownone)
1565
			$field['options'][''] = qa_lang_html('main/no_category'); // this is also copied to first menu created by Javascript
Scott Vivian committed
1566

1567
		$keycategoryids = array();
Scott Vivian committed
1568

Gideon Greenspan committed
1569
		if ($allownosub) {
1570
			$category = @$navcategories[$categoryid];
Scott Vivian committed
1571

1572 1573 1574 1575
			$upcategory = @$navcategories[$category['parentid']]; // first get supercategories
			while (isset($upcategory)) {
				$keycategoryids[$upcategory['categoryid']] = true;
				$upcategory = @$navcategories[$upcategory['parentid']];
Gideon Greenspan committed
1576
			}
Scott Vivian committed
1577

1578
			$keycategoryids = array_reverse($keycategoryids, true);
Gideon Greenspan committed
1579

1580
			$depth = count($keycategoryids); // number of levels above
Scott Vivian committed
1581

Gideon Greenspan committed
1582 1583
			if (isset($category)) {
				$depth++; // to count category itself
Scott Vivian committed
1584

Gideon Greenspan committed
1585 1586
				foreach ($navcategories as $navcategory) // now get siblings and self
					if (!strcmp($navcategory['parentid'], $category['parentid']))
1587
						$keycategoryids[$navcategory['categoryid']] = true;
Gideon Greenspan committed
1588
			}
Scott Vivian committed
1589

1590
			if ($depth < $maxdepth)
Gideon Greenspan committed
1591 1592
				foreach ($navcategories as $navcategory) // now get children, if not too deep
					if (!strcmp($navcategory['parentid'], $categoryid))
1593
						$keycategoryids[$navcategory['categoryid']] = true;
Gideon Greenspan committed
1594 1595

		} else {
1596
			$haschildren = false;
Scott Vivian committed
1597

Gideon Greenspan committed
1598
			foreach ($navcategories as $navcategory) // check if it has any children
1599 1600 1601 1602
				if (!strcmp($navcategory['parentid'], $categoryid)) {
					$haschildren = true;
					break;
				}
Scott Vivian committed
1603

Gideon Greenspan committed
1604
			if (!$haschildren)
1605
				$keycategoryids[$categoryid] = true; // show this category if it has no children
Gideon Greenspan committed
1606
		}
Scott Vivian committed
1607

Gideon Greenspan committed
1608 1609
		foreach ($keycategoryids as $keycategoryid => $dummy)
			if (strcmp($keycategoryid, $excludecategoryid))
1610
				$field['options'][$keycategoryid] = qa_category_path_html($navcategories, $keycategoryid);
Scott Vivian committed
1611

1612 1613 1614 1615 1616
		$field['value'] = @$field['options'][$categoryid];
		$field['note'] =
			'<div id="' . $fieldname . '_note">' .
				'<noscript style="color:red;">' . qa_lang_html('question/category_js_note') . '</noscript>' .
			'</div>';
Gideon Greenspan committed
1617
	}
Scott Vivian committed
1618 1619


Gideon Greenspan committed
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
	function qa_get_category_field_value($fieldname)
/*
	Get the user-entered category id submitted from a field that was created with qa_set_up_category_field(...)
*/
	{
		for ($level=QA_CATEGORY_DEPTH; $level>=1; $level--) {
			$levelid=qa_post_text($fieldname.'_'.$level);
			if (strlen($levelid))
				return $levelid;
		}
Scott Vivian committed
1630

Gideon Greenspan committed
1631 1632 1633 1634 1635
		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 Vivian committed
1636

Gideon Greenspan committed
1637 1638
		return null;
	}
Scott Vivian committed
1639 1640


Gideon Greenspan committed
1641
	function qa_set_up_name_field(&$qa_content, &$fields, $inname, $fieldprefix='')
Gideon Greenspan committed
1642 1643 1644 1645
/*
	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.
*/
Gideon Greenspan committed
1646 1647 1648
	{
		$fields['name']=array(
			'label' => qa_lang_html('question/anon_name_label'),
Gideon Greenspan committed
1649
			'tags' => 'name="'.$fieldprefix.'name"',
Gideon Greenspan committed
1650 1651 1652
			'value' => qa_html($inname),
		);
	}
Gideon Greenspan committed
1653

Scott Vivian committed
1654

Gideon Greenspan committed
1655 1656 1657 1658 1659
	function qa_set_up_notify_fields(&$qa_content, &$fields, $basetype, $login_email, $innotify, $inemail, $errors_email, $fieldprefix='')
/*
	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,
	or null if this is an anonymous post. $innotify, $inemail and $errors_email are from previous submission/validation.
Gideon Greenspan committed
1660
	Pass $fieldprefix to add a prefix to the form field names and IDs used.
Gideon Greenspan committed
1661 1662 1663
*/
	{
		$fields['notify']=array(
Gideon Greenspan committed
1664
			'tags' => 'name="'.$fieldprefix.'notify"',
Gideon Greenspan committed
1665 1666 1667 1668 1669 1670 1671 1672 1673 1674
			'type' => 'checkbox',
			'value' => qa_html($innotify),
		);

		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;
Scott Vivian committed
1675

Gideon Greenspan committed
1676 1677 1678 1679 1680
			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;
Scott Vivian committed
1681

Gideon Greenspan committed
1682 1683 1684 1685 1686 1687
			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 Vivian committed
1688

Gideon Greenspan committed
1689 1690
		if (empty($login_email)) {
			$fields['notify']['label']=
Gideon Greenspan committed
1691 1692
				'<span id="'.$fieldprefix.'email_shown">'.$labelaskemail.'</span>'.
				'<span id="'.$fieldprefix.'email_hidden" style="display:none;">'.$labelonly.'</span>';
Scott Vivian committed
1693

Gideon Greenspan committed
1694
			$fields['notify']['tags'].=' id="'.$fieldprefix.'notify" onclick="if (document.getElementById(\''.$fieldprefix.'notify\').checked) document.getElementById(\''.$fieldprefix.'email\').focus();"';
Gideon Greenspan committed
1695
			$fields['notify']['tight']=true;
Scott Vivian committed
1696

Gideon Greenspan committed
1697 1698
			$fields['email']=array(
				'id' => $fieldprefix.'email_display',
Gideon Greenspan committed
1699
				'tags' => 'name="'.$fieldprefix.'email" id="'.$fieldprefix.'email"',
Gideon Greenspan committed
1700 1701 1702 1703
				'value' => qa_html($inemail),
				'note' => qa_lang_html('question/notify_email_note'),
				'error' => qa_html($errors_email),
			);
Scott Vivian committed
1704

Gideon Greenspan committed
1705 1706 1707 1708 1709
			qa_set_display_rules($qa_content, array(
				$fieldprefix.'email_display' => $fieldprefix.'notify',
				$fieldprefix.'email_shown' => $fieldprefix.'notify',
				$fieldprefix.'email_hidden' => '!'.$fieldprefix.'notify',
			));
Scott Vivian committed
1710

Gideon Greenspan committed
1711 1712 1713 1714 1715
		} else {
			$fields['notify']['label']=str_replace('^', qa_html($login_email), $labelgotemail);
		}
	}

Scott Vivian committed
1716

Gideon Greenspan committed
1717 1718 1719 1720 1721
	function qa_get_site_theme()
/*
	Return the theme that should be used for displaying the page
*/
	{
Gideon Greenspan committed
1722
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott Vivian committed
1723

Gideon Greenspan committed
1724 1725
		return qa_opt(qa_is_mobile_probably() ? 'site_theme_mobile' : 'site_theme');
	}
Scott Vivian committed
1726 1727


Gideon Greenspan committed
1728 1729 1730 1731 1732 1733
	function qa_load_theme_class($theme, $template, $content, $request)
/*
	Return the initialized class for $theme (or the default if it's gone), passing $template, $content and $request.
	Also applies any registered plugin layers.
*/
	{
Gideon Greenspan committed
1734
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott Vivian committed
1735

Gideon Greenspan committed
1736
		global $qa_layers;
Scott Vivian committed
1737

Gideon Greenspan committed
1738
	//	First load the default class
Scott Vivian committed
1739

Gideon Greenspan committed
1740
		require_once QA_INCLUDE_DIR.'qa-theme-base.php';
Scott Vivian committed
1741

Gideon Greenspan committed
1742
		$classname='qa_html_theme_base';
Scott Vivian committed
1743

Gideon Greenspan committed
1744
	//	Then load the selected theme if valid, otherwise load the Classic theme
Scott Vivian committed
1745

Gideon Greenspan committed
1746
		if (!file_exists(QA_THEME_DIR.$theme.'/qa-styles.css'))
Gideon Greenspan committed
1747
			$theme='Classic';
Gideon Greenspan committed
1748 1749

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

Gideon Greenspan committed
1751 1752
		if (file_exists(QA_THEME_DIR.$theme.'/qa-theme.php')) {
			require_once QA_THEME_DIR.$theme.'/qa-theme.php';
Scott Vivian committed
1753

Gideon Greenspan committed
1754 1755 1756
			if (class_exists('qa_html_theme'))
				$classname='qa_html_theme';
		}
Scott Vivian committed
1757

Gideon Greenspan committed
1758
	//	Create the list of layers to load
Scott Vivian committed
1759

Gideon Greenspan committed
1760
		$loadlayers=$qa_layers;
Scott Vivian committed
1761

Gideon Greenspan committed
1762 1763 1764 1765 1766 1767 1768
		if (!qa_user_maximum_permit_error('permit_view_voters_flaggers'))
			$loadlayers[]=array(
				'directory' => QA_INCLUDE_DIR,
				'include' => 'qa-layer-voters-flaggers.php',
				'urltoroot' => null,
			);

Gideon Greenspan committed
1769
	//	Then load any theme layers using some class-munging magic (substitute class names)
Scott Vivian committed
1770

Gideon Greenspan committed
1771
		$layerindex=0;
Scott Vivian committed
1772

Gideon Greenspan committed
1773 1774 1775
		foreach ($loadlayers as $layer) {
			$filename=$layer['directory'].$layer['include'];
			$layerphp=file_get_contents($filename);
Scott Vivian committed
1776

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

Gideon Greenspan committed
1781 1782
				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 Vivian committed
1783

Gideon Greenspan committed
1784
				$searchwordreplace=array(
1785 1786
					'qa_html_theme_base::qa_html_theme_base' => $classname.'::__construct', // PHP5 constructor fix
					'parent::qa_html_theme_base' => 'parent::__construct', // PHP5 constructor fix
Gideon Greenspan committed
1787 1788 1789 1790 1791
					'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 Vivian committed
1792

Gideon Greenspan committed
1793 1794 1795
				foreach ($searchwordreplace as $searchword => $replace)
					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
Scott Vivian committed
1796

Gideon Greenspan committed
1797 1798 1799
						foreach ($searchmatches as $searchmatch)
							$layerphp=substr_replace($layerphp, $replace, $searchmatch[1], strlen($searchmatch[0]));
					}
Scott Vivian committed
1800

Gideon Greenspan committed
1801
			//	echo '<pre style="text-align:left;">'.htmlspecialchars($layerphp).'</pre>'; // to debug munged code
Scott Vivian committed
1802

Gideon Greenspan committed
1803
				qa_eval_from_file($layerphp, $filename);
Scott Vivian committed
1804

Gideon Greenspan committed
1805 1806 1807
				$classname=$newclassname;
			}
		}
Scott Vivian committed
1808

Gideon Greenspan committed
1809
	//	Finally, instantiate the object
Scott Vivian committed
1810

Gideon Greenspan committed
1811
		$themeclass=new $classname($template, $content, $themeroothtml, $request);
Scott Vivian committed
1812

Gideon Greenspan committed
1813 1814
		return $themeclass;
	}
Scott Vivian committed
1815 1816


Gideon Greenspan committed
1817 1818 1819 1820 1821 1822 1823
	function qa_load_editor($content, $format, &$editorname)
/*
	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.
*/
	{
		$maxeditor=qa_load_module('editor', $editorname); // take preferred one first
Scott Vivian committed
1824

Gideon Greenspan committed
1825
		if (isset($maxeditor) && method_exists($maxeditor, 'calc_quality')) {
Scott Vivian committed
1826
			$maxquality=$maxeditor->calc_quality($content, $format);
Gideon Greenspan committed
1827 1828 1829 1830 1831
			if ($maxquality>=0.5)
				return $maxeditor;

		} else
			$maxquality=0;
Scott Vivian committed
1832

Gideon Greenspan committed
1833 1834 1835
		$editormodules=qa_load_modules_with('editor', 'calc_quality');
		foreach ($editormodules as $tryname => $tryeditor) {
			$tryquality=$tryeditor->calc_quality($content, $format);
Scott Vivian committed
1836

Gideon Greenspan committed
1837 1838 1839 1840 1841 1842
			if ($tryquality>$maxquality) {
				$maxeditor=$tryeditor;
				$maxquality=$tryquality;
				$editorname=$tryname;
			}
		}
Scott Vivian committed
1843

Gideon Greenspan committed
1844 1845
		return $maxeditor;
	}
Scott Vivian committed
1846 1847


Gideon Greenspan committed
1848 1849 1850 1851 1852 1853 1854 1855 1856 1857
	function qa_editor_load_field($editor, &$qa_content, $content, $format, $fieldname, $rows, $focusnow=false, $loadnow=true)
/*
	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.
*/
	{
		if (!isset($editor))
			qa_fatal_error('No editor found for format: '.$format);
Scott Vivian committed
1858

Gideon Greenspan committed
1859
		$field=$editor->get_field($qa_content, $content, $format, $fieldname, $rows, $focusnow);
Scott Vivian committed
1860

Gideon Greenspan committed
1861 1862 1863 1864
		$onloads=array();

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

Gideon Greenspan committed
1866 1867
		if ($focusnow && method_exists($editor, 'focus_script'))
			$onloads[]=$editor->focus_script($fieldname);
Scott Vivian committed
1868

Gideon Greenspan committed
1869 1870
		if (count($onloads))
			$qa_content['script_onloads'][]=$onloads;
Scott Vivian committed
1871

Gideon Greenspan committed
1872 1873
		return $field;
	}
Scott Vivian committed
1874 1875


Gideon Greenspan committed
1876 1877 1878 1879 1880 1881 1882
	function qa_load_viewer($content, $format)
/*
	Return an instantiation of the appropriate viewer module class, given $content in $format
*/
	{
		$maxviewer=null;
		$maxquality=0;
Scott Vivian committed
1883

Gideon Greenspan committed
1884
		$viewermodules=qa_load_modules_with('viewer', 'calc_quality');
Scott Vivian committed
1885

Gideon Greenspan committed
1886 1887
		foreach ($viewermodules as $tryviewer) {
			$tryquality=$tryviewer->calc_quality($content, $format);
Scott Vivian committed
1888

Gideon Greenspan committed
1889 1890 1891 1892 1893
			if ($tryquality>$maxquality) {
				$maxviewer=$tryviewer;
				$maxquality=$tryquality;
			}
		}
Scott Vivian committed
1894

Gideon Greenspan committed
1895 1896
		return $maxviewer;
	}
Scott Vivian committed
1897 1898


Gideon Greenspan committed
1899 1900 1901 1902 1903 1904 1905 1906
	function qa_viewer_text($content, $format, $options=array())
/*
	Return the plain text rendering of $content in $format, passing $options to the appropriate module
*/
	{
		$viewer=qa_load_viewer($content, $format);
		return $viewer->get_text($content, $format, $options);
	}
Scott Vivian committed
1907 1908


Gideon Greenspan committed
1909 1910 1911 1912 1913 1914 1915 1916
	function qa_viewer_html($content, $format, $options=array())
/*
	Return the HTML rendering of $content in $format, passing $options to the appropriate module
*/
	{
		$viewer=qa_load_viewer($content, $format);
		return $viewer->get_html($content, $format, $options);
	}
Scott Vivian committed
1917 1918


Gideon Greenspan committed
1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932
	function qa_get_post_content($editorfield, $contentfield, &$ineditor, &$incontent, &$informat, &$intext)
/*
	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
*/
	{
		$ineditor=qa_post_text($editorfield);

		$editor=qa_load_module('editor', $ineditor);
		$readdata=$editor->read_post($contentfield);
		$incontent=$readdata['content'];
		$informat=$readdata['format'];
		$intext=qa_viewer_text($incontent, $informat);
	}
Scott Vivian committed
1933 1934


Gideon Greenspan committed
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947
	function qa_update_post_text(&$fields, $oldfields)
/*
	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']
*/
	{
		if (
			strcmp($oldfields['content'], $fields['content']) ||
			strcmp($oldfields['format'], $fields['format']) ||
			strcmp($oldfields['text'], $fields['text'])
		)
			$fields['text']=qa_viewer_text($fields['content'], $fields['format']);
	}
Scott Vivian committed
1948 1949


Gideon Greenspan committed
1950 1951
	function qa_get_avatar_blob_html($blobid, $width, $height, $size, $padding=false)
/*
Gideon Greenspan committed
1952
	Return the <img...> HTML to display avatar $blobid whose stored size is $width and $height
Gideon Greenspan committed
1953 1954 1955
	Constrain the image to $size (width AND height) and pad it to that size if $padding is true
*/
	{
Gideon Greenspan committed
1956
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott Vivian committed
1957

Gideon Greenspan committed
1958
		require_once QA_INCLUDE_DIR.'qa-util-image.php';
Scott Vivian committed
1959

Gideon Greenspan committed
1960 1961
		if (strlen($blobid) && ($size>0)) {
			qa_image_constrain($width, $height, $size);
Scott Vivian committed
1962

Gideon Greenspan committed
1963 1964
			$html='<img src="'.qa_path_html('image', array('qa_blobid' => $blobid, 'qa_size' => $size), null, QA_URL_FORMAT_PARAMS).
				'"'.(($width && $height) ? (' width="'.$width.'" height="'.$height.'"') : '').' class="qa-avatar-image" alt=""/>';
Scott Vivian committed
1965

Gideon Greenspan committed
1966
			if ($padding && $width && $height) {
Gideon Greenspan committed
1967 1968 1969 1970
				$padleft=floor(($size-$width)/2);
				$padright=$size-$width-$padleft;
				$padtop=floor(($size-$height)/2);
				$padbottom=$size-$height-$padtop;
Gideon Greenspan committed
1971
				$html='<span style="display:inline-block; padding:'.$padtop.'px '.$padright.'px '.$padbottom.'px '.$padleft.'px;">'.$html.'</span>';
Gideon Greenspan committed
1972
			}
Scott Vivian committed
1973

Gideon Greenspan committed
1974 1975 1976 1977 1978
			return $html;

		} else
			return null;
	}
Scott Vivian committed
1979 1980


Gideon Greenspan committed
1981 1982
	function qa_get_gravatar_html($email, $size)
/*
Gideon Greenspan committed
1983
	Return the <img...> HTML to display the Gravatar for $email, constrained to $size
Gideon Greenspan committed
1984 1985
*/
	{
Gideon Greenspan committed
1986
		if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }
Scott Vivian committed
1987

Gideon Greenspan committed
1988
		if ($size>0)
Gideon Greenspan committed
1989
			return '<img src="'.(qa_is_https_probably() ? 'https' : 'http').
Gideon Greenspan committed
1990
				'://www.gravatar.com/avatar/'.md5(strtolower(trim($email))).'?s='.(int)$size.
Gideon Greenspan committed
1991
				'" width="'.(int)$size.'" height="'.(int)$size.'" class="qa-avatar-image" alt=""/>';
Gideon Greenspan committed
1992 1993 1994
		else
			return null;
	}
Scott Vivian committed
1995 1996


Gideon Greenspan committed
1997 1998 1999 2000 2001 2002 2003 2004
	function qa_get_points_title_html($userpoints, $pointstitle)
/*
	Retrieve the appropriate user title from $pointstitle for a user with $userpoints points, or null if none
*/
	{
		foreach ($pointstitle as $points => $title)
			if ($userpoints>=$points)
				return $title;
Scott Vivian committed
2005

Gideon Greenspan committed
2006 2007
		return null;
	}
Scott Vivian committed
2008

Gideon Greenspan committed
2009 2010 2011 2012 2013 2014 2015 2016

	function qa_notice_form($noticeid, $content, $rawnotice=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.
*/
	{
		$elementid='notice_'.$noticeid;
Scott Vivian committed
2017

Gideon Greenspan committed
2018 2019 2020
		return array(
			'id' => qa_html($elementid),
			'raw' => $rawnotice,
Gideon Greenspan committed
2021
			'form_tags' => 'method="post" action="'.qa_self_html().'"',
Gideon Greenspan committed
2022
			'form_hidden' => array('code' => qa_get_form_security_code('notice-'.$noticeid)),
Gideon Greenspan committed
2023
			'close_tags' => 'name="'.qa_html($elementid).'" onclick="return qa_notice_click(this);"',
Gideon Greenspan committed
2024 2025 2026
			'content' => $content,
		);
	}
Scott Vivian committed
2027 2028


Gideon Greenspan committed
2029 2030 2031 2032 2033 2034 2035
	function qa_favorite_form($entitytype, $entityid, $favorite, $title)
/*
	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.
*/
	{
		return array(
Gideon Greenspan committed
2036
			'form_tags' => 'method="post" action="'.qa_self_html().'"',
Gideon Greenspan committed
2037
			'form_hidden' => array('code' => qa_get_form_security_code('favorite-'.$entitytype.'-'.$entityid)),
Gideon Greenspan committed
2038
			'favorite_tags' => 'id="favoriting"',
Gideon Greenspan committed
2039
			($favorite ? 'favorite_remove_tags' : 'favorite_add_tags') =>
Gideon Greenspan committed
2040
				'title="'.qa_html($title).'" name="'.qa_html('favorite_'.$entitytype.'_'.$entityid.'_'.(int)!$favorite).'" onclick="return qa_favorite_click(this);"',
Gideon Greenspan committed
2041 2042
		);
	}
Scott Vivian committed
2043

Gideon Greenspan committed
2044 2045 2046

/*
	Omit PHP closing tag to help avoid accidental output
Scott committed
2047
*/