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.

741 lines
40 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: ./users.php
  11. // Repository: $HeadURL: file:///svn/p/refbase/code/branches/bleeding-edge/users.php $
  12. // Author(s): Matthias Steffens <mailto:refbase@extracts.de>
  13. //
  14. // Created: 29-Jun-03, 00:25
  15. // Modified: $Date: 2017-04-13 02:00:18 +0000 (Thu, 13 Apr 2017) $
  16. // $Author: karnesky $
  17. // $Revision: 1416 $
  18. //
  19. // This script shows the admin a list of all user entries available within the 'users' table.
  20. // User data will be shown in the familiar column view, complete with links to show a user's
  21. // details and add, edit or delete a user.
  22. // TODO: I18n
  23. // Incorporate some include files:
  24. include 'initialize/db.inc.php'; // 'db.inc.php' is included to hide username and password
  25. include 'includes/header.inc.php'; // include header
  26. include 'includes/results_header.inc.php'; // include results 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. // Check if the admin is logged in
  40. if (!(isset($_SESSION['loginEmail']) && ($loginEmail == $adminLoginEmail)))
  41. {
  42. // return an appropriate error message:
  43. $HeaderString = returnMsg("You must be logged in as admin to view any user account details!", "warning", "strong", "HeaderString"); // function 'returnMsg()' is defined in 'include.inc.php'
  44. // save the URL of the currently displayed page:
  45. $referer = $_SERVER['HTTP_REFERER'];
  46. // Write back session variables:
  47. saveSessionVariable("referer", $referer); // function 'saveSessionVariable()' is defined in 'include.inc.php'
  48. header("Location: index.php");
  49. exit;
  50. }
  51. // --------------------------------------------------------------------
  52. // [ Extract form variables sent through POST/GET by use of the '$_REQUEST' variable ]
  53. // [ !! NOTE !!: for details see <http://www.php.net/release_4_2_1.php> & <http://www.php.net/manual/en/language.variables.predefined.php> ]
  54. // Extract the form used for searching:
  55. if (isset($_REQUEST['formType']))
  56. $formType = $_REQUEST['formType'];
  57. else
  58. $formType = "";
  59. // Extract the type of display requested by the user. Normally, this will be one of the following:
  60. // - '' => if the 'submit' parameter is empty, this will produce the default columnar output style ('showUsers()' function)
  61. // - 'Add', 'Remove', 'Allow' or 'Disallow' => these values will trigger actions that act on the selected users
  62. if (isset($_REQUEST['submit']))
  63. $displayType = $_REQUEST['submit'];
  64. else
  65. $displayType = "List";
  66. // extract the original value of the '$displayType' variable:
  67. // (which was included as a hidden form tag within the 'groupSearch' form of a search results page)
  68. if (isset($_REQUEST['originalDisplayType']))
  69. $originalDisplayType = $_REQUEST['originalDisplayType'];
  70. else
  71. $originalDisplayType = "List";
  72. // For a given display type, extract the view type requested by the user (either 'Mobile', 'Print', 'Web' or ''):
  73. // ('' will produce the default 'Web' output style)
  74. if (isset($_REQUEST['viewType']))
  75. $viewType = $_REQUEST['viewType'];
  76. else
  77. $viewType = "";
  78. // Extract other variables from the request:
  79. if (isset($_REQUEST['sqlQuery']))
  80. $sqlQuery = $_REQUEST['sqlQuery'];
  81. else
  82. $sqlQuery = "";
  83. if (preg_match("/%20/", $sqlQuery)) // if '$sqlQuery' still contains URL encoded data... ('%20' is the URL encoded form of a space, see note below!)
  84. $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)
  85. // NOTE: URL encoded data that are included within a *link* will get URL decoded automatically *before* extraction via '$_REQUEST'!
  86. // 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)!
  87. if (isset($_REQUEST['showQuery']) AND ($_REQUEST['showQuery'] == "1"))
  88. $showQuery = "1";
  89. else
  90. $showQuery = "0"; // don't show the SQL query by default
  91. if (isset($_REQUEST['showLinks']) AND ($_REQUEST['showLinks'] == "0"))
  92. $showLinks = "0";
  93. else
  94. $showLinks = "1"; // show the links column by default
  95. if (isset($_REQUEST['showRows']) AND preg_match("/^[1-9]+[0-9]*$/", $_REQUEST['showRows']))
  96. $showRows = $_REQUEST['showRows'];
  97. else
  98. $showRows = $_SESSION['userRecordsPerPage']; // get the default number of records per page preferred by the current user
  99. if (isset($_REQUEST['rowOffset']))
  100. $rowOffset = $_REQUEST['rowOffset'];
  101. else
  102. $rowOffset = "";
  103. // Extract checkbox variable values from the request:
  104. if (isset($_REQUEST['marked']))
  105. $recordSerialsArray = $_REQUEST['marked']; // extract the values of all checked checkboxes (i.e., the serials of all selected records)
  106. else
  107. $recordSerialsArray = array();
  108. // check if the user did mark any checkboxes (and set up variables accordingly)
  109. if (empty($recordSerialsArray)) // no checkboxes were marked
  110. $nothingChecked = true;
  111. else // some checkboxes were marked
  112. $nothingChecked = false;
  113. // --------------------------------------------------------------------
  114. // CONSTRUCT SQL QUERY:
  115. // --- Embedded sql query: ----------------------
  116. if ($formType == "sqlSearch") // the admin used a link with an embedded sql query for searching...
  117. {
  118. $query = preg_replace("/ FROM $tableUsers/i",", user_id FROM $tableUsers",$sqlQuery); // add 'user_id' column (which is required in order to obtain unique checkbox names as well as for use in the 'getUserID()' function)
  119. $query = stripSlashesIfMagicQuotes($query);
  120. }
  121. // --- 'Search within Results' & 'Display Options' forms within 'users.php': ---------------
  122. 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 'users.php')
  123. {
  124. list($query, $displayType) = extractFormElementsRefineDisplay($tableUsers, $displayType, $originalDisplayType, $sqlQuery, $showLinks, "", ""); // function 'extractFormElementsRefineDisplay()' is defined in 'include.inc.php' since it's also used by 'users.php'
  125. }
  126. // --- 'Show User Group' form within 'users.php': ---------------------
  127. elseif ($formType == "groupSearch") // the user used the 'Show User Group' form above the query results list (that was produced by 'users.php')
  128. {
  129. $query = extractFormElementsGroup($sqlQuery);
  130. }
  131. // --- Query results form within 'users.php': ---------------
  132. elseif ($formType == "queryResults") // the user clicked one of the buttons under the query results list (that was produced by 'users.php')
  133. {
  134. list($query, $displayType) = extractFormElementsQueryResults($displayType, $originalDisplayType, $sqlQuery, $recordSerialsArray);
  135. }
  136. else // build the default query:
  137. {
  138. $query = "SELECT first_name, last_name, abbrev_institution, email, last_login, logins, user_id FROM $tableUsers WHERE user_id RLIKE \".+\" ORDER BY last_login DESC, last_name, first_name";
  139. }
  140. // ----------------------------------------------
  141. // (1) OPEN CONNECTION, (2) SELECT DATABASE
  142. connectToMySQLDatabase(); // function 'connectToMySQLDatabase()' is defined in 'include.inc.php'
  143. // (3) RUN the query on the database through the connection:
  144. $result = queryMySQLDatabase($query); // function 'queryMySQLDatabase()' is defined in 'include.inc.php'
  145. // ----------------------------------------------
  146. // (4a) DISPLAY header:
  147. $query = preg_replace("/, user_id FROM $tableUsers/i"," FROM $tableUsers",$query); // strip 'user_id' column from SQL query (so that it won't get displayed in query strings)
  148. $queryURL = rawurlencode($query); // URL encode SQL query
  149. // First, find out how many rows are available:
  150. $rowsFound = @ mysqli_num_rows($result);
  151. if ($rowsFound > 0) // If there were rows found ...
  152. {
  153. // ... setup variables in order to facilitate "previous" & "next" browsing:
  154. // a) Set '$rowOffset' to zero if not previously defined, or if a wrong number (<=0) was given
  155. if (empty($rowOffset) || ($rowOffset <= 0) || ($showRows >= $rowsFound)) // the third condition is only necessary if '$rowOffset' gets embedded within the 'displayOptions' form (see function 'buildDisplayOptionsElements()' in 'include.inc.php')
  156. $rowOffset = 0;
  157. // Adjust the '$showRows' value if not previously defined, or if a wrong number (<=0 or float) was given
  158. if (empty($showRows) || ($showRows <= 0) || !preg_match("/^[0-9]+$/", $showRows))
  159. $showRows = $_SESSION['userRecordsPerPage']; // get the default number of records per page preferred by the current user
  160. // NOTE: The current value of '$rowOffset' is embedded as hidden tag within the 'displayOptions' form. By this, the current row offset can be re-applied
  161. // after the user pressed the 'Show'/'Hide' button within the 'displayOptions' form. But then, to avoid that browse links don't behave as expected,
  162. // we need to adjust the actual value of '$rowOffset' to an exact multiple of '$showRows':
  163. $offsetRatio = ($rowOffset / $showRows);
  164. if (!is_integer($offsetRatio)) // check whether the value of the '$offsetRatio' variable is not an integer
  165. { // if '$offsetRatio' is a float:
  166. $offsetCorrectionFactor = floor($offsetRatio); // get it's next lower integer
  167. if ($offsetCorrectionFactor != 0)
  168. $rowOffset = ($offsetCorrectionFactor * $showRows); // correct the current row offset to the closest multiple of '$showRows' *below* the current row offset
  169. else
  170. $rowOffset = 0;
  171. }
  172. // b) The "Previous" page begins at the current offset LESS the number of rows per page
  173. $previousOffset = $rowOffset - $showRows;
  174. // c) The "Next" page begins at the current offset PLUS the number of rows per page
  175. $nextOffset = $rowOffset + $showRows;
  176. // d) Seek to the current offset
  177. mysqli_data_seek($result, $rowOffset);
  178. }
  179. else // set variables to zero in order to prevent 'Undefined variable...' messages when nothing was found ('$rowsFound = 0'):
  180. {
  181. $rowOffset = 0;
  182. $previousOffset = 0;
  183. $nextOffset = 0;
  184. }
  185. // Second, calculate the maximum result number on each page ('$showMaxRow' is required as parameter to the 'displayDetails()' function)
  186. if (($rowOffset + $showRows) < $rowsFound)
  187. $showMaxRow = ($rowOffset + $showRows); // maximum result number on each page
  188. else
  189. $showMaxRow = $rowsFound; // for the last results page, correct the maximum result number if necessary
  190. // Third, build the appropriate header string (which is required as parameter to the 'showPageHeader()' function):
  191. if (!isset($_SESSION['HeaderString'])) // if there's no stored message available provide the default message:
  192. {
  193. if ($rowsFound == 1)
  194. $HeaderString = " user found:";
  195. else
  196. $HeaderString = " users found:";
  197. if ($rowsFound > 0)
  198. $HeaderString = ($rowOffset + 1) . "-" . $showMaxRow . " of " . $rowsFound . $HeaderString;
  199. elseif ($rowsFound == 0)
  200. $HeaderString = $rowsFound . $HeaderString;
  201. }
  202. else
  203. {
  204. $HeaderString = $_SESSION['HeaderString']; // extract 'HeaderString' session variable (only necessary if register globals is OFF!)
  205. // Note: though we clear the session variable, the current message is still available to this script via '$HeaderString':
  206. deleteSessionVariable("HeaderString"); // function 'deleteSessionVariable()' is defined in 'include.inc.php'
  207. }
  208. // Now, show the login status:
  209. showLogin(); // (function 'showLogin()' is defined in 'include.inc.php')
  210. // Then, call the 'displayHTMLhead()' and 'showPageHeader()' functions (which are defined in 'header.inc.php'):
  211. displayHTMLhead(encodeHTML($officialDatabaseName) . " -- Manage Users", "noindex,nofollow", "Administration page that lists users of the " . encodeHTML($officialDatabaseName) . ", with links for adding, editing or deleting any users", "", true, "", $viewType, array());
  212. if (!preg_match("/^(Print|Mobile)$/i", $viewType)) // Note: we omit the visible header in print/mobile view! ('viewType=Print' or 'viewType=Mobile')
  213. showPageHeader($HeaderString);
  214. // (4b) DISPLAY results:
  215. showUsers($result, $rowsFound, $query, $queryURL, $showQuery, $showLinks, $rowOffset, $showRows, $previousOffset, $nextOffset, $showMaxRow, $viewType, $displayType); // show all users
  216. // ----------------------------------------------
  217. // (5) CLOSE the database connection:
  218. disconnectFromMySQLDatabase(); // function 'disconnectFromMySQLDatabase()' is defined in 'include.inc.php'
  219. // --------------------------------------------------------------------
  220. // Display all users listed within the 'users' table
  221. function showUsers($result, $rowsFound, $query, $queryURL, $showQuery, $showLinks, $rowOffset, $showRows, $previousOffset, $nextOffset, $showMaxRow, $viewType, $displayType)
  222. {
  223. global $connection;
  224. global $HeaderString;
  225. global $loginWelcomeMsg;
  226. global $loginStatus;
  227. global $loginLinks;
  228. global $loginEmail;
  229. global $adminLoginEmail;
  230. global $defaultCiteStyle;
  231. global $maximumBrowseLinks;
  232. global $loc; // '$loc' is made globally available in 'core.php'
  233. if ($rowsFound > 0) // If the query has results ...
  234. {
  235. // BEGIN RESULTS HEADER --------------------
  236. // 1) First, initialize some variables that we'll need later on
  237. // Note: In contrast to 'search.php', we don't hide any columns but the user_id column (see below)
  238. // However, in order to maintain a similar code structure to 'search.php' we define $CounterMax here as well & simply set it to 0:
  239. $CounterMax = "0";
  240. // count the number of fields
  241. $fieldsFound = mysqli_num_fields($result);
  242. // hide those last columns that were added by the script and not by the user
  243. $fieldsToDisplay = $fieldsFound-(1+$CounterMax); // (1+$CounterMax) -> $CounterMax is increased by 1 in order to hide the user_id column (which was added to make the checkbox work)
  244. // Calculate the number of all visible columns (which is needed as colspan value inside some TD tags)
  245. if ($showLinks == "1")
  246. $NoColumns = (1+$fieldsToDisplay+1); // add checkbox & Links column
  247. else
  248. $NoColumns = (1+$fieldsToDisplay); // add checkbox column
  249. // Note: we omit the results header in print/mobile view! ('viewType=Print' or 'viewType=Mobile')
  250. if (!preg_match("/^(Print|Mobile)$/i", $viewType))
  251. {
  252. // Specify which colums are available in the popup menus of the results header:
  253. $dropDownFieldsArray = array("first_name" => "first_name",
  254. "last_name" => "last_name",
  255. "title" => "title",
  256. "institution" => "institution",
  257. "abbrev_institution" => "abbrev_institution",
  258. "corporate_institution" => "corporate_institution",
  259. "address_line_1" => "address_line_1",
  260. "address_line_2" => "address_line_2",
  261. "address_line_3" => "address_line_3",
  262. "zip_code" => "zip_code",
  263. "city" => "city",
  264. "state" => "state",
  265. "country" => "country",
  266. "phone" => "phone",
  267. "email" => "email",
  268. "url" => "url",
  269. "language" => "language",
  270. "keywords" => "keywords",
  271. "notes" => "notes",
  272. "marked" => "marked",
  273. "last_login" => "last_login",
  274. "logins" => "logins",
  275. "user_id" => "user_id",
  276. "user_groups" => "user_groups",
  277. "created_date" => "created_date",
  278. "created_time" => "created_time",
  279. "created_by" => "created_by",
  280. "modified_date" => "modified_date",
  281. "modified_time" => "modified_time",
  282. "modified_by" => "modified_by"
  283. );
  284. // Extract the first field from the 'WHERE' clause:
  285. if (preg_match("/ WHERE [ ()]*(\w+)/i", $query))
  286. $selectedField = preg_replace("/.+ WHERE [ ()]*(\w+).*/i", "\\1", $query);
  287. else
  288. $selectedField = "last_name"; // in the 'Search within Results" form, we'll select the 'last_name' field by default
  289. // Build a TABLE with forms containing options to show the user groups, refine the search results or change the displayed columns:
  290. // - Build a FORM with a popup containing the user groups:
  291. $formElementsGroup = buildGroupSearchElements("users.php", $queryURL, $query, $showQuery, $showLinks, $showRows, $defaultCiteStyle, "", $displayType); // function 'buildGroupSearchElements()' is defined in 'include.inc.php'
  292. // - Build a FORM containing options to refine the search results:
  293. // Call the 'buildRefineSearchElements()' function (defined in 'include.inc.php') which does the actual work:
  294. $formElementsRefine = buildRefineSearchElements("users.php", $queryURL, $showQuery, $showLinks, $showRows, $defaultCiteStyle, "", $dropDownFieldsArray, $selectedField, $displayType);
  295. // - Build a FORM containing display options (show/hide columns or change the number of records displayed per page):
  296. // Call the 'buildDisplayOptionsElements()' function (defined in 'include.inc.php') which does the actual work:
  297. $formElementsDisplayOptions = buildDisplayOptionsElements("users.php", $queryURL, $showQuery, $showLinks, $rowOffset, $showRows, $defaultCiteStyle, "", $dropDownFieldsArray, $selectedField, $fieldsToDisplay, $displayType, "");
  298. echo displayResultsHeader("users.php", $formElementsGroup, $formElementsRefine, $formElementsDisplayOptions, $displayType); // function 'displayResultsHeader()' is defined in 'results_header.inc.php'
  299. }
  300. // and insert a divider line (which separates the results header from the browse links & results data below):
  301. if (!preg_match("/^(Print|Mobile)$/i", $viewType)) // Note: we omit the divider line in print/mobile view! ('viewType=Print' or 'viewType=Mobile')
  302. echo "\n<hr class=\"resultsheader\" align=\"center\" width=\"93%\">";
  303. // Build a TABLE with links for "previous" & "next" browsing, as well as links to intermediate pages
  304. // call the 'buildBrowseLinks()' function (defined in 'include.inc.php'):
  305. $BrowseLinks = buildBrowseLinks("users.php", $query, $NoColumns, $rowsFound, $showQuery, $showLinks, $showRows, $rowOffset, $previousOffset, $nextOffset, "1", $maximumBrowseLinks, "sqlSearch", $displayType, $defaultCiteStyle, "", "", "", $viewType); // Note: we set the last 3 fields ('$citeOrder', '$orderBy' & $headerMsg') to "" since they aren't (yet) required here
  306. echo $BrowseLinks;
  307. // Start a FORM
  308. echo "\n<form action=\"users.php\" method=\"GET\" name=\"queryResults\">"
  309. . "\n<input type=\"hidden\" name=\"formType\" value=\"queryResults\">"
  310. . "\n<input type=\"hidden\" name=\"submit\" value=\"Add\">" // provide a default value for the 'submit' form tag (then, hitting <enter> within the 'ShowRows' text entry field will act as if the user clicked the 'Add' button)
  311. . "\n<input type=\"hidden\" name=\"showRows\" value=\"$showRows\">" // embed the current values of '$showRows', '$rowOffset' and the current sqlQuery so that they can be re-applied after the user pressed the 'Add' or 'Remove' button within the 'queryResults' form
  312. . "\n<input type=\"hidden\" name=\"rowOffset\" value=\"$rowOffset\">"
  313. . "\n<input type=\"hidden\" name=\"sqlQuery\" value=\"$queryURL\">";
  314. // And start a TABLE
  315. echo "\n<table id=\"columns\" class=\"results\" align=\"center\" border=\"0\" cellpadding=\"5\" cellspacing=\"0\" width=\"95%\" summary=\"This table displays users of this database\">";
  316. // For the column headers, start another TABLE ROW ...
  317. echo "\n<tr>";
  318. // ... print a marker ('x') column (which will hold the checkboxes within the results part)
  319. if (!preg_match("/^(Print|Mobile)$/i", $viewType)) // Note: we omit the marker column in print/mobile view! ('viewType=Print' or 'viewType=Mobile')
  320. echo "\n\t<th align=\"left\" valign=\"top\">&nbsp;</th>";
  321. // for each of the attributes in the result set...
  322. for ($i=0; $i<$fieldsToDisplay; $i++)
  323. {
  324. // ...print out each of the attribute names
  325. // in that row as a separate TH (Table Header)...
  326. $HTMLbeforeLink = "\n\t<th align=\"left\" valign=\"top\">"; // start the table header tag
  327. $HTMLafterLink = "</th>"; // close the table header tag
  328. // call the 'buildFieldNameLinks()' function (defined in 'include.inc.php'), which will return a properly formatted table header tag holding the current field's name
  329. // as well as the URL encoded query with the appropriate ORDER clause:
  330. $tableHeaderLink = buildFieldNameLinks("users.php", $query, "", $result, $i, $showQuery, $showLinks, $rowOffset, $showRows, "1", $defaultCiteStyle, $HTMLbeforeLink, $HTMLafterLink, "sqlSearch", $displayType, "", "", "", $viewType);
  331. echo $tableHeaderLink; // print the attribute name as link
  332. }
  333. if ($showLinks == "1")
  334. {
  335. $newORDER = ("ORDER BY user_id"); // Build the appropriate ORDER BY clause to facilitate sorting by Links column
  336. $HTMLbeforeLink = "\n\t<th align=\"left\" valign=\"top\">"; // start the table header tag
  337. $HTMLafterLink = "</th>"; // close the table header tag
  338. // call the 'buildFieldNameLinks()' function (defined in 'include.inc.php'), which will return a properly formatted table header tag holding the current field's name
  339. // as well as the URL encoded query with the appropriate ORDER clause:
  340. $tableHeaderLink = buildFieldNameLinks("users.php", $query, $newORDER, $result, $i, $showQuery, $showLinks, $rowOffset, $showRows, "1", $defaultCiteStyle, $HTMLbeforeLink, $HTMLafterLink, "sqlSearch", $displayType, $loc["Links"], "user_id", "", $viewType);
  341. echo $tableHeaderLink; // print the attribute name as link
  342. }
  343. // Finish the row
  344. echo "\n</tr>";
  345. // END RESULTS HEADER ----------------------
  346. // display default user
  347. echo "<tr class=\"odd\">";
  348. echo "<td align=\"left\" valign=\"top\" width=\"10\"><input DISABLED type=\"checkbox\"</td>";
  349. echo "<td valign=\"top\"colspan=2>Account options for anyone who isn't logged in</td>";
  350. echo "<td valign=\"top\">-</td><td valign=\"top\">-</td><td valign=\"top\">-</td><td valign=\"top\">-</td>";
  351. echo "<td><a href=\"user_options.php?userID=0". "\"><img src=\"img/options.gif\" alt=\""
  352. . $loc["options"] . "\" title=\"" . $loc["LinkTitle_EditOptions"] . "\" width=\"11\" height=\"17\" hspace=\"0\" border=\"0\"></a></td>";
  353. echo "</tr>";
  354. // BEGIN RESULTS DATA COLUMNS --------------
  355. for ($rowCounter=0; (($rowCounter < $showRows) && ($row = @ mysqli_fetch_array($result))); $rowCounter++)
  356. {
  357. if (is_integer($rowCounter / 2)) // if we currently are at an even number of rows
  358. $rowClass = "even";
  359. else
  360. $rowClass = "odd";
  361. // ... start a TABLE ROW ...
  362. echo "\n<tr class=\"" . $rowClass . "\">";
  363. // ... print a column with a checkbox
  364. if (!preg_match("/^(Print|Mobile)$/i", $viewType)) // Note: we omit the marker column in print/mobile view! ('viewType=Print' or 'viewType=Mobile')
  365. echo "\n\t<td align=\"left\" valign=\"top\" width=\"10\"><input type=\"checkbox\" name=\"marked[]\" value=\"" . $row["user_id"] . "\"></td>";
  366. // ... and print out each of the attributes
  367. // in that row as a separate TD (Table Data)
  368. for ($i=0; $i<$fieldsToDisplay; $i++)
  369. {
  370. // fetch the current attribute name:
  371. $orig_fieldname = getMySQLFieldInfo($result, $i, "name"); // function 'getMySQLFieldInfo()' is defined in 'include.inc.php'
  372. if (preg_match("/^email$/", $orig_fieldname))
  373. echo "\n\t<td valign=\"top\"><a href=\"mailto:" . $row["email"] . "\">" . $row["email"] . "</a></td>";
  374. elseif (preg_match("/^url$/", $orig_fieldname) AND !empty($row["url"]))
  375. echo "\n\t<td valign=\"top\"><a href=\"" . $row["url"] . "\">" . $row["url"] . "</a></td>";
  376. else
  377. echo "\n\t<td valign=\"top\">" . encodeHTML($row[$i]) . "</td>";
  378. }
  379. // embed appropriate links (if available):
  380. if ($showLinks == "1")
  381. {
  382. echo "\n\t<td valign=\"top\">";
  383. echo "\n\t\t<a href=\"user_receipt.php?userID=" . $row["user_id"]
  384. . "\"><img src=\"img/details.gif\" alt=\"" . $loc["details"] . "\" title=\"" . $loc["LinkTitle_ShowDetailsAndOptions"] . "\" width=\"9\" height=\"17\" hspace=\"0\" border=\"0\"></a>&nbsp;&nbsp;";
  385. echo "\n\t\t<a href=\"user_details.php?userID=" . $row["user_id"]
  386. . "\"><img src=\"img/edit.gif\" alt=\"" . $loc["edit"] . "\" title=\"" . $loc["LinkTitle_EditDetails"] . "\" width=\"11\" height=\"17\" hspace=\"0\" border=\"0\"></a>&nbsp;&nbsp;";
  387. echo "\n\t\t<a href=\"user_options.php?userID=" . $row["user_id"]
  388. . "\"><img src=\"img/options.gif\" alt=\"" . $loc["options"] . "\" title=\"" . $loc["LinkTitle_EditOptions"] . "\" width=\"11\" height=\"17\" hspace=\"0\" border=\"0\"></a>&nbsp;&nbsp;";
  389. $adminUserID = getUserID($adminLoginEmail); // ...get the admin's 'user_id' using his/her 'adminLoginEmail' (function 'getUserID()' is defined in 'include.inc.php')
  390. if ($row["user_id"] != $adminUserID) // we only provide a delete link if this user isn't the admin:
  391. echo "\n\t\t<a href=\"user_receipt.php?userID=" . $row["user_id"] . "&amp;userAction=Delete"
  392. . "\"><img src=\"img/delete.gif\" alt=\"" . $loc["delete"] . "\" title=\"" . $loc["LinkTitle_DeleteUser"] . "\" width=\"11\" height=\"17\" hspace=\"0\" border=\"0\"></a>";
  393. echo "\n\t</td>";
  394. }
  395. // Finish the row
  396. echo "\n</tr>";
  397. }
  398. // Then, finish the table
  399. echo "\n</table>";
  400. // END RESULTS DATA COLUMNS ----------------
  401. // BEGIN RESULTS FOOTER --------------------
  402. // Note: we omit the results footer in print/mobile view! ('viewType=Print' or 'viewType=Mobile')
  403. if (!preg_match("/^(Print|Mobile)$/i", $viewType))
  404. {
  405. // Again, insert the (already constructed) BROWSE LINKS
  406. // (i.e., a TABLE with links for "previous" & "next" browsing, as well as links to intermediate pages)
  407. echo $BrowseLinks;
  408. // Insert a divider line (which separates the results data from the results footer):
  409. echo "\n<hr class=\"resultsfooter\" align=\"center\" width=\"93%\">";
  410. // Build a TABLE containing rows with buttons which will trigger actions that act on the selected users
  411. // Call the 'buildUserResultsFooter()' function (which does the actual work):
  412. $userResultsFooter = buildUserResultsFooter($NoColumns);
  413. echo $userResultsFooter;
  414. }
  415. // END RESULTS FOOTER ----------------------
  416. // Finally, finish the form
  417. echo "\n</form>";
  418. }
  419. else
  420. {
  421. // Report that nothing was found:
  422. echo "\n<table id=\"error\" class=\"results\" align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"10\" width=\"95%\" summary=\"This table displays users of this database\">"
  423. . "\n<tr>"
  424. . "\n\t<td valign=\"top\">Sorry, but your query didn't produce any results!&nbsp;&nbsp;<a href=\"javascript:history.back()\">Go Back</a></td>"
  425. . "\n</tr>"
  426. . "\n</table>";
  427. }// end if $rowsFound body
  428. }
  429. // --------------------------------------------------------------------
  430. // BUILD USER RESULTS FOOTER
  431. // (i.e., build a TABLE containing a row with buttons for assigning selected users to a particular group)
  432. function buildUserResultsFooter($NoColumns)
  433. {
  434. global $loc; // '$loc' is made globally available in 'core.php'
  435. // Start a TABLE
  436. $userResultsFooterRow = "\n<table class=\"resultsfooter\" align=\"center\" border=\"0\" cellpadding=\"0\" cellspacing=\"10\" width=\"90%\" summary=\"This table holds the results footer which offers a form to assign selected users to a group and set their permissions\">";
  437. $userResultsFooterRow .= "\n<tr>"
  438. . "\n\t<td align=\"left\" valign=\"top\">"
  439. . "Selected Users:"
  440. . "</td>";
  441. // Admin user groups functionality:
  442. if (!isset($_SESSION['adminUserGroups']))
  443. {
  444. $groupSearchDisabled = " disabled"; // disable the (part of the) 'Add to/Remove from group' form elements if the session variable holding the admin's user groups isn't available
  445. $groupSearchPopupMenuChecked = "";
  446. $groupSearchTextInputChecked = " checked";
  447. $groupSearchSelectorTitle = "(to setup a new group with all selected users, enter a group name to the right, then click the 'Add' button)";
  448. $groupSearchTextInputTitle = "to setup a new group with the selected users, specify the name of the group here, then click the 'Add' button";
  449. }
  450. else
  451. {
  452. $groupSearchDisabled = "";
  453. $groupSearchPopupMenuChecked = " checked";
  454. $groupSearchTextInputChecked = "";
  455. $groupSearchSelectorTitle = "choose the group to which the selected users shall belong (or from which they shall be removed)";
  456. $groupSearchTextInputTitle = "to setup a new group with the selected users, click the radio button to the left &amp; specify the name of the group here, then click the 'Add' button";
  457. }
  458. $userResultsFooterRow .= "\n\t<td align=\"left\" valign=\"top\" colspan=\"" . ($NoColumns - 1) . "\">"
  459. . "\n\t\t<input type=\"submit\" name=\"submit\" value=\"Add\" title=\"add all selected users to the specified group\">&nbsp;"
  460. . "\n\t\t<input type=\"submit\" name=\"submit\" value=\"Remove\" title=\"remove all selected users from the specified group\"$groupSearchDisabled>&nbsp;&nbsp;&nbsp;group:&nbsp;&nbsp;"
  461. . "\n\t\t<input type=\"radio\" name=\"userGroupActionRadio\" value=\"1\" title=\"click here if you want to add (remove) the selected users to (from) an existing group; then, choose the group name from the popup menu to the right\"$groupSearchDisabled$groupSearchPopupMenuChecked>"
  462. . "\n\t\t<select name=\"userGroupSelector\" title=\"$groupSearchSelectorTitle\"$groupSearchDisabled>";
  463. if (!isset($_SESSION['adminUserGroups']))
  464. {
  465. $userResultsFooterRow .= "\n\t\t\t<option>(no groups available)</option>";
  466. }
  467. else
  468. {
  469. $optionTags = buildSelectMenuOptions($_SESSION['adminUserGroups'], "/ *; */", "\t\t\t", false); // build properly formatted <option> tag elements from the items listed in the 'adminUserGroups' session variable
  470. $userResultsFooterRow .= $optionTags;
  471. }
  472. $userResultsFooterRow .= "\n\t\t</select>&nbsp;&nbsp;&nbsp;"
  473. . "\n\t\t<input type=\"radio\" name=\"userGroupActionRadio\" value=\"0\" title=\"click here if you want to setup a new group; then, enter the group name in the text box to the right\"$groupSearchTextInputChecked>"
  474. . "\n\t\t<input type=\"text\" name=\"userGroupName\" value=\"\" size=\"8\" title=\"$groupSearchTextInputTitle\">"
  475. . "\n\t</td>"
  476. . "\n</tr>";
  477. // Set user permissions functionality:
  478. $userResultsFooterRow .= "\n<tr>"
  479. . "\n\t<td align=\"left\" valign=\"top\">&nbsp;</td>"
  480. . "\n\t<td align=\"left\" valign=\"top\" colspan=\"" . ($NoColumns - 1) . "\">"
  481. . "\n\t\t<input type=\"submit\" name=\"submit\" value=\"Allow\" title=\"allow all selected users to use the specified feature\">&nbsp;"
  482. . "\n\t\t<input type=\"submit\" name=\"submit\" value=\"Disallow\" title=\"do not allow the selected users to use the specified feature\">&nbsp;&nbsp;&nbsp;feature:&nbsp;&nbsp;"
  483. . "\n\t\t<select name=\"userPermissionSelector\" title=\"select the permission setting you'd like to change for the selected users\">";
  484. // Map raw field names from table 'user_permissions' with items of the global localization array ('$loc'):
  485. $userPermissionsArray = array('allow_add' => $loc['UserPermission_AllowAdd'],
  486. 'allow_edit' => $loc['UserPermission_AllowEdit'],
  487. 'allow_delete' => $loc['UserPermission_AllowDelete'],
  488. 'allow_download' => $loc['UserPermission_AllowDownload'],
  489. 'allow_upload' => $loc['UserPermission_AllowUpload'],
  490. 'allow_list_view' => $loc['UserPermission_AllowListView'],
  491. 'allow_details_view' => $loc['UserPermission_AllowDetailsView'],
  492. 'allow_print_view' => $loc['UserPermission_AllowPrintView'],
  493. // 'allow_browse_view' => $loc['UserPermission_AllowBrowseView'],
  494. 'allow_sql_search' => $loc['UserPermission_AllowSQLSearch'],
  495. 'allow_user_groups' => $loc['UserPermission_AllowUserGroups'],
  496. 'allow_user_queries' => $loc['UserPermission_AllowUserQueries'],
  497. 'allow_rss_feeds' => $loc['UserPermission_AllowRSSFeeds'],
  498. 'allow_import' => $loc['UserPermission_AllowImport'],
  499. 'allow_export' => $loc['UserPermission_AllowExport'],
  500. 'allow_cite' => $loc['UserPermission_AllowCite'],
  501. 'allow_batch_import' => $loc['UserPermission_AllowBatchImport'],
  502. 'allow_batch_export' => $loc['UserPermission_AllowBatchExport'],
  503. 'allow_modify_options' => $loc['UserPermission_AllowModifyOptions']);
  504. // 'allow_edit_call_number' => $loc['UserPermission_AllowEditCallNumber']);
  505. $optionTags = buildSelectMenuOptions($userPermissionsArray, "//", "\t\t\t", true); // build properly formatted <option> tag elements from the items listed in the '$userPermissionsArray' variable
  506. $userResultsFooterRow .= $optionTags;
  507. $userResultsFooterRow .= "\n\t\t</select>"
  508. . "\n\t</td>"
  509. . "\n</tr>";
  510. // Finish the table:
  511. $userResultsFooterRow .= "\n</table>";
  512. return $userResultsFooterRow;
  513. }
  514. // --------------------------------------------------------------------
  515. // Build the database query from user input provided by the "Show User Group" form above the query results list (that was produced by 'users.php'):
  516. function extractFormElementsGroup($sqlQuery)
  517. {
  518. global $tableUsers; // defined in 'db.inc.php'
  519. if (!empty($sqlQuery)) // if there's a previous SQL query available
  520. {
  521. // use the custom set of colums chosen by the user:
  522. $query = "SELECT " . extractSELECTclause($sqlQuery); // function 'extractSELECTclause()' is defined in 'include.inc.php'
  523. // user the custom ORDER BY clause chosen by the user:
  524. $queryOrderBy = extractORDERBYclause($sqlQuery); // function 'extractORDERBYclause()' is defined in 'include.inc.php'
  525. }
  526. else
  527. {
  528. $query = "SELECT first_name, last_name, abbrev_institution, email, last_login, logins, user_id"; // use the default SELECT statement
  529. $queryOrderBy = "last_login DESC, last_name, first_name"; // add the default ORDER BY clause
  530. }
  531. $groupSearchSelector = $_REQUEST['groupSearchSelector']; // extract the user group chosen by the user
  532. $query .= ", user_id"; // add 'user_id' column (although it won't be visible the 'user_id' column gets included in every search query)
  533. // (which is required in order to obtain unique checkbox names as well as for use in the 'getUserID()' function)
  534. $query .= " FROM $tableUsers"; // add FROM clause
  535. $query .= " WHERE user_groups RLIKE " . quote_smart("(^|.*;) *" . $groupSearchSelector . " *(;.*|$)"); // add WHERE clause
  536. $query .= " ORDER BY " . $queryOrderBy; // add ORDER BY clause
  537. return $query;
  538. }
  539. // --------------------------------------------------------------------
  540. // Build the database query from records selected by the user within the query results list (which, in turn, was returned by 'users.php'):
  541. function extractFormElementsQueryResults($displayType, $originalDisplayType, $sqlQuery, $recordSerialsArray)
  542. {
  543. global $tableUsers; // defined in 'db.inc.php'
  544. $userGroupActionRadio = $_REQUEST['userGroupActionRadio']; // extract user option whether we're supposed to process an existing group name or any custom/new group name that was specified by the user
  545. // Extract the chosen user group from the request:
  546. // first, we need to check whether the user did choose an existing group name from the popup menu
  547. // -OR- if he/she did enter a custom group name in the text entry field:
  548. if ($userGroupActionRadio == "1") // if the user checked the radio button next to the group popup menu ('userGroupSelector') [this is the default]
  549. {
  550. if (isset($_REQUEST['userGroupSelector']))
  551. $userGroup = $_REQUEST['userGroupSelector']; // extract the value of the 'userGroupSelector' popup menu
  552. else
  553. $userGroup = "";
  554. }
  555. else // $userGroupActionRadio == "0" // if the user checked the radio button next to the group text entry field ('userGroupName')
  556. {
  557. if (isset($_REQUEST['userGroupName']))
  558. $userGroup = $_REQUEST['userGroupName']; // extract the value of the 'userGroupName' text entry field
  559. else
  560. $userGroup = "";
  561. }
  562. // extract the specified permission setting:
  563. if (isset($_REQUEST['userPermissionSelector']))
  564. $userPermission = $_REQUEST['userPermissionSelector']; // extract the value of the 'userPermissionSelector' popup menu
  565. else
  566. $userPermission = "";
  567. if (!empty($recordSerialsArray))
  568. {
  569. if (preg_match("/^(Add|Remove)$/", $displayType)) // (hitting <enter> within the 'userGroupName' text entry field will act as if the user clicked the 'Add' button)
  570. {
  571. modifyUserGroups($tableUsers, $displayType, $recordSerialsArray, "", $userGroup); // add (remove) selected records to (from) the specified user group (function 'modifyUserGroups()' is defined in 'include.inc.php')
  572. }
  573. elseif (preg_match("/^(Allow|Disallow)$/", $displayType))
  574. {
  575. if ($displayType == "Allow")
  576. $userPermissionsArray = array("$userPermission" => "yes");
  577. else // ($displayType == "Disallow")
  578. $userPermissionsArray = array("$userPermission" => "no");
  579. // Update the specified user permission for the current user:
  580. $updateSucceeded = updateUserPermissions($recordSerialsArray, $userPermissionsArray); // function 'updateUserPermissions()' is defined in 'include.inc.php'
  581. if ($updateSucceeded) // save an informative message:
  582. $HeaderString = returnMsg("User permission $userPermission was updated successfully!", "", "", "HeaderString"); // function 'returnMsg()' is defined in 'include.inc.php'
  583. else // return an appropriate error message:
  584. $HeaderString = returnMsg("User permission $userPermission could not be updated!", "warning", "strong", "HeaderString");
  585. }
  586. }
  587. // re-assign the correct display type if the user clicked the 'Add', 'Remove', 'Allow' or 'Disallow' button of the 'queryResults' form:
  588. $displayType = $originalDisplayType;
  589. // re-apply the current sqlQuery:
  590. $query = preg_replace("/ FROM $tableUsers/i",", user_id FROM $tableUsers",$sqlQuery); // add 'user_id' column (which is required in order to obtain unique checkbox names)
  591. return array($query, $displayType);
  592. }
  593. // --------------------------------------------------------------------
  594. // DISPLAY THE HTML FOOTER:
  595. // call the 'showPageFooter()' and 'displayHTMLfoot()' functions (which are defined in 'footer.inc.php')
  596. if (!preg_match("/^(Print|Mobile)$/i", $viewType)) // Note: we omit the visible footer in print/mobile view! ('viewType=Print' or 'viewType=Mobile')
  597. showPageFooter($HeaderString);
  598. displayHTMLfoot();
  599. // --------------------------------------------------------------------
  600. ?>