/** * To be used for invitation registration. * * @param array $FormPostValues * @param array $Options * @return int UserID. */ public function insertForInvite($FormPostValues, $Options = array()) { $RoleIDs = RoleModel::getDefaultRoles(RoleModel::TYPE_MEMBER); if (!is_array($RoleIDs) || count($RoleIDs) == 0) { throw new Exception(t('The default role has not been configured.'), 400); } // Define the primary key in this model's table. $this->defineSchema(); // Add & apply any extra validation rules: $this->Validation->applyRule('Email', 'Email'); // Make sure that the checkbox val for email is saved as the appropriate enum if (array_key_exists('ShowEmail', $FormPostValues)) { $FormPostValues['ShowEmail'] = forceBool($FormPostValues['ShowEmail'], '0', '1', '0'); } if (array_key_exists('Banned', $FormPostValues)) { $FormPostValues['Banned'] = forceBool($FormPostValues['Banned'], '0', '1', '0'); } $this->addInsertFields($FormPostValues); // Make sure that the user has a valid invitation code, and also grab // the user's email from the invitation: $InviteUserID = 0; $InviteUsername = ''; $InvitationCode = val('InvitationCode', $FormPostValues, ''); $Invitation = $this->SQL->getWhere('Invitation', array('Code' => $InvitationCode))->firstRow(); // If there is no invitation then bail out. if (!$Invitation) { $this->Validation->addValidationResult('InvitationCode', 'Invitation not found.'); return false; } // Get expiration date in timestamp. If nothing set, grab config default. $InviteExpiration = $Invitation->DateExpires; if ($InviteExpiration != null) { $InviteExpiration = Gdn_Format::toTimestamp($InviteExpiration); } else { $DefaultExpire = '1 week'; $InviteExpiration = strtotime(c('Garden.Registration.InviteExpiration', '1 week'), Gdn_Format::toTimestamp($Invitation->DateInserted)); if ($InviteExpiration === false) { $InviteExpiration = strtotime($DefaultExpire); } } if ($InviteExpiration <= time()) { $this->Validation->addValidationResult('DateExpires', 'The invitation has expired.'); } $InviteUserID = $Invitation->InsertUserID; $FormPostValues['Email'] = $Invitation->Email; if ($this->validate($FormPostValues, true)) { // Check for spam. $Spam = SpamModel::isSpam('Registration', $FormPostValues); if ($Spam) { $this->Validation->addValidationResult('Spam', 'You are not allowed to register at this time.'); return; } $Fields = $this->Validation->validationFields(); // All fields on the form that need to be validated (including non-schema field rules defined above) $Username = val('Name', $Fields); $Email = val('Email', $Fields); $Fields = $this->Validation->schemaValidationFields(); // Only fields that are present in the schema unset($Fields[$this->PrimaryKey]); // Make sure the username & email aren't already being used if (!$this->validateUniqueFields($Username, $Email)) { return false; } // Define the other required fields: if ($InviteUserID > 0) { $Fields['InviteUserID'] = $InviteUserID; } // And insert the new user. if (!isset($Options['NoConfirmEmail'])) { $Options['NoConfirmEmail'] = true; } // Use RoleIDs from Invitation table, if any. They are stored as a // serialized array of the Role IDs. $InvitationRoleIDs = $Invitation->RoleIDs; if (strlen($InvitationRoleIDs)) { $InvitationRoleIDs = unserialize($InvitationRoleIDs); if (is_array($InvitationRoleIDs) && count(array_filter($InvitationRoleIDs))) { // Overwrite default RoleIDs set at top of method. $RoleIDs = $InvitationRoleIDs; } } $Fields['Roles'] = $RoleIDs; $UserID = $this->_insert($Fields, $Options); // Associate the new user id with the invitation (so it cannot be used again) $this->SQL->update('Invitation')->set('AcceptedUserID', $UserID)->where('InvitationID', $Invitation->InvitationID)->put(); // Report that the user was created. $ActivityModel = new ActivityModel(); $ActivityModel->save(array('ActivityUserID' => $UserID, 'ActivityType' => 'Registration', 'HeadlineFormat' => t('HeadlineFormat.Registration', '{ActivityUserID,You} joined.'), 'Story' => t('Welcome Aboard!')), false, array('GroupBy' => 'ActivityTypeID')); } else { $UserID = false; } return $UserID; }
/** * To be used for basic registration, and captcha registration. * * @param array $FormPostValues * @param bool $CheckCaptcha * @param array $Options * @return bool|int|string * @throws Exception */ public function insertForBasic($FormPostValues, $CheckCaptcha = true, $Options = []) { $RoleIDs = RoleModel::getDefaultRoles(RoleModel::TYPE_MEMBER); if (!is_array($RoleIDs) || count($RoleIDs) == 0) { throw new Exception(t('The default role has not been configured.'), 400); } if (val('SaveRoles', $Options)) { $RoleIDs = val('RoleID', $FormPostValues); } $UserID = false; // Define the primary key in this model's table. $this->defineSchema(); // Add & apply any extra validation rules. if (val('ValidateEmail', $Options, true)) { $this->Validation->applyRule('Email', 'Email'); } // TODO: DO I NEED THIS?! // Make sure that the checkbox val for email is saved as the appropriate enum if (array_key_exists('ShowEmail', $FormPostValues)) { $FormPostValues['ShowEmail'] = forceBool($FormPostValues['ShowEmail'], '0', '1', '0'); } if (array_key_exists('Banned', $FormPostValues)) { $FormPostValues['Banned'] = forceBool($FormPostValues['Banned'], '0', '1', '0'); } $this->addInsertFields($FormPostValues); if ($this->validate($FormPostValues, true) === true) { $Fields = $this->Validation->validationFields(); // All fields on the form that need to be validated (including non-schema field rules defined above) $Username = val('Name', $Fields); $Email = val('Email', $Fields); $Fields = $this->Validation->schemaValidationFields(); // Only fields that are present in the schema $Fields['Roles'] = $RoleIDs; unset($Fields[$this->PrimaryKey]); // If in Captcha registration mode, check the captcha value. if ($CheckCaptcha && Captcha::enabled()) { $captchaIsValid = Captcha::validate(); if ($captchaIsValid !== true) { $this->Validation->addValidationResult('Garden.Registration.CaptchaPublicKey', 'The captcha was not completed correctly. Please try again.'); return false; } } if (!$this->validateUniqueFields($Username, $Email)) { return false; } // Check for spam. if (val('ValidateSpam', $Options, true)) { $ValidateSpam = $this->validateSpamRegistration($FormPostValues); if ($ValidateSpam !== true) { return $ValidateSpam; } } // Define the other required fields: $Fields['Email'] = $Email; // And insert the new user $UserID = $this->insertInternal($Fields, $Options); if ($UserID > 0 && !val('NoActivity', $Options)) { $ActivityModel = new ActivityModel(); $ActivityModel->save(['ActivityUserID' => $UserID, 'ActivityType' => 'Registration', 'HeadlineFormat' => t('HeadlineFormat.Registration', '{ActivityUserID,You} joined.'), 'Story' => t('Welcome Aboard!')], false, ['GroupBy' => 'ActivityTypeID']); } } return $UserID; }
/** * Convert the locale data to the php data (date and numbers) using the field definizion * param array $data array data to process */ public function convert2PHP($vlu) { if (!isset($this->fields)) { return $vlu; } setLangInfo(array('thousands_sep' => ".")); foreach ($this->fields as $key => $field) { if (isset($field['name'])) { $key = $field['name']; if (array_key_exists($key, $vlu)) { if ($vlu[$key] === null) { $vlu[$key] = ''; } else { $type = strToLower($field['type']); switch ($field['type']) { case 'real': case 'double': case 'number': case 'float': $vlu[$key] = forceFloat($vlu[$key], null, '.'); break; case 'integer': case 'lookup': case 'domain': $vlu[$key] = forceInteger($vlu[$key], null, true, '.'); break; case 'date': $vlu[$key] = forceISODate($vlu[$key]); break; case 'datetime': case 'now': break; case 'boolean': $vlu[$key] = forceBool($vlu[$key], $vlu[$key]); } } } } } return $vlu; }
/** * Save role data. * * @param array $FormPostValues The role row to save. * @param array|false $Settings Not used. * @return bool|mixed Returns the role ID or false on error. */ public function save($FormPostValues, $Settings = false) { // Define the primary key in this model's table. $this->defineSchema(); $RoleID = val('RoleID', $FormPostValues); $Insert = $RoleID > 0 ? false : true; // Strict-mode. setValue('PersonalInfo', $FormPostValues, forceBool(val('PersonalInfo', $FormPostValues), '0', '1', '0')); if ($Insert) { // Figure out the next role ID. $MaxRoleID = $this->SQL->select('r.RoleID', 'MAX')->from('Role r')->get()->value('RoleID', 0); $RoleID = $MaxRoleID + 1; $this->addInsertFields($FormPostValues); $FormPostValues['RoleID'] = strval($RoleID); // string for validation } else { $this->addUpdateFields($FormPostValues); } // Validate the form posted values if ($this->validate($FormPostValues, $Insert)) { $Fields = $this->Validation->schemaValidationFields(); if ($Insert === false) { $this->update($Fields, array('RoleID' => $RoleID)); } else { $this->insert($Fields); } // Now update the role permissions $Role = $this->GetByRoleID($RoleID); $PermissionModel = Gdn::permissionModel(); if (array_key_exists('Permissions', $FormPostValues)) { $globalPermissions = $FormPostValues['Permissions']; $categoryPermissions = val('Category', $globalPermissions, []); // Massage the global permissions. unset($globalPermissions['Category']); $globalPermissions['RoleID'] = $RoleID; $globalPermissions['JunctionTable'] = null; $globalPermissions['JunctionColumn'] = null; $globalPermissions['JunctionID'] = null; $Permissions = [$globalPermissions]; // Massage the category permissions. foreach ($categoryPermissions as $perm) { $row = $perm; $row['RoleID'] = $RoleID; $row['JunctionTable'] = 'Category'; $row['JunctionColumn'] = 'PermissionCategoryID'; $row['JunctionID'] = $row['CategoryID']; unset($row['CategoryID']); $Permissions[] = $row; } } else { $Permissions = val('Permission', $FormPostValues); $Permissions = $PermissionModel->pivotPermissions($Permissions, array('RoleID' => $RoleID)); } $PermissionModel->saveAll($Permissions, array('RoleID' => $RoleID)); if (Gdn::cache()->activeEnabled()) { // Don't update the user table if we are just using cached permissions. $this->ClearCache(); Gdn::userModel()->clearPermissions(); } else { // Remove the cached permissions for all users with this role. $this->SQL->update('User')->join('UserRole', 'User.UserID = UserRole.UserID')->set('Permissions', '')->where(array('UserRole.RoleID' => $RoleID))->put(); } } else { $RoleID = false; } return $RoleID; }
/** * Editing a category. * * @since 2.0.0 * @access public * * @param int $CategoryID Unique ID of the category to be updated. */ public function editCategory($CategoryID = '') { // Check permission $this->permission('Garden.Community.Manage'); // Set up models $RoleModel = new RoleModel(); $PermissionModel = Gdn::permissionModel(); $this->Form->setModel($this->CategoryModel); if (!$CategoryID && $this->Form->authenticatedPostBack()) { if ($ID = $this->Form->getFormValue('CategoryID')) { $CategoryID = $ID; } } // Get category data $this->Category = $this->CategoryModel->getID($CategoryID); if (!$this->Category) { throw notFoundException('Category'); } $this->Category->CustomPermissions = $this->Category->CategoryID == $this->Category->PermissionCategoryID; // Set up head $this->addJsFile('jquery.alphanumeric.js'); $this->addJsFile('categories.js'); $this->addJsFile('jquery.gardencheckboxgrid.js'); $this->title(t('Edit Category')); $this->addSideMenu('vanilla/settings/managecategories'); // Make sure the form knows which item we are editing. $this->Form->addHidden('CategoryID', $CategoryID); $this->setData('CategoryID', $CategoryID); // Load all roles with editable permissions $this->RoleArray = $RoleModel->getArray(); $this->fireEvent('AddEditCategory'); if ($this->Form->authenticatedPostBack()) { $this->setupDiscussionTypes($this->Category); $Upload = new Gdn_Upload(); $TmpImage = $Upload->validateUpload('PhotoUpload', false); if ($TmpImage) { // Generate the target image name $TargetImage = $Upload->generateTargetName(PATH_UPLOADS); $ImageBaseName = pathinfo($TargetImage, PATHINFO_BASENAME); // Save the uploaded image $Parts = $Upload->saveAs($TmpImage, $ImageBaseName); $this->Form->setFormValue('Photo', $Parts['SaveName']); } $this->Form->setFormValue('CustomPoints', (bool) $this->Form->getFormValue('CustomPoints')); // Enforces tinyint values on boolean fields to comply with strict mode $this->Form->setFormValue('HideAllDiscussions', forceBool($this->Form->getFormValue('HideAllDiscussions'), '0', '1', '0')); $this->Form->setFormValue('Archived', forceBool($this->Form->getFormValue('Archived'), '0', '1', '0')); $this->Form->setFormValue('AllowFileUploads', forceBool($this->Form->getFormValue('AllowFileUploads'), '0', '1', '0')); if ($this->Form->save()) { $Category = CategoryModel::categories($CategoryID); $this->setData('Category', $Category); if ($this->deliveryType() == DELIVERY_TYPE_ALL) { redirect('vanilla/settings/managecategories'); } elseif ($this->deliveryType() === DELIVERY_TYPE_DATA && method_exists($this, 'getCategory')) { $this->Data = []; $this->getCategory($CategoryID); return; } } } else { $this->Form->setData($this->Category); $this->setupDiscussionTypes($this->Category); $this->Form->setValue('CustomPoints', $this->Category->PointsCategoryID == $this->Category->CategoryID); } // Get all of the currently selected role/permission combinations for this junction. $Permissions = $PermissionModel->getJunctionPermissions(array('JunctionID' => $CategoryID), 'Category', '', array('AddDefaults' => !$this->Category->CustomPermissions)); $Permissions = $PermissionModel->unpivotPermissions($Permissions, true); if ($this->deliveryType() == DELIVERY_TYPE_ALL) { $this->setData('PermissionData', $Permissions, true); } // Render default view $this->render(); }
/** * Editing a category. * * @since 2.0.0 * @param int|string $CategoryID Unique ID of the category to be updated. * @throws Exception when category cannot be found. */ public function editCategory($CategoryID = '') { // Check permission $this->permission(['Garden.Community.Manage', 'Garden.Settings.Manage'], false); // Set up models $RoleModel = new RoleModel(); $PermissionModel = Gdn::permissionModel(); $this->Form->setModel($this->CategoryModel); if (!$CategoryID && $this->Form->authenticatedPostBack()) { if ($ID = $this->Form->getFormValue('CategoryID')) { $CategoryID = $ID; } } // Get category data $this->Category = CategoryModel::categories($CategoryID); if (!$this->Category) { throw notFoundException('Category'); } // Category data is expected to be in the form of an object. $this->Category = (object) $this->Category; $this->Category->CustomPermissions = $this->Category->CategoryID == $this->Category->PermissionCategoryID; $displayAsOptions = categoryModel::getDisplayAsOptions(); // Restrict "Display As" types based on parent. $parentCategory = $this->CategoryModel->getID($this->Category->ParentCategoryID); $parentDisplay = val('DisplayAs', $parentCategory); if ($parentDisplay === 'Flat') { unset($displayAsOptions['Heading']); } // Set up head $this->addJsFile('jquery.alphanumeric.js'); $this->addJsFile('manage-categories.js'); $this->addJsFile('jquery.gardencheckboxgrid.js'); $this->title(t('Edit Category')); $this->setHighlightRoute('vanilla/settings/categories'); // Make sure the form knows which item we are editing. $this->Form->addHidden('CategoryID', $CategoryID); $this->setData('CategoryID', $CategoryID); // Load all roles with editable permissions $this->RoleArray = $RoleModel->getArray(); $this->fireAs('SettingsController'); $this->fireEvent('AddEditCategory'); if ($this->Form->authenticatedPostBack()) { $this->setupDiscussionTypes($this->Category); $Upload = new Gdn_Upload(); $TmpImage = $Upload->validateUpload('PhotoUpload', false); if ($TmpImage) { // Generate the target image name $TargetImage = $Upload->generateTargetName(PATH_UPLOADS); $ImageBaseName = pathinfo($TargetImage, PATHINFO_BASENAME); // Save the uploaded image $Parts = $Upload->saveAs($TmpImage, $ImageBaseName); $this->Form->setFormValue('Photo', $Parts['SaveName']); } $this->Form->setFormValue('CustomPoints', (bool) $this->Form->getFormValue('CustomPoints')); // Enforces tinyint values on boolean fields to comply with strict mode $this->Form->setFormValue('HideAllDiscussions', forceBool($this->Form->getFormValue('HideAllDiscussions'), '0', '1', '0')); $this->Form->setFormValue('Archived', forceBool($this->Form->getFormValue('Archived'), '0', '1', '0')); $this->Form->setFormValue('AllowFileUploads', forceBool($this->Form->getFormValue('AllowFileUploads'), '0', '1', '0')); if ($parentDisplay === 'Flat' && $this->Form->getFormValue('DisplayAs') === 'Heading') { $this->Form->addError('Cannot display as a heading when your parent category is displayed flat.', 'DisplayAs'); } if ($this->Form->save()) { $Category = CategoryModel::categories($CategoryID); $this->setData('Category', $Category); if ($this->deliveryType() == DELIVERY_TYPE_ALL) { $destination = $this->categoryPageByParent($parentCategory); redirect($destination); } elseif ($this->deliveryType() === DELIVERY_TYPE_DATA && method_exists($this, 'getCategory')) { $this->Data = []; $this->getCategory($CategoryID); return; } } } else { $this->Form->setData($this->Category); $this->setupDiscussionTypes($this->Category); $this->Form->setValue('CustomPoints', $this->Category->PointsCategoryID == $this->Category->CategoryID); } // Get all of the currently selected role/permission combinations for this junction. $Permissions = $PermissionModel->getJunctionPermissions(array('JunctionID' => $CategoryID), 'Category', '', array('AddDefaults' => !$this->Category->CustomPermissions)); $Permissions = $PermissionModel->unpivotPermissions($Permissions, true); if ($this->deliveryType() == DELIVERY_TYPE_ALL) { $this->setData('PermissionData', $Permissions, true); } // Render default view $this->setData('Operation', 'Edit'); $this->setData('DisplayAsOptions', $displayAsOptions); $this->render(); }
protected function setEnabled($messageID, $enabled) { $messageModel = new MessageModel(); $enabled = forceBool($enabled, '0', '1', '0'); $messageModel->setProperty($messageID, 'Enabled', $enabled); $this->MessageModel->setMessageCache(); if ($enabled === '1') { $newToggle = wrap(anchor('<div class="toggle-well"></div><div class="toggle-slider"></div>', '/dashboard/message/disable/' . $messageID, 'Hijack'), 'span', array('class' => "toggle-wrap toggle-wrap-on")); } else { $newToggle = wrap(anchor('<div class="toggle-well"></div><div class="toggle-slider"></div>', '/dashboard/message/enable/' . $messageID, 'Hijack'), 'span', array('class' => "toggle-wrap toggle-wrap-off")); } $this->jsonTarget("#toggle-" . $messageID, $newToggle); if ($enabled === '1') { $this->informMessage(sprintf(t('%s enabled.'), t('Message'))); } else { $this->informMessage(sprintf(t('%s disabled.'), t('Message'))); } $this->render('Blank', 'Utility'); }