/
search.php
5892 lines (5089 loc) · 318 KB
/
search.php
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
// Project: Web Reference Database (refbase) <http://www.refbase.net>
// Copyright: Matthias Steffens <mailto:refbase@extracts.de> and the file's
// original author(s).
//
// This code is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY. Please see the GNU General Public
// License for more details.
//
// File: ./search.php
// Repository: $HeadURL: http://svn.code.sf.net/p/refbase/code/trunk/search.php $
// Author(s): Matthias Steffens <mailto:refbase@extracts.de>
//
// Created: 30-Jul-02, 17:40
// Modified: $Date: 2013-11-19 10:28:06 -0800 (Tue, 19 Nov 2013) $
// $Author: pnault $
// $Revision: 1384 $
// This is the main script that handles the search query and displays the query results.
// Supports three different output styles: 1) List view, with fully configurable columns -> displayColumns() function
// 2) Details view, shows all fields -> displayDetails() function; 3) Citation view -> generateCitations() function
// TODO: - Refactor so that query builder will use a few common functions
// - I18n
// Incorporate some include files:
include 'initialize/db.inc.php'; // 'db.inc.php' is included to hide username and password
include 'includes/header.inc.php'; // include header
include 'includes/results_header.inc.php'; // include results header
include 'includes/footer.inc.php'; // include footer
include 'includes/include.inc.php'; // include common functions
include 'includes/cite.inc.php'; // include citation functions
include 'includes/export.inc.php'; // include export functions
include 'includes/execute.inc.php'; // include functions that deal with execution of shell commands
include 'includes/atomxml.inc.php'; // include functions that deal with Atom XML
include 'includes/modsxml.inc.php'; // include functions that deal with MODS XML
include 'includes/oaidcxml.inc.php'; // include functions that deal with OAI_DC XML
include 'includes/odfxml.inc.php'; // include functions that deal with ODF XML
include 'includes/opensearch.inc.php'; // include functions that return an OpenSearch response
include 'includes/openurl.inc.php';
include 'includes/srwxml.inc.php'; // include functions that deal with SRW XML
include 'initialize/ini.inc.php'; // include common variables
// --------------------------------------------------------------------
// Extract the ID of the client from which the query originated:
// this identifier is used to identify queries that originated from the refbase command line clients ("cli-refbase-1.1", "cli-refbase_import-1.0") or from a bookmarklet (e.g., "jsb-refbase-1.0")
// (note that 'client' parameter has to be extracted *before* the call to the 'start_session()' function, since it's value is required by this function)
if (isset($_REQUEST['client']))
$client = $_REQUEST['client'];
else
$client = "";
// START A SESSION:
// call the 'start_session()' function (from 'include.inc.php') which will also read out available session variables:
start_session(true);
// Read out POST data that were saved as a session variable:
// NOTE: this is done by 'show.php' if the original request was a POST (as is the case for the refbase command line client)
// in order to retain large param/value strings (that would exceed the maximum string limit for GET requests)
if (isset($_SESSION['postData']))
{
foreach ($_SESSION['postData'] as $varname => $value)
{
$_POST[$varname] = $value;
$_REQUEST[$varname] = $value;
}
deleteSessionVariable("postData"); // function 'deleteSessionVariable()' is defined in 'include.inc.php'
}
// --------------------------------------------------------------------
// Initialize preferred display language:
// (note that 'locales.inc.php' has to be included *after* the call to the 'start_session()' function)
include 'includes/locales.inc.php'; // include the locales
// --------------------------------------------------------------------
// EXTRACT FORM VARIABLES
// [ Extract form variables sent through POST/GET by use of the '$_REQUEST' variable ]
// [ !! NOTE !!: for details see <http://www.php.net/release_4_2_1.php> & <http://www.php.net/manual/en/language.variables.predefined.php> ]
// Extract the form used for searching:
$formType = $_REQUEST['formType'];
// Extract the type of display requested by the user. Normally, this will be one of the following:
// - '' => if the 'submit' parameter is empty, this will produce the default view
// - 'List' => display records using the columnar output style ('displayColumns()' function)
// - 'Display' => display details for all found records ('displayDetails()' function)
// - 'Cite' => build a proper citation for all found records ('generateCitations()' function)
// - 'Browse' => browse unique values from a given database field ('displayColumns()' function)
// Note that the 'submit' parameter can be also one of the following:
// - 'Export' => generate and return selected records in the bibliographic format specified by the user ('generateExport()' function)
// - 'RSS' => these value gets included within the 'RSS' link (in the page header) and will cause 'search.php' to return results as RSS feed
// - 'Search', 'Show' or 'Hide' => these values change/refine the search results or their appearance on screen (how many entries & which columns get displayed)
// - 'Add', 'Remove' => these values will trigger actions that act on the selected records
if (isset($_REQUEST['submit']) AND !empty($_REQUEST['submit']))
$displayType = $_REQUEST['submit'];
else
$displayType = $_SESSION['userDefaultView']; // get the default view for the current user
// extract the original value of the '$displayType' variable:
// (which was included as a hidden form tag within the 'groupSearch' form of a search results page, the 'queryResults' form in Details view, and the 'duplicateSearch' form)
if (isset($_REQUEST['originalDisplayType']))
$originalDisplayType = $_REQUEST['originalDisplayType'];
else
$originalDisplayType = "";
// we need to check if the user is allowed to view records with the specified display type:
if ($displayType == "List")
{
if (isset($_SESSION['user_permissions']) AND !preg_match("/allow_list_view/", $_SESSION['user_permissions'])) // if the 'user_permissions' session variable does NOT contain 'allow_list_view'...
{
// return an appropriate error message:
$HeaderString = returnMsg($loc["NoPermission"] . $loc["NoPermission_ForDisplayColumns"] . "!", "warning", "strong", "HeaderString"); // function 'returnMsg()' is defined in 'include.inc.php'
if (!preg_match("/^cli/i", $client))
header("Location: index.php"); // redirect to main page ('index.php')
exit; // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> !EXIT! <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
}
}
elseif ($displayType == "Display")
{
if (isset($_SESSION['user_permissions']) AND !preg_match("/allow_details_view/", $_SESSION['user_permissions'])) // if the 'user_permissions' session variable does NOT contain 'allow_details_view'...
{
// return an appropriate error message:
$HeaderString = returnMsg($loc["NoPermission"] . $loc["NoPermission_ForDisplayDetails"] . "!", "warning", "strong", "HeaderString"); // function 'returnMsg()' is defined in 'include.inc.php'
if (!preg_match("/^cli/i", $client))
header("Location: index.php"); // redirect to main page ('index.php')
exit; // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> !EXIT! <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
}
}
elseif ($displayType == "Cite")
{
if (isset($_SESSION['user_permissions']) AND !preg_match("/allow_cite/", $_SESSION['user_permissions'])) // if the 'user_permissions' session variable does NOT contain 'allow_cite'...
{
// return an appropriate error message:
$HeaderString = returnMsg($loc["NoPermission"] . $loc["NoPermission_ForCite"] . "!", "warning", "strong", "HeaderString"); // function 'returnMsg()' is defined in 'include.inc.php'
if (!preg_match("/^cli/i", $client))
{
if (preg_match("#/extract\.php#i", $referer)) // if the query was submitted by 'extract.php' (variable '$referer' is globally defined in function 'start_session()' in 'include.inc.php')
header("Location: " . $referer); // redirect to calling page
else
header("Location: index.php"); // redirect to main page ('index.php')
}
exit; // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> !EXIT! <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
}
}
elseif ($displayType == "Export")
{
if (isset($_SESSION['user_permissions']) AND !preg_match("/allow_export|allow_batch_export/", $_SESSION['user_permissions'])) // if the 'user_permissions' session variable does NOT contain either 'allow_export' or 'allow_batch_export'...
{
// return an appropriate error message:
$HeaderString = returnMsg($loc["NoPermission"] . $loc["NoPermission_ForExport"] . "!", "warning", "strong", "HeaderString"); // function 'returnMsg()' is defined in 'include.inc.php'
if (!preg_match("/^cli/i", $client))
header("Location: index.php"); // redirect to main page ('index.php')
exit; // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> !EXIT! <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
}
}
if ($formType == "sqlSearch" AND preg_match("#/sql_search\.php#i", $referer))
{
// NOTES: - currently, we restrict this if clause to requests from 'sql_search.php'
// - note that this if clause is in NO way fool-proof since it won't apply if:
// - the SQL query gets sent from another (custom) script
// - the '$referer' variable is empty or defaults to 'index.php'
// - the SQL query contained in the 'search.php' request gets edited directly
// - the other approach would be to disallow SQL searches (if the user has no permission to do so) from any but a few
// selected scripts; however, at least the scripts 'search.php', 'opensearch.php', 'show.php', 'user_login.php' and
// 'query_history.php' must be allowed
// - in that case, 'show.php' should save the URL of the current 'show.php' request to the 'referer' session variable;
// since function 'start_session()' prefers '$_SESSION['referer']' over '$_SERVER['HTTP_REFERER']', this means that
// '$referer' then contains a 'show.php' URL and not e.g. a '*_search.php' URL; this, in turn, prevents the
// "NoPermission_ForSQL" warning if a user clicked the "Show All" link in the header of any of the '*_search.php' pages
// - however, since refbase currently relies heavily on embedded SQL queries, disallowing SQL searches from any but a few
// selected scripts may fail in unforeseen cases; it would also prevent users to embed 'search.php' links in foreign pages
// - since it would be always possible to edit the 'search.php' request directly, we currently just disallow SQL searches via
// the GUI (i.e. the 'sql_search.php' form); BUT:
// - note that further measures (e.g. to prevent cross-site scripting (XSS) attacks or access to unwanted SQL queries & tables)
// are done below
// TODO: is there a way to disallow manual SQL searches (if the user has no permission to do so) which still allows searches from
// 'opensearch.php' & 'show.php' etc and which does not rely on any passed referrer?
if (isset($_SESSION['user_permissions']) AND !preg_match("/allow_sql_search/", $_SESSION['user_permissions'])) // if the 'user_permissions' session variable does NOT contain 'allow_sql_search'...
{
// return an appropriate error message:
$HeaderString = returnMsg($loc["NoPermission"] . $loc["NoPermission_ForSQL"] . "!", "warning", "strong", "HeaderString"); // function 'returnMsg()' is defined in 'include.inc.php'
if (!preg_match("/^cli/i", $client))
{
if (preg_match("#/sql_search\.php#i", $referer)) // if the sql query was entered in the form provided by 'sql_search.php'
header("Location: " . $referer); // redirect to calling page
else
header("Location: index.php"); // redirect to main page ('index.php')
}
exit; // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> !EXIT! <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
}
}
// For a given display type, extract the view type requested by the user (either 'Mobile', 'Print', 'Web' or ''):
// ('' will produce the default 'Web' output style)
if (isset($_REQUEST['viewType']))
$viewType = ucfirst(strtolower($_REQUEST['viewType'])); // we normalize the case of passed values
else
$viewType = "";
// Extract other variables from the request:
if (isset($_REQUEST['sqlQuery']))
$sqlQuery = $_REQUEST['sqlQuery'];
else
$sqlQuery = "";
if (preg_match("/%20/", $sqlQuery)) // if '$sqlQuery' still contains URL encoded data... ('%20' is the URL encoded form of a space, see note below!)
$sqlQuery = rawurldecode($sqlQuery); // URL decode SQL query (it was URL encoded before incorporation into hidden tags of the 'groupSearch', 'refineSearch', 'displayOptions' and 'queryResults' forms to avoid any HTML syntax errors)
// NOTE: URL encoded data that are included within a *link* will get URL decoded automatically *before* extraction via '$_REQUEST'!
// But, opposed to that, URL encoded data that are included within a form by means of a hidden form tag will *NOT* get URL decoded automatically! Then, URL decoding has to be done manually (as is done here)!
if (isset($_REQUEST['showQuery']) AND ($_REQUEST['showQuery'] == "1"))
$showQuery = "1";
else
$showQuery = "0"; // don't show the SQL query by default
if (isset($_REQUEST['showLinks']) AND ($_REQUEST['showLinks'] == "0"))
$showLinks = "0";
else
$showLinks = "1"; // show the links column by default
if (isset($_REQUEST['showRows']) AND preg_match("/^[0-9]+$/", $_REQUEST['showRows'])) // NOTE: we cannot use "^[1-9]+[0-9]*$" here since 'maximumRecords=0' is used in 'opensearch.php' and 'sru.php' queries to return just the number of found records (and not the full record data)
$showRows = $_REQUEST['showRows'];
else
$showRows = $_SESSION['userRecordsPerPage']; // get the default number of records per page preferred by the current user
if (isset($_REQUEST['rowOffset']))
{
// Note: Besides passing the current value of '$rowOffset' within GET queries, this parameter was also included as a hidden tag into the 'queryResults' form.
// This was done, so that the correct offset could be re-applied after the user pressed either of the 'Add' or 'Remove' buttons.
// However, '$rowOffset' MUST NOT be set if the user clicked the 'Display' or 'Cite' button within the 'queryResults' form!
// Therefore, we'll trap this case here:
if (($formType != "queryResults") OR ($formType == "queryResults" AND !preg_match("/^(Display|Cite)$/", $displayType)))
$rowOffset = $_REQUEST['rowOffset'];
else // if ($formType == "queryResults" AND preg_match("/^(Display|Cite)$/", $displayType))
$rowOffset = 0;
}
else
$rowOffset = 0;
if (isset($_REQUEST['wrapResults']) AND ($_REQUEST['wrapResults'] == "0"))
$wrapResults = "0"; // 'wrapResults=0' causes refbase to output only a partial document structure containing solely the search results (e.g. for HTML, everything is omitted except for the <table> block containing the search results)
else
$wrapResults = "1"; // we'll output a full document (HTML, RTF, LaTeX, etc) structure unless the 'wrapResults' parameter is set explicitly to "0"
// In order to generalize routines we have to query further variables here:
if (isset($_REQUEST['citeStyle']) AND !empty($_REQUEST['citeStyle']))
$citeStyle = $_REQUEST['citeStyle']; // get the cite style chosen by the user (only occurs in 'extract.php' form and in query result lists)
else
$citeStyle = $defaultCiteStyle; // if no cite style was given, we'll use the default cite style which is defined by the '$defaultCiteStyle' variable in 'ini.inc.php'
if (preg_match("/%20/", $citeStyle)) // if '$citeStyle' still contains URL encoded data... ('%20' is the URL encoded form of a space, see note below!)
$citeStyle = rawurldecode($citeStyle); // ...URL decode 'citeStyle' statement (it was URL encoded before incorporation into a hidden tag of the 'sqlSearch' form to avoid any HTML syntax errors)
// NOTE: URL encoded data that are included within a *link* will get URL decoded automatically *before* extraction via '$_REQUEST'!
// But, opposed to that, URL encoded data that are included within a form by means of a *hidden form tag* will NOT get URL decoded automatically! Then, URL decoding has to be done manually (as is done here)!
if (isset($_REQUEST['exportFormat']) AND !empty($_REQUEST['exportFormat']))
$exportFormat = $_REQUEST['exportFormat']; // get the export format style chosen by the user (only occurs in 'extract.php' form and in query result lists)
else
$exportFormat = $defaultExportFormat; // if no export format was given, we'll use the default export format which is defined by the '$defaultExportFormat' variable in 'ini.inc.php'
if (preg_match("/%20/", $exportFormat)) // if '$exportFormat' still contains URL encoded data... ('%20' is the URL encoded form of a space, see note below!)
$exportFormat = rawurldecode($exportFormat); // ...URL decode 'exportFormat' statement (it was URL encoded before incorporation into a hidden tag of the 'sqlSearch' form to avoid any HTML syntax errors)
// NOTE: URL encoded data that are included within a *link* will get URL decoded automatically *before* extraction via '$_REQUEST'!
// But, opposed to that, URL encoded data that are included within a form by means of a *hidden form tag* will NOT get URL decoded automatically! Then, URL decoding has to be done manually (as is done here)!
// Standardize XML export format names:
// NOTE: the below regex patterns are potentially too lax and might cause misbehaviour in case any custom export formats have been added
if (preg_match("/^Atom/i", $exportFormat))
$exportFormat = "Atom XML";
elseif (preg_match("/^MODS/i", $exportFormat))
$exportFormat = "MODS XML";
elseif (preg_match("/^(OAI_)?DC/i", $exportFormat))
$exportFormat = "OAI_DC XML";
elseif (preg_match("/^ODF/i", $exportFormat))
$exportFormat = "ODF XML";
elseif (preg_match("/^SRW_DC/i", $exportFormat))
$exportFormat = "SRW_DC XML";
elseif (preg_match("/^SRW/i", $exportFormat))
$exportFormat = "SRW_MODS XML";
elseif (preg_match("/^Word/i", $exportFormat))
$exportFormat = "Word XML";
if (isset($_REQUEST['citeOrder']))
$citeOrder = $_REQUEST['citeOrder']; // get information how the data should be sorted (only occurs in 'extract.php'/'sql_search' forms and in query result lists). If this param is set to 'year', records will be listed in blocks sorted by year.
else
$citeOrder = "";
// get information how citation data shall be returned:
// - 'html' => return citations as HTML with mime type 'text/html'
// - 'RTF' => return citations as RTF data with mime type 'application/rtf'
// - 'PDF' => return citations as PDF data with mime type 'application/pdf'
// - 'LaTeX' => return citations as LaTeX data with mime type 'application/x-latex'
// - 'Markdown' => return citations as Markdown TEXT data with mime type 'text/plain'
// - 'ASCII' => return citations as TEXT data with mime type 'text/plain'
// - 'LaTeX .bbl' => return citations as LaTeX .bbl file (for use with LaTeX/BibTeX) with mime type 'application/x-latex'
if (isset($_REQUEST['citeType']) AND preg_match("/^(html|RTF|PDF|LaTeX|Markdown|ASCII|LaTeX \.bbl)$/i", $_REQUEST['citeType']) AND !preg_match("/^(Add|Remove)$/i", $displayType)) // we always return HTML if the user clicked either the 'Add' or the 'Remove' button
$citeType = $_REQUEST['citeType'];
else
$citeType = "html";
// get information how exported data shall be returned:
// - 'text' => return data with mime type 'text/plain'
// - 'html' => return data with mime type 'text/html'
// - 'xml' => return data with mime type 'application/xml'
// - 'rss' => return data with mime type 'application/rss+xml'
// - 'file' => return data as downloadable file
// - 'email' => send data as email (to the user's login email address)
if (isset($_REQUEST['exportType']) AND preg_match("/^(text|html|xml|rss|file|email)$/i", $_REQUEST['exportType']))
$exportType = $_REQUEST['exportType'];
else
$exportType = "html";
if (isset($_REQUEST['exportStylesheet']))
$exportStylesheet = $_REQUEST['exportStylesheet']; // extract any stylesheet information that has been specified for XML export formats
else
$exportStylesheet = "";
if (isset($_REQUEST['orderBy']))
$orderBy = $_REQUEST['orderBy']; // extract the current ORDER BY parameter so that it can be re-applied when displaying details (only occurs in query result lists)
else
$orderBy = "";
if (preg_match("/%20/", $orderBy)) // if '$orderBy' still contains URL encoded data... ('%20' is the URL encoded form of a space, see note below!)
$orderBy = rawurldecode($orderBy); // ...URL decode 'orderBy' statement (it was URL encoded before incorporation into a hidden tag of the 'queryResults' form to avoid any HTML syntax errors)
// NOTE: URL encoded data that are included within a *link* will get URL decoded automatically *before* extraction via '$_REQUEST'!
// But, opposed to that, URL encoded data that are included within a form by means of a *hidden form tag* will NOT get URL decoded automatically! Then, URL decoding has to be done manually (as is done here)!
if ($orderBy == '') // if there's no ORDER BY parameter...
$orderBy = "author, year DESC, publication"; // ...use the default ORDER BY clause
if (isset($_REQUEST['headerMsg']))
$headerMsg = $_REQUEST['headerMsg']; // get any custom header message (we strip any HTML tags from the custom header message below)
// Note: this feature is provided in 'search.php' so that it's possible to include an information string within a link. This info string could
// e.g. describe who's publications are being displayed (e.g.: "Publications of Matthias Steffens:"). I.e., a link pointing to a persons own
// publications can include the appropriate owner information (it will show up as header message)
else
$headerMsg = "";
if (preg_match("/%20/", $headerMsg)) // if '$headerMsg' still contains URL encoded data... ('%20' is the URL encoded form of a space, see notes above!)
$headerMsg = rawurldecode($headerMsg); // ...URL decode 'headerMsg' statement (it was URL encoded before incorporation into a hidden tag of the 'displayOptions' form to avoid any HTML syntax errors)
if (!empty($headerMsg))
$headerMsg = stripTags($headerMsg); // strip any HTML tags from the custom header message to prevent cross-site scripting (XSS) attacks (function 'stripTags()' is defined in 'include.inc.php')
if (isset($_SESSION['oldQuery']))
$oldQuery = $_SESSION['oldQuery']; // get the query URL of the formerly displayed results page
else
$oldQuery = array();
if (isset($_SESSION['queryHistory']))
$queryHistory = $_SESSION['queryHistory']; // get any saved links to previous search results
else
$queryHistory = array();
// Extract checkbox variable values from the request:
if (isset($_REQUEST['marked']))
$recordSerialsArray = $_REQUEST['marked']; // extract the values of all checked checkboxes (i.e., the serials of all selected records)
else
$recordSerialsArray = array();
if (isset($_REQUEST['recordsSelectionRadio']))
$recordsSelectionRadio = $_REQUEST['recordsSelectionRadio']; // for query results pages, extract user option whether we're supposed to process ALL records or just the ones that have been SELECTED on the current page
else
$recordsSelectionRadio = "1"; // process ALL records
// check if the user did mark any checkboxes (and set up variables accordingly, they will be used within the 'displayDetails()', 'generateCitations()' and 'modifyUserGroups()' functions)
if (preg_match("#[/_]search\.php#i", $referer) AND ($recordsSelectionRadio == "0") AND empty($recordSerialsArray)) // the "Selected Records" option was chosen, but NO checkboxes were marked
$nothingChecked = true;
else // the "All Found Records" option was chosen -OR- the "Selected Records" option was chosen and some checkboxes were marked -OR- the query resulted from another script like 'opensearch.php', 'show.php' or 'rss.php' (which has no checkboxes to mark!)
$nothingChecked = false;
// --------------------------------------------------------------------
// VERIFY SQL QUERY:
// Note that for user-generated SQL queries, further verification is done in function 'verifySQLQuery()'
$notPermitted = false;
// Prevent cross-site scripting (XSS) attacks:
// Note that this is just a rough measure, everything that slips thru will get HTML encoded before output
$htmlTagsArray = array("a", "applet", "base", "basefont", "bgsound", "blink", "body", "br", "div", "embed", "head", "html", "frame", "frameset", "ilayer", "iframe", "img", "input", "layer", "ilayer", "link", "meta", "script", "span", "style", "object", "table", "title", "xml");
if (!empty($sqlQuery) AND preg_match("/(<|<?|�*60;?|�*3C;?|%3C|\\\\x3c|\\\\u003c)\/*(" . join("|", $htmlTagsArray) . ")/i", $sqlQuery)) // if the SQL query contains any unwanted HTML tags
{
$sqlQuery = preg_replace("/(<|<?|�*60;?|�*3C;?|%3C|\\\\x3c|\\\\u003c)\/*(" . join("|", $htmlTagsArray) . ").*?(>|>?|�*62;?|�*3E;?|%3E|\\\\x3e|\\\\u003e)*/i", "", $sqlQuery);
$notPermitted = true;
$HeaderString = $loc["NoPermission"] . $loc["NoPermission_ForThisQuery"] . "!";
}
// For a normal user we only allow the use of SELECT queries (the admin is allowed to do everything that is allowed by his GRANT privileges):
// NOTE: This does only provide for minimal security!
// To avoid further security risks you should grant the MySQL user (who's specified in 'db.inc.php') only those
// permissions that are required to access the literature database. This can be done by use of a GRANT statement:
// GRANT SELECT,INSERT,UPDATE,DELETE ON MYSQL_DATABASE_NAME_GOES_HERE.* TO MYSQL_USER_NAME_GOES_HERE@localhost IDENTIFIED BY 'MYSQL_PASSWORD_GOES_HERE';
// if the SQL query isn't build from scratch but is accepted from user input (which is the case for the forms 'sqlSearch', 'duplicateSearch' and 'refineSearch'):
if (!empty($sqlQuery) AND preg_match("/(sql|duplicate|refine)Search/i", $formType)) // the user used 'sql_search.php', 'duplicate_search.php' -OR- the "Search within Results" form above the query results list (that was produced by 'search.php')
{
if ((!isset($loginEmail)) OR ((isset($loginEmail)) AND ($loginEmail != $adminLoginEmail))) // if the user isn't logged in -OR- any normal user is logged in...
{
$all_fields = "author|author_count|online_citation|doi|online_publication|title|type|year|publication|abbrev_journal|volume|issue|pages|keywords|abstract|address|corporate_author|thesis|publisher|place|editor|language|summary_language|orig_title|series_editor|series_title|abbrev_series_title|series_volume|series_issue|edition|issn|isbn|medium|area|expedition|conference|notes|approved|contribution_id|online_publication|online_citation|created_date|created_time|created_by|modified_date|modified_time|modified_by|serial|call_number|marked|copy|selected|user_keys|user_notes|user_file|user_groups|cite_key|related|location";
$tablesArray = array($tableAuth, $tableDeleted, $tableDepends, $tableFormats, $tableLanguages, $tableQueries, $tableRefs, $tableStyles, $tableTypes, $tableUserData, $tableUserFormats, $tableUserOptions, $tableUserPermissions, $tableUserStyles, $tableUserTypes, $tableUsers);
$forbiddenSQLCommandsArray = array("DROP DATABASE", "DROP TABLE"); // the refbase MySQL user shouldn't have permissions for these commands anyhow, but by listing & checking for them here, we can return a more appropriate error message
// ...and the user did use anything other than a SELECT query:
if (!preg_match("/^SELECT/i", $sqlQuery) OR preg_match("/" . join("|", $forbiddenSQLCommandsArray) . "/i", $sqlQuery))
{
$notPermitted = true;
$HeaderString = $loc["NoPermission_ForSQLOtherThanSELECT"] . "!";
}
// ...or the user tries to SELECT stuff they really shouldn't
elseif (!preg_match("/^SELECT ((" . $all_fields . "),* *)+ FROM/i", $sqlQuery))
{
$notPermitted = true;
$HeaderString = $loc["NoPermission"] . $loc["NoPermission_ForThisQuery"] . "!";
}
// ...or the user tries to hack the SQL query (by providing e.g. the string "FROM refs" within the SELECT statement) -OR- if the user attempts to query anything other than the 'refs' or 'user_data' table:
elseif ((preg_match("/FROM .*(" . join("|", $tablesArray) . ").+ FROM /i", $sqlQuery)) OR (!preg_match("/FROM $tableRefs( LEFT JOIN $tableUserData ON serial ?= ?record_id AND user_id ?= ?\d*)?(?= WHERE| ORDER BY| LIMIT| GROUP BY| HAVING| PROCEDURE| FOR UPDATE| LOCK IN|$)/i", $sqlQuery)))
{
$notPermitted = true;
$HeaderString = $loc["NoPermission"] . $loc["NoPermission_ForThisQuery"] . "!";
}
}
// note that besides the above validation, in case of 'duplicate_search.php' the SQL query will be further restricted so that generally only SELECT queries can be executed (this is handled by function 'findDuplicates()')
}
if ($notPermitted)
{
// return an appropriate error message:
$HeaderString = returnMsg($HeaderString, "warning", "strong", "HeaderString"); // function 'returnMsg()' is defined in 'include.inc.php'
if (!preg_match("/^cli/i", $client))
{
if (preg_match("#/(sql|duplicate)_search\.php#i", $referer)) // if the sql query was entered in the form provided by 'sql_search.php' or 'duplicate_search.php'
header("Location: " . $referer); // relocate back to the calling page
else // if the user didn't come from 'sql_search.php' or 'duplicate_search.php' (e.g., if he attempted to hack parameters of a GET query directly)
header("Location: index.php"); // relocate back to the main page
}
exit; // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> !EXIT! <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
}
// --------------------------------------------------------------------
// (1) OPEN CONNECTION, (2) SELECT DATABASE
connectToMySQLDatabase(); // function 'connectToMySQLDatabase()' is defined in 'include.inc.php'
// --------------------------------------------------------------------
if (isset($_REQUEST["loginEmail"]))
$loginEmail = $_REQUEST["loginEmail"]; // extract the email address of the currently logged in user
if (isset($_SESSION['loginEmail'])) // if a user is logged in...
$userID = getUserID($loginEmail); // ...get the user's 'user_id' using his/her 'loginEmail' (function 'getUserID()' is defined in 'include.inc.php')
else
$userID = 0; // set variable to zero (a user with '$userID = 0' definitely doesn't exist) in order to prevent 'Undefined variable...' messages
// --------------------------------------------------------------------
// CONSTRUCT SQL QUERY from user input provided by any of the search forms:
// --- Form 'sql_search.php': ------------------
if ($formType == "sqlSearch") // the user either used the 'sql_search.php' form for searching -OR- used scripts like 'show.php' or 'rss.php' (which also use 'formType=sqlSearch')...
{
// verify the SQL query specified by the user and modify it if security concerns are encountered:
// (this function does add/remove user-specific query code as required and will fix problems with escape sequences within the SQL query)
$query = verifySQLQuery($sqlQuery, $referer, $displayType, $showLinks); // function 'verifySQLQuery()' is defined in 'include.inc.php' (since it's also used by 'rss.php')
}
// --- Form 'duplicate_search.php': ---------------
elseif ($formType == "duplicateSearch") // the user used the 'duplicate_search.php' form for searching...
{
// find duplicate records within results of the given SQL query (using settings extracted from the 'duplicateSearch' form
// in 'duplicate_search.php') and return a modified database query that only matches these duplicate entries:
list($sqlQuery, $displayType) = findDuplicates($sqlQuery, $originalDisplayType);
// by passing the generated SQL query thru the 'verifySQLQuery()' function we ensure that necessary fields are added as needed:
// (this function does add/remove user-specific query code as required and will fix problems with escape sequences within the SQL query)
$query = verifySQLQuery($sqlQuery, $referer, $displayType, $showLinks); // function 'verifySQLQuery()' is defined in 'include.inc.php' (since it's also used by 'rss.php')
}
// --- Form 'simple_search.php': ---------------
elseif ($formType == "simpleSearch") // the user used the 'simple_search.php' form for searching...
{
$query = extractFormElementsSimple($showLinks, $userID);
}
// --- Form 'library_search.php': --------------
elseif ($formType == "librarySearch") // the user used the 'library_search.php' form for searching...
{
$query = extractFormElementsLibrary($showLinks, $userID);
}
// --- Form 'advanced_search.php': -------------
elseif ($formType == "advancedSearch") // the user used the 'advanced_search.php' form for searching...
{
$query = extractFormElementsAdvanced($showLinks, $loginEmail, $userID);
}
// --- Form within 'search.php': ---------------
elseif ($formType == "refineSearch" OR $formType == "displayOptions") // the user used the "Search within Results" (or "Display Options") form above the query results list (that was produced by 'search.php')
{
list($query, $displayType) = extractFormElementsRefineDisplay($tableRefs, $displayType, $originalDisplayType, $sqlQuery, $showLinks, $citeOrder, $userID); // function 'extractFormElementsRefineDisplay()' is defined in 'include.inc.php' since it's also used by 'users.php'
}
// --- Form within 'search.php': ---------------
elseif ($formType == "queryResults") // the user clicked one of the buttons under the query results list (that was produced by 'search.php')
{
list($query, $displayType) = extractFormElementsQueryResults($displayType, $originalDisplayType, $showLinks, $citeOrder, $orderBy, $userID, $sqlQuery, $referer, $recordSerialsArray, $recordsSelectionRadio);
}
// --- Form 'extract.php': ---------------------
elseif ($formType == "extractSearch") // the user used the 'extract.php' form for searching...
{
$query = extractFormElementsExtract($showLinks, $citeOrder, $userID);
}
// --- My Refs Search Form within 'index.php': -------------------
elseif ($formType == "myRefsSearch") // the user used the 'Show My Refs' search form on the main page ('index.php') for searching...
{
$query = extractFormElementsMyRefs($showLinks, $loginEmail, $userID);
}
// --- Quick Search Form within 'index.php': ---------------------
elseif ($formType == "quickSearch") // the user used the 'Quick Search' form on the main page ('index.php') for searching...
{
list($query, $displayType) = extractFormElementsQuick($sqlQuery, $showLinks, $userID, $displayType, $originalDisplayType);
}
// --- Browse My Refs Form within 'index.php': -------------------
elseif ($formType == "myRefsBrowse") // the user used the 'Browse My Refs' form on the main page ('index.php') for searching...
{
$query = extractFormElementsBrowseMyRefs($showLinks, $loginEmail, $userID);
}
// --- My Groups Search Form within 'index.php': ---------------------
elseif ($formType == "groupSearch") // the user used the 'Show My Group' form on the main page ('index.php') or above the query results list (that was produced by 'search.php')
{
list($query, $displayType) = extractFormElementsGroup($sqlQuery, $showLinks, $userID, $displayType, $originalDisplayType);
}
// --------------------------------------------------------------------
// this is to support the '$fileVisibilityException' feature from 'ini.inc.php':
if (preg_match("/^SELECT/i", $query) AND ($displayType != "Browse") AND !empty($fileVisibilityException) AND !preg_match("/SELECT.+$fileVisibilityException[0].+FROM/i", $query)) // restrict adding of columns to SELECT queries (so that 'DELETE FROM refs ...' statements won't get modified as well);
{
$query = preg_replace("/(, orig_record)?(, serial)?(, file, url, doi, isbn, type)? FROM $tableRefs/i", ", $fileVisibilityException[0]\\1\\2\\3 FROM $tableRefs",$query); // add column that's given in '$fileVisibilityException'
$addCounterMax = 1; // this will ensure that the added column won't get displayed within the 'displayColumns()' and 'displayDetails()' functions
}
else
$addCounterMax = 0;
// (3) RUN QUERY, (4) DISPLAY EXPORT FILE OR HEADER & RESULTS
// (3) RUN the query on the database through the connection:
$result = queryMySQLDatabase($query); // function 'queryMySQLDatabase()' is defined in 'include.inc.php'
// (4) If the display type is 'Export', display the exported file...
if (($displayType == "Export"))
{
// Find out how many rows are available:
$rowsFound = @ mysql_num_rows($result); // for all other display types, the '$rowsFound' variable is set within function 'seekInMySQLResultsToOffset()' (see below)
if ($rowsFound > 0) // If there were rows found ...
{
generateExport($result, $rowOffset, $showRows, $exportFormat, $exportType, $exportStylesheet, $displayType, $viewType, $userID); // export records using the export format specified in '$exportFormat'
// For export, we disconnect from the database and exit this php file:
disconnectFromMySQLDatabase(); // function 'disconnectFromMySQLDatabase()' is defined in 'include.inc.php'
exit; // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> !EXIT! <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
}
// else, if nothing was found, we proceed & return the "No records selected..." feedback (thru the 'displayColumns()' function)
}
// ...else, display HTML:
// (4a) DISPLAY header:
// First, build the appropriate SQL query in order to embed it into the 'your query' URL:
if ($showLinks == "1")
$query = preg_replace("/, file, url, doi, isbn, type FROM $tableRefs/i", " FROM $tableRefs", $query); // strip 'file', 'url', 'doi', 'isbn' & 'type columns from SQL query
$query = preg_replace("/, serial FROM $tableRefs/i", " FROM $tableRefs", $query); // strip 'serial' column from SQL query
$query = preg_replace("/, orig_record FROM $tableRefs/i", " FROM $tableRefs", $query); // strip 'orig_record' column from SQL query
if (!empty($fileVisibilityException))
$query = preg_replace("/, $fileVisibilityException[0] FROM $tableRefs/i", " FROM $tableRefs", $query); // strip column that's given in '$fileVisibilityException' (defined in 'ini.inc.php')
if (preg_match("/(simple|advanced|library|quick)Search/", $formType)) // if $formType is "simpleSearch", "advancedSearch", "librarySearch" or "quickSearch" and there is more than one WHERE clause (indicated by '...AND...'):
$query = preg_replace('/WHERE serial RLIKE "\.\+" AND/i', 'WHERE', $query); // strip first WHERE clause (which was added only due to an internal workaround)
$queryURL = rawurlencode($query); // URL encode SQL query
if (!preg_match("/^SELECT/i", $query)) // for queries other than SELECT queries (e.g. UPDATE, DELETE or INSERT queries that were executed by the admin via use of 'sql_search.php')
$affectedRows = ($result ? mysql_affected_rows ($connection) : 0); // get the number of rows that were modified (or return 0 if an error occurred)
// If the previous query (which is stored in the 'oldQuery' session variable) is different
// from the current query, we append it to the 'queryHistory' session variable:
if (!empty($oldQuery))
{
// Extract the 'WHERE' clause from the current & the previous SQL query:
$queryWhereClause = extractWHEREclause($query); // function 'extractWHEREclause()' is defined in 'include.inc.php'
$oldQueryWhereClause = extractWHEREclause($oldQuery["sqlQuery"]);
if ($queryWhereClause != $oldQueryWhereClause)
{
$oldQueryURL = generateURL("search.php", "html", $oldQuery, true); // function 'generateURL()' is defined in 'include.inc.php'
$oldQueryTitle = encodeHTML(explainSQLQuery($oldQueryWhereClause)); // functions 'encodeHTML()' and 'explainSQLQuery()' are defined in 'include.inc.php'
$queryHistory[] = "<a href=\"" . $oldQueryURL . "\">" . $oldQueryTitle . "</a>";
if (count($queryHistory) > 30) // we only keep the 30 most recent queries
array_shift($queryHistory); // remove the first array element (i.e. remove the oldest query) if there are more than 30 saved queries
saveSessionVariable("queryHistory", $queryHistory);
}
}
// Second, save the generated query to a session variable:
// NOTE: we exclude queries for export formats & citation formats other than HTML
// (otherwise the history list would contain links to non-HTML content such as RTF or BibTeX files)
if (($displayType != "Export") AND preg_match("/^html$/i", $citeType))
{
$queryParametersArray = array("sqlQuery" => $query,
"client" => $client,
"formType" => "sqlSearch",
"submit" => $displayType,
"viewType" => $viewType,
"showQuery" => $showQuery,
"showLinks" => $showLinks,
"showRows" => $showRows,
"rowOffset" => $rowOffset,
"wrapResults" => $wrapResults,
"citeOrder" => $citeOrder,
"citeStyle" => $citeStyle,
"exportFormat" => $exportFormat,
"exportType" => $exportType,
"exportStylesheet" => $exportStylesheet,
"citeType" => $citeType,
"headerMsg" => $headerMsg
);
saveSessionVariable("oldQuery", $queryParametersArray);
}
// Third, find out how many rows are available and (if there were rows found) seek to the current offset:
// Note that the 'seekInMySQLResultsToOffset()' function will also (re-)assign values to the variables
// '$rowOffset', '$showRows', '$rowsFound', '$previousOffset', '$nextOffset' and '$showMaxRow'.
list($result, $rowOffset, $showRows, $rowsFound, $previousOffset, $nextOffset, $showMaxRow) = seekInMySQLResultsToOffset($result, $rowOffset, $showRows, $displayType, $citeType); // function 'seekInMySQLResultsToOffset()' is defined in 'include.inc.php'
// If the current result set contains multiple records, we save the generated query URL to yet another session variable:
// (after a record has been successfully added/edited/deleted, this query will be included as a link ["Display previous search results"] in the feedback header message
// if the SQL query in 'oldQuery' is different from that one stored in 'oldMultiRecordQuery', i.e. if 'oldQuery' points to a single record)
if (($rowsFound > 1) AND ($displayType != "Export") AND preg_match("/^html$/i", $citeType)) // as above, we exclude queries for export formats & citation formats other than HTML
saveSessionVariable("oldMultiRecordQuery", $queryParametersArray);
// Fourth, setup an array of arrays holding URL and title information for all RSS/Atom feeds available on this page:
// (appropriate <link...> tags will be included in the HTML header for every URL specified)
$rssURLArray = array();
if (isset($_SESSION['user_permissions']) AND preg_match("/allow_rss_feeds/", $_SESSION['user_permissions'])) // if the 'user_permissions' session variable contains 'allow_rss_feeds'...
{
// ...extract the 'WHERE' clause from the SQL query to include it within the feed URL:
$queryWhereClause = extractWHEREclause($query); // function 'extractWHEREclause()' is defined in 'include.inc.php'
// generate an URL pointing to the RSS/Atom feed that matches the current query:
$rssURL = generateURL("show.php", $defaultFeedFormat, array("where" => $queryWhereClause), true, $showRows); // function 'generateURL()' is defined in 'include.inc.php', variable '$defaultFeedFormat' is defined in 'ini.inc.php'
// build a title string that matches the current query:
// (alternatively we could always use: "records matching current query")
$rssTitle = "records where " . encodeHTML(explainSQLQuery($queryWhereClause)); // functions 'encodeHTML()' and 'explainSQLQuery()' are defined in 'include.inc.php'
$rssURLArray[] = array("href" => $rssURL,
"title" => $rssTitle);
}
// Finally, build the appropriate header string (which is required as parameter to the 'showPageHeader()' function):
if (!isset($_SESSION['HeaderString'])) // if there's no stored message available
{
if (!empty($headerMsg)) // if there's a custom header message available, e.g. one that describes who's literature is being displayed...
{
// ...we use that string as header message ('$headerMsg' could contain something like: "Literature of **Matthias Steffens**:"):
// Perform search & replace actions on the provided header message (which will e.g. convert '**...**' to '<b>...</b>' etc):
// (the array '$transtab_refbase_html' in 'transtab_refbase_html.inc.php' defines which search & replace actions will be employed)
$HeaderString = searchReplaceText($transtab_refbase_html, encodeHTML($headerMsg), true); // functions 'searchReplaceText()' and 'encodeHTML()' are defined in 'include.inc.php'
}
else // provide the default message:
{
if (preg_match("/^SELECT/i", $query)) // for SELECT queries:
{
if ($rowsFound == 1)
{
if ($displayType == "Browse")
$HeaderStringPart = " item ";
else
$HeaderStringPart = " record ";
}
else
{
if ($displayType == "Browse")
$HeaderStringPart = " items ";
else
$HeaderStringPart = " records ";
}
$HeaderStringPart .= "found matching ";
if (isset($_SESSION['user_permissions']) AND preg_match("/allow_sql_search/", $_SESSION['user_permissions'])) // if the 'user_permissions' session variable contains 'allow_sql_search'...
// ...generate a link to 'sql_search.php' with a custom SQL query that matches the current result set & display options:
$HeaderString = $HeaderStringPart
. "<a href=\"sql_search.php?customQuery=1"
. "&sqlQuery=" . $queryURL
. "&showQuery=" . $showQuery
. "&showLinks=" . $showLinks
. "&showRows=" . $showRows
. "&submit=" . $displayType
. "&citeStyle=" . rawurlencode($citeStyle)
. "&citeOrder=" . $citeOrder
. "\"" . addAccessKey("attribute", "sql_query") . " title=\"modify your current query" . addAccessKey("title", "sql_query") . "\">your query</a>"; // function 'addAccessKey()' is defined in 'include.inc.php'
else // use of 'sql_search.php' isn't allowed for this user
$HeaderString = $HeaderStringPart . "your query"; // so we omit the link
// add query links:
$queryLinksArray = array();
if (isset($_SESSION['loginEmail']) AND (isset($_SESSION['user_permissions']) AND preg_match("/allow_user_queries/", $_SESSION['user_permissions']))) // if a user is logged in AND the 'user_permissions' session variable contains 'allow_user_queries'...
{
// ...we'll show a link to save the current query:
$queryLinksArray[] = "<a href=\"query_manager.php?customQuery=1"
. "&sqlQuery=" . $queryURL
. "&showQuery=" . $showQuery
. "&showLinks=" . $showLinks
. "&showRows=" . $showRows
. "&displayType=" . $displayType
. "&citeStyle=" . rawurlencode($citeStyle)
. "&citeOrder=" . $citeOrder
. "&viewType=" . $viewType
. "\"" . addAccessKey("attribute", "save_query") . " title=\"save your current query" . addAccessKey("title", "save_query") . "\">save</a>";
}
if (isset($_SESSION['user_permissions']) AND preg_match("/allow_rss_feeds/", $_SESSION['user_permissions'])) // if the 'user_permissions' session variable contains 'allow_rss_feeds'...
{
// ...we'll display a link that will generate a dynamic RSS feed for the current query:
$queryLinksArray[] = "<a href=\"" . $rssURL . "\" title=\"track newly added records matching your current query by subscribing to this RSS feed\">RSS</a>";
}
if (isset($_SESSION['loginEmail'])) // if a user is logged in...
{
// ...we'll show a link to find any duplicates within the current query results:
$queryLinksArray[] = "<a href=\"duplicate_search.php?customQuery=1"
. "&sqlQuery=" . $queryURL
. "&showLinks=" . $showLinks
. "&showRows=" . $showRows
. "&originalDisplayType=" . $displayType
. "&citeStyle=" . rawurlencode($citeStyle)
. "&citeOrder=" . $citeOrder
. "\"" . addAccessKey("attribute", "dups") . " title=\"find duplicates that match your current query" . addAccessKey("title", "dups") . "\">dups</a>";
}
if (isset($_SESSION['queryHistory']))
{
// ...include a link to display the query history (if any) for the user's current session:
$queryLinksArray[] = "<a href=\"query_history.php"
. "\"" . addAccessKey("attribute", "history") . " title=\"recall a previous query from your current session" . addAccessKey("title", "history") . "\">history</a>";
}
if (!empty($queryLinksArray))
$HeaderString .= " (" . implode(" | ", $queryLinksArray) . ")";
if ($showQuery == "1")
$HeaderString .= ":\n<br>\n<br>\n<code>" . encodeHTML($query) . "</code>"; // function 'encodeHTML()' is defined in 'include.inc.php'
else // $showQuery == "0" or wasn't specified
$HeaderString .= ":";
if ($rowsFound > 0)
$HeaderString = ($rowOffset + 1) . "–" . $showMaxRow . " of " . $rowsFound . $HeaderString;
elseif ($rowsFound == 0)
$HeaderString = $rowsFound . $HeaderString;
else
$HeaderString = $HeaderString; // well, this is actually bad coding but I do it for clearity reasons...
}
else // for queries other than SELECT queries (e.g. UPDATE, DELETE or INSERT queries that were executed by the admin via use of 'sql_search.php') display the number of rows that were modified:
{
if ($affectedRows == 1)
$HeaderStringPart = " record was ";
else
$HeaderStringPart = " records were ";
$HeaderString = $affectedRows . $HeaderStringPart . "affected by "
. "<a href=\"sql_search.php?customQuery=1"
. "&sqlQuery=" . $queryURL
. "&showQuery=" . $showQuery
. "&showLinks=" . $showLinks
. "&showRows=" . $showRows
. "&submit=" . $displayType
. "&citeStyle=" . rawurlencode($citeStyle)
. "&citeOrder=" . $citeOrder
. "\">your query</a>:";
if ($showQuery == "1")
$HeaderString .= "\n<br>\n<br>\n<code>" . encodeHTML($query) . "</code>";
}
}
}
else
{
$HeaderString = $_SESSION['HeaderString']; // extract 'HeaderString' session variable (only necessary if register globals is OFF!)
// Note: though we clear the session variable, the current message is still available to this script via '$HeaderString':
deleteSessionVariable("HeaderString"); // function 'deleteSessionVariable()' is defined in 'include.inc.php'
}
// Now, show the login status:
showLogin(); // function 'showLogin()' is defined in 'include.inc.php'
if (!preg_match("/^cli/i", $client) AND ($wrapResults != "0") AND (!(($displayType == "Cite") AND (!preg_match("/^html$/i", $citeType))) OR ($rowsFound == 0))) // we exclude the HTML page header for citation formats other than HTML if something was found
{
// Then, call the 'displayHTMLhead()' and 'showPageHeader()' functions (which are defined in 'header.inc.php'):
displayHTMLhead(encodeHTML($officialDatabaseName) . " -- Query Results", "index,follow", "Results from the " . encodeHTML($officialDatabaseName), "", true, "", $viewType, $rssURLArray);
if ((!preg_match("/^(Print|Mobile)$/i", $viewType)) AND (!preg_match("/^inc/i", $client))) // Note: we omit the visible header in print/mobile view ('viewType=Print' or 'viewType=Mobile') and for include mechanisms!
showPageHeader($HeaderString);
}
// (4b) DISPLAY results:
if ($displayType == "Display") // display full record details (Details view)
displayDetails($result, $rowsFound, $query, $queryURL, $showQuery, $showLinks, $rowOffset, $showRows, $previousOffset, $nextOffset, $wrapResults, $nothingChecked, $citeStyle, $citeOrder, $orderBy, $showMaxRow, $headerMsg, $userID, $displayType, $viewType, $addCounterMax, $formType);
elseif ($displayType == "Cite") // return found records as citations (Citation view)
generateCitations($result, $rowsFound, $query, $queryURL, $showQuery, $showLinks, $rowOffset, $showRows, $previousOffset, $nextOffset, $wrapResults, $nothingChecked, $citeStyle, $citeOrder, $citeType, $orderBy, $headerMsg, $userID, $viewType);
else // produce the columnar output style (List view or Browse view)
displayColumns($result, $rowsFound, $query, $queryURL, $showQuery, $showLinks, $rowOffset, $showRows, $previousOffset, $nextOffset, $wrapResults, $nothingChecked, $citeStyle, $citeOrder, $headerMsg, $userID, $displayType, $viewType, $addCounterMax, $formType);
// --------------------------------------------------------------------
// (5) CLOSE CONNECTION
disconnectFromMySQLDatabase(); // function 'disconnectFromMySQLDatabase()' is defined in 'include.inc.php'
// --------------------------------------------------------------------
// SHOW THE RESULTS IN AN HTML <TABLE> (columnar layout)
function displayColumns($result, $rowsFound, $query, $queryURL, $showQuery, $showLinks, $rowOffset, $showRows, $previousOffset, $nextOffset, $wrapResults, $nothingChecked, $citeStyle, $citeOrder, $headerMsg, $userID, $displayType, $viewType, $addCounterMax, $formType)
{
global $searchReplaceActionsArray; // these variables are defined in 'ini.inc.php'
global $databaseBaseURL;
global $defaultDropDownFieldsEveryone;
global $defaultDropDownFieldsLogin;
global $displayResultsHeaderDefault;
global $displayResultsFooterDefault;
global $showFieldItemLinks;
global $showLinkTypesInListView;
global $maximumBrowseLinks;
global $tableRefs, $tableUserData; // defined in 'db.inc.php'
global $loc; // '$loc' is made globally available in 'core.php'
global $client;
if (preg_match("/.+LIMIT *[0-9]+/i",$query)) // query does contain the 'LIMIT' parameter
$orderBy = preg_replace("/.+ORDER BY (.+) LIMIT.+/i","\\1",$query); // extract 'ORDER BY'... parameter (without including any 'LIMIT' parameter)
else // query does not contain the 'LIMIT' parameter
$orderBy = preg_replace("/.+ORDER BY (.+)/i","\\1",$query); // extract 'ORDER BY'... parameter
if (($formType != "queryResults") OR (($formType == "queryResults") AND !($nothingChecked))) // some checkboxes were marked within the 'queryResults' form (or the request stems from a different script without checkboxes)
{
// If the query has results ...
if ($rowsFound > 0)
{
// BEGIN RESULTS HEADER --------------------
// 1) First, initialize some variables that we'll need later on
if ($showLinks == "1" AND $displayType != "Browse") // we exclude the Browse view since it has a special type of 'Links' column and the 'file', 'url', 'doi', 'isbn' & 'type columns weren't included in the query
$CounterMax = 5; // When displaying a 'Links' column truncate the last five columns (i.e., hide the 'file', 'url', 'doi', 'isbn' & 'type columns)
else
$CounterMax = 0; // Otherwise don't hide any columns
// count the number of fields
$fieldsFound = mysql_num_fields($result);
if ($displayType != "Browse")
{
// hide those last columns that were added by the script and not by the user
$fieldsToDisplay = $fieldsFound-(2+$CounterMax+$addCounterMax); // (2+$CounterMax) -> $CounterMax is increased by 2 in order to hide the 'orig_record' & 'serial' columns (which were added to make checkboxes & dup warning work)
// $addCounterMax is set to 1 when the field given in '$fileVisibilityException[0]' (defined in 'ini.inc.php') was added to the query, otherwise '$addCounterMax = 0'
}
else // for Browse view the 'orig_record' & 'serial' columns weren't included in the query
$fieldsToDisplay = $fieldsFound;
// Calculate the number of all visible columns (which is needed as colspan value inside some TD tags)
if ($showLinks == "1")
$NoColumns = (1+$fieldsToDisplay+1); // add checkbox & Links column
else
$NoColumns = (1+$fieldsToDisplay); // add checkbox column
// Save the current List view query to a session variable:
saveSessionVariable("lastListViewQuery", $query);
// Defines field-specific search & replace 'actions' that will be applied to all those refbase
// fields that are listed in the corresponding 'fields' element:
// (These search and replace actions will be performed *in addition* to those specified globally
// in '$searchReplaceActionsArray' (defined in 'ini.inc.php'). Same rules apply as for
// '$searchReplaceActionsArray'.)
$fieldSpecificSearchReplaceActionsArray = array(
array(
'fields' => array("thesis", "approved", "marked", "copy", "selected", "type"), // see also note for '$encodingExceptionsArray' below
'actions' => array("/(.+)/e" => "\$loc['\\1']") // use localized field values (e.g., in case of german we display 'ja' instead of 'yes', etc)
),
array(
'fields' => array("type"),
'actions' => array("/(.+)/e" => "\$loc['type\\1']") // for the 'type' field, prefix variable with 'type' to match to localized value
)
);
// NOTE: We substitute contents of the given fields with localized field values from variable
// '$loc' (see '$fieldSpecificSearchReplaceActionsArray'). Since the locales in '$loc'
// are already HTML encoded, we have to exclude these fields from any further HTML encoding.
static $encodingExceptionsArray = array("thesis", "approved", "marked", "copy", "selected", "type");
// Note: we omit the results header, browse links & query form for CLI clients, and when outputting only a partial document structure ('wrapResults=0')
if (!preg_match("/^cli/i", $client) AND ($wrapResults != "0"))
{
// Note: we also omit the results header in print/mobile view! ('viewType=Print' or 'viewType=Mobile')
if ((!preg_match("/^(Print|Mobile)$/i", $viewType)) AND (!isset($displayResultsHeaderDefault[$displayType]) OR (isset($displayResultsHeaderDefault[$displayType]) AND ($displayResultsHeaderDefault[$displayType] != "hidden"))))
{
if ($displayType == "Browse")
$selectedField = preg_replace("/^SELECT (\w+).*/i","\\1", $query); // extract the field that's currently used in Browse view (so that we can re-select it in the drop-downs of the 'refineSearch' and 'displayOptions' forms)
elseif (preg_match("/ WHERE [ ()]*(\w+)/i", $query)) // extract the first field from the 'WHERE' clause:
$selectedField = preg_replace("/.+ WHERE [ ()]*(\w+).*/i", "\\1", $query);
else
$selectedField = "author"; // otherwise we'll select the 'author' field by default
// Map MySQL field names to localized column names:
$fieldNamesArray = mapFieldNames(true); // function 'mapFieldNames()' is defined in 'include.inc.php'
$localizedDropDownFieldsArray = array();
if (isset($_SESSION['loginEmail']) AND !empty($defaultDropDownFieldsLogin)) // if a user is logged in -AND- there were any additional fields specified...
$dropDownFieldsArray = array_merge($defaultDropDownFieldsEveryone, $defaultDropDownFieldsLogin); // ...add these additional fields to the list of fields visible in the dropdown menus of the results header
else
$dropDownFieldsArray = $defaultDropDownFieldsEveryone;
foreach ($dropDownFieldsArray as $field)
{
if (isset($fieldNamesArray[$field]))
$localizedDropDownFieldsArray[$field] = $fieldNamesArray[$field];
else // no localized field name exists, so we use the original field name
$localizedDropDownFieldsArray[$field] = $field;
}
// 2) Build forms containing options to show the user's groups, refine the search results or change the displayed columns:
// TODO for 2b+2c: should we allow users to choose via the web interface which columns are included in the popup menus?
// 2a) Build a FORM with a popup containing the user's groups:
$formElementsGroup = buildGroupSearchElements("search.php", $queryURL, $query, $showQuery, $showLinks, $showRows, $citeStyle, $citeOrder, $displayType); // function 'buildGroupSearchElements()' is defined in 'include.inc.php'
// 2b) Build a FORM containing options to refine the search results:
// Call the 'buildRefineSearchElements()' function (defined in 'include.inc.php') which does the actual work:
$formElementsRefine = buildRefineSearchElements("search.php", $queryURL, $showQuery, $showLinks, $showRows, $citeStyle, $citeOrder, $localizedDropDownFieldsArray, $selectedField, $displayType);
// 2c) Build a FORM containing display options (show/hide columns or change the number of records displayed per page):
// Call the 'buildDisplayOptionsElements()' function (defined in 'include.inc.php') which does the actual work:
$formElementsDisplayOptions = buildDisplayOptionsElements("search.php", $queryURL, $showQuery, $showLinks, $rowOffset, $showRows, $citeStyle, $citeOrder, $localizedDropDownFieldsArray, $selectedField, $fieldsToDisplay, $displayType, $headerMsg);
echo displayResultsHeader("search.php", $formElementsGroup, $formElementsRefine, $formElementsDisplayOptions, $displayType); // function 'displayResultsHeader()' is defined in 'results_header.inc.php'
// and insert a divider line (which separates the results header from the browse links & results data below):
echo "\n";
}
// 3) Build a TABLE with links for "previous" & "next" browsing, as well as links to intermediate pages
// call the 'buildBrowseLinks()' function (defined in 'include.inc.php'):
$BrowseLinks = buildBrowseLinks("search.php", $query, $NoColumns, $rowsFound, $showQuery, $showLinks, $showRows, $rowOffset, $previousOffset, $nextOffset, $wrapResults, $maximumBrowseLinks, "sqlSearch", $displayType, $citeStyle, $citeOrder, $orderBy, $headerMsg, $viewType);
echo $BrowseLinks;
// 4) Start a FORM
if ((!preg_match("/^Print$/i", $viewType)) AND (!isset($displayResultsFooterDefault[$displayType]) OR (isset($displayResultsFooterDefault[$displayType]) AND ($displayResultsFooterDefault[$displayType] != "hidden"))))
{
echo "\n<form action=\"search.php\" method=\"GET\" name=\"queryResults\">"
. "\n<input type=\"hidden\" name=\"formType\" value=\"queryResults\">"
. "\n<input type=\"hidden\" name=\"submit\" value=\"Cite\">" // provide a default value for the 'submit' form tag (then, if any form element is selected, hitting <enter> will act as if the user clicked the 'Cite' button)
. "\n<input type=\"hidden\" name=\"originalDisplayType\" value=\"$displayType\">" // embed the original value of the '$displayType' variable