You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

478 lines
21 KiB

  1. <?php
  2. // turn on warnings and notice during developement
  3. include('initialize/PhpErrorSettings.inc.php');
  4. // Project: Web Reference Database (refbase) <http://www.refbase.net>
  5. // Copyright: Matthias Steffens <mailto:refbase@extracts.de> and the file's
  6. // original author(s).
  7. //
  8. // This code is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY. Please see the GNU General Public
  10. // License for more details.
  11. //
  12. // File: ./query_manager.php
  13. // Repository: $HeadURL: file:///svn/p/refbase/code/branches/bleeding-edge/query_manager.php $
  14. // Author(s): Matthias Steffens <mailto:refbase@extracts.de>
  15. //
  16. // Created: 04-Feb-04, 22:29
  17. // Modified: $Date: 2017-04-13 02:00:18 +0000 (Thu, 13 Apr 2017) $
  18. // $Author: karnesky $
  19. // $Revision: 1416 $
  20. // This script enables you to manage your custom queries.
  21. // It offers a form to save the current query or update/delete any of your saved queries.
  22. // Saved queries are user specific and can be accessed from a popup on the main page.
  23. // TODO: I18n
  24. // Incorporate some include files:
  25. include 'initialize/db.inc.php'; // 'db.inc.php' is included to hide username and password
  26. include 'includes/header.inc.php'; // include header
  27. include 'includes/footer.inc.php'; // include footer
  28. include 'includes/include.inc.php'; // include common functions
  29. include 'initialize/ini.inc.php'; // include common variables
  30. // --------------------------------------------------------------------
  31. // START A SESSION:
  32. // call the 'start_session()' function (from 'include.inc.php') which will also read out available session variables:
  33. start_session(true);
  34. // --------------------------------------------------------------------
  35. // Initialize preferred display language:
  36. // (note that 'locales.inc.php' has to be included *after* the call to the 'start_session()' function)
  37. include 'includes/locales.inc.php'; // include the locales
  38. // --------------------------------------------------------------------
  39. // Extract session variables (only necessary if register globals is OFF!):
  40. if (isset($_SESSION['errors']))
  41. $errors = $_SESSION['errors'];
  42. else
  43. $errors = array(); // initialize variable (in order to prevent 'Undefined index/variable...' messages)
  44. if (isset($_SESSION['formVars']))
  45. $formVars = $_SESSION['formVars'];
  46. else
  47. $formVars = array(); // initialize variable (in order to prevent 'Undefined index/variable...' messages)
  48. // The current values of the session variables 'errors' and 'formVars' get stored in '$errors' or '$formVars', respectively. (either automatically if
  49. // register globals is ON, or explicitly if register globals is OFF [by uncommenting the code above]).
  50. // We need to clear these session variables here, since they would otherwise be still there on a subsequent call of 'query_manager.php'!
  51. // Note: though we clear the session variables, the current error message (or form variables) is still available to this script via '$errors' (or '$formVars', respectively).
  52. deleteSessionVariable("errors"); // function 'deleteSessionVariable()' is defined in 'include.inc.php'
  53. deleteSessionVariable("formVars");
  54. // --------------------------------------------------------------------
  55. // A user must be logged in to save, modify or delete any queries:
  56. if (!isset($_SESSION['loginEmail']))
  57. {
  58. // return an appropriate error message:
  59. $HeaderString = returnMsg($loc["Warning_LoginToUseSavedQueries"] . "!", "warning", "strong", "HeaderString"); // function 'returnMsg()' is defined in 'include.inc.php'
  60. // save the URL of the currently displayed page:
  61. $referer = $_SERVER['HTTP_REFERER'];
  62. // Write back session variables:
  63. saveSessionVariable("referer", $referer); // function 'saveSessionVariable()' is defined in 'include.inc.php'
  64. header("Location: user_login.php");
  65. exit; // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> !EXIT! <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  66. }
  67. // --------------------------------------------------------------------
  68. // Extract the view type requested by the user (either 'Mobile', 'Print', 'Web' or ''):
  69. // ('' will produce the default 'Web' output style)
  70. if (isset($_REQUEST['viewType']))
  71. $viewType = $_REQUEST['viewType'];
  72. else
  73. $viewType = "";
  74. // Check if the script was called with parameters (like: 'query_manager.php?customQuery=1&sqlQuery=...&showQuery=...&showLinks=...')
  75. // If so, the parameter 'customQuery=1' will be set:
  76. if (isset($_REQUEST['customQuery']))
  77. $customQuery = $_REQUEST['customQuery']; // accept any previous SQL queries
  78. else
  79. $customQuery = "0";
  80. if (isset($_REQUEST['queryAction']))
  81. $queryAction = $_REQUEST['queryAction']; // check whether the user wants to *add* a query or *edit* an existing one
  82. else
  83. $queryAction = "add"; // *add* query will be the default action if no parameter is given
  84. if (isset($_REQUEST['queryID']))
  85. $queryID = $_REQUEST['queryID']; // fetch the query ID of the query to edit
  86. else
  87. $queryID = "";
  88. // Setup some required variables:
  89. // If there's no stored message available:
  90. if (!isset($_SESSION['HeaderString']))
  91. {
  92. if (empty($errors)) // provide one of the default messages:
  93. {
  94. $errors = array(); // re-assign an empty array (in order to prevent 'Undefined variable "errors"...' messages when calling the 'fieldError' function later on)
  95. if ($queryAction == "edit") // *edit* query
  96. $HeaderString = "Edit saved query:";
  97. else // *add* query will be the default action if no parameter is given
  98. {
  99. if ($customQuery == "1") // the script was called with parameters
  100. $HeaderString = "Save your current query:"; // Provide the default message
  101. else // the script was called without any custom SQL query
  102. $HeaderString = "Save a query for later retrieval:"; // Provide the default message
  103. }
  104. }
  105. else // -> there were errors validating the data entered by the user
  106. $HeaderString = returnMsg($loc["Warning_InputDataError"] . ":", "warning", "strong"); // function 'returnMsg()' is defined in 'include.inc.php'
  107. }
  108. else
  109. {
  110. $HeaderString = $_SESSION['HeaderString']; // extract 'HeaderString' session variable (only necessary if register globals is OFF!)
  111. // Note: though we clear the session variable, the current message is still available to this script via '$HeaderString':
  112. deleteSessionVariable("HeaderString"); // function 'deleteSessionVariable()' is defined in 'include.inc.php'
  113. }
  114. // Adjust the page (= button) title & the help text:
  115. if ($queryAction == "edit") // *edit* query
  116. {
  117. $pageTitle = "Edit Query"; // set the correct page title
  118. $helpText = "Modify the elements of your query as needed and click the <em>Edit Query</em> button. You can change the name of your query, refine the SQL query string or modify any of the display options.";
  119. }
  120. else // *add* query
  121. {
  122. $pageTitle = "Add Query"; // set the correct page title
  123. // Adjust the help text:
  124. if ($customQuery == "1") // if the script was called with parameters
  125. $helpText = "Name your query and click the <em>Add Query</em> button. If you like, you can refine your query or modify any of the display options before saving.";
  126. else
  127. $helpText = "Enter your query and set the display options to suit your needs. Then, name your query and click the <em>Add Query</em> button.";
  128. }
  129. // --------------------------------------------------------------------
  130. if ($queryAction == "edit" && empty($errors))
  131. {
  132. $exit = false;
  133. // CONSTRUCT SQL QUERY:
  134. // for the selected query, select *all* fields that are available in the form:
  135. $query = "SELECT query_id, user_id, query_name, display_type, view_type, query, show_query, show_links, show_rows, cite_style_selector, cite_order"
  136. . " FROM $tableQueries WHERE query_id = " . quote_smart($queryID); // since we'll only fetch one record, the ORDER BY clause is obsolete here
  137. // (1) OPEN CONNECTION, (2) SELECT DATABASE
  138. connectToMySQLDatabase(); // function 'connectToMySQLDatabase()' is defined in 'include.inc.php'
  139. // (3a) RUN the query on the database through the connection:
  140. $result = queryMySQLDatabase($query); // function 'queryMySQLDatabase()' is defined in 'include.inc.php'
  141. if (@ mysqli_num_rows($result) == 1) // this condition is added here to avoid the case that editing a query item which got deleted in the meantime invokes a seemingly correct but empty 'edit query' form
  142. {
  143. // (3b) EXTRACT results:
  144. $row = mysqli_fetch_array($result); // fetch the current row into the array $row (it'll be always *one* row, but anyhow)
  145. // check whether the user tries to edit a query that does not belong to his own set of saved queries:
  146. if ($row['user_id'] != getUserID($loginEmail)) // the function 'getUserID' and the '$loginEmail' variable are specified in 'include.inc.php'
  147. {
  148. $HeaderString = "You can only edit your own queries!";
  149. $exit = true;
  150. }
  151. }
  152. else // the query did NOT return any results (since we searched for a unique primary key of the queries table, the number of rows found can be only 1 or 0)
  153. {
  154. $HeaderString = "The specified query does not exist!";
  155. $exit = true;
  156. }
  157. if ($exit)
  158. {
  159. // return an appropriate error message:
  160. $HeaderString = returnMsg($HeaderString, "warning", "strong", "HeaderString"); // function 'returnMsg()' is defined in 'include.inc.php'
  161. header("Location: index.php"); // relocate back to the main page
  162. exit; // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> !EXIT! <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  163. }
  164. }
  165. // --------------------------------------------------------------------
  166. // assign correct values to the form variables:
  167. if (empty($errors))
  168. {
  169. if ($queryAction == "edit")
  170. {
  171. // fetch attributes of the current query into variables:
  172. $queryID = $row['query_id'];
  173. $queryName = $row['query_name'];
  174. $displayType = $row['display_type'];
  175. $queryViewType = $row['view_type'];
  176. $showQuery = $row['show_query'];
  177. $showLinks = $row['show_links'];
  178. $showRows = $row['show_rows'];
  179. $citeStyle = encodeHTML($row['cite_style_selector']);
  180. $citeOrder = $row['cite_order'];
  181. $sqlQuery = $row['query'];
  182. $origQueryName = $row['query_name'];
  183. }
  184. else // $queryAction == "add"
  185. {
  186. $queryID = "0"; // since '' would cause an SQL error we use '0' to indicate that there's no query ID
  187. $queryName = "";
  188. $queryViewType = ""; // ('' will produce the default 'Web' view)
  189. $origQueryName = "";
  190. if ($customQuery == "1") // the script was called with parameters
  191. {
  192. $displayType = $_REQUEST['displayType']; // extract the type of display requested by the user (either 'Display', 'Cite' or '')
  193. $showQuery = $_REQUEST['showQuery']; // extract the $showQuery parameter
  194. $showLinks = $_REQUEST['showLinks']; // extract the $showLinks parameter
  195. $showRows = $_REQUEST['showRows']; // extract the $showRows parameter
  196. $citeStyle = $_REQUEST['citeStyle']; // get the cite style chosen by the user (only occurs in 'extract.php' form and in query result lists)
  197. $citeOrder = $_REQUEST['citeOrder']; // get the citation sort order chosen by the user (only occurs in 'extract.php' form and in query result lists)
  198. $sqlQuery = $_REQUEST['sqlQuery']; // accept any previous SQL queries
  199. $sqlQuery = stripSlashesIfMagicQuotes($sqlQuery); // function 'stripSlashesIfMagicQuotes()' is defined in 'include.inc.php'
  200. }
  201. else // if there was no previous SQL query provide the default query and options:
  202. {
  203. $displayType = ""; // ('' will produce the default view)
  204. $showQuery = "0";
  205. $showLinks = "1";
  206. $showRows = $_SESSION['userRecordsPerPage']; // get the default number of records per page preferred by the current user
  207. $citeStyle = "";
  208. $citeOrder = "";
  209. // TODO: build the complete SQL query using functions 'buildFROMclause()' and 'buildORDERclause()'
  210. $sqlQuery = buildSELECTclause($displayType, $showLinks, "created_by, modified_date, modified_time, modified_by", false, false, $defaultFieldsListViewMajor); // function 'buildSELECTclause()' is defined in 'include.inc.php', and '$defaultFieldsListViewMajor' is defined in 'ini.inc.php'
  211. $sqlQuery .= " FROM $tableRefs WHERE modified_date = CURDATE() ORDER BY modified_date DESC, modified_time DESC";
  212. }
  213. }
  214. }
  215. else // there were some errors on submit
  216. {
  217. // load the form data that were entered by the user:
  218. $queryID = $formVars['queryID'];
  219. $queryName = $formVars['queryName'];
  220. $displayType = $formVars['displayType'];
  221. $queryViewType = $formVars['queryViewType'];
  222. if (isset($formVars['showQuery']))
  223. $showQuery = $formVars['showQuery'];
  224. else
  225. $showQuery = "";
  226. if (isset($formVars['showLinks']))
  227. $showLinks = $formVars['showLinks'];
  228. else
  229. $showLinks = "";
  230. $showRows = $formVars['showRows'];
  231. if (isset($formVars['citeStyle']))
  232. $citeStyle = $formVars['citeStyle'];
  233. else
  234. $citeStyle = "";
  235. if (preg_match("/%20/", $citeStyle)) // if '$citeStyle' still contains URL encoded data... ('%20' is the URL encoded form of a space, see note below!)
  236. $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)
  237. // NOTE: URL encoded data that are included within a *link* will get URL decoded automatically *before* extraction via '$_REQUEST'!
  238. // 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)!
  239. $citeOrder = $formVars['citeOrder'];
  240. $sqlQuery = $formVars['sqlQuery'];
  241. $sqlQuery = stripSlashesIfMagicQuotes($sqlQuery); // function 'stripSlashesIfMagicQuotes()' is defined in 'include.inc.php'
  242. if (isset($formVars['origQueryName']))
  243. $origQueryName = rawurldecode($formVars['origQueryName']); // get the original query name that was included within a hidden form tag (and since it got URL encoded, we'll need to decode it again)
  244. else
  245. $origQueryName = "";
  246. }
  247. // set display options according to the fetched attribute values:
  248. if ($showQuery == "1")
  249. $checkQuery = " checked";
  250. else
  251. $checkQuery = "";
  252. if ($showLinks == "1")
  253. $checkLinks = " checked";
  254. else
  255. $checkLinks = "";
  256. if (preg_match("/^Print$/i", $queryViewType))
  257. {
  258. $webViewTypeSelected = "";
  259. $printViewTypeSelected = " selected";
  260. $mobileViewTypeSelected = "";
  261. }
  262. elseif (preg_match("/^Mobile$/i", $queryViewType))
  263. {
  264. $webViewTypeSelected = "";
  265. $printViewTypeSelected = "";
  266. $mobileViewTypeSelected = " selected";
  267. }
  268. else // '$queryViewType' is 'Web' or ''
  269. {
  270. $webViewTypeSelected = " selected";
  271. $printViewTypeSelected = "";
  272. $mobileViewTypeSelected = "";
  273. }
  274. // Show the login status:
  275. showLogin(); // (function 'showLogin()' is defined in 'include.inc.php')
  276. // (2a) Display header:
  277. // call the 'displayHTMLhead()' and 'showPageHeader()' functions (which are defined in 'header.inc.php'):
  278. displayHTMLhead(encodeHTML($officialDatabaseName) . " -- " . $pageTitle, "index,follow", "Manage queries that are used to search the " . encodeHTML($officialDatabaseName), "", false, "", $viewType, array());
  279. showPageHeader($HeaderString);
  280. // (2b) Start <form> and <table> holding the form elements:
  281. // note: we provide a default value for the 'submit' form tag so that hitting <enter> within a text entry field will act as if the user clicked the 'Add/Edit Query' button
  282. ?>
  283. <form action="query_modify.php" method="POST" name="saveQuery">
  284. <input type="hidden" name="formType" value="saveQuery">
  285. <input type="hidden" name="submit" value="<?php echo $pageTitle; ?>">
  286. <input type="hidden" name="queryAction" value="<?php echo encodeHTML($queryAction); ?>">
  287. <input type="hidden" name="queryID" value="<?php echo encodeHTML($queryID); ?>">
  288. <input type="hidden" name="displayType" value="<?php echo encodeHTML($displayType); ?>">
  289. <input type="hidden" name="citeStyle" value="<?php echo rawurlencode($citeStyle); ?>">
  290. <input type="hidden" name="citeOrder" value="<?php echo encodeHTML($citeOrder); ?>">
  291. <input type="hidden" name="origQueryName" value="<?php echo rawurlencode($origQueryName); ?>">
  292. <table align="center" border="0" cellpadding="0" cellspacing="10" width="95%" summary="This table holds forms that enable you to manage your custom queries">
  293. <tr>
  294. <td width="120" valign="middle">
  295. <div class="sect"><?php echo $loc["QueryName"]; ?>:</div>
  296. </td>
  297. <td><?php echo fieldError("queryName", $errors); ?>
  298. <input type="text" name="queryName" value="<?php echo encodeHTML($queryName); ?>" size="62">
  299. </td>
  300. </tr>
  301. <tr>
  302. <td>&nbsp;</td>
  303. <td>
  304. <input type="submit" name="submit" value="<?php echo $pageTitle; ?>"><?php
  305. if ($queryAction == "edit") // add a DELETE button (CAUTION: the delete button must be displayed *AFTER* the edit button, otherwise DELETE will be the default action if the user hits return!!)
  306. // (this is since the first displayed submit button represents the default submit action in several browsers!! [like OmniWeb or Mozilla])
  307. {
  308. ?>
  309. &nbsp;&nbsp;&nbsp;<input type="submit" name="submit" value="Delete Query"><?php
  310. }
  311. ?>
  312. </td>
  313. </tr>
  314. </table>
  315. <table class="showhide" align="center" border="0" cellpadding="0" cellspacing="10" width="95%">
  316. <tr>
  317. <td class="small" width="120" valign="top">
  318. <a href="javascript:toggleVisibility('searchopt','optToggleimg','optToggletxt','<?php echo rawurlencode($loc["SearchAndDisplayOptions"]); ?>')"<?php echo addAccessKey("attribute", "search_opt"); ?> title="<?php echo $loc["LinkTitle_ToggleVisibility"] . addAccessKey("title", "search_opt"); ?>">
  319. <img id="optToggleimg" class="toggleimg" src="img/closed.gif" alt="<?php echo $loc["LinkTitle_ToggleVisibility"]; ?>" width="9" height="9" hspace="0" border="0">
  320. <span id="optToggletxt" class="toggletxt"><?php echo $loc["SearchAndDisplayOptions"]; ?></span>
  321. </a>
  322. </td>
  323. </tr>
  324. </table>
  325. <table id="searchopt" align="center" border="0" cellpadding="0" cellspacing="10" width="95%" summary="This table holds search &amp; display options" style="display: none;">
  326. <tr>
  327. <td width="120" valign="top">
  328. <div class="sect"><?php echo $loc["SQLQuery"]; ?>:</div>
  329. </td>
  330. <td colspan="2"><?php echo fieldError("sqlQuery", $errors); ?>
  331. <textarea name="sqlQuery" rows="6" cols="60"><?php echo encodeHTML($sqlQuery); ?>
  332. </textarea>
  333. </td>
  334. </tr>
  335. <tr>
  336. <td valign="middle">
  337. <div class="sect"><?php echo $loc["DisplayOptions"]; ?>:</div>
  338. </td>
  339. <td width="205" valign="middle">
  340. <input type="checkbox" name="showLinks" value="1"<?php echo $checkLinks; ?>>&nbsp;&nbsp;&nbsp;<?php echo $loc["ShowLinks"]; ?>
  341. </td>
  342. <td valign="middle">
  343. <?php echo $loc["ShowRecordsPerPage_Prefix"]; ?>&nbsp;&nbsp;&nbsp;<input type="text" name="showRows" value="<?php echo encodeHTML($showRows); ?>" size="4" title="<?php echo $loc["DescriptionShowRecordsPerPage"]; ?>">&nbsp;&nbsp;&nbsp;<?php echo $loc["ShowRecordsPerPage_Suffix"]; ?>
  344. </td>
  345. </tr>
  346. <tr>
  347. <td>&nbsp;</td>
  348. <td valign="top">
  349. <input type="checkbox" name="showQuery" value="1"<?php echo $checkQuery; ?>>&nbsp;&nbsp;&nbsp;<?php echo $loc["DisplaySQLquery"]; ?>
  350. </td>
  351. <td valign="top">
  352. <?php echo $loc["ViewType"]; ?>:&nbsp;&nbsp;
  353. <select name="queryViewType">
  354. <option value="Web"<?php echo $webViewTypeSelected; ?>><?php echo $loc["web"]; ?></option>
  355. <option value="Print"<?php echo $printViewTypeSelected; ?>><?php echo $loc["print"]; ?></option>
  356. <option value="Mobile"<?php echo $mobileViewTypeSelected; ?>><?php echo $loc["mobile"]; ?></option>
  357. </select>
  358. </td>
  359. </tr>
  360. </table>
  361. <table class="showhide" align="center" border="0" cellpadding="0" cellspacing="10" width="95%">
  362. <tr>
  363. <td class="small" width="120" valign="top">
  364. <a href="javascript:toggleVisibility('helptxt','helpToggleimg','helpToggletxt','<?php echo rawurlencode($loc["Help"]); ?>')"<?php echo addAccessKey("attribute", "search_help"); ?> title="<?php echo $loc["LinkTitle_ToggleVisibility"] . addAccessKey("title", "search_help"); ?>">
  365. <img id="helpToggleimg" class="toggleimg" src="img/closed.gif" alt="<?php echo $loc["LinkTitle_ToggleVisibility"]; ?>" width="9" height="9" hspace="0" border="0">
  366. <span id="helpToggletxt" class="toggletxt"><?php echo $loc["Help"]; ?></span>
  367. </a>
  368. </td>
  369. </tr>
  370. </table>
  371. <table id="helptxt" align="center" border="0" cellpadding="0" cellspacing="10" width="95%" summary="This table holds some help text and example queries" style="display: none;">
  372. <tr>
  373. <td width="120" valign="top">
  374. <div class="sect"><?php echo $loc["Help"]; ?>:</div>
  375. </td>
  376. <td class="helpbody" valign="top">
  377. <div class="even">
  378. <?php echo $helpText; ?>
  379. </div>
  380. <div class="odd">
  381. <?php echo $loc["MySQL-Info"]; ?>
  382. </div>
  383. </td>
  384. </tr>
  385. </table>
  386. </form><?php
  387. // --------------------------------------------------------------------
  388. // SHOW ERROR IN RED:
  389. function fieldError($fieldName, $errors)
  390. {
  391. if (isset($errors[$fieldName]))
  392. return returnMsg($errors[$fieldName], "warning2", "strong", "", "", "<br>"); // function 'returnMsg()' is defined in 'include.inc.php'
  393. }
  394. // --------------------------------------------------------------------
  395. // DISPLAY THE HTML FOOTER:
  396. // call the 'showPageFooter()' and 'displayHTMLfoot()' functions (which are defined in 'footer.inc.php')
  397. showPageFooter($HeaderString);
  398. displayHTMLfoot();
  399. // --------------------------------------------------------------------
  400. ?>