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.

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