Open Monograph Press  3.3.0
RegistrationForm.inc.php
1 <?php
19 import('lib.pkp.classes.form.Form');
20 
21 class RegistrationForm extends Form {
22 
24  var $user;
25 
28 
30  var $defaultAuth;
31 
34 
38  function __construct($site) {
39  parent::__construct('frontend/pages/userRegister.tpl');
40 
41  // Validation checks for this form
42  $form = $this;
43  $this->addCheck(new FormValidatorCustom($this, 'username', 'required', 'user.register.form.usernameExists', array(DAORegistry::getDAO('UserDAO'), 'userExistsByUsername'), array(), true));
44  $this->addCheck(new FormValidator($this, 'username', 'required', 'user.profile.form.usernameRequired'));
45  $this->addCheck(new FormValidator($this, 'password', 'required', 'user.profile.form.passwordRequired'));
46  $this->addCheck(new FormValidatorUsername($this, 'username', 'required', 'user.register.form.usernameAlphaNumeric'));
47  $this->addCheck(new FormValidatorLength($this, 'password', 'required', 'user.register.form.passwordLengthRestriction', '>=', $site->getMinPasswordLength()));
48  $this->addCheck(new FormValidatorCustom($this, 'password', 'required', 'user.register.form.passwordsDoNotMatch', function($password) use ($form) {
49  return $password == $form->getData('password2');
50  }));
51 
52  $this->addCheck(new FormValidator($this, 'givenName', 'required', 'user.profile.form.givenNameRequired'));
53 
54  $this->addCheck(new FormValidator($this, 'country', 'required', 'user.profile.form.countryRequired'));
55 
56  // Email checks
57  $this->addCheck(new FormValidatorEmail($this, 'email', 'required', 'user.profile.form.emailRequired'));
58  $this->addCheck(new FormValidatorCustom($this, 'email', 'required', 'user.register.form.emailExists', array(DAORegistry::getDAO('UserDAO'), 'userExistsByEmail'), array(), true));
59 
60  $this->captchaEnabled = Config::getVar('captcha', 'captcha_on_register') && Config::getVar('captcha', 'recaptcha');
61  if ($this->captchaEnabled) {
62  $request = Application::get()->getRequest();
63  $this->addCheck(new FormValidatorReCaptcha($this, $request->getRemoteAddr(), 'common.captcha.error.invalid-input-response', $request->getServerHost()));
64  }
65 
66  $authDao = DAORegistry::getDAO('AuthSourceDAO'); /* @var $authDao AuthSourceDAO */
67  $this->defaultAuth = $authDao->getDefaultPlugin();
68  if (isset($this->defaultAuth)) {
69  $auth = $this->defaultAuth;
70  $this->addCheck(new FormValidatorCustom($this, 'username', 'required', 'user.register.form.usernameExists', function($username) use ($form, $auth) {
71  return (!$auth->userExists($username) || $auth->authenticate($username, $form->getData('password')));
72  }));
73  }
74 
75  $context = Application::get()->getRequest()->getContext();
76  if ($context && $context->getData('privacyStatement')) {
77  $this->addCheck(new FormValidator($this, 'privacyConsent', 'required', 'user.profile.form.privacyConsentRequired'));
78  }
79 
80  $this->addCheck(new FormValidatorPost($this));
81  $this->addCheck(new FormValidatorCSRF($this));
82  }
83 
87  function fetch($request, $template = null, $display = false) {
88  $templateMgr = TemplateManager::getManager($request);
89  $site = $request->getSite();
90  $context = $request->getContext();
91 
92  if ($this->captchaEnabled) {
93  $publicKey = Config::getVar('captcha', 'recaptcha_public_key');
94  $reCaptchaHtml = '<div class="g-recaptcha" data-sitekey="' . $publicKey . '"></div>';
95  $templateMgr->assign(array(
96  'reCaptchaHtml' => $reCaptchaHtml,
97  'captchaEnabled' => true,
98  ));
99  }
100 
101  $isoCodes = new \Sokil\IsoCodes\IsoCodesFactory();
102  $countries = array();
103  foreach ($isoCodes->getCountries() as $country) {
104  $countries[$country->getAlpha2()] = $country->getLocalName();
105  }
106  asort($countries);
107  $templateMgr->assign('countries', $countries);
108 
109  import('lib.pkp.classes.user.form.UserFormHelper');
110  $userFormHelper = new UserFormHelper();
111  $userFormHelper->assignRoleContent($templateMgr, $request);
112 
113  $templateMgr->assign(array(
114  'source' =>$request->getUserVar('source'),
115  'minPasswordLength' => $site->getMinPasswordLength(),
116  'enableSiteWidePrivacyStatement' => Config::getVar('general', 'sitewide_privacy_statement'),
117  'siteWidePrivacyStatement' => $site->getData('privacyStatement'),
118  ));
119 
120  return parent::fetch($request, $template, $display);
121  }
122 
126  function initData() {
127  $this->_data = array(
128  'userLocales' => array(),
129  'userGroupIds' => array(),
130  );
131  }
132 
136  function readInputData() {
137  parent::readInputData();
138 
139  $this->readUserVars(array(
140  'username',
141  'password',
142  'password2',
143  'givenName',
144  'familyName',
145  'affiliation',
146  'email',
147  'country',
148  'interests',
149  'emailConsent',
150  'privacyConsent',
151  'readerGroup',
152  'reviewerGroup',
153  ));
154 
155  if ($this->captchaEnabled) {
156  $this->readUserVars(array(
157  'g-recaptcha-response',
158  ));
159  }
160 
161  // Collect the specified user group IDs into a single piece of data
162  $this->setData('userGroupIds', array_merge(
163  array_keys((array) $this->getData('readerGroup')),
164  array_keys((array) $this->getData('reviewerGroup'))
165  ));
166  }
167 
171  function validate($callHooks = true) {
172  $request = Application::get()->getRequest();
173 
174  // Ensure the consent checkbox has been completed for the site and any user
175  // group signups if we're in the site-wide registration form
176  if (!$request->getContext()) {
177 
178  if ($request->getSite()->getData('privacyStatement')) {
179  $privacyConsent = $this->getData('privacyConsent');
180  if (!is_array($privacyConsent) || !array_key_exists(CONTEXT_ID_NONE, $privacyConsent)) {
181  $this->addError('privacyConsent[' . CONTEXT_ID_NONE . ']', __('user.register.form.missingSiteConsent'));
182  }
183  }
184 
185  if (!Config::getVar('general', 'sitewide_privacy_statement')) {
186  $userGroupDao = DAORegistry::getDAO('UserGroupDAO'); /* @var $userGroupDao UserGroupDAO */
187  $contextIds = array();
188  foreach ($this->getData('userGroupIds') as $userGroupId) {
189  $userGroup = $userGroupDao->getById($userGroupId);
190  $contextIds[] = $userGroup->getContextId();
191  }
192 
193  $contextIds = array_unique($contextIds);
194  if (!empty($contextIds)) {
195  $contextDao = Application::getContextDao();
196  $privacyConsent = (array) $this->getData('privacyConsent');
197  foreach ($contextIds as $contextId) {
198  $context = $contextDao->getById($contextId);
199  if ($context->getData('privacyStatement') && !array_key_exists($contextId, $privacyConsent)) {
200  $this->addError('privacyConsent[' . $contextId . ']', __('user.register.form.missingContextConsent'));
201  break;
202  }
203  }
204  }
205  }
206  }
207 
208  return parent::validate($callHooks);
209  }
210 
215  function execute(...$functionArgs) {
216  $requireValidation = Config::getVar('email', 'require_validation');
217  $userDao = DAORegistry::getDAO('UserDAO'); /* @var $userDao UserDAO */
218 
219  // New user
220  $this->user = $user = $userDao->newDataObject();
221 
222  $user->setUsername($this->getData('username'));
223 
224  // The multilingual user data (givenName, familyName and affiliation) will be saved
225  // in the current UI locale and copied in the site's primary locale too
226  $request = Application::get()->getRequest();
227  $site = $request->getSite();
228  $sitePrimaryLocale = $site->getPrimaryLocale();
229  $currentLocale = AppLocale::getLocale();
230 
231  // Set the base user fields (name, etc.)
232  $user->setGivenName($this->getData('givenName'), $currentLocale);
233  $user->setFamilyName($this->getData('familyName'), $currentLocale);
234  $user->setEmail($this->getData('email'));
235  $user->setCountry($this->getData('country'));
236  $user->setAffiliation($this->getData('affiliation'), $currentLocale);
237 
238  if ($sitePrimaryLocale != $currentLocale) {
239  $user->setGivenName($this->getData('givenName'), $sitePrimaryLocale);
240  $user->setFamilyName($this->getData('familyName'), $sitePrimaryLocale);
241  $user->setAffiliation($this->getData('affiliation'), $sitePrimaryLocale);
242  }
243 
244  $user->setDateRegistered(Core::getCurrentDate());
245  $user->setInlineHelp(1); // default new users to having inline help visible.
246 
247  if (isset($this->defaultAuth)) {
248  $user->setPassword($this->getData('password'));
249  // FIXME Check result and handle failures
250  $this->defaultAuth->doCreateUser($user);
251  $user->setAuthId($this->defaultAuth->authId);
252  }
253  $user->setPassword(Validation::encryptCredentials($this->getData('username'), $this->getData('password')));
254 
255  if ($requireValidation) {
256  // The account should be created in a disabled
257  // state.
258  $user->setDisabled(true);
259  $user->setDisabledReason(__('user.login.accountNotValidated', array('email' => $this->getData('email'))));
260  }
261 
262  parent::execute(...$functionArgs);
263 
264  $userDao->insertObject($user);
265  $userId = $user->getId();
266  if (!$userId) {
267  return false;
268  }
269 
270  // Associate the new user with the existing session
271  $sessionManager = SessionManager::getManager();
272  $session = $sessionManager->getUserSession();
273  $session->setSessionVar('username', $user->getUsername());
274 
275  // Save the selected roles or assign the Reader role if none selected
276  if ($request->getContext() && !$this->getData('reviewerGroup')) {
277  $userGroupDao = DAORegistry::getDAO('UserGroupDAO'); /* @var $userGroupDao UserGroupDAO */
278  $defaultReaderGroup = $userGroupDao->getDefaultByRoleId($request->getContext()->getId(), ROLE_ID_READER);
279  if ($defaultReaderGroup) $userGroupDao->assignUserToGroup($user->getId(), $defaultReaderGroup->getId(), $request->getContext()->getId());
280  } else {
281  import('lib.pkp.classes.user.form.UserFormHelper');
282  $userFormHelper = new UserFormHelper();
283  $userFormHelper->saveRoleContent($this, $user);
284  }
285 
286  // Save the email notification preference
287  if ($request->getContext() && !$this->getData('emailConsent')) {
288 
289  // Get the public notification types
290  import('classes.notification.form.NotificationSettingsForm');
291  $notificationSettingsForm = new NotificationSettingsForm();
292  $notificationCategories = $notificationSettingsForm->getNotificationSettingCategories();
293  foreach ($notificationCategories as $notificationCategory) {
294  if ($notificationCategory['categoryKey'] === 'notification.type.public') {
295  $publicNotifications = $notificationCategory['settings'];
296  }
297  }
298  if (isset($publicNotifications)) {
299  $notificationSubscriptionSettingsDao = DAORegistry::getDAO('NotificationSubscriptionSettingsDAO'); /* @var $notificationSubscriptionSettingsDao NotificationSubscriptionSettingsDAO */
300  $notificationSubscriptionSettingsDao->updateNotificationSubscriptionSettings(
301  'blocked_emailed_notification',
302  $publicNotifications,
303  $user->getId(),
304  $request->getContext()->getId()
305  );
306  }
307  }
308 
309  // Insert the user interests
310  import('lib.pkp.classes.user.InterestManager');
311  $interestManager = new InterestManager();
312  $interestManager->setInterestsForUser($user, $this->getData('interests'));
313 
314  import('lib.pkp.classes.mail.MailTemplate');
315  if ($requireValidation) {
316  // Create an access key
317  import('lib.pkp.classes.security.AccessKeyManager');
318  $accessKeyManager = new AccessKeyManager();
319  $accessKey = $accessKeyManager->createKey('RegisterContext', $user->getId(), null, Config::getVar('email', 'validation_timeout'));
320 
321  // Send email validation request to user
322  $mail = new MailTemplate('USER_VALIDATE');
323  $this->_setMailFrom($request, $mail);
324  $context = $request->getContext();
325  $contextPath = $context ? $context->getPath() : null;
326  $mail->assignParams(array(
327  'userFullName' => $user->getFullName(),
328  'contextName' => $context ? $context->getLocalizedName() : $site->getLocalizedTitle(),
329  'activateUrl' => $request->url($contextPath, 'user', 'activateUser', array($this->getData('username'), $accessKey))
330  ));
331  $mail->addRecipient($user->getEmail(), $user->getFullName());
332  if (!$mail->send()) {
333  import('classes.notification.NotificationManager');
334  $notificationMgr = new NotificationManager();
335  $notificationMgr->createTrivialNotification($user->getId(), NOTIFICATION_TYPE_ERROR, array('contents' => __('email.compose.error')));
336  }
337  unset($mail);
338  }
339  return $userId;
340  }
341 
347  function _setMailFrom($request, $mail) {
348  $site = $request->getSite();
349  $context = $request->getContext();
350 
351  // Set the sender based on the current context
352  if ($context && $context->getData('supportEmail')) {
353  $mail->setReplyTo($context->getData('supportEmail'), $context->getData('supportName'));
354  } else {
355  $mail->setReplyTo($site->getLocalizedContactEmail(), $site->getLocalizedContactName());
356  }
357  }
358 }
SessionManager\getManager
static getManager()
Definition: SessionManager.inc.php:124
Validation\encryptCredentials
static encryptCredentials($username, $password, $encryption=false, $legacy=false)
Definition: Validation.inc.php:255
RegistrationForm\initData
initData()
Definition: RegistrationForm.inc.php:138
FormValidatorUsername
Form validation check for usernames (lowercase alphanumeric with interior dash/underscore.
Definition: FormValidatorUsername.inc.php:19
FormValidatorLength
Form validation check that checks if a field's length meets certain requirements.
Definition: FormValidatorLength.inc.php:18
DAORegistry\getDAO
static & getDAO($name, $dbconn=null)
Definition: DAORegistry.inc.php:57
RegistrationForm\fetch
fetch($request, $template=null, $display=false)
Definition: RegistrationForm.inc.php:99
RegistrationForm\execute
execute(... $functionArgs)
Definition: RegistrationForm.inc.php:227
AccessKeyManager
Class defining operations for AccessKey management.
Definition: AccessKeyManager.inc.php:18
FormValidatorReCaptcha
Form validation check reCaptcha values.
Definition: FormValidatorReCaptcha.inc.php:20
Form\setData
setData($key, $value=null)
Definition: Form.inc.php:229
Form\readUserVars
readUserVars($vars)
Definition: Form.inc.php:378
FormValidatorEmail
Form validation check for email addresses.
Definition: FormValidatorEmail.inc.php:20
Form\getData
getData($key)
Definition: Form.inc.php:220
FormValidatorPost
Form validation check to make sure the form is POSTed.
Definition: FormValidatorPost.inc.php:18
RegistrationForm\_setMailFrom
_setMailFrom($request, $mail)
Definition: RegistrationForm.inc.php:359
Form\addError
addError($field, $message)
Definition: Form.inc.php:404
NotificationSettingsForm
Form to edit notification settings.
Definition: NotificationSettingsForm.inc.php:19
RegistrationForm
Form for user registration.
Definition: RegistrationForm.inc.php:21
MailTemplate
Subclass of Mail for mailing a template email.
Definition: MailTemplate.inc.php:21
RegistrationForm\$existingUser
$existingUser
Definition: RegistrationForm.inc.php:33
Config\getVar
static getVar($section, $key, $default=null)
Definition: Config.inc.php:35
PKPTemplateManager\getManager
static & getManager($request=null)
Definition: PKPTemplateManager.inc.php:1239
RegistrationForm\readInputData
readInputData()
Definition: RegistrationForm.inc.php:148
InterestManager
Handle user interest functions.
Definition: InterestManager.inc.php:16
FormValidator
Class to represent a form validation check.
Definition: FormValidator.inc.php:23
Core\getCurrentDate
static getCurrentDate($ts=null)
Definition: Core.inc.php:63
Form\addCheck
addCheck($formValidator)
Definition: Form.inc.php:395
RegistrationForm\__construct
__construct($site)
Definition: RegistrationForm.inc.php:50
NotificationManager
Definition: NotificationManager.inc.php:19
RegistrationForm\$defaultAuth
$defaultAuth
Definition: RegistrationForm.inc.php:39
FormValidatorCSRF
Form validation check to make sure the CSRF token is correct.
Definition: FormValidatorCSRF.inc.php:18
Form
Class defining basic operations for handling HTML forms.
Definition: Form.inc.php:47
RegistrationForm\validate
validate($callHooks=true)
Definition: RegistrationForm.inc.php:183
PKPApplication\get
static get()
Definition: PKPApplication.inc.php:235
FormValidatorCustom
Form validation check with a custom user function performing the validation check.
Definition: FormValidatorCustom.inc.php:18
AppLocale\getLocale
static getLocale()
Definition: env1/MockAppLocale.inc.php:40
RegistrationForm\$captchaEnabled
$captchaEnabled
Definition: RegistrationForm.inc.php:45
UserFormHelper
Helper functions for shared user form concerns.
Definition: UserFormHelper.inc.php:16
RegistrationForm\$user
$user
Definition: RegistrationForm.inc.php:27