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.

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