/** 
  * Processes the request to create a new user (from the admin controls).
  * 
  * Processes the request from the user creation form, checking that:
  * 1. The username and email are not already in use;
  * 2. The logged-in user has the necessary permissions to update the posted field(s);
  * 3. The submitted data is valid.
  * This route requires authentication.
  * Request type: POST
  * @see formUserCreate
  */
 public function createUser()
 {
     $post = $this->_app->request->post();
     // Load the request schema
     $requestSchema = new \Fortress\RequestSchema($this->_app->config('schema.path') . "/forms/user-create.json");
     // Get the alert message stream
     $ms = $this->_app->alerts;
     // Access-controlled resource
     if (!$this->_app->user->checkAccess('create_account')) {
         $ms->addMessageTranslated("danger", "ACCESS_DENIED");
         $this->_app->halt(403);
     }
     // Set up Fortress to process the request
     $rf = new \Fortress\HTTPRequestFortress($ms, $requestSchema, $post);
     // Sanitize data
     $rf->sanitize();
     // Validate, and halt on validation errors.
     $error = !$rf->validate(true);
     // Get the filtered data
     $data = $rf->data();
     // Remove csrf_token from object data
     $rf->removeFields(['csrf_token']);
     // Perform desired data transformations on required fields.  Is this a feature we could add to Fortress?
     $data['display_name'] = trim($data['display_name']);
     $data['email'] = strtolower(trim($data['email']));
     $data['flag_verified'] = 1;
     // Set password as empty on initial creation.  We will then send email so new user can set it themselves via secret token
     $data['password'] = "";
     // Check if username or email already exists
     if (UserLoader::exists($data['user_name'], 'user_name')) {
         $ms->addMessageTranslated("danger", "ACCOUNT_USERNAME_IN_USE", $data);
         $error = true;
     }
     if (UserLoader::exists($data['email'], 'email')) {
         $ms->addMessageTranslated("danger", "ACCOUNT_EMAIL_IN_USE", $data);
         $error = true;
     }
     // Halt on any validation errors
     if ($error) {
         $this->_app->halt(400);
     }
     // Get default primary group (is_default = GROUP_DEFAULT_PRIMARY)
     $primaryGroup = GroupLoader::fetch(GROUP_DEFAULT_PRIMARY, "is_default");
     // Set default values if not specified or not authorized
     if (!isset($data['locale']) || !$this->_app->user->checkAccess("update_account_setting", ["property" => "locale"])) {
         $data['locale'] = $this->_app->site->default_locale;
     }
     if (!isset($data['title']) || !$this->_app->user->checkAccess("update_account_setting", ["property" => "title"])) {
         // Set default title for new users
         $data['title'] = $primaryGroup->new_user_title;
     }
     if (!isset($data['primary_group_id']) || !$this->_app->user->checkAccess("update_account_setting", ["property" => "primary_group_id"])) {
         $data['primary_group_id'] = $primaryGroup->id;
     }
     // Set groups to default groups if not specified or not authorized to set groups
     if (!isset($data['groups']) || !$this->_app->user->checkAccess("update_account_setting", ["property" => "groups"])) {
         $default_groups = GroupLoader::fetchAll(GROUP_DEFAULT, "is_default");
         $data['groups'] = [];
         foreach ($default_groups as $group_id => $group) {
             $data['groups'][$group_id] = "1";
         }
     }
     // Create the user
     $user = new User($data);
     // Add user to groups, including selected primary group
     $user->addGroup($data['primary_group_id']);
     foreach ($data['groups'] as $group_id => $is_member) {
         if ($is_member == "1") {
             $user->addGroup($group_id);
         }
     }
     // Create events - account creation and password reset
     $user->newEventSignUp($this->_app->user);
     $user->newEventPasswordReset();
     // Save user again after creating events
     $user->save();
     // Send an email to the user's email address to set up password
     $twig = $this->_app->view()->getEnvironment();
     $template = $twig->loadTemplate("mail/password-create.twig");
     $notification = new Notification($template);
     $notification->fromWebsite();
     // Automatically sets sender and reply-to
     $notification->addEmailRecipient($user->email, $user->display_name, ['user' => $user, 'create_password_expiration' => $this->_app->site->create_password_expiration / 3600 . " hours"]);
     try {
         $notification->send();
     } catch (\Exception\phpmailerException $e) {
         $ms->addMessageTranslated("danger", "MAIL_ERROR");
         error_log('Mailer Error: ' . $e->errorMessage());
         $this->_app->halt(500);
     }
     // Success message
     $ms->addMessageTranslated("success", "ACCOUNT_CREATION_COMPLETE", $data);
 }
 /**
  * Processes an new account registration request.
  *
  * Processes the request from the form on the registration page, checking that:
  * 1. The honeypot was not modified;
  * 2. The master account has already been created (during installation);
  * 3. Account registration is enabled;
  * 4. The user is not already logged in;
  * 5. Valid information was entered;
  * 6. The captcha, if enabled, is correct;
  * 7. The username and email are not already taken.
  * Automatically sends an activation link upon success, if account activation is enabled.
  * This route is "public access".
  * Request type: POST
  * Returns the User Object for the user record that was created.
  */
 public function register()
 {
     // POST: user_name, display_name, email, title, password, passwordc, captcha, spiderbro, csrf_token
     $post = $this->_app->request->post();
     // Get the alert message stream
     $ms = $this->_app->alerts;
     // Check the honeypot. 'spiderbro' is not a real field, it is hidden on the main page and must be submitted with its default value for this to be processed.
     if (!$post['spiderbro'] || $post['spiderbro'] != "http://") {
         error_log("Possible spam received:" . print_r($this->_app->request->post(), true));
         $ms->addMessage("danger", "Aww hellllls no!");
         $this->_app->halt(500);
         // Don't let on about why the request failed ;-)
     }
     // Load the request schema
     $requestSchema = new \Fortress\RequestSchema($this->_app->config('schema.path') . "/forms/register.json");
     // Set up Fortress to process the request
     $rf = new \Fortress\HTTPRequestFortress($ms, $requestSchema, $post);
     // Security measure: do not allow registering new users until the master account has been created.
     if (!User::find($this->_app->config('user_id_master'))) {
         $ms->addMessageTranslated("danger", "MASTER_ACCOUNT_NOT_EXISTS");
         $this->_app->halt(403);
     }
     // Check if registration is currently enabled
     if (!$this->_app->site->can_register) {
         $ms->addMessageTranslated("danger", "ACCOUNT_REGISTRATION_DISABLED");
         $this->_app->halt(403);
     }
     // Prevent the user from registering if he/she is already logged in
     if (!$this->_app->user->isGuest()) {
         $ms->addMessageTranslated("danger", "ACCOUNT_REGISTRATION_LOGOUT");
         $this->_app->halt(200);
     }
     // Sanitize data
     $rf->sanitize();
     // Validate, and halt on validation errors.
     $error = !$rf->validate(true);
     // Get the filtered data
     $data = $rf->data();
     // Check captcha, if required
     if ($this->_app->site->enable_captcha == "1") {
         if (!$data['captcha'] || md5($data['captcha']) != $_SESSION['userfrosting']['captcha']) {
             $ms->addMessageTranslated("danger", "CAPTCHA_FAIL");
             $error = true;
         }
     }
     // Remove captcha, password confirmation from object data
     $rf->removeFields(['captcha', 'passwordc']);
     // Perform desired data transformations.  Is this a feature we could add to Fortress?
     $data['display_name'] = trim($data['display_name']);
     $data['locale'] = $this->_app->site->default_locale;
     if ($this->_app->site->require_activation) {
         $data['flag_verified'] = 0;
     } else {
         $data['flag_verified'] = 1;
     }
     // Check if username or email already exists
     if (User::where('user_name', $data['user_name'])->first()) {
         $ms->addMessageTranslated("danger", "ACCOUNT_USERNAME_IN_USE", $data);
         $error = true;
     }
     if (User::where('email', $data['email'])->first()) {
         $ms->addMessageTranslated("danger", "ACCOUNT_EMAIL_IN_USE", $data);
         $error = true;
     }
     // Halt on any validation errors
     if ($error) {
         $this->_app->halt(400);
     }
     // Get default primary group (is_default = GROUP_DEFAULT_PRIMARY)
     $primaryGroup = Group::where('is_default', GROUP_DEFAULT_PRIMARY)->first();
     // Check that a default primary group is actually set
     if (!$primaryGroup) {
         $ms->addMessageTranslated("danger", "ACCOUNT_REGISTRATION_BROKEN");
         error_log("Account registration is not working because a default primary group has not been set.");
         $this->_app->halt(500);
     }
     $data['primary_group_id'] = $primaryGroup->id;
     // Set default title for new users
     $data['title'] = $primaryGroup->new_user_title;
     // Hash password
     $data['password'] = Authentication::hashPassword($data['password']);
     // Create the user
     $user = new User($data);
     // Add user to default groups, including default primary group
     $defaultGroups = Group::where('is_default', GROUP_DEFAULT)->get();
     $user->addGroup($primaryGroup->id);
     foreach ($defaultGroups as $group) {
         $user->addGroup($group->id);
     }
     // Create sign-up event
     $user->newEventSignUp();
     // Store new user to database
     $user->save();
     if ($this->_app->site->require_activation) {
         // Create verification request event
         $user->newEventVerificationRequest();
         $user->save();
         // Re-save with verification event
         // Create and send verification email
         $twig = $this->_app->view()->getEnvironment();
         $template = $twig->loadTemplate("mail/activate-new.twig");
         $notification = new Notification($template);
         $notification->fromWebsite();
         // Automatically sets sender and reply-to
         $notification->addEmailRecipient($user->email, $user->display_name, ["user" => $user]);
         try {
             $notification->send();
         } catch (\phpmailerException $e) {
             $ms->addMessageTranslated("danger", "MAIL_ERROR");
             error_log('Mailer Error: ' . $e->errorMessage());
             $this->_app->halt(500);
         }
         $ms->addMessageTranslated("success", "ACCOUNT_REGISTRATION_COMPLETE_TYPE2");
     } else {
         // No activation required
         $ms->addMessageTranslated("success", "ACCOUNT_REGISTRATION_COMPLETE_TYPE1");
     }
     // Return the user object to the calling program
     return $user;
 }
 /**
  * Processes a request to create the master account.
  *
  * Processes the request from the master account creation form, checking that:
  * 1. The honeypot has not been changed;
  * 2. The master account does not already exist;
  * 3. The correct configuration token was submitted;
  * 3. The submitted data is valid.
  * This route is "public access" (until the master account has been created, that is)
  * Request type: POST     
  */
 public function setupMasterAccount()
 {
     $post = $this->_app->request->post();
     // Get the alert message stream
     $ms = $this->_app->alerts;
     // Check the honeypot. 'spiderbro' is not a real field, it is hidden on the main page and must be submitted with its default value for this to be processed.
     if (!$post['spiderbro'] || $post['spiderbro'] != "http://") {
         error_log("Possible spam received:" . print_r($this->_app->request->post(), true));
         $ms->addMessage("danger", "Aww hellllls no!");
         $this->_app->halt(500);
         // Don't let on about why the request failed ;-)
     }
     // Do not allow registering a master account if one has already been created
     if (User::find($this->_app->config('user_id_master'))) {
         $ms->addMessageTranslated("danger", "MASTER_ACCOUNT_EXISTS");
         $this->_app->halt(403);
     }
     // Check the configuration token
     if ($post['root_account_config_token'] != $this->_app->site->root_account_config_token) {
         $ms->addMessageTranslated("danger", "CONFIG_TOKEN_MISMATCH");
         $this->_app->halt(403);
     }
     // Load the request schema
     $requestSchema = new \Fortress\RequestSchema($this->_app->config('schema.path') . "/forms/register.json");
     // Set up Fortress to process the request
     $rf = new \Fortress\HTTPRequestFortress($ms, $requestSchema, $post);
     // Sanitize data
     $rf->sanitize();
     // Validate, and halt on validation errors.
     $error = !$rf->validate(true);
     // Get the filtered data
     $data = $rf->data();
     // Remove configuration token, password confirmation from object data
     $rf->removeFields(['root_account_config_token', 'passwordc']);
     // Perform desired data transformations.  Is this a feature we could add to Fortress?
     $data['display_name'] = trim($data['display_name']);
     $data['flag_verified'] = 1;
     $data['locale'] = $this->_app->site->default_locale;
     // Halt on any validation errors
     if ($error) {
         $this->_app->halt(400);
     }
     // Get default primary group (is_default = GROUP_DEFAULT_PRIMARY)
     $primaryGroup = Group::where('is_default', GROUP_DEFAULT_PRIMARY)->first();
     $data['primary_group_id'] = $primaryGroup->id;
     // Set default title for new users
     $data['title'] = $primaryGroup->new_user_title;
     // Hash password
     $data['password'] = Authentication::hashPassword($data['password']);
     // Create the master user
     $user = new User($data);
     $user->id = $this->_app->config('user_id_master');
     // Add user to default groups, including default primary group
     $defaultGroups = Group::where('is_default', GROUP_DEFAULT)->get();
     $user->addGroup($primaryGroup->id);
     foreach ($defaultGroups as $group) {
         $group_id = $group->id;
         $user->addGroup($group_id);
     }
     // Add sign-up event
     $user->newEventSignUp();
     // Store new user to database
     $user->save();
     // No activation required
     $ms->addMessageTranslated("success", "ACCOUNT_REGISTRATION_COMPLETE_TYPE1");
     // Update install status
     $this->_app->site->install_status = "new";
     $this->_app->site->root_account_config_token = "";
     $this->_app->site->store();
 }