File: UserXMLParser.inc.php

package info (click to toggle)
ojs 2.2.4%2Bdfsg2-1
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 40,820 kB
  • ctags: 25,186
  • sloc: xml: 131,068; php: 87,237; sh: 75; makefile: 27
file content (416 lines) | stat: -rw-r--r-- 12,219 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
<?php

/**
 * @file UserXMLParser.inc.php
 *
 * Copyright (c) 2003-2009 John Willinsky
 * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.
 *
 * @class UserXMLParser
 * @ingroup plugins_importexport_users
 *
 * @brief Class to import and export user data from an XML format.
 * See dbscripts/xml/dtd/users.dtd for the XML schema used.
 */

// $Id$


import('xml.XMLParser');

class UserXMLParser {

	/** @var XMLParser the parser to use */
	var $parser;

	/** @var array ImportedUsers users to import */
	var $usersToImport;

	/** @var array ImportedUsers imported users */
	var $importedUsers;

	/** @var array error messages that occurred during import */
	var $errors;

	/** @var int the ID of the journal to import users into */
	var $journalId;

	/**
	 * Constructor.
	 * @param $journalId int assumed to be a valid journal ID
	 */
	function UserXMLParser($journalId) {
		$this->parser = &new XMLParser();
		$this->journalId = $journalId;
	}

	/**
	 * Parse an XML users file into a set of users to import.
	 * @param $file string path to the XML file to parse
	 * @return array ImportedUsers the collection of users read from the file
	 */
	function &parseData($file) {	
		$roleDao = &DAORegistry::getDAO('RoleDAO');

		$success = true;
		$this->usersToImport = array();
		$tree = $this->parser->parse($file);

		$journalDao = &DAORegistry::getDAO('JournalDAO');
		$journal = &$journalDao->getJournal($this->journalId);
		$journalPrimaryLocale = Locale::getPrimaryLocale();

		$site = &Request::getSite();
		$siteSupportedLocales = $site->getSupportedLocales();

		if ($tree !== false) {
			foreach ($tree->getChildren() as $user) {
				if ($user->getName() == 'user') {
					// Match user element
					$newUser = &new ImportedUser();

					foreach ($user->getChildren() as $attrib) {
						switch ($attrib->getName()) {
							case 'username':
								// Usernames must be lowercase
								$newUser->setUsername(strtolower($attrib->getValue()));
								break;
							case 'password':
								$newUser->setMustChangePassword($attrib->getAttribute('change') == 'true'?1:0);
								$encrypted = $attrib->getAttribute('encrypted');
								if (isset($encrypted) && $encrypted !== 'plaintext') {
									$ojsEncryptionScheme = Config::getVar('security', 'encryption');
									if ($encrypted != $ojsEncryptionScheme) {
										$this->errors[] = Locale::translate('plugins.importexport.users.import.encryptionMismatch', array('importHash' => $encrypted, 'ojsHash' => $ojsEncryptionScheme));
									}
									$newUser->setPassword($attrib->getValue());
								} else {
									$newUser->setUnencryptedPassword($attrib->getValue());
								}
								break;
							case 'salutation':
								$newUser->setSalutation($attrib->getValue());
								break;
							case 'first_name':
								$newUser->setFirstName($attrib->getValue());
								break;
							case 'middle_name':
								$newUser->setMiddleName($attrib->getValue());
								break;
							case 'last_name':
								$newUser->setLastName($attrib->getValue());
								break;
							case 'initials':
								$newUser->setInitials($attrib->getValue());
								break;
							case 'gender':
								$newUser->setGender($attrib->getValue());
								break;
							case 'affiliation':
								$newUser->setAffiliation($attrib->getValue());
								break;
							case 'email':
								$newUser->setEmail($attrib->getValue());
								break;
							case 'url':
								$newUser->setUrl($attrib->getValue());
								break;
							case 'phone':
								$newUser->setPhone($attrib->getValue());
								break;
							case 'fax':
								$newUser->setFax($attrib->getValue());
								break;
							case 'mailing_address':
								$newUser->setMailingAddress($attrib->getValue());
								break;
							case 'country':
								$newUser->setCountry($attrib->getValue());
								break;
							case 'signature':
								$locale = $attrib->getAttribute('locale');
								if (empty($locale)) $locale = $journalPrimaryLocale;
								$newUser->setInterests($attrib->getValue(), $locale);
								break;
							case 'interests':
								$locale = $attrib->getAttribute('locale');
								if (empty($locale)) $locale = $journalPrimaryLocale;
								$newUser->setInterests($attrib->getValue(), $locale);
								break;
							case 'biography':
								$locale = $attrib->getAttribute('locale');
								if (empty($locale)) $locale = $journalPrimaryLocale;
								$newUser->setBiography($attrib->getValue(), $locale);
								break;
							case 'locales':
								$locales = array();
								foreach (explode(':', $attrib->getValue()) as $locale) {
									if (Locale::isLocaleValid($locale) && in_array($locale, $siteSupportedLocales)) {
										array_push($locales, $locale);
									}
								}
								$newUser->setLocales($locales);
								break;
							case 'role':
								$roleType = $attrib->getAttribute('type');
								if ($this->validRole($roleType)) {
									$role = &new Role();
									$role->setRoleId($roleDao->getRoleIdFromPath($roleType));
									$newUser->addRole($role);
								}
								break;
						}
					}
					array_push($this->usersToImport, $newUser);
				}
			}
		}

		return $this->usersToImport;
	}

	/**
	 * Import the parsed users into the system.
	 * @param $sendNotify boolean send an email notification to each imported user containing their username and password
	 * @param $continueOnError boolean continue to import remaining users if a failure occurs
	 * @return boolean success
	 */
	function importUsers($sendNotify = false, $continueOnError = false) {
		$success = true;
		$this->importedUsers = array();
		$this->errors = array();

		$userDao = &DAORegistry::getDAO('UserDAO');
		$roleDao = &DAORegistry::getDAO('RoleDAO');

		if ($sendNotify) {
			// Set up mail template to send to added users
			import('mail.MailTemplate');
			$mail = &new MailTemplate('USER_REGISTER');

			$journalDao = &DAORegistry::getDAO('JournalDAO');
			$journal = &$journalDao->getJournal($this->journalId);
			$mail->setFrom($journal->getSetting('contactEmail'), $journal->getSetting('contactName'));
		}

		for ($i=0, $count=count($this->usersToImport); $i < $count; $i++) {
			$user = &$this->usersToImport[$i];
			// If the email address already exists in the system,
			// then assign the user the username associated with that email address.
			if ($user->getEmail() != null) {
				$emailExists = $userDao->getUserByEmail($user->getEmail(), true);
				if ($emailExists != null) {
					$user->setUsername($emailExists->getUsername());
				}
			}
			if ($user->getUsername() == null) {
				$newUsername = true;
				$this->generateUsername($user);
			} else {
				$newUsername = false;
			}
			if ($user->getUnencryptedPassword() != null) {
				$user->setPassword(Validation::encryptCredentials($user->getUsername(), $user->getUnencryptedPassword()));
			} else if ($user->getPassword() == null) {
				$this->generatePassword($user);
			}

			if (!$newUsername) {
				// Check if user already exists
				$userExists = $userDao->getUserByUsername($user->getUsername(), true);
				if ($userExists != null) {
					$user->setUserId($userExists->getUserId());
				}
			} else {
				$userExists = false;
			}

			if ($newUsername || !$userExists) {
				// Create new user account
				// If the user's username was specified in the data file and
				// the username already exists, only the new roles are added for that user
				if (!$userDao->insertUser($user)) {
					// Failed to add user!
					$this->errors[] = sprintf('%s: %s (%s)',
						Locale::translate('manager.people.importUsers.failedToImportUser'),
						$user->getFullName(), $user->getUsername());

					if ($continueOnError) {
						// Skip to next user
						$success = false;
						continue;
					} else {
						return false;
					}
				}
			}

			// Enroll user in specified roles
			// If the user is already enrolled in a role, that role is skipped
			foreach ($user->getRoles() as $role) {
				$role->setUserId($user->getUserId());
				$role->setJournalId($this->journalId);
				if (!$roleDao->roleExists($role->getJournalId(), $role->getUserId(), $role->getRoleId())) {
					if (!$roleDao->insertRole($role)) {
						// Failed to add role!
						$this->errors[] = sprintf('%s: %s - %s (%s)',
							Locale::translate('manager.people.importUsers.failedToImportRole'),
							$role->getRoleName(),
							$user->getFullName(), $user->getUsername());

						if ($continueOnError) {
							// Continue to insert other roles for this user
							$success = false;
							continue;
						} else {
							return false;
						}
					}
				}
			}

			if ($sendNotify && !$userExists) {
				// Send email notification to user as if user just registered themselves			
				$mail->addRecipient($user->getEmail(), $user->getFullName());
				$mail->sendWithParams(array(
					'username' => $user->getUsername(),
					'password' => $user->getUnencryptedPassword() ==  null ? '-' : $user->getUnencryptedPassword(),
					'userFullName' => $user->getFullName()
				));
				$mail->clearRecipients();
			}

			array_push($this->importedUsers, $user);
		}

		return $success;
	}

	/**
	 * Return the set of parsed users.
	 * @return array ImportedUsers
	 */
	function &getUsersToImport() {
		return $this->usersToImport;
	}

	/**
	 * Specify the set of parsed users.
	 * @param $usersToImport ImportedUsers
	 */
	function setUsersToImport($users) {
		$this->usersToImport = $users;
	}

	/**
	 * Return the set of users who were successfully imported.
	 * @return array ImportedUsers
	 */
	function &getImportedUsers() {
		return $this->importedUsers;
	}

	/**
	 * Return an array of error messages that occurred during the import.
	 * @return array string
	 */
	function &getErrors() {
		return $this->errors;
	}

	/**
	 * Check if a role type value identifies a valid role that can be imported.
	 * Note we do not allow users to be imported into the "admin" role.
	 * @param $roleType string
	 * @return boolean
	 */
	function validRole($roleType) {
		return isset($roleType) && in_array($roleType, array('manager', 'editor', 'sectionEditor', 'layoutEditor', 'reviewer', 'copyeditor', 'proofreader', 'author', 'reader', 'subscriptionManager'));
	}

	/**
	 * Generate a unique username for a user based on the user's name.
	 * @param $user ImportedUser the user to be modified by this function
	 */
	function generateUsername(&$user) {
		$userDao = &DAORegistry::getDAO('UserDAO');
		$baseUsername = String::regexp_replace('/[^A-Z0-9]/i', '', $user->getLastName());
		if (empty($baseUsername)) {
			$baseUsername = String::regexp_replace('/[^A-Z0-9]/i', '', $user->getFirstName());
		}
		if (empty($username)) {
			// Default username if we can't use the user's last or first name
			$baseUsername = 'user';
		}

		for ($username = $baseUsername, $i=1; $userDao->userExistsByUsername($username, true); $i++) {
			$username = $baseUsername . $i;
		}
		$user->setUsername($username);
	}

	/**
	 * Generate a random password for a user.
	 * @param $user ImportedUser the user to be modified by this function
	 */
	function generatePassword(&$user) {
		$password = Validation::generatePassword();
		$user->setUnencryptedPassword($password);
		$user->setPassword(Validation::encryptCredentials($user->getUsername(), $password));
	}

}


/**
 * Helper class representing a user imported from a user data file.
 */
import('user.User');
class ImportedUser extends User {

	/** @var array Roles of this user */
	var $roles;

	/**
	 * Constructor.
	 */
	function ImportedUser() {
		$this->roles = array();
		parent::User();
	}

	/**
	 * Set the unencrypted form of the user's password.
	 * @param $unencryptedPassword string
	 */
	function setUnencryptedPassword($unencryptedPassword) {
		$this->setData('unencryptedPassword', $unencryptedPassword);	
	}

	/**
	 * Get the user's unencrypted password.
	 * @return string
	 */
	function getUnencryptedPassword() {
		return $this->getData('unencryptedPassword');
	}

	/**
	 * Add a new role to this user.
	 * @param $role Role
	 */
	function addRole(&$role) {
		array_push($this->roles, $role);
	}

	/**
	 * Get this user's roles.
	 * @return array Roles
	 */
	function &getRoles() {
		return $this->roles;
	}

}

?>