Open Monograph Press  1.1
 All Classes Namespaces Functions Variables Groups Pages
PKPValidation.inc.php
1 <?php
2 
17 
26  static function &login($username, $password, &$reason, $remember = false) {
27  $implicitAuth = Config::getVar('security', 'implicit_auth');
28 
29  $reason = null;
30  $valid = false;
31  $userDao = DAORegistry::getDAO('UserDAO');
32 
33  if ($implicitAuth) { // Implicit auth
34  if (!Validation::isLoggedIn()) {
35  PluginRegistry::loadCategory('implicitAuth');
36 
37  // Call the implicitAuth hook. It will set user.
38 
39  HookRegistry::call('ImplicitAuthPlugin::implicitAuth', array(&$user));
40 
41  $valid=true;
42  }
43  } else { // Regular Auth
44  $user =& $userDao->getByUsername($username, true);
45 
46  if (!isset($user)) {
47  // User does not exist
48  return $valid;
49  }
50 
51  if ($user->getAuthId()) {
52  $authDao = DAORegistry::getDAO('AuthSourceDAO');
53  $auth =& $authDao->getPlugin($user->getAuthId());
54  }
55 
56  if (isset($auth)) {
57  // Validate against remote authentication source
58  $valid = $auth->authenticate($username, $password);
59  if ($valid) {
60  $oldEmail = $user->getEmail();
61  $auth->doGetUserInfo($user);
62  if ($user->getEmail() != $oldEmail) {
63  // FIXME requires email addresses to be unique; if changed email already exists, ignore
64  if ($userDao->userExistsByEmail($user->getEmail())) {
65  $user->setEmail($oldEmail);
66  }
67  }
68  }
69  } else {
70  // Validate against user database
71  $valid = ($user->getPassword() === Validation::encryptCredentials($username, $password));
72  }
73  }
74 
75  if (!$valid) {
76  // Login credentials are invalid
77  return $valid;
78 
79  } else {
80  return self::registerUserSession($user, $reason, $remember);
81  }
82  }
83 
91  static function &registerUserSession($user, &$reason, $remember = false) {
92  $userDao = DAORegistry::getDAO('UserDAO');
93 
94  if (!is_a($user, 'User')) return false;
95 
96  if ($user->getDisabled()) {
97  // The user has been disabled.
98  $reason = $user->getDisabledReason();
99  if ($reason === null) $reason = '';
100  return false;
101  }
102 
103  // The user is valid, mark user as logged in in current session
104  $sessionManager = SessionManager::getManager();
105 
106  // Regenerate session ID first
107  $sessionManager->regenerateSessionId();
108 
109  $session = $sessionManager->getUserSession();
110  $session->setSessionVar('userId', $user->getId());
111  $session->setUserId($user->getId());
112  $session->setSessionVar('username', $user->getUsername());
113  $session->setRemember($remember);
114 
115  if ($remember && Config::getVar('general', 'session_lifetime') > 0) {
116  // Update session expiration time
117  $sessionManager->updateSessionLifetime(time() + Config::getVar('general', 'session_lifetime') * 86400);
118  }
119 
120  $user->setDateLastLogin(Core::getCurrentDate());
121  $userDao->updateObject($user);
122 
123  return $user;
124  }
125 
130  static function logout() {
131  $sessionManager = SessionManager::getManager();
132  $session = $sessionManager->getUserSession();
133  $session->unsetSessionVar('userId');
134  $session->unsetSessionVar('signedInAs');
135  $session->setUserId(null);
136 
137  if ($session->getRemember()) {
138  $session->setRemember(0);
139  $sessionManager->updateSessionLifetime(0);
140  }
141 
142  $sessionDao = DAORegistry::getDAO('SessionDAO');
143  $sessionDao->updateObject($session);
144 
145  return true;
146  }
147 
152  static function redirectLogin($message = null) {
153  $args = array();
154 
155  if (isset($_SERVER['REQUEST_URI'])) {
156  $args['source'] = $_SERVER['REQUEST_URI'];
157  }
158  if ($message !== null) {
159  $args['loginMessage'] = $message;
160  }
161 
162  Request::redirect(null, 'login', null, null, $args);
163  }
164 
171  static function checkCredentials($username, $password) {
172  $userDao = DAORegistry::getDAO('UserDAO');
173  $user =& $userDao->getByUsername($username, false);
174 
175  $valid = false;
176  if (isset($user)) {
177  if ($user->getAuthId()) {
178  $authDao = DAORegistry::getDAO('AuthSourceDAO');
179  $auth =& $authDao->getPlugin($user->getAuthId());
180  }
181 
182  if (isset($auth)) {
183  $valid = $auth->authenticate($username, $password);
184  } else {
185  $valid = ($user->getPassword() === Validation::encryptCredentials($username, $password));
186  }
187  }
188 
189  return $valid;
190  }
191 
198  static function isAuthorized($roleId, $contextId = 0) {
199  if (!Validation::isLoggedIn()) {
200  return false;
201  }
202 
203  if ($contextId === -1) {
204  // Get context ID from request
205  $application = PKPApplication::getApplication();
206  $request = $application->getRequest();
207  $context = $request->getContext();
208  $contextId = $context == null ? 0 : $context->getId();
209  }
210 
211  $sessionManager = SessionManager::getManager();
212  $session = $sessionManager->getUserSession();
213  $user = $session->getUser();
214 
215  $roleDao = DAORegistry::getDAO('RoleDAO');
216  return $roleDao->userHasRole($contextId, $user->getId(), $roleId);
217  }
218 
228  static function encryptCredentials($username, $password, $encryption = false) {
229  $valueToEncrypt = $username . $password;
230 
231  if ($encryption == false) {
232  $encryption = Config::getVar('security', 'encryption');
233  }
234 
235  switch ($encryption) {
236  case 'sha1':
237  if (function_exists('sha1')) {
238  return sha1($valueToEncrypt);
239  }
240  case 'md5':
241  default:
242  return md5($valueToEncrypt);
243  }
244  }
245 
252  static function generatePassword($length = 8) {
253  $letters = 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
254  $numbers = '23456789';
255 
256  $password = "";
257  for ($i=0; $i<$length; $i++) {
258  $password .= mt_rand(1, 4) == 4 ? $numbers[mt_rand(0,strlen($numbers)-1)] : $letters[mt_rand(0, strlen($letters)-1)];
259  }
260  return $password;
261  }
262 
268  static function generatePasswordResetHash($userId) {
269  $userDao = DAORegistry::getDAO('UserDAO');
270  if (($user = $userDao->getById($userId)) == null) {
271  // No such user
272  return false;
273  }
274  return substr(md5($user->getId() . $user->getUsername() . $user->getPassword()), 0, 6);
275  }
276 
281  static function suggestUsername($firstName, $lastName) {
282  $initial = String::substr($firstName, 0, 1);
283 
284  $suggestion = String::regexp_replace('/[^a-zA-Z0-9_-]/', '', String::strtolower($initial . $lastName));
285  $userDao = DAORegistry::getDAO('UserDAO');
286  for ($i = ''; $userDao->userExistsByUsername($suggestion . $i); $i++);
287  return $suggestion . $i;
288  }
289 
294  static function isLoggedIn() {
295  $sessionManager = SessionManager::getManager();
296  $session = $sessionManager->getUserSession();
297 
298  $userId = $session->getUserId();
299  return isset($userId) && !empty($userId);
300  }
301 
306  static function isLoggedInAs() {
307  $sessionManager = SessionManager::getManager();
308  $session = $sessionManager->getUserSession();
309  $signedInAs = $session->getSessionVar('signedInAs');
310 
311  return isset($signedInAs) && !empty($signedInAs);
312  }
313 
318  static function isSiteAdmin() {
319  return Validation::isAuthorized(ROLE_ID_SITE_ADMIN);
320  }
321 
328  static function canAdminister($administeredUserId, $administratorUserId) {
329  $roleDao = DAORegistry::getDAO('RoleDAO');
330 
331  // You can administer yourself
332  if ($administeredUserId == $administratorUserId) return true;
333 
334  // You cannot adminster administrators
335  if ($roleDao->userHasRole(CONTEXT_SITE, $administeredUserId, ROLE_ID_SITE_ADMIN)) return false;
336 
337  // Otherwise, administrators can administer everyone
338  if ($roleDao->userHasRole(CONTEXT_SITE, $administratorUserId, ROLE_ID_SITE_ADMIN)) return true;
339 
340  // Check for administered user group assignments in other contexts
341  // that the administrator user doesn't have a manager role in.
342  $userGroupDao = DAORegistry::getDAO('UserGroupDAO');
343  $userGroups = $userGroupDao->getByUserId($administeredUserId);
344  while ($userGroup = $userGroups->next()) {
345  if ($userGroup->getContextId()!=CONTEXT_SITE && !$roleDao->userHasRole($userGroup->getContextId(), $administratorUserId, ROLE_ID_MANAGER)) {
346  // Found an assignment: disqualified.
347  return false;
348  }
349  }
350 
351  // Make sure the administering user has a manager role somewhere
352  $foundManagerRole = false;
353  $roles = $roleDao->getByUserId($administratorUserId);
354  foreach ($roles as $role) {
355  if ($role->getRoleId() == ROLE_ID_MANAGER) $foundManagerRole = true;
356  }
357  if (!$foundManagerRole) return false;
358 
359  // There were no conflicting roles. Permit administration.
360  return true;
361  }
362 }
363 
364 ?>
static & getDAO($name, $dbconn=null)
static & login($username, $password, &$reason, $remember=false)
static substr($string, $start, $length=false)
Definition: String.inc.php:187
static regexp_replace($pattern, $replacement, $subject, $limit=-1)
Definition: String.inc.php:377
static generatePasswordResetHash($userId)
static & loadCategory($category, $enabledOnly=false, $mainContextId=null)
redirect($context=null, $page=null, $op=null, $path=null, $params=null, $anchor=null)
static canAdminister($administeredUserId, $administratorUserId)
static generatePassword($length=8)
static getVar($section, $key, $default=null)
Definition: Config.inc.php:35
Class providing user validation/authentication operations.
static redirectLogin($message=null)
static isAuthorized($roleId, $contextId=0)
static call($hookName, $args=null)
static & registerUserSession($user, &$reason, $remember=false)
static strtolower($string)
Definition: String.inc.php:238
static suggestUsername($firstName, $lastName)
static encryptCredentials($username, $password, $encryption=false)
static checkCredentials($username, $password)
static getCurrentDate($ts=null)
Definition: Core.inc.php:95