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.

596 lines
32 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: ./user_validation.php
  13. // Repository: $HeadURL: file:///svn/p/refbase/code/branches/bleeding-edge/user_validation.php $
  14. // Author(s): Matthias Steffens <mailto:refbase@extracts.de>
  15. //
  16. // Created: 16-Apr-02, 10:54
  17. // Modified: $Date: 2017-04-13 02:00:18 +0000 (Thu, 13 Apr 2017) $
  18. // $Author: karnesky $
  19. // $Revision: 1416 $
  20. // This script validates user data entered into the form that is provided by 'user_details.php'.
  21. // If validation succeeds, it INSERTs or UPDATEs a user and redirects to a receipt page;
  22. // if it fails, it creates error messages and these are later displayed by 'user_details.php'.
  23. // TODO: I18n
  24. // Incorporate some include files:
  25. include 'initialize/db.inc.php'; // 'db.inc.php' is included to hide username and password
  26. include 'includes/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. // Clear any errors that might have been found previously:
  38. $errors = array();
  39. // Write the (POST) form variables into an array:
  40. foreach($_POST as $varname => $value)
  41. $formVars[$varname] = $value;
  42. // $formVars[$varname] = trim(clean($value, 50)); // the use of the clean function would be more secure!
  43. // --------------------------------------------------------------------
  44. // First of all, check if this script was called by something else than 'user_details.php':
  45. if (!preg_match("#/user_details\.php#i", $referer)) // variable '$referer' is globally defined in function 'start_session()' in 'include.inc.php'
  46. {
  47. // return an appropriate error message:
  48. $HeaderString = returnMsg($loc["Warning_InvalidCallToScript"] . " '" . scriptURL() . "'!", "warning", "strong", "HeaderString"); // functions 'returnMsg()' and 'scriptURL()' are defined in 'include.inc.php'
  49. header("Location: " . $referer); // redirect to calling page
  50. exit; // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> !EXIT! <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  51. }
  52. // --------------------------------------------------------------------
  53. // (1) OPEN CONNECTION, (2) SELECT DATABASE
  54. connectToMySQLDatabase(); // function 'connectToMySQLDatabase()' is defined in 'include.inc.php'
  55. // --------------------------------------------------------------------
  56. // Validate the First Name
  57. if (empty($formVars["firstName"]))
  58. // First name cannot be a null string
  59. $errors["firstName"] = "The first name field cannot be blank:";
  60. // elseif (preg_match("/\(" . $adminLoginEmail . "\)$/", empty($formVars["firstName"]))
  61. // elseif (!preg_match("/^[a-z'-]*$/i", $formVars["firstName"]))
  62. // // First name cannot contain white space
  63. // $errors["firstName"] = "The first name can only contain alphabetic characters or \"-\" or \"'\":";
  64. elseif (strlen($formVars["firstName"]) > 50)
  65. $errors["firstName"] = "The first name can be no longer than 50 characters:";
  66. // Validate the Last Name
  67. if (empty($formVars["lastName"]))
  68. // the user's last name cannot be a null string
  69. $errors["lastName"] = "The last name field cannot be blank:";
  70. elseif (strlen($formVars["lastName"]) > 50)
  71. $errors["lastName"] = "The last name can be no longer than 50 characters:";
  72. // Validate the Institution
  73. if (strlen($formVars["institution"]) > 255)
  74. $errors["institution"] = "The institution name can be no longer than 255 characters:";
  75. // Validate the Institutional Abbreviation
  76. if (empty($formVars["abbrevInstitution"]))
  77. // the institutional abbreviation cannot be a null string
  78. $errors["abbrevInstitution"] = "The institutional abbreviation field cannot be blank:";
  79. elseif (strlen($formVars["abbrevInstitution"]) > 25)
  80. $errors["abbrevInstitution"] = "The institutional abbreviation can be no longer than 25 characters:";
  81. // Validate the Corporate Institution
  82. if (strlen($formVars["corporateInstitution"]) > 255)
  83. $errors["corporateInstitution"] = "The corporate institution name can be no longer than 255 characters:";
  84. // Validate the Address
  85. // if (empty($formVars["address1"]) && empty($formVars["address2"]) && empty($formVars["address3"]))
  86. // // all the fields of the address cannot be null
  87. // $errors["address"] = "You must supply at least one address line:";
  88. // else
  89. // {
  90. if (strlen($formVars["address1"]) > 50)
  91. $errors["address1"] = "The address line 1 can be no longer than 50 characters:";
  92. if (strlen($formVars["address2"]) > 50)
  93. $errors["address2"] = "The address line 2 can be no longer than 50 characters:";
  94. if (strlen($formVars["address3"]) > 50)
  95. $errors["address3"] = "The address line 3 can be no longer than 50 characters:";
  96. // }
  97. // Validate the City
  98. // if (empty($formVars["city"]))
  99. // // the user's city cannot be a null string
  100. // $errors["city"] = "You must supply a city:";
  101. if (strlen($formVars["city"]) > 40)
  102. $errors["city"] = "The city can be no longer than 40 characters:";
  103. // Validate State - any string less than 51 characters
  104. if (strlen($formVars["state"]) > 50)
  105. $errors["state"] = "The state can be no longer than 50 characters:";
  106. // Validate Zip code
  107. // if (!preg_match("/^([0-9]{4,5})$/", $formVars["zipCode"]))
  108. // $errors["zipCode"] = "The zip code must be 4 or 5 digits in length:";
  109. if (strlen($formVars["zipCode"]) > 25)
  110. $errors["zipCode"] = "The zip code can be no longer than 25 characters:";
  111. // Validate Country
  112. if (strlen($formVars["country"]) > 40)
  113. $errors["country"] = "The country can be no longer than 40 characters:";
  114. // Validate Phone
  115. if (strlen($formVars["phone"]) > 50)
  116. $errors["phone"] = "The phone number can be no longer than 50 characters:";
  117. elseif (!empty($formVars["phone"]) && !preg_match("#^[0-9 /+-]+$#i", $formVars["phone"])) // '+49 431/600-1233' would be a valid format
  118. // The phone must match the above regular expression (i.e., it should only consist out of digits, the characters '/+-' and a space)
  119. $errors["phone"] = "The phone number must consist out of digits plus the optional characters '+/- ',\n\t\t<br>\n\t\te.g., '+49 431/600-1233' would be a valid format:";
  120. // // Phone is optional, but if it is entered it must have correct format
  121. // $validPhoneExpr = "^([0-9]{2,3}[ ]?)?[0-9]{4}[ ]?[0-9]{4}$";
  122. // if (!empty($formVars["phone"]) && !preg_match("/" . $validPhoneExpr . "/", $formVars["phone"]))
  123. // $errors["phone"] = "The phone number must be 8 digits in length, with an optional 2 or 3 digit area code:";
  124. // Validate URL
  125. if (strlen($formVars["url"]) > 255)
  126. $errors["url"] = "The URL can be no longer than 255 characters:";
  127. // Only validate email if this is an INSERT:
  128. // Validation is triggered for NEW USERS (visitors who aren't logged in) as well as the ADMIN
  129. // (the email field isn't shown to logged in non-admin-users anyhow)
  130. if (!isset($_SESSION['loginEmail']) | (isset($_SESSION['loginEmail']) && ($loginEmail == $adminLoginEmail) && ($_REQUEST['userID'] == "")))
  131. {
  132. // Check syntax
  133. $validEmailExpr = "^[0-9a-z~!#$%&_-]([.]?[0-9a-z~!#$%&_-])*@[0-9a-z~!#$%&_-]([.]?[0-9a-z~!#$%&_-])*$";
  134. if (empty($formVars["email"]))
  135. // the user's email cannot be a null string
  136. $errors["email"] = "You must supply an email address:";
  137. elseif (!preg_match("/" . $validEmailExpr . "/i", $formVars["email"]))
  138. // The email must match the above regular expression
  139. $errors["email"] = "The email address must be in the name@domain format:";
  140. elseif (strlen($formVars["email"]) > 50)
  141. // The length cannot exceed 50 characters
  142. $errors["email"] = "The email address can be no longer than 50 characters:";
  143. // elseif (!(getmxrr(substr(strstr($formVars["email"], '@'), 1), $temp)) || checkdnsrr(gethostbyname(substr(strstr($formVars["email"], '@'), 1)), "ANY"))
  144. // // There must be a Domain Name Server (DNS) record for the domain name
  145. // $errors["email"] = "The domain does not exist:";
  146. else // Check if the email address is already in use in the database:
  147. {
  148. $query = "SELECT * FROM $tableAuth WHERE email = " . quote_smart($formVars["email"]); // CONSTRUCT SQL QUERY
  149. // (3) RUN the query on the database through the connection:
  150. $result = queryMySQLDatabase($query); // function 'queryMySQLDatabase()' is defined in 'include.inc.php'
  151. if (mysqli_num_rows($result) == 1) // (4) Interpret query result: Is it taken?
  152. $errors["email"] = "A user already exists with this email address as login name.\n\t\t<br>\n\t\tPlease enter a different one:";
  153. }
  154. }
  155. // If this was an INSERT, we do not allow the password field to be blank:
  156. // Validation is triggered for NEW USERS (visitors who aren't logged in) as well as the ADMIN
  157. if (!isset($_SESSION['loginEmail']) | (isset($_SESSION['loginEmail']) && ($loginEmail == $adminLoginEmail) && ($_REQUEST['userID'] == "")))
  158. if (empty($formVars["loginPassword"]))
  159. // Password cannot be a null string
  160. $errors["loginPassword"] = "The password field cannot be blank:";
  161. if ($formVars["loginPassword"] != $formVars["loginPasswordRetyped"])
  162. $errors["loginPassword"] = "You typed <em>two</em> different passwords! Please make sure\n\t\t<br>\n\t\tthat you type your password correctly:";
  163. elseif (strlen($formVars["loginPassword"]) > 15)
  164. $errors["loginPassword"] = "The password can be no longer than 15 characters:";
  165. // alternatively, only validate password if it's length is between 6 and 8 characters
  166. // elseif (!isset($_SESSION['loginEmail']) && (strlen($formVars["loginPassword"]) < 6 || strlen($formVars["loginPassword"] > 8)))
  167. // $errors["loginPassword"] = "The password must be between 6 and 8 characters in length:";
  168. // --------------------------------------------------------------------
  169. // Now the script has finished the validation, check if there were any errors:
  170. if (count($errors) > 0)
  171. {
  172. // Write back session variables:
  173. saveSessionVariable("errors", $errors); // function 'saveSessionVariable()' is defined in 'include.inc.php'
  174. saveSessionVariable("formVars", $formVars);
  175. // There are errors. Relocate back to the client form:
  176. header("Location: user_details.php?userID=" . $_REQUEST['userID']); // 'userID' got included as hidden form tag by 'user_details.php' (for new users 'userID' will be empty but will get ignored by 'INSERT...' anyhow)
  177. exit; // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> !EXIT! <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  178. }
  179. // --------------------------------------------------------------------
  180. // If we made it here, then the data is valid!
  181. // CONSTRUCT SQL QUERY:
  182. // First, setup some required variables:
  183. // Get the current date (e.g. '2003-12-31'), time (e.g. '23:59:49') and user name & email address (e.g. 'Matthias Steffens (refbase@extracts.de)'):
  184. list ($currentDate, $currentTime, $currentUser) = getCurrentDateTimeUser(); // function 'getCurrentDateTimeUser()' is defined in 'include.inc.php'
  185. // If a user is logged in and has submitted 'user_details.php' with a 'userID' parameter:
  186. // (while the admin has no restrictions, a normal user can only submit 'user_details.php' with his own 'userID' as parameter!)
  187. if (isset($_SESSION['loginEmail']) && ($_REQUEST['userID'] != "")) // -> perform an update:
  188. {
  189. if ($loginEmail != $adminLoginEmail) // if not admin logged in
  190. $userID = getUserID($loginEmail); // Get the 'user_id' using 'loginEmail' (function 'getUserID()' is defined in 'include.inc.php')
  191. else // if the admin is logged in he should be able to make any changes to account data of _other_ users...
  192. $userID = $_REQUEST['userID']; // ...in this case we accept 'userID' from the GET/POST request (it got included as hidden form tag by 'user_details.php')
  193. // UPDATE - construct a query to update the relevant record
  194. $query = "UPDATE $tableUsers SET "
  195. . "first_name = " . quote_smart($formVars["firstName"])
  196. . ", last_name = " . quote_smart($formVars["lastName"])
  197. . ", title = " . quote_smart($formVars["title"])
  198. . ", institution = " . quote_smart($formVars["institution"])
  199. . ", abbrev_institution = " . quote_smart($formVars["abbrevInstitution"])
  200. . ", corporate_institution = " . quote_smart($formVars["corporateInstitution"])
  201. . ", address_line_1 = " . quote_smart($formVars["address1"])
  202. . ", address_line_2 = " . quote_smart($formVars["address2"])
  203. . ", address_line_3 = " . quote_smart($formVars["address3"])
  204. . ", zip_code = " . quote_smart($formVars["zipCode"])
  205. . ", city = " . quote_smart($formVars["city"])
  206. . ", state = " . quote_smart($formVars["state"])
  207. . ", country = " . quote_smart($formVars["country"])
  208. . ", phone = " . quote_smart($formVars["phone"])
  209. . ", url = " . quote_smart($formVars["url"]);
  210. if (isset($_SESSION['loginEmail']) && ($loginEmail == $adminLoginEmail))
  211. {
  212. $query .= ", keywords = " . quote_smart($formVars["keywords"])
  213. . ", notes = " . quote_smart($formVars["notes"])
  214. . ", marked = " . quote_smart($formVars["marked"]);
  215. }
  216. if (isset($_SESSION['loginEmail']))
  217. $query .= ", modified_by = " . quote_smart($currentUser);
  218. $query .= ", modified_date = " . quote_smart($currentDate)
  219. . ", modified_time = " . quote_smart($currentTime);
  220. $query .= " WHERE user_id = " . quote_smart($userID);
  221. }
  222. // If an authorized user uses 'user_details.php' to add a new user (-> 'userID' is empty!):
  223. // INSERTs are allowed to:
  224. // 1. EVERYONE who's not logged in (but ONLY if variable '$addNewUsers' in 'ini.inc.php' is set to "everyone"!)
  225. // (Note that this feature is actually only meant to add the very first user to the users table.
  226. // After you've done so, it is highly recommended to change the value of '$addNewUsers' to 'admin'!)
  227. // -or- 2. the ADMIN only (if variable '$addNewUsers' in 'ini.inc.php' is set to "admin")
  228. elseif ((!isset($_SESSION['loginEmail']) && ($addNewUsers == "everyone") && ($_REQUEST['userID'] == "")) | (isset($_SESSION['loginEmail']) && ($loginEmail == $adminLoginEmail) && ($_REQUEST['userID'] == ""))) // -> perform an insert:
  229. {
  230. // INSERT - construct a query to add data as new record
  231. $query = "INSERT INTO $tableUsers SET "
  232. . "first_name = " . quote_smart($formVars["firstName"])
  233. . ", last_name = " . quote_smart($formVars["lastName"])
  234. . ", title = " . quote_smart($formVars["title"])
  235. . ", institution = " . quote_smart($formVars["institution"])
  236. . ", abbrev_institution = " . quote_smart($formVars["abbrevInstitution"])
  237. . ", corporate_institution = " . quote_smart($formVars["corporateInstitution"])
  238. . ", address_line_1 = " . quote_smart($formVars["address1"])
  239. . ", address_line_2 = " . quote_smart($formVars["address2"])
  240. . ", address_line_3 = " . quote_smart($formVars["address3"])
  241. . ", zip_code = " . quote_smart($formVars["zipCode"])
  242. . ", city = " . quote_smart($formVars["city"])
  243. . ", state = " . quote_smart($formVars["state"])
  244. . ", country = " . quote_smart($formVars["country"])
  245. . ", phone = " . quote_smart($formVars["phone"])
  246. . ", url = " . quote_smart($formVars["url"]);
  247. if (isset($_SESSION['loginEmail']) && ($loginEmail == $adminLoginEmail))
  248. {
  249. $query .= ", keywords = " . quote_smart($formVars["keywords"])
  250. . ", notes = " . quote_smart($formVars["notes"])
  251. . ", marked = " . quote_smart($formVars["marked"]);
  252. }
  253. $query .= ", email = " . quote_smart($formVars["email"]);
  254. if (isset($_SESSION['loginEmail']))
  255. $query .= ", created_by = " . quote_smart($currentUser);
  256. $query .= ", created_date = " . quote_smart($currentDate)
  257. . ", created_time = " . quote_smart($currentTime);
  258. if (isset($_SESSION['loginEmail']))
  259. $query .= ", modified_by = " . quote_smart($currentUser);
  260. $query .= ", modified_date = " . quote_smart($currentDate)
  261. . ", modified_time = " . quote_smart($currentTime);
  262. $query .= ", language = \"" . $defaultLanguage . "\"" // '$defaultLanguage' is defined in 'ini.inc.php' (the language setting can be changed by the user in 'user_options.php')
  263. . ", last_login = NOW()" // set 'last_login' field to the current date & time in 'DATETIME' format (which is 'YYYY-MM-DD HH:MM:SS', e.g.: '2003-12-31 23:45:59')
  264. . ", logins = 1 "; // set the number of logins to 1 (so that any subsequent login attempt can be counted correctly)
  265. }
  266. // if '$addNewUsers' is set to 'admin': MAIL feedback to new user & send data to admin for approval:
  267. // no user is logged in (since 'user_details.php' cannot be called w/o a 'userID' by a logged in user,
  268. // 'user_details.php' must have been submitted by a NEW user!)
  269. elseif ($addNewUsers == "admin" && ($_REQUEST['userID'] == ""))
  270. {
  271. // First, we have to query for the proper admin name, so that we can include this name within the emails:
  272. $query = "SELECT first_name, last_name FROM $tableUsers WHERE email = " . quote_smart($adminLoginEmail); // CONSTRUCT SQL QUERY ('$adminLoginEmail' is specified in 'ini.inc.php')
  273. // (3a) RUN the query on the database through the connection:
  274. $result = queryMySQLDatabase($query); // function 'queryMySQLDatabase()' is defined in 'include.inc.php'
  275. $row = mysqli_fetch_array($result); // (3b) EXTRACT results: fetch the current row into the array $row
  276. // 1) Mail feedback to user, i.e., send the person who wants to be added as new user a notification email:
  277. $emailRecipient = $formVars["firstName"] . " " . $formVars["lastName"] . " <" . $formVars["email"] . ">";
  278. $emailSubject = "Your request to participate at the " . $officialDatabaseName; // ('$officialDatabaseName' is specified in 'ini.inc.php')
  279. $emailBody = "Dear " . $formVars["firstName"] . " " . $formVars["lastName"] . ","
  280. . "\n\nthanks for your interest in the " . $officialDatabaseName . "!"
  281. . "\nThe data you provided have been sent to our database admin."
  282. . "\nWe'll process your request and mail back to you as soon as we can."
  283. . "\n\n--"
  284. . "\n" . $databaseBaseURL . "index.php"; // ('$databaseBaseURL' is specified in 'ini.inc.php')
  285. sendEmail($emailRecipient, $emailSubject, $emailBody);
  286. // 2) Send user data to admin for approval:
  287. $emailRecipient = $row["first_name"] . " " . $row["last_name"] . " <" . $adminLoginEmail . ">"; // ('$adminLoginEmail' is specified in 'ini.inc.php')
  288. $emailSubject = "User request to participate at the " . $officialDatabaseName; // ('$officialDatabaseName' is specified in 'ini.inc.php')
  289. $emailBody = "Dear " . $row["first_name"] . " " . $row["last_name"] . ","
  290. . "\n\nsomebody wants to join the " . $officialDatabaseName . ":"
  291. . "\n\n" . $formVars["firstName"] . " " . $formVars["lastName"] . " (" . $formVars["abbrevInstitution"] . ") submitted the form at"
  292. . "\n\n <" . $databaseBaseURL . "user_details.php>"
  293. . "\n\nwith the data below:"
  294. . "\n\n first name: " . $formVars["firstName"]
  295. . "\n last name: " . $formVars["lastName"]
  296. . "\n institution: " . $formVars["institution"]
  297. . "\n institutional abbreviation: " . $formVars["abbrevInstitution"]
  298. . "\n corporate institution: " . $formVars["corporateInstitution"]
  299. . "\n address line 1: " . $formVars["address1"]
  300. . "\n address line 2: " . $formVars["address2"]
  301. . "\n address line 3: " . $formVars["address3"]
  302. . "\n zip code: " . $formVars["zipCode"]
  303. . "\n city: " . $formVars["city"]
  304. . "\n state: " . $formVars["state"]
  305. . "\n country: " . $formVars["country"]
  306. . "\n phone: " . $formVars["phone"]
  307. . "\n url: " . $formVars["url"]
  308. . "\n email: " . $formVars["email"]
  309. . "\n password: " . $formVars["loginPassword"]
  310. . "\n\nPlease contact " . $formVars["firstName"] . " " . $formVars["lastName"] . " to approve the request."
  311. . "\n\n--"
  312. . "\n" . $databaseBaseURL . "index.php"; // ('$databaseBaseURL' is specified in 'ini.inc.php')
  313. sendEmail($emailRecipient, $emailSubject, $emailBody);
  314. header("Location: user_receipt.php?userID=-1"); // Note: we use the non-existing user ID '-1' as trigger to show the email notification receipt page (instead of the standard receipt page)
  315. exit; // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> !EXIT! <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  316. }
  317. // --------------------------------------------------------------------
  318. // (3) RUN the query on the database through the connection:
  319. $result = queryMySQLDatabase($query); // function 'queryMySQLDatabase()' is defined in 'include.inc.php'
  320. // ----------------------------------------------
  321. // If this was an UPDATE - we save possible name changes to the session file (so that this new user name can be displayed by the 'showLogin()' function):
  322. if (isset($_SESSION['loginEmail']) && ($_REQUEST['userID'] != ""))
  323. {
  324. // We only save name changes if a normal user is logged in -OR- the admin is logged in AND the updated user data are his own!
  325. // (We have to account for that the admin is allowed to view and edit account data from other users)
  326. if (($loginEmail != $adminLoginEmail) | (($loginEmail == $adminLoginEmail) && ($userID == getUserID($loginEmail))))
  327. {
  328. $loginFirstName = $formVars["firstName"];
  329. $loginLastName = $formVars["lastName"];
  330. }
  331. // If the user provided a new password, we need to UPDATE also the 'auth' table (which contains the login credentials for each user):
  332. if ($formVars["loginPassword"] != "") // a new password was provided by the user...
  333. {
  334. // Use the first two characters of the email as a salt for the password
  335. // Note: The user's email is NOT included as a regular form field for UPDATEs. To make it available as 'salt'
  336. // the user's email gets included as a hidden form tag by 'user_details.php'!
  337. $salt = substr($formVars["email"], 0, 2);
  338. // Create the encrypted password
  339. $stored_password = crypt($formVars["loginPassword"], $salt);
  340. // Update the user's password within the auth table
  341. $query = "UPDATE $tableAuth SET "
  342. . "password = " . quote_smart($stored_password)
  343. . " WHERE user_id = " . quote_smart($userID);
  344. $result = queryMySQLDatabase($query); // function 'queryMySQLDatabase()' is defined in 'include.inc.php'
  345. }
  346. }
  347. // If this was an INSERT, we'll also need to INSERT into the 'auth' table (which contains the login credentials for each user) as well as into some 'user_*' tables:
  348. // INSERTs are allowed to:
  349. // 1. EVERYONE who's not logged in (but ONLY if variable '$addNewUsers' in 'ini.inc.php' is set to "everyone"!)
  350. // (Note that this feature is actually only meant to add the very first user to the users table.
  351. // After you've done so, it is highly recommended to change the value of '$addNewUsers' to 'admin'!)
  352. // -or- 2. the ADMIN only (if variable '$addNewUsers' in 'ini.inc.php' is set to "admin")
  353. elseif ((!isset($_SESSION['loginEmail']) && ($addNewUsers == "everyone") && ($_REQUEST['userID'] == "")) | (isset($_SESSION['loginEmail']) && ($loginEmail == $adminLoginEmail) && ($_REQUEST['userID'] == ""))) // -> perform an insert:
  354. {
  355. // Get the user id that was created
  356. $userID = @ mysqli_insert_id($connection);
  357. // Use the first two characters of the email as a salt for the password
  358. $salt = substr($formVars["email"], 0, 2);
  359. // Create the encrypted password
  360. $stored_password = crypt($formVars["loginPassword"], $salt);
  361. // Insert a new user into the auth table
  362. $queryArray[] = "INSERT INTO $tableAuth SET "
  363. . "user_id = " . quote_smart($userID) . ", "
  364. . "email = " . quote_smart($formVars["email"]) . ", "
  365. . "password = " . quote_smart($stored_password);
  366. // Insert a row for this new user into the 'user_permissions' table:
  367. $defaultUserPermissionsString = implode("\", \"", $defaultUserPermissions); // '$defaultUserPermissions' is defined in 'ini.inc.php'
  368. // TODO: quote_smart()
  369. $queryArray[] = "INSERT INTO $tableUserPermissions VALUES (NULL, " . $userID . ", \"" . $defaultUserPermissionsString . "\")";
  370. // Note: Refbase lets you define default formats/styles/types in 'ini.inc.php' by their name (and not by ID numbers) which means that
  371. // the format/style/type names within the 'formats/styles/types' table must be unique!
  372. foreach($defaultUserExportFormats as $defaultUserExportFormat)
  373. {
  374. // get the 'format_id' for the record entry in table 'formats' whose 'format_name' matches that in '$defaultUserExportFormats' (defined in 'ini.inc.php'):
  375. $query = "SELECT format_id FROM $tableFormats WHERE format_name = " . quote_smart($defaultUserExportFormat) . " AND format_type = 'export'";
  376. $result = queryMySQLDatabase($query); // function 'queryMySQLDatabase()' is defined in 'include.inc.php'
  377. $row = mysqli_fetch_array($result);
  378. // Insert a row with the found format ID for this new user into the 'user_formats' table:
  379. $queryArray[] = "INSERT INTO $tableUserFormats VALUES (NULL, " . quote_smart($row["format_id"]) . ", " . quote_smart($userID) . ", \"true\")";
  380. }
  381. foreach($defaultUserCiteFormats as $defaultUserCiteFormat)
  382. {
  383. // get the 'format_id' for the record entry in table 'formats' whose 'format_name' matches that in '$defaultUserCiteFormats' (defined in 'ini.inc.php'):
  384. $query = "SELECT format_id FROM $tableFormats WHERE format_name = " . quote_smart($defaultUserCiteFormat) . " AND format_type = 'cite'";
  385. $result = queryMySQLDatabase($query); // function 'queryMySQLDatabase()' is defined in 'include.inc.php'
  386. $row = mysqli_fetch_array($result);
  387. // Insert a row with the found format ID for this new user into the 'user_formats' table:
  388. $queryArray[] = "INSERT INTO $tableUserFormats VALUES (NULL, " . quote_smart($row["format_id"]) . ", " . quote_smart($userID) . ", \"true\")";
  389. }
  390. foreach($defaultUserStyles as $defaultUserStyle)
  391. {
  392. // get the 'style_id' for the record entry in table 'styles' whose 'style_name' matches that in '$defaultUserStyles' (defined in 'ini.inc.php'):
  393. $query = "SELECT style_id FROM $tableStyles WHERE style_name = " . quote_smart($defaultUserStyle);
  394. $result = queryMySQLDatabase($query); // function 'queryMySQLDatabase()' is defined in 'include.inc.php'
  395. $row = mysqli_fetch_array($result);
  396. // Insert a row with the found style ID for this new user into the 'user_styles' table:
  397. $queryArray[] = "INSERT INTO $tableUserStyles VALUES (NULL, " . quote_smart($row["style_id"]) . ", " . quote_smart($userID) . ", \"true\")";
  398. }
  399. foreach($defaultUserTypes as $defaultUserType)
  400. {
  401. // get the 'type_id' for the record entry in table 'types' whose 'type_name' matches that in '$defaultUserTypes' (defined in 'ini.inc.php'):
  402. $query = "SELECT type_id FROM $tableTypes WHERE type_name = " . quote_smart($defaultUserType);
  403. $result = queryMySQLDatabase($query); // function 'queryMySQLDatabase()' is defined in 'include.inc.php'
  404. $row = mysqli_fetch_array($result);
  405. // Insert a row with the found type ID for this new user into the 'user_types' table:
  406. $queryArray[] = "INSERT INTO $tableUserTypes VALUES (NULL, " . quote_smart($row["type_id"]) . ", " . quote_smart($userID) . ", \"true\")";
  407. }
  408. // Insert a row for this new user into the 'user_options' table:
  409. $defaultUserOptionsString = implode("\", \"", $defaultUserOptions); // '$defaultUserOptions' is defined in 'ini.inc.php'
  410. $defaultUserOptionsString = preg_replace('/""/', "NULL", $defaultUserOptionsString); // replace empty string with NULL
  411. // TODO: quote_smart()
  412. $queryArray[] = "INSERT INTO $tableUserOptions VALUES (NULL, " . $userID . ", \"" . $defaultUserOptionsString . "\")";
  413. // RUN the queries on the database through the connection:
  414. foreach($queryArray as $query)
  415. $result = queryMySQLDatabase($query); // function 'queryMySQLDatabase()' is defined in 'include.inc.php'
  416. // if EVERYONE who's not logged in is able to add a new user (which is the case if the variable '$addNewUsers' in 'ini.inc.php'
  417. // is set to "everyone", see note above!), then we have to make sure that this visitor gets logged into his new
  418. // account - otherwise the following receipt page ('users_receipt.php') will generate an error:
  419. if (!isset($_SESSION['loginEmail']) && ($addNewUsers == "everyone") && ($_REQUEST['userID'] == ""))
  420. {
  421. // Log the user into his new account by assigning his information to
  422. // those variables that will be written to the '$_SESSION' variable below:
  423. $loginEmail = $formVars["email"];
  424. $loginUserID = $userID;
  425. $loginFirstName = $formVars["firstName"];
  426. $loginLastName = $formVars["lastName"];
  427. $abbrevInstitution = $formVars["abbrevInstitution"];
  428. $lastLogin = date('Y-m-d H:i:s'); // use the current date & time
  429. // Get the user permissions for the newly created user
  430. // and save all allowed user actions as semicolon-delimited string to the session variable 'user_permissions':
  431. getPermissions($userID, "user", true); // function 'getPermissions()' is defined in 'include.inc.php'
  432. }
  433. }
  434. // Write back session variables:
  435. saveSessionVariable("loginEmail", $loginEmail); // function 'saveSessionVariable()' is defined in 'include.inc.php'
  436. saveSessionVariable("loginUserID", $loginUserID);
  437. saveSessionVariable("loginFirstName", $loginFirstName);
  438. saveSessionVariable("loginLastName", $loginLastName);
  439. saveSessionVariable("abbrevInstitution", $abbrevInstitution);
  440. saveSessionVariable("lastLogin", $lastLogin);
  441. // If an authorized user uses 'user_details.php' to add a new user (-> 'userID' is empty!):
  442. if ((!isset($_SESSION['loginEmail']) && ($addNewUsers == "everyone") && ($_REQUEST['userID'] == "")) | (isset($_SESSION['loginEmail']) && ($loginEmail == $adminLoginEmail) && ($_REQUEST['userID'] == "")))
  443. {
  444. saveSessionVariable("userLanguage", $defaultLanguage); // '$defaultLanguage' is defined in 'ini.inc.php'
  445. saveSessionVariable("userRecordsPerPage", $defaultUserOptions['records_per_page']); // '$defaultUserOptions' is defined in 'ini.inc.php'
  446. saveSessionVariable("userAutoCompletions", $defaultUserOptions['show_auto_completions']);
  447. saveSessionVariable("userMainFields", $defaultUserOptions['main_fields']);
  448. }
  449. // Get all user groups specified by the current user
  450. // and (if some groups were found) save them as semicolon-delimited string to the session variable 'userGroups':
  451. getUserGroups($tableUserData, $loginUserID); // function 'getUserGroups()' is defined in 'include.inc.php'
  452. if ($loginEmail == $adminLoginEmail) // ('$adminLoginEmail' is specified in 'ini.inc.php')
  453. // Get all user groups specified by the admin
  454. // and (if some groups were found) save them as semicolon-delimited string to the session variable 'adminUserGroups':
  455. getUserGroups($tableUsers, $loginUserID); // function 'getUserGroups()' is defined in 'include.inc.php'
  456. // Similarly, get all queries that were saved previously by the current user
  457. // and (if some queries were found) save them as semicolon-delimited string to the session variable 'userQueries':
  458. getUserQueries($loginUserID); // function 'getUserQueries()' is defined in 'include.inc.php'
  459. // Clear the 'errors' and 'formVars' session variables so a future <form> is blank:
  460. deleteSessionVariable("errors"); // function 'deleteSessionVariable()' is defined in 'include.inc.php'
  461. deleteSessionVariable("formVars");
  462. // ----------------------------------------------
  463. // (4) Now show the user RECEIPT:
  464. header("Location: user_receipt.php?userID=$userID");
  465. // (5) CLOSE the database connection:
  466. disconnectFromMySQLDatabase(); // function 'disconnectFromMySQLDatabase()' is defined in 'include.inc.php'
  467. // --------------------------------------------------------------------
  468. ?>