PageRenderTime 25ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/ojs/ojs-2.0.2-1/plugins/importexport/users/UserXMLParser.inc.php

https://github.com/mcrider/pkpUpgradeTestSuite
PHP | 382 lines | 215 code | 48 blank | 119 comment | 43 complexity | d13259ecefbf67462c16d1c58c7e407b MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1
  1. <?php
  2. /**
  3. * UserXMLParser.inc.php
  4. *
  5. * Copyright (c) 2003-2004 The Public Knowledge Project
  6. * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.
  7. *
  8. * @package db
  9. *
  10. * Class to import and export user data from an XML format.
  11. * See dbscripts/xml/dtd/users.dtd for the XML schema used.
  12. *
  13. * $Id: UserXMLParser.inc.php,v 1.4 2005/08/04 21:15:27 alec Exp $
  14. */
  15. /** Sample user datafile:
  16. ****************************************
  17. <users>
  18. <user>
  19. <username>username</username>
  20. <password>password</password>
  21. <first_name>FirstName</first_name>
  22. <last_name>LastName</last_name>
  23. <affiliation>Affiliation</affiliation>
  24. <email>user@pkp.sfu.ca</email>
  25. <role type="editor"/>
  26. <role type="sectionEditor"/>
  27. </user>
  28. </users>
  29. ****************************************
  30. */
  31. import('xml.XMLParser');
  32. class UserXMLParser {
  33. /** @var XMLParser the parser to use */
  34. var $parser;
  35. /** @var array ImportedUsers users to import */
  36. var $usersToImport;
  37. /** @var array ImportedUsers imported users */
  38. var $importedUsers;
  39. /** @var array error messages that occurred during import */
  40. var $errors;
  41. /** @var int the ID of the journal to import users into */
  42. var $journalId;
  43. /**
  44. * Constructor.
  45. * @param $journalId int assumed to be a valid journal ID
  46. */
  47. function UserXMLParser($journalId) {
  48. $this->parser = &new XMLParser();
  49. $this->journalId = $journalId;
  50. }
  51. /**
  52. * Parse an XML users file into a set of users to import.
  53. * @param $file string path to the XML file to parse
  54. * @return array ImportedUsers the collection of users read from the file
  55. */
  56. function &parseData($file) {
  57. $roleDao = &DAORegistry::getDAO('RoleDAO');
  58. $this->usersToImport = array();
  59. $tree = $this->parser->parse($file);
  60. if ($tree !== false) {
  61. foreach ($tree->getChildren() as $user) {
  62. if ($user->getName() == 'user') {
  63. // Match user element
  64. $newUser = &new ImportedUser();
  65. foreach ($user->getChildren() as $attrib) {
  66. switch ($attrib->getName()) {
  67. case 'username':
  68. // Usernames must be lowercase
  69. $newUser->setUsername(strtolower($attrib->getValue()));
  70. break;
  71. case 'password':
  72. $encrypted = $attrib->getAttribute('encrypted');
  73. if (isset($encrypted) && $encrypted == 'md5') {
  74. $newUser->setPassword($attrib->getValue());
  75. } else {
  76. $newUser->setUnencryptedPassword($attrib->getValue());
  77. }
  78. break;
  79. case 'first_name':
  80. $newUser->setFirstName($attrib->getValue());
  81. break;
  82. case 'middle_name':
  83. $newUser->setMiddleName($attrib->getValue());
  84. break;
  85. case 'last_name':
  86. $newUser->setLastName($attrib->getValue());
  87. break;
  88. case 'affiliation':
  89. $newUser->setAffiliation($attrib->getValue());
  90. break;
  91. case 'email':
  92. $newUser->setEmail($attrib->getValue());
  93. break;
  94. case 'phone':
  95. $newUser->setPhone($attrib->getValue());
  96. break;
  97. case 'fax':
  98. $newUser->setFax($attrib->getValue());
  99. break;
  100. case 'mailing_address':
  101. $newUser->setMailingAddress($attrib->getValue());
  102. break;
  103. case 'biography':
  104. $newUser->setBiography($attrib->getValue());
  105. break;
  106. case 'role':
  107. $roleType = $attrib->getAttribute('type');
  108. if ($this->validRole($roleType)) {
  109. $role = &new Role();
  110. $role->setRoleId($roleDao->getRoleIdFromPath($roleType));
  111. $newUser->addRole($role);
  112. }
  113. break;
  114. }
  115. }
  116. array_push($this->usersToImport, $newUser);
  117. }
  118. }
  119. }
  120. return $this->usersToImport;
  121. }
  122. /**
  123. * Import the parsed users into the system.
  124. * @param $sendNotify boolean send an email notification to each imported user containing their username and password
  125. * @param $continueOnError boolean continue to import remaining users if a failure occurs
  126. * @return boolean success
  127. */
  128. function importUsers($sendNotify = false, $continueOnError = false) {
  129. $success = true;
  130. $this->importedUsers = array();
  131. $this->errors = array();
  132. $userDao = &DAORegistry::getDAO('UserDAO');
  133. $roleDao = &DAORegistry::getDAO('RoleDAO');
  134. if ($sendNotify) {
  135. // Set up mail template to send to added users
  136. import('mail.MailTemplate');
  137. $mail = &new MailTemplate('USER_REGISTER');
  138. $journalDao = &DAORegistry::getDAO('JournalDAO');
  139. $journal = &$journalDao->getJournal($this->journalId);
  140. $mail->setFrom($journal->getSetting('contactEmail'), $journal->getSetting('contactName'));
  141. }
  142. for ($i=0, $count=count($this->usersToImport); $i < $count; $i++) {
  143. $user = &$this->usersToImport[$i];
  144. // If the email address already exists in the system,
  145. // then assign the user the username associated with that email address.
  146. if ($user->getEmail() != null) {
  147. $emailExists = $userDao->getUserByEmail($user->getEmail(), true);
  148. if ($emailExists != null) {
  149. $user->setUsername($emailExists->getUsername());
  150. }
  151. }
  152. if ($user->getUsername() == null) {
  153. $newUsername = true;
  154. $this->generateUsername($user);
  155. } else {
  156. $newUsername = false;
  157. }
  158. if ($user->getUnencryptedPassword() != null) {
  159. $user->setPassword(Validation::encryptCredentials($user->getUsername(), $user->getUnencryptedPassword()));
  160. } else if ($user->getPassword() == null) {
  161. $this->generatePassword($user);
  162. }
  163. if (!$newUsername) {
  164. // Check if user already exists
  165. $userExists = $userDao->getUserByUsername($user->getUsername(), true);
  166. if ($userExists != null) {
  167. $user->setUserId($userExists->getUserId());
  168. }
  169. } else {
  170. $userExists = false;
  171. }
  172. if ($newUsername || !$userExists) {
  173. // Create new user account
  174. // If the user's username was specified in the data file and
  175. // the username already exists, only the new roles are added for that user
  176. if (!$userDao->insertUser($user)) {
  177. // Failed to add user!
  178. $this->errors[] = sprintf('%s: %s (%s)',
  179. Locale::translate('manager.people.importUsers.failedToImportUser'),
  180. $user->getFullName(), $user->getUsername());
  181. if ($continueOnError) {
  182. // Skip to next user
  183. $success = false;
  184. continue;
  185. } else {
  186. return false;
  187. }
  188. }
  189. }
  190. // Enroll user in specified roles
  191. // If the user is already enrolled in a role, that role is skipped
  192. foreach ($user->getRoles() as $role) {
  193. $role->setUserId($user->getUserId());
  194. $role->setJournalId($this->journalId);
  195. if (!$roleDao->roleExists($role->getJournalId(), $role->getUserId(), $role->getRoleId())) {
  196. if (!$roleDao->insertRole($role)) {
  197. // Failed to add role!
  198. $this->errors[] = sprintf('%s: %s - %s (%s)',
  199. Locale::translate('manager.people.importUsers.failedToImportRole'),
  200. $role->getRoleName(),
  201. $user->getFullName(), $user->getUsername());
  202. if ($continueOnError) {
  203. // Continue to insert other roles for this user
  204. $success = false;
  205. continue;
  206. } else {
  207. return false;
  208. }
  209. }
  210. }
  211. }
  212. if ($sendNotify && !$userExists) {
  213. // Send email notification to user as if user just registered themselves
  214. $mail->addRecipient($user->getEmail(), $user->getFullName());
  215. $mail->sendWithParams(array(
  216. 'username' => $user->getUsername(),
  217. 'password' => $user->getUnencryptedPassword() == null ? '-' : $user->getUnencryptedPassword()
  218. ));
  219. $mail->clearRecipients();
  220. }
  221. array_push($this->importedUsers, $user);
  222. }
  223. return $success;
  224. }
  225. /**
  226. * Return the set of parsed users.
  227. * @return array ImportedUsers
  228. */
  229. function &getUsersToImport() {
  230. return $this->usersToImport;
  231. }
  232. /**
  233. * Specify the set of parsed users.
  234. * @param $usersToImport ImportedUsers
  235. */
  236. function setUsersToImport($users) {
  237. $this->usersToImport = $users;
  238. }
  239. /**
  240. * Return the set of users who were successfully imported.
  241. * @return array ImportedUsers
  242. */
  243. function &getImportedUsers() {
  244. return $this->importedUsers;
  245. }
  246. /**
  247. * Return an array of error messages that occurred during the import.
  248. * @return array string
  249. */
  250. function &getErrors() {
  251. return $this->errors;
  252. }
  253. /**
  254. * Check if a role type value identifies a valid role that can be imported.
  255. * Note we do not allow users to be imported into the "admin" role.
  256. * @param $roleType string
  257. * @return boolean
  258. */
  259. function validRole($roleType) {
  260. return isset($roleType) && in_array($roleType, array('manager', 'editor', 'sectionEditor', 'layoutEditor', 'reviewer', 'copyeditor', 'proofreader', 'author', 'reader'));
  261. }
  262. /**
  263. * Generate a unique username for a user based on the user's name.
  264. * @param $user ImportedUser the user to be modified by this function
  265. */
  266. function generateUsername(&$user) {
  267. $userDao = &DAORegistry::getDAO('UserDAO');
  268. $baseUsername = String::regexp_replace('/[^A-Z0-9]/i', '', $user->getLastName());
  269. if (empty($baseUsername)) {
  270. $baseUsername = String::regexp_replace('/[^A-Z0-9]/i', '', $user->getFirstName());
  271. }
  272. if (empty($username)) {
  273. // Default username if we can't use the user's last or first name
  274. $baseUsername = 'user';
  275. }
  276. for ($username = $baseUsername, $i=1; $userDao->userExistsByUsername($username, true); $i++) {
  277. $username = $baseUsername . $i;
  278. }
  279. $user->setUsername($username);
  280. }
  281. /**
  282. * Generate a random password for a user.
  283. * @param $user ImportedUser the user to be modified by this function
  284. */
  285. function generatePassword(&$user) {
  286. $password = Validation::generatePassword();
  287. $user->setUnencryptedPassword($password);
  288. $user->setPassword(Validation::encryptCredentials($user->getUsername(), $password));
  289. }
  290. }
  291. /**
  292. * Helper class representing a user imported from a user data file.
  293. */
  294. import('user.User');
  295. class ImportedUser extends User {
  296. /** @var array Roles of this user */
  297. var $roles;
  298. /**
  299. * Constructor.
  300. */
  301. function ImportedUser() {
  302. $this->roles = array();
  303. parent::User();
  304. }
  305. /**
  306. * Set the unencrypted form of the user's password.
  307. * @param $unencryptedPassword string
  308. */
  309. function setUnencryptedPassword($unencryptedPassword) {
  310. $this->setData('unencryptedPassword', $unencryptedPassword);
  311. }
  312. /**
  313. * Get the user's unencrypted password.
  314. * @return string
  315. */
  316. function getUnencryptedPassword() {
  317. return $this->getData('unencryptedPassword');
  318. }
  319. /**
  320. * Add a new role to this user.
  321. * @param $role Role
  322. */
  323. function addRole(&$role) {
  324. array_push($this->roles, $role);
  325. }
  326. /**
  327. * Get this user's roles.
  328. * @return array Roles
  329. */
  330. function &getRoles() {
  331. return $this->roles;
  332. }
  333. }
  334. ?>