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.

476 lines
21 KiB

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