-
Notifications
You must be signed in to change notification settings - Fork 618
Expand file tree
/
Copy pathselects.php
More file actions
2038 lines (1671 loc) · 74.9 KB
/
selects.php
File metadata and controls
2038 lines (1671 loc) · 74.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
Question2Answer by Gideon Greenspan and contributors
http://www.question2answer.org/
Description: 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
*/
if (!defined('QA_VERSION')) { // don't allow this page to be requested directly from browser
header('Location: ../../');
exit;
}
require_once QA_INCLUDE_DIR.'db/maxima.php';
/**
* 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.
*/
function qa_db_select_with_pending() // any number of parameters read via func_get_args()
{
require_once QA_INCLUDE_DIR . 'app/options.php';
global $qa_db_pending_selectspecs, $qa_db_pending_results;
$selectspecs = func_get_args();
$singleresult = (count($selectspecs) == 1);
$outresults = array();
foreach ($selectspecs as $key => $selectspec) { // can pass null parameters
if (empty($selectspec)) {
unset($selectspecs[$key]);
$outresults[$key] = null;
}
}
if (is_array($qa_db_pending_selectspecs)) {
foreach ($qa_db_pending_selectspecs as $pendingid => $selectspec) {
if (!isset($qa_db_pending_results[$pendingid])) {
$selectspecs['pending_' . $pendingid] = $selectspec;
}
}
}
$outresults = $outresults + qa_db_multi_select($selectspecs);
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]);
}
}
}
return $singleresult ? $outresults[0] : $outresults;
}
/**
* Queue a $selectspec for running later, with $pendingid (used for retrieval)
* @param $pendingid
* @param $selectspec
*/
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.
* @param $pendingid
* @param $selectspec
* @return
*/
function qa_db_get_pending_result($pendingid, $selectspec = null)
{
global $qa_db_pending_selectspecs, $qa_db_pending_results;
if (isset($selectspec)) {
qa_db_queue_pending_select($pendingid, $selectspec);
} elseif (!isset($qa_db_pending_selectspecs[$pendingid])) {
qa_fatal_error('Pending query was never set up: ' . $pendingid);
}
if (!isset($qa_db_pending_results[$pendingid])) {
qa_db_select_with_pending();
}
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()
* @param $pendingid
*/
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.
* @param $selectSpec
* @return mixed
*/
function qa_db_selectspec_count($selectSpec)
{
$selectSpec['columns'] = array('count' => 'COUNT(*)');
$selectSpec['single'] = true;
unset($selectSpec['arraykey']);
return $selectSpec;
}
/**
* 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).
* @param $voteuserid
* @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(
'^posts.postid', '^posts.categoryid', '^posts.type', 'basetype' => 'LEFT(^posts.type, 1)',
'hidden' => "INSTR(^posts.type, '_HIDDEN')>0", 'queued' => "INSTR(^posts.type, '_QUEUED')>0",
'^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';
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';
}
}
$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.
* @param $selectspec
* @param $poststable
* @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';
if ($fromupdated) {
$selectspec['columns']['oupdatetype'] = $poststable . '.updatetype';
}
if ($full) {
$selectspec['columns']['ocontent'] = $poststable . '.content';
$selectspec['columns']['oformat'] = $poststable . '.format';
}
if ($fromupdated || $full) {
$selectspec['columns']['oupdated'] = 'UNIX_TIMESTAMP(' . $poststable . '.updated)';
}
}
/**
* 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.
* @param $selectspec
* @param $userstable
* @param $pointstable
*/
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
* @param $categoryslugs
* @return string
*/
function qa_db_slugs_to_backpath($categoryslugs)
{
if (!is_array($categoryslugs)) {
// accept old-style string arguments for one category deep
$categoryslugs = array($categoryslugs);
}
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
* @param $categoryslugs
* @param $arguments
* @return string
*/
function qa_db_categoryslugs_sql_args($categoryslugs, &$arguments)
{
if (!is_array($categoryslugs)) {
// accept old-style string arguments for one category deep
$categoryslugs = strlen($categoryslugs) ? array($categoryslugs) : array();
}
$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.
* @param $voteuserid
* @param $sort
* @param $start
* @param $categoryslugs
* @param $createip
* @param bool $specialtype
* @param bool $full
* @param $count
* @return array
*/
function qa_db_qs_selectspec($voteuserid, $sort, $start, $categoryslugs = null, $createip = null, $specialtype = false, $full = false, $count = null)
{
if ($specialtype == 'Q' || $specialtype == 'Q_QUEUED') {
$type = $specialtype;
} else {
$type = $specialtype ? 'Q_HIDDEN' : 'Q'; // for backwards compatibility
}
$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);
$selectspec['source'] .=
" JOIN (SELECT postid FROM ^posts WHERE " .
qa_db_categoryslugs_sql_args($categoryslugs, $selectspec['arguments']) .
(isset($createip) ? "createip=UNHEX($) AND " : "") .
"type=$ " . $sortsql . " LIMIT #,#) y ON ^posts.postid=y.postid";
if (isset($createip)) {
$selectspec['arguments'][] = bin2hex(@inet_pton($createip));
}
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.
* @param $voteuserid
* @param $by
* @param $start
* @param $categoryslugs
* @param bool $specialtype
* @param bool $full
* @param $count
* @return array
*/
function qa_db_unanswered_qs_selectspec($voteuserid, $by, $start, $categoryslugs = null, $specialtype = false, $full = false, $count = null)
{
if ($specialtype == 'Q' || $specialtype == 'Q_QUEUED') {
$type = $specialtype;
} else {
$type = $specialtype ? 'Q_HIDDEN' : 'Q'; // for backwards compatibility
}
$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'.
* @param $voteuserid
* @param $start
* @param $categoryslugs
* @param $createip
* @param bool $specialtype
* @param bool $fullanswers
* @param $count
* @return array
*/
function qa_db_recent_a_qs_selectspec($voteuserid, $start, $categoryslugs = null, $createip = null, $specialtype = false, $fullanswers = false, $count = null)
{
if ($specialtype == 'A' || $specialtype == 'A_QUEUED') {
$type = $specialtype;
} else {
$type = $specialtype ? 'A_HIDDEN' : 'A'; // for backwards compatibility
}
$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');
$selectspec['source'] .=
" JOIN ^posts AS aposts ON ^posts.postid=aposts.parentid" .
(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']) .
(isset($createip) ? "createip=UNHEX($) AND " : "") .
"type=$ ORDER BY ^posts.created DESC LIMIT #,#) y ON aposts.postid=y.postid" .
($specialtype ? '' : " WHERE ^posts.type='Q'");
if (isset($createip)) {
$selectspec['arguments'][] = bin2hex(@inet_pton($createip));
}
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'.
* @param $voteuserid
* @param $start
* @param $categoryslugs
* @param $createip
* @param bool $specialtype
* @param bool $fullcomments
* @param $count
* @return array
*/
function qa_db_recent_c_qs_selectspec($voteuserid, $start, $categoryslugs = null, $createip = null, $specialtype = false, $fullcomments = false, $count = null)
{
if ($specialtype == 'C' || $specialtype == 'C_QUEUED') {
$type = $specialtype;
} else {
$type = $specialtype ? 'C_HIDDEN' : 'C'; // for backwards compatibility
}
$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');
$selectspec['source'] .=
" JOIN ^posts AS parentposts ON" .
" ^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']) .
(isset($createip) ? "createip=UNHEX($) AND " : "") .
"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'))");
if (isset($createip)) {
$selectspec['arguments'][] = bin2hex(@inet_pton($createip));
}
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'.
* @param $voteuserid
* @param $start
* @param $categoryslugs
* @param $lastip
* @param bool $onlyvisible
* @param bool $fulledited
* @param $count
* @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');
$selectspec['source'] .=
" JOIN ^posts AS parentposts ON" .
" ^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']) .
(isset($lastip) ? "lastip=UNHEX($) AND " : "") .
($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')" : "");
if (isset($lastip)) {
$selectspec['arguments'][] = bin2hex(@inet_pton($lastip));
}
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).
* @param $voteuserid
* @param $start
* @param bool $fullflagged
* @param $count
* @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');
$selectspec['source'] .=
" JOIN ^posts AS parentposts ON" .
" ^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.
* @param $voteuserid
* @param $postids
* @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
* @param $postids
* @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
* @param $voteuserid
* @param $postids
* @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';
$selectspec['source'] .=
" JOIN ^posts AS parentposts ON" .
" ^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)
* @param $voteuserid
* @param $postid
* @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)
* @param $voteuserid
* @param $parentid
* @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)
* @param $voteuserid
* @param $questionid
* @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.
* @param $postid
* @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
* @param $questionid
* @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
* @param $questionid int The canonical question.
* @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;
}
/**
* Return the selectspec to retrieve the metadata value for $postid with key $title
* @param $postid
* @param $title
* @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',
);
if (is_array($title)) {
$selectspec['arraykey'] = 'title';
} else {
$selectspec['single'] = true;
}
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.
* @param $voteuserid
* @param $questionid
* @param $count
* @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'),
);
}
return $selectspec;
}
/**
* 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().
* @param $voteuserid
* @param $titlewords
* @param $contentwords
* @param $tagwords
* @param $handlewords
* @param $handle
* @param $start
* @param bool $full
* @param $count
* @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;
// 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.
$selectspec = qa_db_posts_basic_selectspec($voteuserid, $full);
$selectspec['columns'][] = 'score';
$selectspec['columns'][] = 'matchparts';
$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 (";
$selectspec['sortdesc'] = 'score';
array_push($selectspec['arguments'], QA_IGNORED_WORDS_FREQ);
$selectparts = 0;
if (!empty($titlewords)) {
// At the indexing stage, duplicate words in title are ignored, so this doesn't count multiple appearances.
$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<#)";
array_push($selectspec['arguments'], QA_IGNORED_WORDS_FREQ, $titlewords, QA_IGNORED_WORDS_FREQ);
}
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.
$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<#)";
array_push($selectspec['arguments'], QA_IGNORED_WORDS_FREQ, $contentwords, QA_IGNORED_WORDS_FREQ);
}
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.
$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<#)";
array_push($selectspec['arguments'], QA_IGNORED_WORDS_FREQ, $tagwords, QA_IGNORED_WORDS_FREQ);
}
if (!empty($handlewords)) {
if (QA_FINAL_EXTERNAL_USERS) {
require_once QA_INCLUDE_DIR . 'app/users.php';
$userids = qa_get_userids_from_public($handlewords);
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')";
array_push($selectspec['arguments'], QA_IGNORED_WORDS_FREQ, $userids);
}
} 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')";
array_push($selectspec['arguments'], QA_IGNORED_WORDS_FREQ, $handlewords);
}
}
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));
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')";
array_push($selectspec['arguments'], QA_IGNORED_WORDS_FREQ, reset($userids));
}
} 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')";
array_push($selectspec['arguments'], QA_IGNORED_WORDS_FREQ, $handle);
}
}
if ($selectparts == 0) {
$selectspec['source'] .= '(SELECT NULL as questionid, 0 AS score, NULL AS matchposttype, NULL AS matchpostid FROM ^posts WHERE postid IS NULL)';
}
$selectspec['source'] .= ") x LEFT JOIN ^posts ON ^posts.postid=questionid GROUP BY questionid ORDER BY score DESC LIMIT #,#) y ON ^posts.postid=y.questionid";
array_push($selectspec['arguments'], $start, $count);
return $selectspec;
}
/**
* 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
* @param $question
* @param $type
* @param $postid
* @return null
*/
function qa_search_set_max_match($question, &$type, &$postid)
{
$type = 'Q';
$postid = $question['postid'];
$bestscore = null;
$matchparts = explode(',', $question['matchparts']);
foreach ($matchparts as $matchpart) {