selects.php 75.9 KB
Newer Older
Scott committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
<?php
/*
	Question2Answer by Gideon Greenspan and contributors
	http://www.question2answer.org/

	Description: Builders of selectspec arrays (see qa-db.php) used to specify database SELECTs


	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	More about this license: http://www.question2answer.org/license.php
*/

Scott committed
22
if (!defined('QA_VERSION')) { // don't allow this page to be requested directly from browser
23
	header('Location: ../../');
Scott committed
24 25
	exit;
}
Scott committed
26

Scott committed
27
require_once QA_INCLUDE_DIR.'db/maxima.php';
Scott committed
28 29


Scott committed
30 31 32 33
/**
 * Return the results of all the SELECT operations specified by the supplied selectspec parameters, while also
 * performing all pending selects that have not yet been executed. If only one parameter is supplied, return its
 * result, otherwise return an array of results indexed as per the parameters.
34
 * @return mixed
Scott committed
35 36 37 38
 */
function qa_db_select_with_pending() // any number of parameters read via func_get_args()
{
	require_once QA_INCLUDE_DIR . 'app/options.php';
Scott committed
39

Scott committed
40
	global $qa_db_pending_selectspecs, $qa_db_pending_results;
Scott committed
41

Scott committed
42 43 44
	$selectspecs = func_get_args();
	$singleresult = (count($selectspecs) == 1);
	$outresults = array();
Scott committed
45

Scott committed
46 47 48 49
	foreach ($selectspecs as $key => $selectspec) { // can pass null parameters
		if (empty($selectspec)) {
			unset($selectspecs[$key]);
			$outresults[$key] = null;
Scott committed
50 51 52
		}
	}

Scott committed
53 54
	if (is_array($qa_db_pending_selectspecs)) {
		foreach ($qa_db_pending_selectspecs as $pendingid => $selectspec) {
Scott committed
55
			if (!isset($qa_db_pending_results[$pendingid])) {
Scott committed
56
				$selectspecs['pending_' . $pendingid] = $selectspec;
Scott committed
57
			}
Scott committed
58 59 60
		}
	}

Scott committed
61
	$outresults = $outresults + qa_db_multi_select($selectspecs);
Scott committed
62

Scott committed
63 64 65 66 67 68
	if (is_array($qa_db_pending_selectspecs)) {
		foreach ($qa_db_pending_selectspecs as $pendingid => $selectspec) {
			if (!isset($qa_db_pending_results[$pendingid])) {
				$qa_db_pending_results[$pendingid] = $outresults['pending_' . $pendingid];
				unset($outresults['pending_' . $pendingid]);
			}
Scott committed
69 70 71
		}
	}

Scott committed
72 73 74 75 76 77
	return $singleresult ? $outresults[0] : $outresults;
}


/**
 * Queue a $selectspec for running later, with $pendingid (used for retrieval)
78 79
 * @param string $pendingid
 * @param array $selectspec
Scott committed
80 81 82 83 84 85 86 87 88 89 90 91
 */
function qa_db_queue_pending_select($pendingid, $selectspec)
{
	global $qa_db_pending_selectspecs;

	$qa_db_pending_selectspecs[$pendingid] = $selectspec;
}


/**
 * Get the result of the queued SELECT query identified by $pendingid. Run the query if it hasn't run already. If
 * $selectspec is supplied, it doesn't matter if this hasn't been queued before - it will be queued and run now.
92 93 94
 * @param string $pendingid
 * @param array|null $selectspec
 * @return mixed
Scott committed
95 96 97 98 99
 */
function qa_db_get_pending_result($pendingid, $selectspec = null)
{
	global $qa_db_pending_selectspecs, $qa_db_pending_results;

Scott committed
100
	if (isset($selectspec)) {
Scott committed
101
		qa_db_queue_pending_select($pendingid, $selectspec);
Scott committed
102
	} elseif (!isset($qa_db_pending_selectspecs[$pendingid])) {
Scott committed
103
		qa_fatal_error('Pending query was never set up: ' . $pendingid);
Scott committed
104
	}
Scott committed
105

Scott committed
106
	if (!isset($qa_db_pending_results[$pendingid])) {
Scott committed
107
		qa_db_select_with_pending();
Scott committed
108
	}
Scott committed
109 110 111 112 113 114 115 116

	return $qa_db_pending_results[$pendingid];
}


/**
 * Remove the results of queued SELECT query identified by $pendingid if it has already been run. This means it will
 * run again if its results are requested via qa_db_get_pending_result()
117
 * @param string $pendingid
Scott committed
118 119 120 121 122 123 124 125 126 127 128
 */
function qa_db_flush_pending_result($pendingid)
{
	global $qa_db_pending_results;
	unset($qa_db_pending_results[$pendingid]);
}


/**
 * Modify a selectspec to count the number of items. This assumes the original selectspec does not have a LIMIT clause.
 * Currently works with message inbox/outbox functions and user-flags function.
129 130
 * @param array $selectspec
 * @return array
Scott committed
131
 */
132
function qa_db_selectspec_count($selectspec)
Scott committed
133
{
134 135 136
	$selectspec['columns'] = array('count' => 'COUNT(*)');
	$selectspec['single'] = true;
	unset($selectspec['arraykey']);
Scott committed
137

138
	return $selectspec;
Scott committed
139 140 141 142 143 144 145 146
}


/**
 * Return the common selectspec used to build any selectspecs which retrieve posts from the database.
 * If $voteuserid is set, retrieve the vote made by a particular that user on each post.
 * If $full is true, get full information on the posts, instead of just information for listing pages.
 * If $user is true, get information about the user who wrote the post (or cookie if anonymous).
147
 * @param mixed|null $voteuserid
Scott committed
148 149 150 151 152 153 154 155 156 157
 * @param bool $full
 * @param bool $user
 * @return array
 */
function qa_db_posts_basic_selectspec($voteuserid = null, $full = false, $user = true)
{
	if (qa_to_override(__FUNCTION__)) { $args=func_get_args(); return qa_call_override(__FUNCTION__, $args); }

	$selectspec = array(
		'columns' => array(
158 159
			'^posts.postid', '^posts.categoryid', '^posts.type', 'basetype' => 'LEFT(^posts.type, 1)',
			'hidden' => "INSTR(^posts.type, '_HIDDEN')>0", 'queued' => "INSTR(^posts.type, '_QUEUED')>0",
Scott committed
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
			'^posts.acount', '^posts.selchildid', '^posts.closedbyid', '^posts.upvotes', '^posts.downvotes', '^posts.netvotes', '^posts.views', '^posts.hotness',
			'^posts.flagcount', '^posts.title', '^posts.tags', 'created' => 'UNIX_TIMESTAMP(^posts.created)', '^posts.name',
			'categoryname' => '^categories.title', 'categorybackpath' => "^categories.backpath",
			'categoryids' => "CONCAT_WS(',', ^posts.catidpath1, ^posts.catidpath2, ^posts.catidpath3, ^posts.categoryid)",
		),

		'arraykey' => 'postid',
		'source' => '^posts LEFT JOIN ^categories ON ^categories.categoryid=^posts.categoryid',
		'arguments' => array(),
	);

	if (isset($voteuserid)) {
		require_once QA_INCLUDE_DIR . 'app/updates.php';

		$selectspec['columns']['uservote'] = '^uservotes.vote';
		$selectspec['columns']['userflag'] = '^uservotes.flag';
		$selectspec['columns']['userfavoriteq'] = '^userfavorites.entityid<=>^posts.postid';
		$selectspec['source'] .= ' LEFT JOIN ^uservotes ON ^posts.postid=^uservotes.postid AND ^uservotes.userid=$';
		$selectspec['source'] .= ' LEFT JOIN ^userfavorites ON ^posts.postid=^userfavorites.entityid AND ^userfavorites.userid=$ AND ^userfavorites.entitytype=$';
		array_push($selectspec['arguments'], $voteuserid, $voteuserid, QA_ENTITY_QUESTION);
	}

	if ($full) {
		$selectspec['columns']['content'] = '^posts.content';
		$selectspec['columns']['notify'] = '^posts.notify';
		$selectspec['columns']['updated'] = 'UNIX_TIMESTAMP(^posts.updated)';
		$selectspec['columns']['updatetype'] = '^posts.updatetype';
		$selectspec['columns'][] = '^posts.format';
		$selectspec['columns'][] = '^posts.lastuserid';
		$selectspec['columns']['lastip'] = '^posts.lastip';
		$selectspec['columns'][] = '^posts.parentid';
		$selectspec['columns']['lastviewip'] = '^posts.lastviewip';
	}

	if ($user) {
		$selectspec['columns'][] = '^posts.userid';
		$selectspec['columns'][] = '^posts.cookieid';
		$selectspec['columns']['createip'] = '^posts.createip';
		$selectspec['columns'][] = '^userpoints.points';
Scott committed
199

Scott committed
200 201 202 203 204 205 206 207 208 209 210 211 212 213
		if (!QA_FINAL_EXTERNAL_USERS) {
			$selectspec['columns'][] = '^users.flags';
			$selectspec['columns'][] = '^users.level';
			$selectspec['columns']['email'] = '^users.email';
			$selectspec['columns']['handle'] = '^users.handle';
			$selectspec['columns']['avatarblobid'] = 'BINARY ^users.avatarblobid';
			$selectspec['columns'][] = '^users.avatarwidth';
			$selectspec['columns'][] = '^users.avatarheight';
			$selectspec['source'] .= ' LEFT JOIN ^users ON ^posts.userid=^users.userid';

			if ($full) {
				$selectspec['columns']['lasthandle'] = 'lastusers.handle';
				$selectspec['source'] .= ' LEFT JOIN ^users AS lastusers ON ^posts.lastuserid=lastusers.userid';
			}
Scott committed
214 215
		}

Scott committed
216 217 218 219 220 221 222 223 224 225 226 227
		$selectspec['source'] .= ' LEFT JOIN ^userpoints ON ^posts.userid=^userpoints.userid';
	}

	return $selectspec;
}


/**
 * Supplement a selectspec returned by qa_db_posts_basic_selectspec() to get information about another post (answer or
 * comment) which is related to the main post (question) retrieved. Pass the name of table which will contain the other
 * post in $poststable. Set $fromupdated to true to get information about when this other post was edited, rather than
 * created. If $full is true, get full information on this other post.
228 229
 * @param array $selectspec
 * @param string $poststable
Scott committed
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
 * @param bool $fromupdated
 * @param bool $full
 */
function qa_db_add_selectspec_opost(&$selectspec, $poststable, $fromupdated = false, $full = false)
{
	$selectspec['arraykey'] = 'opostid';

	$selectspec['columns']['obasetype'] = 'LEFT(' . $poststable . '.type, 1)';
	$selectspec['columns']['ohidden'] = "INSTR(" . $poststable . ".type, '_HIDDEN')>0";
	$selectspec['columns']['opostid'] = $poststable . '.postid';
	$selectspec['columns']['ouserid'] = $poststable . ($fromupdated ? '.lastuserid' : '.userid');
	$selectspec['columns']['ocookieid'] = $poststable . '.cookieid';
	$selectspec['columns']['oname'] = $poststable . '.name';
	$selectspec['columns']['oip'] = $poststable . ($fromupdated ? '.lastip' : '.createip');
	$selectspec['columns']['otime'] = 'UNIX_TIMESTAMP(' . $poststable . ($fromupdated ? '.updated' : '.created') . ')';
	$selectspec['columns']['oflagcount'] = $poststable . '.flagcount';

Scott committed
247
	if ($fromupdated) {
Scott committed
248
		$selectspec['columns']['oupdatetype'] = $poststable . '.updatetype';
Scott committed
249
	}
Scott committed
250 251 252 253 254 255

	if ($full) {
		$selectspec['columns']['ocontent'] = $poststable . '.content';
		$selectspec['columns']['oformat'] = $poststable . '.format';
	}

Scott committed
256
	if ($fromupdated || $full) {
Scott committed
257
		$selectspec['columns']['oupdated'] = 'UNIX_TIMESTAMP(' . $poststable . '.updated)';
Scott committed
258
	}
Scott committed
259 260 261 262 263 264 265 266
}


/**
 * Supplement a selectspec returned by qa_db_posts_basic_selectspec() to get information about the author of another
 * post (answer or comment) which is related to the main post (question) retrieved. Pass the name of table which will
 * contain the other user's details in $userstable and the name of the table which will contain the other user's points
 * in $pointstable.
267 268 269
 * @param array $selectspec
 * @param string $userstable
 * @param string $pointstable
Scott committed
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
 */
function qa_db_add_selectspec_ousers(&$selectspec, $userstable, $pointstable)
{
	if (!QA_FINAL_EXTERNAL_USERS) {
		$selectspec['columns']['oflags'] = $userstable . '.flags';
		$selectspec['columns']['olevel'] = $userstable . '.level';
		$selectspec['columns']['oemail'] = $userstable . '.email';
		$selectspec['columns']['ohandle'] = $userstable . '.handle';
		$selectspec['columns']['oavatarblobid'] = 'BINARY ' . $userstable . '.avatarblobid'; // cast to BINARY due to MySQL bug which renders it signed in a union
		$selectspec['columns']['oavatarwidth'] = $userstable . '.avatarwidth';
		$selectspec['columns']['oavatarheight'] = $userstable . '.avatarheight';
	}

	$selectspec['columns']['opoints'] = $pointstable . '.points';
}


/**
 * Given $categoryslugs in order of the hierarchiy, return the equivalent value for the backpath column in the categories table
289
 * @param array $categoryslugs
Scott committed
290 291 292 293
 * @return string
 */
function qa_db_slugs_to_backpath($categoryslugs)
{
Scott committed
294 295
	if (!is_array($categoryslugs)) {
		// accept old-style string arguments for one category deep
Scott committed
296
		$categoryslugs = array($categoryslugs);
Scott committed
297
	}
Scott committed
298 299 300 301 302 303 304

	return implode('/', array_reverse($categoryslugs));
}


/**
 * Return SQL code that represents the constraint of a post being in the category with $categoryslugs, or any of its subcategories
305 306
 * @param array $categoryslugs
 * @param array $arguments
Scott committed
307 308 309 310
 * @return string
 */
function qa_db_categoryslugs_sql_args($categoryslugs, &$arguments)
{
Scott committed
311 312
	if (!is_array($categoryslugs)) {
		// accept old-style string arguments for one category deep
Scott committed
313
		$categoryslugs = strlen($categoryslugs) ? array($categoryslugs) : array();
Scott committed
314
	}
Scott committed
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331

	$levels = count($categoryslugs);

	if ($levels > 0 && $levels <= QA_CATEGORY_DEPTH) {
		$arguments[] = qa_db_slugs_to_backpath($categoryslugs);
		return (($levels == QA_CATEGORY_DEPTH) ? 'categoryid' : ('catidpath' . $levels)) . '=(SELECT categoryid FROM ^categories WHERE backpath=$ LIMIT 1) AND ';
	}

	return '';
}


/**
 * Return the selectspec to retrieve questions (of type $specialtype if provided, or 'Q' by default) sorted by $sort,
 * restricted to $createip (if not null) and the category for $categoryslugs (if not null), with the corresponding vote
 * made by $voteuserid (if not null) and including $full content or not. Return $count (if null, a default is used)
 * questions starting from offset $start.
332 333 334 335 336
 * @param mixed $voteuserid
 * @param string $sort
 * @param int $start
 * @param array|null $categoryslugs
 * @param string|null $createip
Scott committed
337 338
 * @param bool $specialtype
 * @param bool $full
339
 * @param int|null $count
Scott committed
340 341 342 343
 * @return array
 */
function qa_db_qs_selectspec($voteuserid, $sort, $start, $categoryslugs = null, $createip = null, $specialtype = false, $full = false, $count = null)
{
Scott committed
344
	if ($specialtype == 'Q' || $specialtype == 'Q_QUEUED') {
Scott committed
345
		$type = $specialtype;
Scott committed
346
	} else {
Scott committed
347
		$type = $specialtype ? 'Q_HIDDEN' : 'Q'; // for backwards compatibility
Scott committed
348
	}
Scott committed
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371

	$count = isset($count) ? min($count, QA_DB_RETRIEVE_QS_AS) : QA_DB_RETRIEVE_QS_AS;

	switch ($sort) {
		case 'acount':
		case 'flagcount':
		case 'netvotes':
		case 'views':
			$sortsql = 'ORDER BY ^posts.' . $sort . ' DESC, ^posts.created DESC';
			break;

		case 'created':
		case 'hotness':
			$sortsql = 'ORDER BY ^posts.' . $sort . ' DESC';
			break;

		default:
			qa_fatal_error('qa_db_qs_selectspec() called with illegal sort value');
			break;
	}

	$selectspec = qa_db_posts_basic_selectspec($voteuserid, $full);

Scott committed
372 373
	$selectspec['source'] .=
		" JOIN (SELECT postid FROM ^posts WHERE " .
Scott committed
374
		qa_db_categoryslugs_sql_args($categoryslugs, $selectspec['arguments']) .
375
		(isset($createip) ? "createip=UNHEX($) AND " : "") .
Scott committed
376 377
		"type=$ " . $sortsql . " LIMIT #,#) y ON ^posts.postid=y.postid";

Scott committed
378
	if (isset($createip)) {
379
		$selectspec['arguments'][] = bin2hex(@inet_pton($createip));
Scott committed
380
	}
Scott committed
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395

	array_push($selectspec['arguments'], $type, $start, $count);

	$selectspec['sortdesc'] = $sort;

	return $selectspec;
}


/**
 * Return the selectspec to retrieve recent questions (of type $specialtype if provided, or 'Q' by default) which,
 * depending on $by, either (a) have no answers, (b) have on selected answers, or (c) have no upvoted answers. The
 * questions are restricted to the category for $categoryslugs (if not null), and will have the corresponding vote made
 * by $voteuserid (if not null) and will include $full content or not. Return $count (if null, a default is used)
 * questions starting from offset $start.
396 397 398 399
 * @param mixed $voteuserid
 * @param string $by
 * @param int $start
 * @param array|null $categoryslugs
Scott committed
400 401
 * @param bool $specialtype
 * @param bool $full
402
 * @param int|null $count
Scott committed
403 404 405 406
 * @return array
 */
function qa_db_unanswered_qs_selectspec($voteuserid, $by, $start, $categoryslugs = null, $specialtype = false, $full = false, $count = null)
{
Scott committed
407
	if ($specialtype == 'Q' || $specialtype == 'Q_QUEUED') {
Scott committed
408
		$type = $specialtype;
Scott committed
409
	} else {
Scott committed
410
		$type = $specialtype ? 'Q_HIDDEN' : 'Q'; // for backwards compatibility
Scott committed
411
	}
Scott committed
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446

	$count = isset($count) ? min($count, QA_DB_RETRIEVE_QS_AS) : QA_DB_RETRIEVE_QS_AS;

	switch ($by) {
		case 'selchildid':
			$bysql = 'selchildid IS NULL';
			break;

		case 'amaxvote':
			$bysql = 'amaxvote=0';
			break;

		default:
			$bysql = 'acount=0';
			break;
	}

	$selectspec = qa_db_posts_basic_selectspec($voteuserid, $full);

	$selectspec['source'] .= " JOIN (SELECT postid FROM ^posts WHERE " . qa_db_categoryslugs_sql_args($categoryslugs, $selectspec['arguments']) . "type=$ AND " . $bysql . " AND closedbyid IS NULL ORDER BY ^posts.created DESC LIMIT #,#) y ON ^posts.postid=y.postid";

	array_push($selectspec['arguments'], $type, $start, $count);

	$selectspec['sortdesc'] = 'created';

	return $selectspec;
}


/**
 * Return the selectspec to retrieve the antecedent questions for recent answers (of type $specialtype if provided, or
 * 'A' by default), restricted to $createip (if not null) and the category for $categoryslugs (if not null), with the
 * corresponding vote on those questions made by $voteuserid (if not null). Return $count (if null, a default is used)
 * questions starting from offset $start. The selectspec will also retrieve some information about the answers
 * themselves (including the content if $fullanswers is true), in columns named with the prefix 'o'.
447 448 449 450
 * @param mixed $voteuserid
 * @param int $start
 * @param array|null $categoryslugs
 * @param string|null $createip
Scott committed
451 452
 * @param bool $specialtype
 * @param bool $fullanswers
453
 * @param int|null $count
Scott committed
454 455 456 457
 * @return array
 */
function qa_db_recent_a_qs_selectspec($voteuserid, $start, $categoryslugs = null, $createip = null, $specialtype = false, $fullanswers = false, $count = null)
{
Scott committed
458
	if ($specialtype == 'A' || $specialtype == 'A_QUEUED') {
Scott committed
459
		$type = $specialtype;
Scott committed
460
	} else {
Scott committed
461
		$type = $specialtype ? 'A_HIDDEN' : 'A'; // for backwards compatibility
Scott committed
462
	}
Scott committed
463 464 465 466 467 468 469 470

	$count = isset($count) ? min($count, QA_DB_RETRIEVE_QS_AS) : QA_DB_RETRIEVE_QS_AS;

	$selectspec = qa_db_posts_basic_selectspec($voteuserid);

	qa_db_add_selectspec_opost($selectspec, 'aposts', false, $fullanswers);
	qa_db_add_selectspec_ousers($selectspec, 'ausers', 'auserpoints');

Scott committed
471 472
	$selectspec['source'] .=
		" JOIN ^posts AS aposts ON ^posts.postid=aposts.parentid" .
Scott committed
473 474 475 476
		(QA_FINAL_EXTERNAL_USERS ? "" : " LEFT JOIN ^users AS ausers ON aposts.userid=ausers.userid") .
		" LEFT JOIN ^userpoints AS auserpoints ON aposts.userid=auserpoints.userid" .
		" JOIN (SELECT postid FROM ^posts WHERE " .
		qa_db_categoryslugs_sql_args($categoryslugs, $selectspec['arguments']) .
477
		(isset($createip) ? "createip=UNHEX($) AND " : "") .
Scott committed
478 479 480
		"type=$ ORDER BY ^posts.created DESC LIMIT #,#) y ON aposts.postid=y.postid" .
		($specialtype ? '' : " WHERE ^posts.type='Q'");

Scott committed
481
	if (isset($createip)) {
482
		$selectspec['arguments'][] = bin2hex(@inet_pton($createip));
Scott committed
483
	}
Scott committed
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498

	array_push($selectspec['arguments'], $type, $start, $count);

	$selectspec['sortdesc'] = 'otime';

	return $selectspec;
}


/**
 * Return the selectspec to retrieve the antecedent questions for recent comments (of type $specialtype if provided, or
 * 'C' by default), restricted to $createip (if not null) and the category for $categoryslugs (if not null), with the
 * corresponding vote on those questions made by $voteuserid (if not null). Return $count (if null, a default is used)
 * questions starting from offset $start. The selectspec will also retrieve some information about the comments
 * themselves (including the content if $fullcomments is true), in columns named with the prefix 'o'.
499 500 501 502
 * @param mixed $voteuserid
 * @param int $start
 * @param array|null $categoryslugs
 * @param string|null $createip
Scott committed
503 504
 * @param bool $specialtype
 * @param bool $fullcomments
505
 * @param int|null $count
Scott committed
506 507 508 509
 * @return array
 */
function qa_db_recent_c_qs_selectspec($voteuserid, $start, $categoryslugs = null, $createip = null, $specialtype = false, $fullcomments = false, $count = null)
{
Scott committed
510
	if ($specialtype == 'C' || $specialtype == 'C_QUEUED') {
Scott committed
511
		$type = $specialtype;
Scott committed
512
	} else {
Scott committed
513
		$type = $specialtype ? 'C_HIDDEN' : 'C'; // for backwards compatibility
Scott committed
514
	}
Scott committed
515 516 517 518 519 520 521 522

	$count = isset($count) ? min($count, QA_DB_RETRIEVE_QS_AS) : QA_DB_RETRIEVE_QS_AS;

	$selectspec = qa_db_posts_basic_selectspec($voteuserid);

	qa_db_add_selectspec_opost($selectspec, 'cposts', false, $fullcomments);
	qa_db_add_selectspec_ousers($selectspec, 'cusers', 'cuserpoints');

Scott committed
523 524
	$selectspec['source'] .=
		" JOIN ^posts AS parentposts ON" .
Scott committed
525 526 527 528 529 530
		" ^posts.postid=(CASE LEFT(parentposts.type, 1) WHEN 'A' THEN parentposts.parentid ELSE parentposts.postid END)" .
		" JOIN ^posts AS cposts ON parentposts.postid=cposts.parentid" .
		(QA_FINAL_EXTERNAL_USERS ? "" : " LEFT JOIN ^users AS cusers ON cposts.userid=cusers.userid") .
		" LEFT JOIN ^userpoints AS cuserpoints ON cposts.userid=cuserpoints.userid" .
		" JOIN (SELECT postid FROM ^posts WHERE " .
		qa_db_categoryslugs_sql_args($categoryslugs, $selectspec['arguments']) .
531
		(isset($createip) ? "createip=UNHEX($) AND " : "") .
Scott committed
532 533 534
		"type=$ ORDER BY ^posts.created DESC LIMIT #,#) y ON cposts.postid=y.postid" .
		($specialtype ? '' : " WHERE ^posts.type='Q' AND ((parentposts.type='Q') OR (parentposts.type='A'))");

Scott committed
535
	if (isset($createip)) {
536
		$selectspec['arguments'][] = bin2hex(@inet_pton($createip));
Scott committed
537
	}
Scott committed
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552

	array_push($selectspec['arguments'], $type, $start, $count);

	$selectspec['sortdesc'] = 'otime';

	return $selectspec;
}


/**
 * Return the selectspec to retrieve the antecedent questions for recently edited posts, restricted to edits by $lastip
 * (if not null), the category for $categoryslugs (if not null) and only visible posts (if $onlyvisible), with the
 * corresponding vote on those questions made by $voteuserid (if not null). Return $count (if null, a default is used)
 * questions starting from offset $start. The selectspec will also retrieve some information about the edited posts
 * themselves (including the content if $fulledited is true), in columns named with the prefix 'o'.
553 554 555 556
 * @param mixed $voteuserid
 * @param int $start
 * @param array|null $categoryslugs
 * @param string|null $lastip
Scott committed
557 558
 * @param bool $onlyvisible
 * @param bool $fulledited
559
 * @param int|null $count
Scott committed
560 561 562 563 564 565 566 567 568 569 570
 * @return array
 */
function qa_db_recent_edit_qs_selectspec($voteuserid, $start, $categoryslugs = null, $lastip = null, $onlyvisible = true, $fulledited = false, $count = null)
{
	$count = isset($count) ? min($count, QA_DB_RETRIEVE_QS_AS) : QA_DB_RETRIEVE_QS_AS;

	$selectspec = qa_db_posts_basic_selectspec($voteuserid);

	qa_db_add_selectspec_opost($selectspec, 'editposts', true, $fulledited);
	qa_db_add_selectspec_ousers($selectspec, 'editusers', 'edituserpoints');

Scott committed
571 572
	$selectspec['source'] .=
		" JOIN ^posts AS parentposts ON" .
Scott committed
573 574 575 576 577 578
		" ^posts.postid=IF(LEFT(parentposts.type, 1)='Q', parentposts.postid, parentposts.parentid)" .
		" JOIN ^posts AS editposts ON parentposts.postid=IF(LEFT(editposts.type, 1)='Q', editposts.postid, editposts.parentid)" .
		(QA_FINAL_EXTERNAL_USERS ? "" : " LEFT JOIN ^users AS editusers ON editposts.lastuserid=editusers.userid") .
		" LEFT JOIN ^userpoints AS edituserpoints ON editposts.lastuserid=edituserpoints.userid" .
		" JOIN (SELECT postid FROM ^posts WHERE " .
		qa_db_categoryslugs_sql_args($categoryslugs, $selectspec['arguments']) .
579
		(isset($lastip) ? "lastip=UNHEX($) AND " : "") .
Scott committed
580 581 582 583
		($onlyvisible ? "type IN ('Q', 'A', 'C')" : "1") .
		" ORDER BY ^posts.updated DESC LIMIT #,#) y ON editposts.postid=y.postid" .
		($onlyvisible ? " WHERE parentposts.type IN ('Q', 'A', 'C') AND ^posts.type IN ('Q', 'A', 'C')" : "");

Scott committed
584
	if (isset($lastip)) {
585
		$selectspec['arguments'][] = bin2hex(@inet_pton($lastip));
Scott committed
586
	}
Scott committed
587 588 589 590 591 592 593 594 595 596 597 598 599 600

	array_push($selectspec['arguments'], $start, $count);

	$selectspec['sortdesc'] = 'otime';

	return $selectspec;
}


/**
 * Return the selectspec to retrieve the antecedent questions for the most flagged posts, with the corresponding vote
 * on those questions made by $voteuserid (if not null). Return $count (if null, a default is used) questions starting
 * from offset $start. The selectspec will also retrieve some information about the flagged posts themselves (including
 * the content if $fullflagged is true).
601 602
 * @param mixed $voteuserid
 * @param int $start
Scott committed
603
 * @param bool $fullflagged
604
 * @param int|null $count
Scott committed
605 606 607 608 609 610 611 612 613 614 615
 * @return array
 */
function qa_db_flagged_post_qs_selectspec($voteuserid, $start, $fullflagged = false, $count = null)
{
	$count = isset($count) ? min($count, QA_DB_RETRIEVE_QS_AS) : QA_DB_RETRIEVE_QS_AS;

	$selectspec = qa_db_posts_basic_selectspec($voteuserid);

	qa_db_add_selectspec_opost($selectspec, 'flagposts', false, $fullflagged);
	qa_db_add_selectspec_ousers($selectspec, 'flagusers', 'flaguserpoints');

Scott committed
616 617
	$selectspec['source'] .=
		" JOIN ^posts AS parentposts ON" .
Scott committed
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
		" ^posts.postid=IF(LEFT(parentposts.type, 1)='Q', parentposts.postid, parentposts.parentid)" .
		" JOIN ^posts AS flagposts ON parentposts.postid=IF(LEFT(flagposts.type, 1)='Q', flagposts.postid, flagposts.parentid)" .
		(QA_FINAL_EXTERNAL_USERS ? "" : " LEFT JOIN ^users AS flagusers ON flagposts.userid=flagusers.userid") .
		" LEFT JOIN ^userpoints AS flaguserpoints ON flagposts.userid=flaguserpoints.userid" .
		" JOIN (SELECT postid FROM ^posts WHERE flagcount>0 AND type IN ('Q', 'A', 'C') ORDER BY ^posts.flagcount DESC, ^posts.created DESC LIMIT #,#) y ON flagposts.postid=y.postid";

	array_push($selectspec['arguments'], $start, $count);

	$selectspec['sortdesc'] = 'oflagcount';
	$selectspec['sortdesc_2'] = 'otime';

	return $selectspec;
}


/**
 * Return the selectspec to retrieve the posts in $postids, with the corresponding vote on those posts made by
 * $voteuserid (if not null). Returns full information if $full is true.
636 637
 * @param mixed $voteuserid
 * @param array $postids
Scott committed
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
 * @param bool $full
 * @return array
 */
function qa_db_posts_selectspec($voteuserid, $postids, $full = false)
{
	$selectspec = qa_db_posts_basic_selectspec($voteuserid, $full);

	$selectspec['source'] .= " WHERE ^posts.postid IN (#)";
	$selectspec['arguments'][] = $postids;

	return $selectspec;
}


/**
 * Return the selectspec to retrieve the basetype for the posts in $postids, as an array mapping postid => basetype
654
 * @param array $postids
Scott committed
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
 * @return array
 */
function qa_db_posts_basetype_selectspec($postids)
{
	return array(
		'columns' => array('postid', 'basetype' => 'LEFT(type, 1)'),
		'source' => "^posts WHERE postid IN (#)",
		'arguments' => array($postids),
		'arraykey' => 'postid',
		'arrayvalue' => 'basetype',
	);
}


/**
 * Return the selectspec to retrieve the basetype for the posts in $postids, as an array mapping postid => basetype
671 672
 * @param mixed $voteuserid
 * @param array $postids
Scott committed
673 674 675 676 677 678 679 680 681 682
 * @param bool $full
 * @return array
 */
function qa_db_posts_to_qs_selectspec($voteuserid, $postids, $full = false)
{
	$selectspec = qa_db_posts_basic_selectspec($voteuserid, $full);

	$selectspec['columns']['obasetype'] = 'LEFT(childposts.type, 1)';
	$selectspec['columns']['opostid'] = 'childposts.postid';

Scott committed
683 684
	$selectspec['source'] .=
		" JOIN ^posts AS parentposts ON" .
Scott committed
685 686 687 688 689 690 691 692 693 694 695 696 697
		" ^posts.postid=IF(LEFT(parentposts.type, 1)='Q', parentposts.postid, parentposts.parentid)" .
		" JOIN ^posts AS childposts ON parentposts.postid=IF(LEFT(childposts.type, 1)='Q', childposts.postid, childposts.parentid)" .
		" WHERE childposts.postid IN (#)";

	$selectspec['arraykey'] = 'opostid';
	$selectspec['arguments'][] = $postids;

	return $selectspec;
}


/**
 * Return the selectspec to retrieve the full information for $postid, with the corresponding vote made by $voteuserid (if not null)
698 699
 * @param mixed $voteuserid
 * @param int $postid
Scott committed
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
 * @return array
 */
function qa_db_full_post_selectspec($voteuserid, $postid)
{
	$selectspec = qa_db_posts_basic_selectspec($voteuserid, true);

	$selectspec['source'] .= " WHERE ^posts.postid=#";
	$selectspec['arguments'][] = $postid;
	$selectspec['single'] = true;

	return $selectspec;
}


/**
 * Return the selectspec to retrieve the full information for all posts whose parent is $parentid, with the
 * corresponding vote made by $voteuserid (if not null)
717 718
 * @param mixed $voteuserid
 * @param int $parentid
Scott committed
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
 * @return array
 */
function qa_db_full_child_posts_selectspec($voteuserid, $parentid)
{
	$selectspec = qa_db_posts_basic_selectspec($voteuserid, true);

	$selectspec['source'] .= " WHERE ^posts.parentid=#";
	$selectspec['arguments'][] = $parentid;

	return $selectspec;
}


/**
 * Return the selectspec to retrieve the full information for all posts whose parent is an answer which
 * has $questionid as its parent, with the corresponding vote made by $voteuserid (if not null)
735 736
 * @param mixed $voteuserid
 * @param int $questionid
Scott committed
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
 * @return array
 */
function qa_db_full_a_child_posts_selectspec($voteuserid, $questionid)
{
	$selectspec = qa_db_posts_basic_selectspec($voteuserid, true);

	$selectspec['source'] .= " JOIN ^posts AS parents ON ^posts.parentid=parents.postid WHERE parents.parentid=# AND LEFT(parents.type, 1)='A'";
	$selectspec['arguments'][] = $questionid;

	return $selectspec;
}


/**
 * Return the selectspec to retrieve the question for the parent of $postid (where $postid is of a follow-on question or comment),
 * i.e. the parent of $questionid's parent if $questionid's parent is an answer, otherwise $questionid's parent itself.
753
 * @param int $postid
Scott committed
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
 * @return array
 */
function qa_db_post_parent_q_selectspec($postid)
{
	$selectspec = qa_db_posts_basic_selectspec();

	$selectspec['source'] .= " WHERE ^posts.postid=(SELECT IF(LEFT(parent.type, 1)='A', parent.parentid, parent.postid) FROM ^posts AS child LEFT JOIN ^posts AS parent ON parent.postid=child.parentid WHERE child.postid=# AND parent.type IN('Q','A'))";
	$selectspec['arguments'] = array($postid);
	$selectspec['single'] = true;

	return $selectspec;
}


/**
 * Return the selectspec to retrieve the post (either duplicate question or explanatory note) which has closed $questionid, if any
770
 * @param int $questionid
Scott committed
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
 * @return array
 */
function qa_db_post_close_post_selectspec($questionid)
{
	$selectspec = qa_db_posts_basic_selectspec(null, true);

	$selectspec['source'] .= " WHERE ^posts.postid=(SELECT closedbyid FROM ^posts WHERE postid=#)";
	$selectspec['arguments'] = array($questionid);
	$selectspec['single'] = true;

	return $selectspec;
}


/**
 * Return the selectspec to retrieve the posts that have been closed as a duplicate of this question, if any
787
 * @param int $questionid int The canonical question.
Scott committed
788 789 790 791 792 793 794 795 796 797 798 799 800 801
 * @return array
 */
function qa_db_post_duplicates_selectspec($questionid)
{
	$selectspec = qa_db_posts_basic_selectspec(null, true);

	$selectspec['source'] .= " WHERE ^posts.closedbyid=#";
	$selectspec['arguments'] = array($questionid);

	return $selectspec;
}


/**
802 803 804 805
 * Return the selectspec to retrieve the metadata value for $postid with key $title. If $title is an array then the
 * selectspec will return an array of the matched titles.
 * @param int $postid
 * @param string|array $title
Scott committed
806 807 808 809 810 811 812 813 814 815 816
 * @return array
 */
function qa_db_post_meta_selectspec($postid, $title)
{
	$selectspec = array(
		'columns' => array('title', 'content'),
		'source' => "^postmetas WHERE postid=# AND " . (is_array($title) ? "title IN ($)" : "title=$"),
		'arguments' => array($postid, $title),
		'arrayvalue' => 'content',
	);

Scott committed
817
	if (is_array($title)) {
Scott committed
818
		$selectspec['arraykey'] = 'title';
Scott committed
819
	} else {
Scott committed
820
		$selectspec['single'] = true;
Scott committed
821
	}
Scott committed
822 823 824 825 826 827 828 829 830

	return $selectspec;
}


/**
 * Return the selectspec to retrieve the most closely related questions to $questionid, with the corresponding vote
 * made by $voteuserid (if not null). Return $count (if null, a default is used) questions. This works by looking for
 * other questions which have title words, tag words or an (exact) category in common.
831 832 833
 * @param mixed $voteuserid
 * @param int $questionid
 * @param int|null $count
Scott committed
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
 * @return array
 */
function qa_db_related_qs_selectspec($voteuserid, $questionid, $count = null)
{
	$count = isset($count) ? min($count, QA_DB_RETRIEVE_QS_AS) : QA_DB_RETRIEVE_QS_AS;

	$selectspec = qa_db_posts_basic_selectspec($voteuserid);

	$selectspec['columns'][] = 'score';

	// added LOG(postid)/1000000 here to ensure ordering is deterministic even if several posts have same score

	$selectspec['source'] .= " JOIN (SELECT postid, SUM(score)+LOG(postid)/1000000 AS score FROM ((SELECT ^titlewords.postid, LOG(#/titlecount) AS score FROM ^titlewords JOIN ^words ON ^titlewords.wordid=^words.wordid JOIN ^titlewords AS source ON ^titlewords.wordid=source.wordid WHERE source.postid=# AND titlecount<#) UNION ALL (SELECT ^posttags.postid, 2*LOG(#/tagcount) AS score FROM ^posttags JOIN ^words ON ^posttags.wordid=^words.wordid JOIN ^posttags AS source ON ^posttags.wordid=source.wordid WHERE source.postid=# AND tagcount<#) UNION ALL (SELECT ^posts.postid, LOG(#/^categories.qcount) FROM ^posts JOIN ^categories ON ^posts.categoryid=^categories.categoryid AND ^posts.type='Q' WHERE ^categories.categoryid=(SELECT categoryid FROM ^posts WHERE postid=#) AND ^categories.qcount<#)) x WHERE postid!=# GROUP BY postid ORDER BY score DESC LIMIT #) y ON ^posts.postid=y.postid";

	array_push($selectspec['arguments'], QA_IGNORED_WORDS_FREQ, $questionid, QA_IGNORED_WORDS_FREQ, QA_IGNORED_WORDS_FREQ,
		$questionid, QA_IGNORED_WORDS_FREQ, QA_IGNORED_WORDS_FREQ, $questionid, QA_IGNORED_WORDS_FREQ, $questionid, $count);

	$selectspec['sortdesc'] = 'score';

	if (!isset($voteuserid)) {
		$selectspec['caching'] = array(
			'key' => __FUNCTION__ . ":$questionid:$count",
			'ttl' => qa_opt('caching_q_time'),
Scott committed
857 858 859
		);
	}

Scott committed
860 861
	return $selectspec;
}
Scott committed
862 863


Scott committed
864 865 866 867 868 869 870 871 872 873
/**
 * Return the selectspec to retrieve the top question matches for a search, with the corresponding vote made by
 * $voteuserid (if not null) and including $full content or not. Return $count (if null, a default is used) questions
 * starting from offset $start. The search is performed for any of $titlewords in the title, $contentwords in the
 * content (of the question or an answer or comment for whom that is the antecedent question), $tagwords in tags, for
 * question author usernames which match a word in $handlewords or which match $handle as a whole. The results also
 * include a 'score' column based on the matching strength and post hotness, and a 'matchparts' column that tells us
 * where the score came from (since a question could get weight from a match in the question itself, and/or weight from
 * a match in its answers, comments, or comments on answers). The 'matchparts' is a comma-separated list of tuples
 * matchtype:matchpostid:matchscore to be used with qa_search_set_max_match().
874 875 876 877 878 879 880
 * @param mixed $voteuserid
 * @param string $titlewords
 * @param string $contentwords
 * @param array $tagwords
 * @param string $handlewords
 * @param string $handle
 * @param int $start
Scott committed
881
 * @param bool $full
882
 * @param int|null $count
Scott committed
883 884 885 886 887
 * @return array
 */
function qa_db_search_posts_selectspec($voteuserid, $titlewords, $contentwords, $tagwords, $handlewords, $handle, $start, $full = false, $count = null)
{
	$count = isset($count) ? min($count, QA_DB_RETRIEVE_QS_AS) : QA_DB_RETRIEVE_QS_AS;
Scott committed
888

Scott committed
889 890 891
	// add LOG(postid)/1000000 here to ensure ordering is deterministic even if several posts have same score
	// The score also gives a bonus for hot questions, where the bonus scales linearly with hotness. The hottest
	// question gets a bonus equivalent to a matching unique tag, and the least hot question gets zero bonus.
Scott committed
892

Scott committed
893
	$selectspec = qa_db_posts_basic_selectspec($voteuserid, $full);
Scott committed
894

Scott committed
895 896
	$selectspec['columns'][] = 'score';
	$selectspec['columns'][] = 'matchparts';
897
	$selectspec['source'] .= " JOIN (SELECT questionid, SUM(score)+2*(LOG(#)*(MAX(^posts.hotness)-(SELECT MIN(hotness) FROM ^posts WHERE type='Q'))/((SELECT MAX(hotness) FROM ^posts WHERE type='Q')-(SELECT MIN(hotness) FROM ^posts WHERE type='Q')))+LOG(questionid)/1000000 AS score, GROUP_CONCAT(CONCAT_WS(':', matchposttype, matchpostid, ROUND(score,3))) AS matchparts FROM (";
Scott committed
898 899
	$selectspec['sortdesc'] = 'score';
	array_push($selectspec['arguments'], QA_IGNORED_WORDS_FREQ);
Scott committed
900

Scott committed
901
	$selectparts = 0;
Scott committed
902

Scott committed
903 904
	if (!empty($titlewords)) {
		// At the indexing stage, duplicate words in title are ignored, so this doesn't count multiple appearances.
Scott committed
905

Scott committed
906 907
		$selectspec['source'] .= ($selectparts++ ? " UNION ALL " : "") .
			"(SELECT postid AS questionid, LOG(#/titlecount) AS score, 'Q' AS matchposttype, postid AS matchpostid FROM ^titlewords JOIN ^words ON ^titlewords.wordid=^words.wordid WHERE word IN ($) AND titlecount<#)";
Scott committed
908

Scott committed
909
		array_push($selectspec['arguments'], QA_IGNORED_WORDS_FREQ, $titlewords, QA_IGNORED_WORDS_FREQ);
Scott committed
910 911
	}

Scott committed
912 913 914 915 916 917
	if (!empty($contentwords)) {
		// (1-1/(1+count)) weights words in content based on their frequency: If a word appears once in content
		// it's equivalent to 1/2 an appearance in the title (ignoring the contentcount/titlecount factor).
		// If it appears an infinite number of times, it's equivalent to one appearance in the title.
		// This will discourage keyword stuffing while still giving some weight to multiple appearances.
		// On top of that, answer matches are worth half a question match, and comment/note matches half again.
Scott committed
918

Scott committed
919 920
		$selectspec['source'] .= ($selectparts++ ? " UNION ALL " : "") .
			"(SELECT questionid, (1-1/(1+count))*LOG(#/contentcount)*(CASE ^contentwords.type WHEN 'Q' THEN 1.0 WHEN 'A' THEN 0.5 ELSE 0.25 END) AS score, ^contentwords.type AS matchposttype, ^contentwords.postid AS matchpostid FROM ^contentwords JOIN ^words ON ^contentwords.wordid=^words.wordid WHERE word IN ($) AND contentcount<#)";
921

Scott committed
922
		array_push($selectspec['arguments'], QA_IGNORED_WORDS_FREQ, $contentwords, QA_IGNORED_WORDS_FREQ);
923 924
	}

Scott committed
925 926 927
	if (!empty($tagwords)) {
		// Appearances in the tag words count like 2 appearances in the title (ignoring the tagcount/titlecount factor).
		// This is because tags express explicit semantic intent, whereas titles do not necessarily.
928

Scott committed
929 930
		$selectspec['source'] .= ($selectparts++ ? " UNION ALL " : "") .
			"(SELECT postid AS questionid, 2*LOG(#/tagwordcount) AS score, 'Q' AS matchposttype, postid AS matchpostid FROM ^tagwords JOIN ^words ON ^tagwords.wordid=^words.wordid WHERE word IN ($) AND tagwordcount<#)";
Scott committed
931

Scott committed
932
		array_push($selectspec['arguments'], QA_IGNORED_WORDS_FREQ, $tagwords, QA_IGNORED_WORDS_FREQ);
Scott committed
933 934
	}

Scott committed
935 936 937
	if (!empty($handlewords)) {
		if (QA_FINAL_EXTERNAL_USERS) {
			require_once QA_INCLUDE_DIR . 'app/users.php';
Scott committed
938

Scott committed
939
			$userids = qa_get_userids_from_public($handlewords);
Scott committed
940

Scott committed
941 942 943
			if (count($userids)) {
				$selectspec['source'] .= ($selectparts++ ? " UNION ALL " : "") .
					"(SELECT postid AS questionid, LOG(#/qposts) AS score, 'Q' AS matchposttype, postid AS matchpostid FROM ^posts JOIN ^userpoints ON ^posts.userid=^userpoints.userid WHERE ^posts.userid IN ($) AND type='Q')";
Scott committed
944

Scott committed
945 946
				array_push($selectspec['arguments'], QA_IGNORED_WORDS_FREQ, $userids);
			}
Scott committed
947

Scott committed
948 949 950
		} else {
			$selectspec['source'] .= ($selectparts++ ? " UNION ALL " : "") .
				"(SELECT postid AS questionid, LOG(#/qposts) AS score, 'Q' AS matchposttype, postid AS matchpostid FROM ^posts JOIN ^users ON ^posts.userid=^users.userid JOIN ^userpoints ON ^userpoints.userid=^users.userid WHERE handle IN ($) AND type='Q')";
Scott committed
951

Scott committed
952
			array_push($selectspec['arguments'], QA_IGNORED_WORDS_FREQ, $handlewords);
Scott committed
953
		}
Scott committed
954 955
	}

Scott committed
956 957 958
	if (strlen($handle)) { // to allow searching for multi-word usernames (only works if search query contains full username and nothing else)
		if (QA_FINAL_EXTERNAL_USERS) {
			$userids = qa_get_userids_from_public(array($handle));
Scott committed
959

Scott committed
960 961 962
			if (count($userids)) {
				$selectspec['source'] .= ($selectparts++ ? " UNION ALL " : "") .
					"(SELECT postid AS questionid, LOG(#/qposts) AS score, 'Q' AS matchposttype, postid AS matchpostid FROM ^posts JOIN ^userpoints ON ^posts.userid=^userpoints.userid WHERE ^posts.userid=$ AND type='Q')";
Scott committed
963

Scott committed
964 965
				array_push($selectspec['arguments'], QA_IGNORED_WORDS_FREQ, reset($userids));
			}
Scott committed
966

Scott committed
967 968 969
		} else {
			$selectspec['source'] .= ($selectparts++ ? " UNION ALL " : "") .
				"(SELECT postid AS questionid, LOG(#/qposts) AS score, 'Q' AS matchposttype, postid AS matchpostid FROM ^posts JOIN ^users ON ^posts.userid=^users.userid JOIN ^userpoints ON ^userpoints.userid=^users.userid WHERE handle=$ AND type='Q')";
Scott committed
970

Scott committed
971
			array_push($selectspec['arguments'], QA_IGNORED_WORDS_FREQ, $handle);
Scott committed
972
		}
Scott committed
973
	}
Scott committed
974

Scott committed
975
	if ($selectparts == 0) {
Scott committed
976
		$selectspec['source'] .= '(SELECT NULL as questionid, 0 AS score, NULL AS matchposttype, NULL AS matchpostid FROM ^posts WHERE postid IS NULL)';
Scott committed
977
	}
Scott committed
978

Scott committed
979
	$selectspec['source'] .= ") x LEFT JOIN ^posts ON ^posts.postid=questionid GROUP BY questionid ORDER BY score DESC LIMIT #,#) y ON ^posts.postid=y.questionid";
Scott committed
980

Scott committed
981
	array_push($selectspec['arguments'], $start, $count);
Scott committed
982

Scott committed
983 984
	return $selectspec;
}
Scott committed
985 986


Scott committed
987 988 989
/**
 * Processes the matchparts column in $question which was returned from a search performed via qa_db_search_posts_selectspec()
 * Returns the id of the strongest matching answer or comment, or null if the question itself was the strongest match
990 991 992
 * @param array $question
 * @param string $type
 * @param int $postid
Scott committed
993 994 995 996 997 998
 */
function qa_search_set_max_match($question, &$type, &$postid)
{
	$type = 'Q';
	$postid = $question['postid'];
	$bestscore = null;
Scott committed
999

Scott committed
1000 1001 1002 1003 1004 1005 1006
	$matchparts = explode(',', $question['matchparts']);
	foreach ($matchparts as $matchpart) {
		if (sscanf($matchpart, '%1s:%f:%f', $matchposttype, $matchpostid, $matchscore) == 3) {
			if (!isset($bestscore) || $matchscore > $bestscore) {
				$bestscore = $matchscore;
				$type = $matchposttype;
				$postid = $matchpostid;
Scott committed
1007 1008 1009
			}
		}
	}
Scott committed
1010 1011 1012 1013 1014 1015
}


/**
 * Return a selectspec to retrieve the full information on the category whose id is $slugsorid (if $isid is true),
 * otherwise whose backpath matches $slugsorid
1016 1017
 * @param int|array $slugsorid
 * @param bool $isid
Scott committed
1018 1019 1020 1021
 * @return array
 */
function qa_db_full_category_selectspec($slugsorid, $isid)
{
Scott committed
1022
	if ($isid) {
Scott committed
1023
		$identifiersql = 'categoryid=#';
Scott committed
1024
	} else {
Scott committed
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
		$identifiersql = 'backpath=$';
		$slugsorid = qa_db_slugs_to_backpath($slugsorid);
	}

	return array(
		'columns' => array('categoryid', 'parentid', 'title', 'tags', 'qcount', 'content', 'backpath'),
		'source' => '^categories WHERE ' . $identifiersql,
		'arguments' => array($slugsorid),
		'single' => 'true',
	);
}


/**
 * Return the selectspec to retrieve ($full or not) info on the categories which "surround" the central category specified
 * by $slugsorid, $isid and $ispostid. The "surrounding" categories include all categories (even unrelated) at the
 * top level, any ancestors (at any level) of the category, the category's siblings and sub-categories (to one level).
 * The central category is specified as follows. If $isid AND $ispostid then $slugsorid is the ID of a post with the category.
 * Otherwise if $isid then $slugsorid is the category's own id. Otherwise $slugsorid is the full backpath of the category.
1044 1045
 * @param int|array $slugsorid
 * @param bool $isid
Scott committed
1046 1047 1048 1049 1050 1051 1052
 * @param bool $ispostid
 * @param bool $full
 * @return array
 */
function qa_db_category_nav_selectspec($slugsorid, $isid, $ispostid = false, $full = false)
{
	if ($isid) {
Scott committed
1053
		if ($ispostid) {
Scott committed
1054
			$identifiersql = 'categoryid=(SELECT categoryid FROM ^posts WHERE postid=#)';
Scott committed
1055
		} else {
Scott committed
1056
			$identifiersql = 'categoryid=#';
Scott committed
1057
		}
Scott committed
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
	} else {
		$identifiersql = 'backpath=$';
		$slugsorid = qa_db_slugs_to_backpath($slugsorid);
	}

	$parentselects = array( // requires QA_CATEGORY_DEPTH=4
		'SELECT NULL AS parentkey', // top level
		'SELECT grandparent.parentid FROM ^categories JOIN ^categories AS parent ON ^categories.parentid=parent.categoryid JOIN ^categories AS grandparent ON parent.parentid=grandparent.categoryid WHERE ^categories.' . $identifiersql, // 2 gens up
		'SELECT parent.parentid FROM ^categories JOIN ^categories AS parent ON ^categories.parentid=parent.categoryid WHERE ^categories.' . $identifiersql,
		// 1 gen up
		'SELECT parentid FROM ^categories WHERE ' . $identifiersql, // same gen
		'SELECT categoryid FROM ^categories WHERE ' . $identifiersql, // gen below
	);

1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
	$columns = array(
		'parentid' => '^categories.parentid',
		'title' => '^categories.title',
		'tags' => '^categories.tags',
		'qcount' => '^categories.qcount',
		'position' => '^categories.position',
	);

	if ($full) {
		foreach ($columns as $alias => $column) {
			$columns[$alias] = 'MAX(' . $column . ')';
		}

		$columns['childcount'] = 'COUNT(child.categoryid)';
		$columns['content'] = 'MAX(^categories.content)';
		$columns['backpath'] = 'MAX(^categories.backpath)';
	}

	array_unshift($columns, '^categories.categoryid');

Scott committed
1092
	$selectspec = array(
1093 1094 1095 1096
		'columns' => $columns,
		'source' => '^categories JOIN (' . implode(' UNION ', $parentselects) . ') y ON ^categories.parentid<=>parentkey' .
			($full ? ' LEFT JOIN ^categories AS child ON child.parentid=^categories.categoryid GROUP BY ^categories.categoryid' : '') .
			' ORDER BY ^categories.position',
Scott committed
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
		'arguments' => array($slugsorid, $slugsorid, $slugsorid, $slugsorid),
		'arraykey' => 'categoryid',
		'sortasc' => 'position',
	);

	return $selectspec;
}


/**
 * Return the selectspec to retrieve information on all subcategories of $categoryid (used for Ajax navigation of hierarchy)
1108
 * @param int $categoryid
Scott committed
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
 * @return array
 */
function qa_db_category_sub_selectspec($categoryid)
{
	return array(
		'columns' => array('categoryid', 'title', 'tags', 'qcount', 'position'),
		'source' => '^categories WHERE parentid<=># ORDER BY position',
		'arguments' => array($categoryid),
		'arraykey' => 'categoryid',
		'sortasc' => 'position',
	);
}


/**
 * Return the selectspec to retrieve a single category as specified by its $slugs (in order of hierarchy)
1125
 * @param array $slugs
Scott committed
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
 * @return array
 */
function qa_db_slugs_to_category_id_selectspec($slugs)
{
	return array(
		'columns' => array('categoryid'),
		'source' => '^categories WHERE backpath=$',
		'arguments' => array(qa_db_slugs_to_backpath($slugs)),
		'arrayvalue' => 'categoryid',
		'single' => true,
	);
}


/**
 * Return the selectspec to retrieve the list of custom pages or links, ordered for display
1142 1143
 * @param array $onlynavin
 * @param array $onlypageids
Scott committed
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
 * @return array
 */
function qa_db_pages_selectspec($onlynavin = null, $onlypageids = null)
{
	$selectspec = array(
		// +0 required to work around MySQL bug where by permit value is mis-read as signed, e.g. -106 instead of 150
		'columns' => array('pageid', 'title', 'flags', 'permit' => 'permit+0', 'nav', 'tags', 'position', 'heading'),
		'arraykey' => 'pageid',
		'sortasc' => 'position',
	);

	if (isset($onlypageids)) {
		$selectspec['source'] = '^pages WHERE pageid IN (#)';
		$selectspec['arguments'] = array($onlypageids);
	} elseif (isset($onlynavin)) {
		$selectspec['source'] = '^pages WHERE nav IN ($) ORDER BY position';
		$selectspec['arguments'] = array($onlynavin);
Scott committed
1161
	} else {
Scott committed
1162
		$selectspec['source'] = '^pages ORDER BY position';
Scott committed
1163
	}
Scott committed
1164 1165 1166 1167 1168 1169 1170

	return $selectspec;
}


/**
 * Return the selectspec to retrieve the list of widgets, ordered for display
1171
 * @return array
Scott committed
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
 */
function qa_db_widgets_selectspec()
{
	return array(
		'columns' => array('widgetid', 'place', 'position', 'tags', 'title'),
		'source' => '^widgets ORDER BY position',
		'sortasc' => 'position',
	);
}


/**
 * Return the selectspec to retrieve the full information about a custom page
1185 1186
 * @param int|array $slugorpageid
 * @param bool $ispageid
Scott committed
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
 * @return array
 */
function qa_db_page_full_selectspec($slugorpageid, $ispageid)
{
	return array(
		'columns' => array('pageid', 'title', 'flags', 'permit', 'nav', 'tags', 'position', 'heading', 'content'),
		'source' => '^pages WHERE ' . ($ispageid ? 'pageid' : 'tags') . '=$',
		'arguments' => array($slugorpageid),
		'single' => true,
	);
}


/**
 * Return the selectspec to retrieve the most recent questions with $tag, with the corresponding vote on those
 * questions made by $voteuserid (if not null) and including $full content or not. Return $count (if null, a default is
 * used) questions starting from $start.
1204 1205 1206
 * @param mixed $voteuserid
 * @param string $tag
 * @param int $start
Scott committed
1207
 * @param bool $full
1208
 * @param int|null $count
Scott committed
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
 * @return array
 */
function qa_db_tag_recent_qs_selectspec($voteuserid, $tag, $start, $full = false, $count = null)
{
	$count = isset($count) ? min($count, QA_DB_RETRIEVE_QS_AS) : QA_DB_RETRIEVE_QS_AS;

	require_once QA_INCLUDE_DIR . 'util/string.php';

	$selectspec = qa_db_posts_basic_selectspec($voteuserid, $full);

	// use two tests here - one which can use the index, and the other which narrows it down exactly - then limit to 1 just in case
	$selectspec['source'] .= " JOIN (SELECT postid FROM ^posttags WHERE wordid=(SELECT wordid FROM ^words WHERE word=$ AND word=$ COLLATE utf8_bin LIMIT 1) ORDER BY postcreated DESC LIMIT #,#) y ON ^posts.postid=y.postid";
	array_push($selectspec['arguments'], $tag, qa_strtolower($tag), $start, $count);
	$selectspec['sortdesc'] = 'created';

	return $selectspec;
}


/**
 * Return the selectspec to retrieve the number of questions tagged with $tag (single value)
1230
 * @param string $tag
Scott committed
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
 * @return array
 */
function qa_db_tag_word_selectspec($tag)
{
	return array(
		'columns' => array('wordid', 'word', 'tagcount'),
		'source' => '^words WHERE word=$ AND word=$ COLLATE utf8_bin',
		'arguments' => array($tag, qa_strtolower($tag)),
		'single' => true,
	);
}


/**
 * Return the selectspec to retrieve recent questions by the user identified by $identifier, where $identifier is a
 * handle if we're using internal user management, or a userid if we're using external users. Also include the
 * corresponding vote on those questions made by $voteuserid (if not null). Return $count (if null, a default is used)
 * questions.
1249 1250 1251
 * @param mixed $voteuserid
 * @param mixed $identifier
 * @param int|null $count
Scott committed
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
 * @param int $start
 * @return array
 */
function qa_db_user_recent_qs_selectspec($voteuserid, $identifier, $count = null, $start = 0)
{
	$count = isset($count) ? min($count, QA_DB_RETRIEVE_QS_AS) : QA_DB_RETRIEVE_QS_AS;

	$selectspec = qa_db_posts_basic_selectspec($voteuserid);

	$selectspec['source'] .= " WHERE ^posts.userid=" . (QA_FINAL_EXTERNAL_USERS ? "$" : "(SELECT userid FROM ^users WHERE handle=$ LIMIT 1)") . " AND type='Q' ORDER BY ^posts.created DESC LIMIT #,#";
	array_push($selectspec['arguments'], $identifier, $start, $count);
	$selectspec['sortdesc'] = 'created';

	return $selectspec;
}


/**
 * Return the selectspec to retrieve the antecedent questions for recent answers by the user identified by $identifier
 * (see qa_db_user_recent_qs_selectspec() comment), with the corresponding vote on those questions made by $voteuserid
 * (if not null). Return $count (if null, a default is used) questions. The selectspec will also retrieve some
 * information about the answers themselves, in columns named with the prefix 'o'.
1274 1275 1276
 * @param mixed $voteuserid
 * @param mixed $identifier
 * @param int|null $count
Scott committed
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
 * @param int $start
 * @return array
 */
function qa_db_user_recent_a_qs_selectspec($voteuserid, $identifier, $count = null, $start = 0)
{
	$count = isset($count) ? min($count, QA_DB_RETRIEVE_QS_AS) : QA_DB_RETRIEVE_QS_AS;

	$selectspec = qa_db_posts_basic_selectspec($voteuserid);

	qa_db_add_selectspec_opost($selectspec, 'aposts');

	$selectspec['columns']['oupvotes'] = 'aposts.upvotes';
	$selectspec['columns']['odownvotes'] = 'aposts.downvotes';
	$selectspec['columns']['onetvotes'] = 'aposts.netvotes';

Scott committed
1292 1293
	$selectspec['source'] .=
		" JOIN ^posts AS aposts ON ^posts.postid=aposts.parentid" .
Scott committed
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
		" JOIN (SELECT postid FROM ^posts WHERE " .
		" userid=" . (QA_FINAL_EXTERNAL_USERS ? "$" : "(SELECT userid FROM ^users WHERE handle=$ LIMIT 1)") .
		" AND type='A' ORDER BY created DESC LIMIT #,#) y ON aposts.postid=y.postid WHERE ^posts.type='Q'";

	array_push($selectspec['arguments'], $identifier, $start, $count);
	$selectspec['sortdesc'] = 'otime';

	return $selectspec;
}


/**
 * Return the selectspec to retrieve the antecedent questions for recent comments by the user identified by $identifier
 * (see qa_db_user_recent_qs_selectspec() comment), with the corresponding vote on those questions made by $voteuserid
 * (if not null). Return $count (if null, a default is used) questions. The selectspec will also retrieve some
 * information about the comments themselves, in columns named with the prefix 'o'.
1310 1311 1312
 * @param mixed $voteuserid
 * @param mixed $identifier
 * @param int $count
Scott committed
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
 * @return array
 */
function qa_db_user_recent_c_qs_selectspec($voteuserid, $identifier, $count = null)
{
	$count = isset($count) ? min($count, QA_DB_RETRIEVE_QS_AS) : QA_DB_RETRIEVE_QS_AS;

	$selectspec = qa_db_posts_basic_selectspec($voteuserid);

	qa_db_add_selectspec_opost($selectspec, 'cposts');

Scott committed
1323 1324
	$selectspec['source'] .=
		" JOIN ^posts AS parentposts ON" .
Scott committed
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
		" ^posts.postid=(CASE parentposts.type WHEN 'A' THEN parentposts.parentid ELSE parentposts.postid END)" .
		" JOIN ^posts AS cposts ON parentposts.postid=cposts.parentid" .
		" JOIN (SELECT postid FROM ^posts WHERE " .
		" userid=" . (QA_FINAL_EXTERNAL_USERS ? "$" : "(SELECT userid FROM ^users WHERE handle=$ LIMIT 1)") .
		" AND type='C' ORDER BY created DESC LIMIT #) y ON cposts.postid=y.postid WHERE ^posts.type='Q' AND parentposts.type IN ('Q', 'A')";

	array_push($selectspec['arguments'], $identifier, $count);
	$selectspec['sortdesc'] = 'otime';

	return $selectspec;
}


/**
 * Return the selectspec to retrieve the antecedent questions for recently edited posts by the user identified by
 * $identifier (see qa_db_user_recent_qs_selectspec() comment), with the corresponding vote on those questions made by
 * $voteuserid (if not null). Return $count (if null, a default is used) questions. The selectspec will also retrieve
 * some information about the edited posts themselves, in columns named with the prefix 'o'.
1343 1344 1345
 * @param mixed $voteuserid
 * @param mixed $identifier
 * @param int $count
Scott committed
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
 * @return array
 */
function qa_db_user_recent_edit_qs_selectspec($voteuserid, $identifier, $count = null)
{
	$count = isset($count) ? min($count, QA_DB_RETRIEVE_QS_AS) : QA_DB_RETRIEVE_QS_AS;

	$selectspec = qa_db_posts_basic_selectspec($voteuserid);

	qa_db_add_selectspec_opost($selectspec, 'editposts', true);

Scott committed
1356 1357
	$selectspec['source'] .=
		" JOIN ^posts AS parentposts ON" .
Scott committed
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
		" ^posts.postid=IF(LEFT(parentposts.type, 1)='Q', parentposts.postid, parentposts.parentid)" .
		" JOIN ^posts AS editposts ON parentposts.postid=IF(LEFT(editposts.type, 1)='Q', editposts.postid, editposts.parentid)" .
		" JOIN (SELECT postid FROM ^posts WHERE " .
		" lastuserid=" . (QA_FINAL_EXTERNAL_USERS ? "$" : "(SELECT userid FROM ^users WHERE handle=$ LIMIT 1)") .
		" AND type IN ('Q', 'A', 'C') ORDER BY updated DESC LIMIT #) y ON editposts.postid=y.postid " .
		" WHERE parentposts.type IN ('Q', 'A', 'C') AND ^posts.type IN ('Q', 'A', 'C')";

	array_push($selectspec['arguments'], $identifier, $count);
	$selectspec['sortdesc'] = 'otime';

	return $selectspec;
}


/**
 * Return the selectspec to retrieve the most popular tags. Return $count (if null, a default is used) tags, starting
 * from offset $start. The selectspec will produce a sorted array with tags in the key, and counts in the values.
1375 1376
 * @param int $start
 * @param int $count
Scott committed
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
 * @return array
 */
function qa_db_popular_tags_selectspec($start, $count = null)
{
	$count = isset($count) ? $count : QA_DB_RETRIEVE_TAGS;

	return array(
		'columns' => array('word', 'tagcount'),
		'source' => '^words JOIN (SELECT wordid FROM ^words WHERE tagcount>0 ORDER BY tagcount DESC LIMIT #,#) y ON ^words.wordid=y.wordid',
		'arguments' => array($start, $count),
		'arraykey' => 'word',
		'arrayvalue' => 'tagcount',
		'sortdesc' => 'tagcount',
	);
}


/**
 * Return the selectspec to retrieve the list of user profile fields, ordered for display
 */
function qa_db_userfields_selectspec()
{
	return array(
		'columns' => array('fieldid', 'title', 'content', 'flags', 'permit', 'position'),
		'source' => '^userfields',
		'arraykey' => 'title',
		'sortasc' => 'position',
	);
}


/**
 * Return the selecspec to retrieve a single array with details of the account of the user identified by
 * $useridhandle, which should be a userid if $isuserid is true, otherwise $useridhandle should be a handle.
1411 1412
 * @param mixed $useridhandle
 * @param bool $isuserid
Scott committed
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
 * @return array
 */
function qa_db_user_account_selectspec($useridhandle, $isuserid)
{
	return array(
		'columns' => array(
			'^users.userid', 'passsalt', 'passcheck' => 'HEX(passcheck)', 'passhash', 'email', 'level', 'emailcode', 'handle',
			'created' => 'UNIX_TIMESTAMP(created)', 'sessioncode', 'sessionsource', 'flags', 'loggedin' => 'UNIX_TIMESTAMP(loggedin)',
			'loginip', 'written' => 'UNIX_TIMESTAMP(written)', 'writeip',
			'avatarblobid' => 'BINARY avatarblobid', // cast to BINARY due to MySQL bug which renders it signed in a union
			'avatarwidth', 'avatarheight', 'points', 'wallposts',
		),

		'source' => '^users LEFT JOIN ^userpoints ON ^userpoints.userid=^users.userid WHERE ^users.' . ($isuserid ? 'userid' : 'handle') . '=$',
		'arguments' => array($useridhandle),
		'single' => true,
	);
}


/**
 * Return the selectspec to retrieve all user profile information of the user identified by
 * $useridhandle (see qa_db_user_account_selectspec() comment), as an array of [field] => [value]
1436 1437
 * @param mixed $useridhandle
 * @param bool $isuserid
Scott committed
1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
 * @return array
 */
function qa_db_user_profile_selectspec($useridhandle, $isuserid)
{
	return array(
		'columns' => array('title', 'content'),
		'source' => '^userprofile WHERE userid=' . ($isuserid ? '$' : '(SELECT userid FROM ^users WHERE handle=$ LIMIT 1)'),
		'arguments' => array($useridhandle),
		'arraykey' => 'title',
		'arrayvalue' => 'content',
	);
}


/**
 * Return the selectspec to retrieve all notices for the user $userid
1454
 * @param mixed $userid
Scott committed
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
 * @return array
 */
function qa_db_user_notices_selectspec($userid)
{
	return array(
		'columns' => array('noticeid', 'content', 'format', 'tags', 'created' => 'UNIX_TIMESTAMP(created)'),
		'source' => '^usernotices WHERE userid=$ ORDER BY created',
		'arguments' => array($userid),
		'sortasc' => 'created',
	);
}


/**
 * Return the selectspec to retrieve all columns from the userpoints table for the user identified by $identifier
 * (see qa_db_user_recent_qs_selectspec() comment), as a single array
1471
 * @param mixed $identifier
Scott committed
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
 * @param bool $isuserid
 * @return array
 */
function qa_db_user_points_selectspec($identifier, $isuserid = QA_FINAL_EXTERNAL_USERS)
{
	return array(
		'columns' => array('points', 'qposts', 'aposts', 'cposts', 'aselects', 'aselecteds', 'qupvotes', 'qdownvotes', 'aupvotes', 'adownvotes', 'qvoteds', 'avoteds', 'upvoteds', 'downvoteds', 'bonus'),
		'source' => '^userpoints WHERE userid=' . ($isuserid ? '$' : '(SELECT userid FROM ^users WHERE handle=$ LIMIT 1)'),
		'arguments' => array($identifier),
		'single' => true,
	);
}


/**
 * Return the selectspec to calculate the rank in points of the user identified by $identifier
 * (see qa_db_user_recent_qs_selectspec() comment), as a single value
1489
 * @param mixed $identifier
Scott committed
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
 * @param bool $isuserid
 * @return array
 */
function qa_db_user_rank_selectspec($identifier, $isuserid = QA_FINAL_EXTERNAL_USERS)
{
	return array(
		'columns' => array('rank' => '1+COUNT(*)'),
		'source' => '^userpoints WHERE points>COALESCE((SELECT points FROM ^userpoints WHERE userid=' . ($isuserid ? '$' : '(SELECT userid FROM ^users WHERE handle=$ LIMIT 1)') . '), 0)',
		'arguments' => array($identifier),
		'arrayvalue' => 'rank',
		'single' => true,
	);
}


/**
 * Return the selectspec to get the top scoring users, with handles if we're using internal user management. Return
 * $count (if null, a default is used) users starting from the offset $start.
1508 1509
 * @param int $start
 * @param int|null $count
Scott committed
1510 1511 1512 1513 1514 1515
 * @return array
 */
function qa_db_top_users_selectspec($start, $count = null)
{
	$count = isset($count) ? min($count, QA_DB_RETRIEVE_USERS) : QA_DB_RETRIEVE_USERS;

Scott committed
1516
	if (QA_FINAL_EXTERNAL_USERS) {
Scott committed
1517 1518 1519 1520 1521 1522 1523
		return array(
			'columns' => array('userid', 'points'),
			'source' => '^userpoints ORDER BY points DESC LIMIT #,#',
			'arguments' => array($start, $count),
			'arraykey' => 'userid',
			'sortdesc' => 'points',
		);
Scott committed
1524
	}
Scott committed
1525

1526 1527 1528 1529 1530 1531 1532 1533
	// If the site is configured to share the ^users table then there might not be a record in the ^userpoints table
	if (defined('QA_MYSQL_USERS_PREFIX')) {
		$basePoints = (int)qa_opt('points_base');
		$source = '^users JOIN (SELECT ^users.userid, COALESCE(points,' . $basePoints . ') AS points FROM ^users LEFT JOIN ^userpoints ON ^users.userid=^userpoints.userid ORDER BY points DESC LIMIT #,#) y ON ^users.userid=y.userid';
	} else {
		$source = '^users JOIN (SELECT userid FROM ^userpoints ORDER BY points DESC LIMIT #,#) y ON ^users.userid=y.userid JOIN ^userpoints ON ^users.userid=^userpoints.userid';;
	}

Scott committed
1534 1535
	return array(
		'columns' => array('^users.userid', 'handle', 'points', 'flags', '^users.email', 'avatarblobid' => 'BINARY avatarblobid', 'avatarwidth', 'avatarheight'),
1536
		'source' => $source,
Scott committed
1537 1538 1539 1540
		'arguments' => array($start, $count),
		'arraykey' => 'userid',
		'sortdesc' => 'points',
	);
Scott committed
1541 1542 1543 1544 1545 1546
}


/**
 * Return the selectspec to get the newest users. Return $count (if null, a default is used) users starting from the
 * offset $start. This query must not be run when using external users
1547 1548
 * @param int $start
 * @param int|null $count
Scott committed
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
 * @return array
 */
function qa_db_newest_users_selectspec($start, $count = null)
{
	$count = isset($count) ? min($count, QA_DB_RETRIEVE_USERS) : QA_DB_RETRIEVE_USERS;

	return array(
		'columns' => array('userid', 'handle', 'flags', 'email', 'created' => 'UNIX_TIMESTAMP(created)', 'avatarblobid' => 'BINARY avatarblobid', 'avatarwidth', 'avatarheight'),
		'source' => '^users ORDER BY created DESC, userid DESC LIMIT #,#',
		'arguments' => array($start, $count),
		'sortdesc' => 'created',
		'sortdesc_2' => 'userid',
	);
}


/**
 * Return the selectspec to get information about users at a certain privilege level or higher
1567
 * @param int $level
Scott committed
1568 1569 1570 1571 1572
 * @return array
 */
function qa_db_users_from_level_selectspec($level)
{
	return array(
1573
		'columns' => array('^users.userid', 'handle', 'flags', 'level', 'email', 'avatarblobid' => 'BINARY avatarblobid', 'avatarwidth', 'avatarheight'),
Scott committed
1574 1575 1576 1577 1578 1579 1580 1581 1582
		'source' => '^users WHERE level>=# ORDER BY level DESC',
		'arguments' => array($level),
		'sortdesc' => 'level',
	);
}


/**
 * Return the selectspec to get information about users with the $flag bit set (unindexed query)
1583
 * @param int $flag
Scott committed
1584
 * @param int $start
1585
 * @param int|null $limit
Scott committed
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
 * @return array
 */
function qa_db_users_with_flag_selectspec($flag, $start = 0, $limit = null)
{
	$source = '^users WHERE (flags & #)';
	$arguments = array($flag);

	if (isset($limit)) {
		$limit = min($limit, QA_DB_RETRIEVE_USERS);
		$source .= ' LIMIT #,#';
		array_push($arguments, $start, $limit);
	}

	return array(
1600
		'columns' => array('^users.userid', 'handle', 'flags', 'level', 'email', 'avatarblobid' => 'BINARY avatarblobid', 'avatarwidth', 'avatarheight'),
Scott committed
1601 1602 1603 1604 1605 1606 1607 1608
		'source' => $source,
		'arguments' => $arguments,
	);
}


/**
 * Return columns for standard messages selectspec
1609
 * @return array
Scott committed
1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
 */
function qa_db_messages_columns()
{
	return array(
		'messageid', 'fromuserid', 'touserid', 'content', 'format',
		'created' => 'UNIX_TIMESTAMP(^messages.created)',

		'fromflags' => 'ufrom.flags', 'fromlevel' => 'ufrom.level',
		'fromemail' => 'ufrom.email', 'fromhandle' => 'ufrom.handle',
		'fromavatarblobid' => 'BINARY ufrom.avatarblobid', // cast to BINARY due to MySQL bug which renders it signed in a union
		'fromavatarwidth' => 'ufrom.avatarwidth', 'fromavatarheight' => 'ufrom.avatarheight',

		'toflags' => 'uto.flags', 'tolevel' => 'uto.level',
		'toemail' => 'uto.email', 'tohandle' => 'uto.handle',
		'toavatarblobid' => 'BINARY uto.avatarblobid', // cast to BINARY due to MySQL bug which renders it signed in a union
		'toavatarwidth' => 'uto.avatarwidth', 'toavatarheight' => 'uto.avatarheight',
	);
}


/**
 * If $fromidentifier is not null, return the selectspec to get recent private messages which have been sent from
 * the user identified by $fromidentifier+$fromisuserid to the user identified by $toidentifier+$toisuserid (see
 * qa_db_user_recent_qs_selectspec() comment). If $fromidentifier is null, then get recent wall posts
 * for the user identified by $toidentifier+$toisuserid. Return $count (if null, a default is used) messages.
1635 1636 1637 1638 1639
 * @param mixed $fromidentifier
 * @param bool $fromisuserid
 * @param mixed $toidentifier
 * @param bool $toisuserid
 * @param int|null $count
Scott committed
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
 * @param int $start
 * @return array
 */
function qa_db_recent_messages_selectspec($fromidentifier, $fromisuserid, $toidentifier, $toisuserid, $count = null, $start = 0)
{
	$count = isset($count) ? min($count, QA_DB_RETRIEVE_MESSAGES) : QA_DB_RETRIEVE_MESSAGES;

	if (isset($fromidentifier)) {
		$fromsub = $fromisuserid ? '$' : '(SELECT userid FROM ^users WHERE handle=$ LIMIT 1)';
		$where = 'fromuserid=' . $fromsub . " AND type='PRIVATE'";
Scott committed
1650
	} else {
Scott committed
1651
		$where = "type='PUBLIC'";
Scott committed
1652
	}
Scott committed
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
	$tosub = $toisuserid ? '$' : '(SELECT userid FROM ^users WHERE handle=$ LIMIT 1)';

	$source = '^messages LEFT JOIN ^users ufrom ON fromuserid=ufrom.userid LEFT JOIN ^users uto ON touserid=uto.userid WHERE ' . $where . ' AND touserid=' . $tosub . ' ORDER BY ^messages.created DESC LIMIT #,#';

	$arguments = isset($fromidentifier) ? array($fromidentifier, $toidentifier, $start, $count) : array($toidentifier, $start, $count);

	return array(
		'columns' => qa_db_messages_columns(),
		'source' => $source,
		'arguments' => $arguments,
		'arraykey' => 'messageid',
		'sortdesc' => 'created',
	);
}


/**
 * Get selectspec for messages *to* specified user. $type is either 'public' or 'private'.
 * $toidentifier is a handle or userid depending on the value of $toisuserid.
 * Returns $limit messages, or all of them if $limit is null (used in qa_db_selectspec_count).
1673 1674 1675
 * @param string $type
 * @param mixed $toidentifier
 * @param mixed $toisuserid
Scott committed
1676
 * @param int $start
1677
 * @param int|null $limit
Scott committed
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708
 * @return array
 */
function qa_db_messages_inbox_selectspec($type, $toidentifier, $toisuserid, $start = 0, $limit = null)
{
	$type = strtoupper($type);

	$where = 'touserid=' . ($toisuserid ? '$' : '(SELECT userid FROM ^users WHERE handle=$ LIMIT 1)') . ' AND type=$ AND tohidden=0';
	$source = '^messages LEFT JOIN ^users ufrom ON fromuserid=ufrom.userid LEFT JOIN ^users uto ON touserid=uto.userid WHERE ' . $where . ' ORDER BY ^messages.created DESC';
	$arguments = array($toidentifier, $type);

	if (isset($limit)) {
		$limit = min($limit, QA_DB_RETRIEVE_MESSAGES);
		$source .= ' LIMIT #,#';
		$arguments[] = $start;
		$arguments[] = $limit;
	}

	return array(
		'columns' => qa_db_messages_columns(),
		'source' => $source,
		'arguments' => $arguments,
		'arraykey' => 'messageid',
		'sortdesc' => 'created',
	);
}


/**
 * Get selectspec for messages *from* specified user. $type is either 'public' or 'private'.
 * $fromidentifier is a handle or userid depending on the value of $fromisuserid.
 * Returns $limit messages, or all of them if $limit is null (used in qa_db_selectspec_count).
1709 1710 1711
 * @param string $type
 * @param mixed $fromidentifier
 * @param bool $fromisuserid
Scott committed
1712
 * @param int $start
1713
 * @param int|null $limit
Scott committed
1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
 * @return array
 */
function qa_db_messages_outbox_selectspec($type, $fromidentifier, $fromisuserid, $start = 0, $limit = null)
{
	$type = strtoupper($type);

	$where = 'fromuserid=' . ($fromisuserid ? '$' : '(SELECT userid FROM ^users WHERE handle=$ LIMIT 1)') . ' AND type=$ AND fromhidden=0';
	$source = '^messages LEFT JOIN ^users ufrom ON fromuserid=ufrom.userid LEFT JOIN ^users uto ON touserid=uto.userid WHERE ' . $where . ' ORDER BY ^messages.created DESC';
	$arguments = array($fromidentifier, $type);

	if (isset($limit)) {
		$limit = min($limit, QA_DB_RETRIEVE_MESSAGES);
		$source .= ' LIMIT #,#';
		$arguments[] = $start;
		$arguments[] = $limit;
	}

	return array(
		'columns' => qa_db_messages_columns(),
		'source' => $source,
		'arguments' => $arguments,
		'arraykey' => 'messageid',
		'sortdesc' => 'created',
	);
}


/**
 * Return the selectspec to retrieve whether or not $userid has favorited entity $entitytype identifier by $identifier.
 * The $identifier should be a handle, word, backpath or postid for users, tags, categories and questions respectively.
1744 1745 1746
 * @param mixed $userid
 * @param string $entitytype
 * @param mixed $identifier
Scott committed
1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787
 * @return array
 */
function qa_db_is_favorite_selectspec($userid, $entitytype, $identifier)
{
	require_once QA_INCLUDE_DIR . 'app/updates.php';

	$selectspec = array(
		'columns' => array('flags' => 'COUNT(*)'),
		'source' => '^userfavorites WHERE userid=$ AND entitytype=$',
		'arrayvalue' => 'flags',
		'single' => true,
	);

	switch ($entitytype) {
		case QA_ENTITY_USER:
			$selectspec['source'] .= ' AND entityid=(SELECT userid FROM ^users WHERE handle=$ LIMIT 1)';
			break;

		case QA_ENTITY_TAG:
			$selectspec['source'] .= ' AND entityid=(SELECT wordid FROM ^words WHERE word=$ LIMIT 1)';
			break;

		case QA_ENTITY_CATEGORY:
			$selectspec['source'] .= ' AND entityid=(SELECT categoryid FROM ^categories WHERE backpath=$ LIMIT 1)';
			$identifier = qa_db_slugs_to_backpath($identifier);
			break;

		default:
			$selectspec['source'] .= ' AND entityid=$';
			break;
	}

	$selectspec['arguments'] = array($userid, $entitytype, $identifier);

	return $selectspec;
}


/**
 * Return the selectspec to retrieve an array of $userid's favorited questions, with the usual information.
 * Returns $limit questions, or all of them if $limit is null (used in qa_db_selectspec_count).
1788 1789
 * @param mixed $userid
 * @param int|null $limit
Scott committed
1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
 * @param int $start
 * @return array
 */
function qa_db_user_favorite_qs_selectspec($userid, $limit = null, $start = 0)
{
	require_once QA_INCLUDE_DIR . 'app/updates.php';

	$selectspec = qa_db_posts_basic_selectspec($userid);

	$selectspec['source'] .= ' JOIN ^userfavorites AS selectfave ON ^posts.postid=selectfave.entityid WHERE selectfave.userid=$ AND selectfave.entitytype=$ AND ^posts.type="Q" ORDER BY ^posts.created DESC';
	$selectspec['arguments'][] = $userid;
	$selectspec['arguments'][] = QA_ENTITY_QUESTION;

	if (isset($limit)) {
		$limit = min($limit, QA_DB_RETRIEVE_QS_AS);
		$selectspec['source'] .= ' LIMIT #,#';
		$selectspec['arguments'][] = $start;
		$selectspec['arguments'][] = $limit;
	}

	$selectspec['sortdesc'] = 'created';

	return $selectspec;
}


/**
 * Return the selectspec to retrieve an array of $userid's favorited users, with information about those users' accounts.
 * Returns $limit users, or all of them if $limit is null (used in qa_db_selectspec_count).
1819 1820
 * @param mixed $userid
 * @param int|null $limit
Scott committed
1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849
 * @param int $start
 * @return array
 */
function qa_db_user_favorite_users_selectspec($userid, $limit = null, $start = 0)
{
	require_once QA_INCLUDE_DIR . 'app/updates.php';

	$source = '^users JOIN ^userpoints ON ^users.userid=^userpoints.userid JOIN ^userfavorites ON ^users.userid=^userfavorites.entityid WHERE ^userfavorites.userid=$ AND ^userfavorites.entitytype=$ ORDER BY ^users.handle';
	$arguments = array($userid, QA_ENTITY_USER);

	if (isset($limit)) {
		$limit = min($limit, QA_DB_RETRIEVE_USERS);
		$source .= ' LIMIT #,#';
		$arguments[] = $start;
		$arguments[] = $limit;
	}

	return array(
		'columns' => array('^users.userid', 'handle', 'points', 'flags', '^users.email', 'avatarblobid' => 'BINARY avatarblobid', 'avatarwidth', 'avatarheight'),
		'source' => $source,
		'arguments' => $arguments,
		'sortasc' => 'handle',
	);
}


/**
 * Return the selectspec to retrieve an array of $userid's favorited tags, with information about those tags.
 * Returns $limit tags, or all of them if $limit is null (used in qa_db_selectspec_count).
1850 1851
 * @param mixed $userid
 * @param int|null $limit
Scott committed
1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879
 * @param int $start
 * @return array
 */
function qa_db_user_favorite_tags_selectspec($userid, $limit = null, $start = 0)
{
	require_once QA_INCLUDE_DIR . 'app/updates.php';

	$source = '^words JOIN ^userfavorites ON ^words.wordid=^userfavorites.entityid WHERE ^userfavorites.userid=$ AND ^userfavorites.entitytype=$ ORDER BY ^words.tagcount DESC';
	$arguments = array($userid, QA_ENTITY_TAG);

	if (isset($limit)) {
		$limit = min($limit, QA_DB_RETRIEVE_TAGS);
		$source .= ' LIMIT #,#';
		$arguments[] = $start;
		$arguments[] = $limit;
	}

	return array(
		'columns' => array('word', 'tagcount'),
		'source' => $source,
		'arguments' => $arguments,
		'sortdesc' => 'tagcount',
	);
}


/**
 * Return the selectspec to retrieve an array of $userid's favorited categories, with information about those categories.
1880
 * @param mixed $userid
Scott committed
1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898
 * @return array
 */
function qa_db_user_favorite_categories_selectspec($userid)
{
	require_once QA_INCLUDE_DIR . 'app/updates.php';

	return array(
		'columns' => array('categoryid', 'title', 'tags', 'qcount', 'backpath', 'content'),
		'source' => "^categories JOIN ^userfavorites ON ^categories.categoryid=^userfavorites.entityid WHERE ^userfavorites.userid=$ AND ^userfavorites.entitytype=$",
		'arguments' => array($userid, QA_ENTITY_CATEGORY),
		'sortasc' => 'title',
	);
}


/**
 * Return the selectspec to retrieve information about all a user's favorited items except the questions. Depending on
 * the type of item, the array for each item will contain a userid, category backpath or tag word.
1899
 * @param mixed $userid
Scott committed
1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
 * @return array
 */
function qa_db_user_favorite_non_qs_selectspec($userid)
{
	require_once QA_INCLUDE_DIR . 'app/updates.php';

	return array(
		'columns' => array('type' => 'entitytype', 'userid' => 'IF (entitytype=$, entityid, NULL)', 'categorybackpath' => '^categories.backpath', 'tags' => '^words.word'),
		'source' => '^userfavorites LEFT JOIN ^words ON entitytype=$ AND wordid=entityid LEFT JOIN ^categories ON entitytype=$ AND categoryid=entityid WHERE userid=$ AND entitytype!=$',
		'arguments' => array(QA_ENTITY_USER, QA_ENTITY_TAG, QA_ENTITY_CATEGORY, $userid, QA_ENTITY_QUESTION),
	);
}


/**
 * Return the selectspec to retrieve the list of recent updates for $userid. Set $forfavorites to whether this should
 * include updates on the user's favorites and $forcontent to whether it should include responses to user's content.
 * This combines events from both the user's stream and the the shared stream for any entities which the user has
1918
 * favorited and which no longer post to user streams (see long comment in /qa-include/db/favorites.php).
1919
 * @param mixed $userid
Scott committed
1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953
 * @param bool $forfavorites
 * @param bool $forcontent
 * @return array
 */
function qa_db_user_updates_selectspec($userid, $forfavorites = true, $forcontent = true)
{
	require_once QA_INCLUDE_DIR . 'app/updates.php';

	$selectspec = qa_db_posts_basic_selectspec($userid);

	$nonesql = qa_db_argument_to_mysql(QA_ENTITY_NONE, true);

	$selectspec['columns']['obasetype'] = 'LEFT(updateposts.type, 1)';
	$selectspec['columns']['oupdatetype'] = 'fullevents.updatetype';
	$selectspec['columns']['ohidden'] = "INSTR(updateposts.type, '_HIDDEN')>0";
	$selectspec['columns']['opostid'] = 'fullevents.lastpostid';
	$selectspec['columns']['ouserid'] = 'fullevents.lastuserid';
	$selectspec['columns']['otime'] = 'UNIX_TIMESTAMP(fullevents.updated)';
	$selectspec['columns']['opersonal'] = 'fullevents.entitytype=' . $nonesql;
	$selectspec['columns']['oparentid'] = 'updateposts.parentid';

	qa_db_add_selectspec_ousers($selectspec, 'eventusers', 'eventuserpoints');

	if ($forfavorites) { // life is hard
		$selectspec['source'] .= ' JOIN ' .
			"(SELECT entitytype, questionid, lastpostid, updatetype, lastuserid, updated FROM ^userevents WHERE userid=$" .
			($forcontent ? '' : " AND entitytype!=" . $nonesql) .
			" UNION SELECT ^sharedevents.entitytype, questionid, lastpostid, updatetype, lastuserid, updated FROM ^sharedevents JOIN ^userfavorites ON ^sharedevents.entitytype=^userfavorites.entitytype AND ^sharedevents.entityid=^userfavorites.entityid AND ^userfavorites.nouserevents=1 WHERE userid=$) fullevents ON ^posts.postid=fullevents.questionid";

		array_push($selectspec['arguments'], $userid, $userid);

	} else { // life is easy
		$selectspec['source'] .= " JOIN ^userevents AS fullevents ON ^posts.postid=fullevents.questionid AND fullevents.userid=$ AND fullevents.entitytype=" . $nonesql;
		$selectspec['arguments'][] = $userid;
Scott committed
1954 1955
	}

Scott committed
1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973
	$selectspec['source'] .=
		" JOIN ^posts AS updateposts ON updateposts.postid=fullevents.lastpostid" .
		" AND (updateposts.type IN ('Q', 'A', 'C') OR fullevents.entitytype=" . $nonesql . ")" .
		" AND (^posts.selchildid=fullevents.lastpostid OR NOT fullevents.updatetype<=>$) AND ^posts.type IN ('Q', 'Q_HIDDEN')" .
		(QA_FINAL_EXTERNAL_USERS ? '' : ' LEFT JOIN ^users AS eventusers ON fullevents.lastuserid=eventusers.userid') .
		' LEFT JOIN ^userpoints AS eventuserpoints ON fullevents.lastuserid=eventuserpoints.userid';
	$selectspec['arguments'][] = QA_UPDATE_SELECTED;

	unset($selectspec['arraykey']); // allow same question to be retrieved multiple times

	$selectspec['sortdesc'] = 'otime';

	return $selectspec;
}


/**
 * Return the selectspec to retrieve all of the per-hour activity limits for user $userid
1974
 * @param mixed $userid
Scott committed
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989
 * @return array
 */
function qa_db_user_limits_selectspec($userid)
{
	return array(
		'columns' => array('action', 'period', 'count'),
		'source' => '^userlimits WHERE userid=$',
		'arguments' => array($userid),
		'arraykey' => 'action',
	);
}


/**
 * Return the selectspec to retrieve all of the per-hour activity limits for ip address $ip
1990
 * @param string $ip
Scott committed
1991 1992 1993 1994 1995 1996
 * @return array
 */
function qa_db_ip_limits_selectspec($ip)
{
	return array(
		'columns' => array('action', 'period', 'count'),
1997 1998
		'source' => '^iplimits WHERE ip=UNHEX($)',
		'arguments' => array(bin2hex(@inet_pton($ip))),
Scott committed
1999 2000 2001 2002 2003 2004 2005 2006 2007
		'arraykey' => 'action',
	);
}


/**
 * Return the selectspec to retrieve all of the context specific (currently per-categpry) levels for the user identified by
 * $identifier, which is treated as a userid if $isuserid is true, otherwise as a handle. Set $full to true to obtain extra
 * information about these contexts (currently, categories).
2008
 * @param mixed $identifier
Scott committed
2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029
 * @param bool $isuserid
 * @param bool $full
 * @return array
 */
function qa_db_user_levels_selectspec($identifier, $isuserid = QA_FINAL_EXTERNAL_USERS, $full = false)
{
	require_once QA_INCLUDE_DIR . 'app/updates.php';

	$selectspec = array(
		'columns' => array('entityid', 'entitytype', 'level'),
		'source' => '^userlevels' . ($full ? ' LEFT JOIN ^categories ON ^userlevels.entitytype=$ AND ^userlevels.entityid=^categories.categoryid' : '') . ' WHERE userid=' . ($isuserid ? '$' : '(SELECT userid FROM ^users WHERE handle=$ LIMIT 1)'),
		'arguments' => array($identifier),
	);

	if ($full) {
		array_push($selectspec['columns'], 'title', 'backpath');
		array_unshift($selectspec['arguments'], QA_ENTITY_CATEGORY);
	}

	return $selectspec;
}