/** * @test */ public function firstThrown_returnFiveDices() { $player = new Player(); $result = $player->throwDices(); assertThat($result, arrayValue()); assertThat(count($result), is(equalTo(5))); }
/** * Is the application/plugin/theme removable? * * @param string $Type self::TYPE_APPLICATION or self::TYPE_PLUGIN or self::TYPE_THEME * @param string $Name * @return boolean */ public static function isRemovable($Type, $Name) { switch ($Type) { case self::TYPE_APPLICATION: $ApplicationManager = Gdn::Factory('ApplicationManager'); if ($IsRemovable = !array_key_exists($Name, $ApplicationManager->EnabledApplications())) { $ApplicationInfo = arrayValue($Name, $ApplicationManager->AvailableApplications(), array()); $ApplicationFolder = arrayValue('Folder', $ApplicationInfo, ''); $IsRemovable = IsWritable(PATH_APPLICATIONS . DS . $ApplicationFolder); } break; case self::TYPE_PLUGIN: if ($IsRemovable = !array_key_exists($Name, Gdn::pluginManager()->EnabledPlugins())) { $PluginInfo = arrayValue($Name, Gdn::pluginManager()->AvailablePlugins(), false); $PluginFolder = arrayValue('Folder', $PluginInfo, false); $IsRemovable = IsWritable(PATH_PLUGINS . DS . $PluginFolder); } break; case self::TYPE_THEME: // TODO $IsRemovable = false; break; } return $IsRemovable; }
public function testAccessorForCredentialsConvertsStringIntoArray() { $user = Factory::create('User', ['id' => 1]); $credentialsNotAccessed = $user->getAttributes()['credentials']; $credentialsAccessed = $user->credentials; assertThat($credentialsNotAccessed, is(stringValue())); assertThat($credentialsAccessed, is(arrayValue())); }
/** * Update the configuration. * * @return void */ protected function config() { saveToConfig('Garden.Cookie.Salt', RandomString(10)); $ApplicationInfo = []; include CombinePaths([PATH_APPLICATIONS . DS . 'dashboard' . DS . 'settings' . DS . 'about.php']); // Detect Internet connection for CDNs $Disconnected = !(bool) @fsockopen('ajax.googleapis.com', 80); saveToConfig(['Garden.Version' => arrayValue('Version', val('Dashboard', $ApplicationInfo, []), 'Undefined'), 'Garden.Cdns.Disable' => $Disconnected, 'Garden.CanProcessImages' => function_exists('gd_info'), 'EnabledPlugins.HtmLawed' => 'HtmLawed']); }
function getVisitIp() { $matchIp = '/^([0-9]{1,3}\\.){3}[0-9]{1,3}$/'; $ipKeys = array('HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_CF_CONNECTING_IP'); foreach ($ipKeys as $ipKey) { if (isset($_SERVER[$ipKey]) && preg_match($matchIp, $_SERVER[$ipKey])) { return $_SERVER[$ipKey]; } } return arrayValue($_SERVER, 'REMOTE_ADDR'); }
/** * Constructor * * @param array $connectionData Connection Data parsed by parse_url() * @return self */ public function __construct(array $connectionData) { if (!class_exists("Memcache", false)) { error("Memcache Extension not installed - Update your PHP configuration"); } $this->memcache = new Memcache(); $host = $connectionData["host"]; $port = arrayValue($connectionData, "port"); $port = $port ? $port : 11211; $connectState = $this->memcache->connect($host, $port); if (!$connectState) { error("Could not connect to Memcache Server at " . $host . ":" . $port); } }
/** * Get an route that exactly matches a string. * @param string|int $Route The route to search for. * @param int $Indexed If the route is a number then it will be looked up as an index. * * @return array|bool A route or false if there is no matching route. */ public function getRoute($Route, $Indexed = true) { if ($Indexed && is_numeric($Route) && $Route !== false) { $Keys = array_keys($this->Routes); $Route = arrayValue($Route, $Keys); } $Decoded = $this->_decodeRouteKey($Route); if ($Decoded !== false && array_key_exists($Decoded, $this->Routes)) { $Route = $Decoded; } if ($Route === false || !array_key_exists($Route, $this->Routes)) { return false; } //return $this->Routes[$Route]; return array_merge($this->Routes[$Route], array('TypeLocale' => T($this->RouteTypes[$this->Routes[$Route]['Type']]), 'FinalDestination' => $this->Routes[$Route]['Destination'])); }
/** * Edit a route. * * @since 2.0.0 * @access public * @param string $RouteIndex Name of route. */ public function edit($RouteIndex = false) { $this->permission('Garden.Settings.Manage'); $this->addSideMenu('dashboard/routes'); $this->Route = Gdn::router()->GetRoute($RouteIndex); $Validation = new Gdn_Validation(); $ConfigurationModel = new Gdn_ConfigurationModel($Validation); $ConfigurationModel->setField(array('Route', 'Target', 'Type')); // Set the model on the form. $this->Form->setModel($ConfigurationModel); // If seeing the form for the first time... if (!$this->Form->authenticatedPostBack()) { // Apply the route info to the form. if ($this->Route !== false) { $this->Form->setData(array('Route' => $this->Route['Route'], 'Target' => $this->Route['Destination'], 'Type' => $this->Route['Type'])); } } else { // Define some validation rules for the fields being saved $ConfigurationModel->Validation->applyRule('Route', 'Required'); $ConfigurationModel->Validation->applyRule('Target', 'Required'); $ConfigurationModel->Validation->applyRule('Type', 'Required'); // Validate & Save $FormPostValues = $this->Form->formValues(); // Dunno. if ($this->Route['Reserved']) { $FormPostValues['Route'] = $this->Route['Route']; } if ($ConfigurationModel->validate($FormPostValues)) { $NewRouteName = arrayValue('Route', $FormPostValues); if ($this->Route !== false && $NewRouteName != $this->Route['Route']) { Gdn::router()->DeleteRoute($this->Route['Route']); } Gdn::router()->SetRoute($NewRouteName, arrayValue('Target', $FormPostValues), arrayValue('Type', $FormPostValues)); $this->informMessage(t("The route was saved successfully.")); $this->RedirectUrl = url('dashboard/routes'); } else { $this->Form->setValidationResults($ConfigurationModel->validationResults()); } } $this->render(); }
/** * Create or update a comment. * * @since 2.0.0 * @access public * * @param int $DiscussionID Unique ID to add the comment to. If blank, this method will throw an error. */ public function comment($DiscussionID = '') { // Get $DiscussionID from RequestArgs if valid if ($DiscussionID == '' && count($this->RequestArgs)) { if (is_numeric($this->RequestArgs[0])) { $DiscussionID = $this->RequestArgs[0]; } } // If invalid $DiscussionID, get from form. $this->Form->setModel($this->CommentModel); $DiscussionID = is_numeric($DiscussionID) ? $DiscussionID : $this->Form->getFormValue('DiscussionID', 0); // Set discussion data $this->DiscussionID = $DiscussionID; $this->Discussion = $Discussion = $this->DiscussionModel->getID($DiscussionID); // Is this an embedded comment being posted to a discussion that doesn't exist yet? $vanilla_type = $this->Form->getFormValue('vanilla_type', ''); $vanilla_url = $this->Form->getFormValue('vanilla_url', ''); $vanilla_category_id = $this->Form->getFormValue('vanilla_category_id', ''); $Attributes = array('ForeignUrl' => $vanilla_url); $vanilla_identifier = $this->Form->getFormValue('vanilla_identifier', ''); // Only allow vanilla identifiers of 32 chars or less - md5 if larger if (strlen($vanilla_identifier) > 32) { $Attributes['vanilla_identifier'] = $vanilla_identifier; $vanilla_identifier = md5($vanilla_identifier); } if (!$Discussion && $vanilla_url != '' && $vanilla_identifier != '') { $Discussion = $Discussion = $this->DiscussionModel->GetForeignID($vanilla_identifier, $vanilla_type); if ($Discussion) { $this->DiscussionID = $DiscussionID = $Discussion->DiscussionID; $this->Form->setValue('DiscussionID', $DiscussionID); } } // If so, create it! if (!$Discussion && $vanilla_url != '' && $vanilla_identifier != '') { // Add these values back to the form if they exist! $this->Form->addHidden('vanilla_identifier', $vanilla_identifier); $this->Form->addHidden('vanilla_type', $vanilla_type); $this->Form->addHidden('vanilla_url', $vanilla_url); $this->Form->addHidden('vanilla_category_id', $vanilla_category_id); $PageInfo = FetchPageInfo($vanilla_url); if (!($Title = $this->Form->getFormValue('Name'))) { $Title = val('Title', $PageInfo, ''); if ($Title == '') { $Title = t('Undefined discussion subject.'); } } $Description = val('Description', $PageInfo, ''); $Images = val('Images', $PageInfo, array()); $LinkText = t('EmbededDiscussionLinkText', 'Read the full story here'); if (!$Description && count($Images) == 0) { $Body = formatString('<p><a href="{Url}">{LinkText}</a></p>', array('Url' => $vanilla_url, 'LinkText' => $LinkText)); } else { $Body = formatString(' <div class="EmbeddedContent">{Image}<strong>{Title}</strong> <p>{Excerpt}</p> <p><a href="{Url}">{LinkText}</a></p> <div class="ClearFix"></div> </div>', array('Title' => $Title, 'Excerpt' => $Description, 'Image' => count($Images) > 0 ? img(val(0, $Images), array('class' => 'LeftAlign')) : '', 'Url' => $vanilla_url, 'LinkText' => $LinkText)); } if ($Body == '') { $Body = $vanilla_url; } if ($Body == '') { $Body = t('Undefined discussion body.'); } // Validate the CategoryID for inserting. $Category = CategoryModel::categories($vanilla_category_id); if (!$Category) { $vanilla_category_id = c('Vanilla.Embed.DefaultCategoryID', 0); if ($vanilla_category_id <= 0) { // No default category defined, so grab the first non-root category and use that. $vanilla_category_id = $this->DiscussionModel->SQL->select('CategoryID')->from('Category')->where('CategoryID >', 0)->get()->firstRow()->CategoryID; // No categories in the db? default to 0 if (!$vanilla_category_id) { $vanilla_category_id = 0; } } } else { $vanilla_category_id = $Category['CategoryID']; } $EmbedUserID = c('Garden.Embed.UserID'); if ($EmbedUserID) { $EmbedUser = Gdn::userModel()->getID($EmbedUserID); } if (!$EmbedUserID || !$EmbedUser) { $EmbedUserID = Gdn::userModel()->GetSystemUserID(); } $EmbeddedDiscussionData = array('InsertUserID' => $EmbedUserID, 'DateInserted' => Gdn_Format::toDateTime(), 'DateUpdated' => Gdn_Format::toDateTime(), 'CategoryID' => $vanilla_category_id, 'ForeignID' => $vanilla_identifier, 'Type' => $vanilla_type, 'Name' => $Title, 'Body' => $Body, 'Format' => 'Html', 'Attributes' => serialize($Attributes)); $this->EventArguments['Discussion'] =& $EmbeddedDiscussionData; $this->fireEvent('BeforeEmbedDiscussion'); $DiscussionID = $this->DiscussionModel->SQL->insert('Discussion', $EmbeddedDiscussionData); $ValidationResults = $this->DiscussionModel->validationResults(); if (count($ValidationResults) == 0 && $DiscussionID > 0) { $this->Form->addHidden('DiscussionID', $DiscussionID); // Put this in the form so reposts won't cause new discussions. $this->Form->setFormValue('DiscussionID', $DiscussionID); // Put this in the form values so it is used when saving comments. $this->setJson('DiscussionID', $DiscussionID); $this->Discussion = $Discussion = $this->DiscussionModel->getID($DiscussionID, DATASET_TYPE_OBJECT, array('Slave' => false)); // Update the category discussion count if ($vanilla_category_id > 0) { $this->DiscussionModel->UpdateDiscussionCount($vanilla_category_id, $DiscussionID); } } } // If no discussion was found, error out if (!$Discussion) { $this->Form->addError(t('Failed to find discussion for commenting.')); } $PermissionCategoryID = val('PermissionCategoryID', $Discussion); // Setup head $this->addJsFile('jquery.autosize.min.js'); $this->addJsFile('autosave.js'); $this->addJsFile('post.js'); // Setup comment model, $CommentID, $DraftID $Session = Gdn::session(); $CommentID = isset($this->Comment) && property_exists($this->Comment, 'CommentID') ? $this->Comment->CommentID : ''; $DraftID = isset($this->Comment) && property_exists($this->Comment, 'DraftID') ? $this->Comment->DraftID : ''; $this->EventArguments['CommentID'] = $CommentID; $this->EventArguments['DraftID'] = $DraftID; // Determine whether we are editing $Editing = $CommentID > 0 || $DraftID > 0; $this->EventArguments['Editing'] = $Editing; // If closed, cancel & go to discussion if ($Discussion && $Discussion->Closed == 1 && !$Editing && !$Session->checkPermission('Vanilla.Discussions.Close', true, 'Category', $PermissionCategoryID)) { redirect(DiscussionUrl($Discussion)); } // Add hidden IDs to form $this->Form->addHidden('DiscussionID', $DiscussionID); $this->Form->addHidden('CommentID', $CommentID); $this->Form->addHidden('DraftID', $DraftID, true); // Check permissions if ($Discussion && $Editing) { // Permission to edit if ($this->Comment->InsertUserID != $Session->UserID) { $this->permission('Vanilla.Comments.Edit', true, 'Category', $Discussion->PermissionCategoryID); } // Make sure that content can (still) be edited. $EditContentTimeout = c('Garden.EditContentTimeout', -1); $CanEdit = $EditContentTimeout == -1 || strtotime($this->Comment->DateInserted) + $EditContentTimeout > time(); if (!$CanEdit) { $this->permission('Vanilla.Comments.Edit', true, 'Category', $Discussion->PermissionCategoryID); } // Make sure only moderators can edit closed things if ($Discussion->Closed) { $this->permission('Vanilla.Comments.Edit', true, 'Category', $Discussion->PermissionCategoryID); } $this->Form->setFormValue('CommentID', $CommentID); } elseif ($Discussion) { // Permission to add $this->permission('Vanilla.Comments.Add', true, 'Category', $Discussion->PermissionCategoryID); } if ($this->Form->authenticatedPostBack()) { // Save as a draft? $FormValues = $this->Form->formValues(); $FormValues = $this->CommentModel->filterForm($FormValues); if (!$Editing) { unset($FormValues['CommentID']); } if ($DraftID == 0) { $DraftID = $this->Form->getFormValue('DraftID', 0); } $Type = GetIncomingValue('Type'); $Draft = $Type == 'Draft'; $this->EventArguments['Draft'] = $Draft; $Preview = $Type == 'Preview'; if ($Draft) { $DraftID = $this->DraftModel->save($FormValues); $this->Form->addHidden('DraftID', $DraftID, true); $this->Form->setValidationResults($this->DraftModel->validationResults()); } elseif (!$Preview) { // Fix an undefined title if we can. if ($this->Form->getFormValue('Name') && val('Name', $Discussion) == t('Undefined discussion subject.')) { $Set = array('Name' => $this->Form->getFormValue('Name')); if (isset($vanilla_url) && $vanilla_url && strpos(val('Body', $Discussion), t('Undefined discussion subject.')) !== false) { $LinkText = t('EmbededDiscussionLinkText', 'Read the full story here'); $Set['Body'] = formatString('<p><a href="{Url}">{LinkText}</a></p>', array('Url' => $vanilla_url, 'LinkText' => $LinkText)); } $this->DiscussionModel->setField(val('DiscussionID', $Discussion), $Set); } $Inserted = !$CommentID; $CommentID = $this->CommentModel->save($FormValues); // The comment is now half-saved. if (is_numeric($CommentID) && $CommentID > 0) { if (in_array($this->deliveryType(), array(DELIVERY_TYPE_ALL, DELIVERY_TYPE_DATA))) { $this->CommentModel->Save2($CommentID, $Inserted, true, true); } else { $this->jsonTarget('', url("/post/comment2.json?commentid={$CommentID}&inserted={$Inserted}"), 'Ajax'); } // $Discussion = $this->DiscussionModel->getID($DiscussionID); $Comment = $this->CommentModel->getID($CommentID, DATASET_TYPE_OBJECT, array('Slave' => false)); $this->EventArguments['Discussion'] = $Discussion; $this->EventArguments['Comment'] = $Comment; $this->fireEvent('AfterCommentSave'); } elseif ($CommentID === SPAM || $CommentID === UNAPPROVED) { $this->StatusMessage = t('CommentRequiresApprovalStatus', 'Your comment will appear after it is approved.'); } $this->Form->setValidationResults($this->CommentModel->validationResults()); if ($CommentID > 0 && $DraftID > 0) { $this->DraftModel->delete($DraftID); } } // Handle non-ajax requests first: if ($this->_DeliveryType == DELIVERY_TYPE_ALL) { if ($this->Form->errorCount() == 0) { // Make sure that this form knows what comment we are editing. if ($CommentID > 0) { $this->Form->addHidden('CommentID', $CommentID); } // If the comment was not a draft if (!$Draft) { // Redirect to the new comment. if ($CommentID > 0) { redirect("discussion/comment/{$CommentID}/#Comment_{$CommentID}"); } elseif ($CommentID == SPAM) { $this->setData('DiscussionUrl', DiscussionUrl($Discussion)); $this->View = 'Spam'; } } elseif ($Preview) { // If this was a preview click, create a comment shell with the values for this comment $this->Comment = new stdClass(); $this->Comment->InsertUserID = $Session->User->UserID; $this->Comment->InsertName = $Session->User->Name; $this->Comment->InsertPhoto = $Session->User->Photo; $this->Comment->DateInserted = Gdn_Format::date(); $this->Comment->Body = arrayValue('Body', $FormValues, ''); $this->Comment->Format = val('Format', $FormValues, c('Garden.InputFormatter')); $this->AddAsset('Content', $this->fetchView('preview')); } else { // If this was a draft save, notify the user about the save $this->informMessage(sprintf(t('Draft saved at %s'), Gdn_Format::date())); } } } else { // Handle ajax-based requests if ($this->Form->errorCount() > 0) { // Return the form errors $this->ErrorMessage($this->Form->errors()); } else { // Make sure that the ajax request form knows about the newly created comment or draft id $this->setJson('CommentID', $CommentID); $this->setJson('DraftID', $DraftID); if ($Preview) { // If this was a preview click, create a comment shell with the values for this comment $this->Comment = new stdClass(); $this->Comment->InsertUserID = $Session->User->UserID; $this->Comment->InsertName = $Session->User->Name; $this->Comment->InsertPhoto = $Session->User->Photo; $this->Comment->DateInserted = Gdn_Format::date(); $this->Comment->Body = arrayValue('Body', $FormValues, ''); $this->View = 'preview'; } elseif (!$Draft) { // If the comment was not a draft // If Editing a comment if ($Editing) { // Just reload the comment in question $this->Offset = 1; $Comments = $this->CommentModel->GetIDData($CommentID, array('Slave' => false)); $this->setData('Comments', $Comments); $this->setData('Discussion', $Discussion); // Load the discussion $this->ControllerName = 'discussion'; $this->View = 'comments'; // Also define the discussion url in case this request came from the post screen and needs to be redirected to the discussion $this->setJson('DiscussionUrl', DiscussionUrl($this->Discussion) . '#Comment_' . $CommentID); } else { // If the comment model isn't sorted by DateInserted or CommentID then we can't do any fancy loading of comments. $OrderBy = valr('0.0', $this->CommentModel->orderBy()); // $Redirect = !in_array($OrderBy, array('c.DateInserted', 'c.CommentID')); // $DisplayNewCommentOnly = $this->Form->getFormValue('DisplayNewCommentOnly'); // if (!$Redirect) { // // Otherwise load all new comments that the user hasn't seen yet // $LastCommentID = $this->Form->getFormValue('LastCommentID'); // if (!is_numeric($LastCommentID)) // $LastCommentID = $CommentID - 1; // Failsafe back to this new comment if the lastcommentid was not defined properly // // // Don't reload the first comment if this new comment is the first one. // $this->Offset = $LastCommentID == 0 ? 1 : $this->CommentModel->GetOffset($LastCommentID); // // Do not load more than a single page of data... // $Limit = c('Vanilla.Comments.PerPage', 30); // // // Redirect if the new new comment isn't on the same page. // $Redirect |= !$DisplayNewCommentOnly && PageNumber($this->Offset, $Limit) != PageNumber($Discussion->CountComments - 1, $Limit); // } // if ($Redirect) { // // The user posted a comment on a page other than the last one, so just redirect to the last page. // $this->RedirectUrl = Gdn::request()->Url("discussion/comment/$CommentID/#Comment_$CommentID", true); // } else { // // Make sure to load all new comments since the page was last loaded by this user // if ($DisplayNewCommentOnly) $this->Offset = $this->CommentModel->GetOffset($CommentID); $Comments = $this->CommentModel->GetIDData($CommentID, array('Slave' => false)); $this->setData('Comments', $Comments); $this->setData('NewComments', true); $this->ClassName = 'DiscussionController'; $this->ControllerName = 'discussion'; $this->View = 'comments'; // } // Make sure to set the user's discussion watch records $CountComments = $this->CommentModel->getCount($DiscussionID); $Limit = is_object($this->data('Comments')) ? $this->data('Comments')->numRows() : $Discussion->CountComments; $Offset = $CountComments - $Limit; $this->CommentModel->SetWatch($this->Discussion, $Limit, $Offset, $CountComments); } } else { // If this was a draft save, notify the user about the save $this->informMessage(sprintf(t('Draft saved at %s'), Gdn_Format::date())); } // And update the draft count $UserModel = Gdn::userModel(); $CountDrafts = $UserModel->getAttribute($Session->UserID, 'CountDrafts', 0); $this->setJson('MyDrafts', t('My Drafts')); $this->setJson('CountDrafts', $CountDrafts); } } } elseif ($this->Request->isPostBack()) { throw new Gdn_UserException('Invalid CSRF token.', 401); } else { // Load form if (isset($this->Comment)) { $this->Form->setData((array) $this->Comment); } } // Include data for FireEvent if (property_exists($this, 'Discussion')) { $this->EventArguments['Discussion'] = $this->Discussion; } if (property_exists($this, 'Comment')) { $this->EventArguments['Comment'] = $this->Comment; } $this->fireEvent('BeforeCommentRender'); if ($this->deliveryType() == DELIVERY_TYPE_DATA) { $Comment = $this->data('Comments')->firstRow(DATASET_TYPE_ARRAY); if ($Comment) { $Photo = $Comment['InsertPhoto']; if (strpos($Photo, '//') === false) { $Photo = Gdn_Upload::url(changeBasename($Photo, 'n%s')); } $Comment['InsertPhoto'] = $Photo; } $this->Data = array('Comment' => $Comment); $this->RenderData($this->Data); } else { require_once $this->fetchViewLocation('helper_functions', 'Discussion'); // Render default view. $this->render(); } }
/** * Gets the value associated with $FieldName. * * If the form has been posted back, it will retrieve the value from the form. * If it hasn't been posted back, it gets the value from $this->_DataArray. * Failing either of those, it returns $Default. * * @param string $FieldName * @param mixed $Default * @return mixed * * @todo check returned value type */ public function getValue($FieldName, $Default = false) { $Return = ''; // Only retrieve values from the form collection if this is a postback. if ($this->isMyPostBack()) { $Return = $this->getFormValue($FieldName, $Default); } else { $Return = arrayValue($FieldName, $this->_DataArray, $Default); } return $Return; }
/** * Convert a datetime to a timestamp * * @param string $DateTime The Mysql-formatted datetime to convert to a timestamp. Should be in one * of the following formats: YYYY-MM-DD or YYYY-MM-DD HH:MM:SS. Returns * FALSE upon failure. * @return unknown */ public static function toTimestamp($DateTime = '') { if ($DateTime === '0000-00-00 00:00:00') { return false; } elseif (($TestTime = strtotime($DateTime)) !== false) { return $TestTime; } elseif (preg_match('/^(\\d{4})-(\\d{1,2})-(\\d{1,2})(?:\\s{1}(\\d{1,2}):(\\d{1,2})(?::(\\d{1,2}))?)?$/', $DateTime, $Matches)) { $Year = $Matches[1]; $Month = $Matches[2]; $Day = $Matches[3]; $Hour = arrayValue(4, $Matches, 0); $Minute = arrayValue(5, $Matches, 0); $Second = arrayValue(6, $Matches, 0); return mktime($Hour, $Minute, $Second, $Month, $Day, $Year); } elseif (preg_match('/^(\\d{4})-(\\d{1,2})-(\\d{1,2})$/', $DateTime, $Matches)) { $Year = $Matches[1]; $Month = $Matches[2]; $Day = $Matches[3]; return mktime(0, 0, 0, $Month, $Day, $Year); // } elseif ($DateTime == '') { // return time(); } else { return false; } }
/** * Get attribute value * * @param mixed $key * @return string */ public function get($key) { return arrayValue($this->arr, $key, ""); }
/** * If JSON is going to be sent to the client, this method allows you to add * extra values to the JSON array. * * @param string $Key The name of the array key to add. * @param mixed $Value The value to be added. If null, then it won't be set. * @return mixed The value at the key. */ public function json($Key, $Value = null) { if (!is_null($Value)) { $this->_Json[$Key] = $Value; } return arrayValue($Key, $this->_Json, null); }
/** * Get the database id * 0 if not stored in database * * @return int */ public function getId() { return (int) arrayValue($this->_dbValues, "id"); }
/** * Save a message. * * @param array $FormPostValues Message data. * @param bool $Settings * @return int The MessageID. */ public function save($FormPostValues, $Settings = false) { // The "location" is packed into a single input with a / delimiter. Need to explode it into three different fields for saving $Location = arrayValue('Location', $FormPostValues, ''); if ($Location != '') { $Location = explode('/', $Location); $Application = val(0, $Location, ''); if (in_array($Application, $this->_SpecialLocations)) { $FormPostValues['Application'] = null; $FormPostValues['Controller'] = $Application; $FormPostValues['Method'] = null; } else { $FormPostValues['Application'] = $Application; $FormPostValues['Controller'] = val(1, $Location, ''); $FormPostValues['Method'] = val(2, $Location, ''); } } Gdn::cache()->remove('Messages'); return parent::save($FormPostValues, $Settings); }
/** * * * @param array $FormPostValues * @param array|bool $UserModel * @param array $Options * @return bool * @throws Exception */ public function save($FormPostValues, $UserModel, $Options = array()) { $Session = Gdn::session(); $UserID = $Session->UserID; $SendEmail = val('SendEmail', $Options, true); $Resend = val('Resend', $Options, false); // Define the primary key in this model's table. $this->defineSchema(); // Add & apply any extra validation rules: $this->Validation->applyRule('Email', 'Email'); // Make sure required db fields are present. $this->AddInsertFields($FormPostValues); if (!isset($FormPostValues['DateExpires'])) { $Expires = strtotime(c('Garden.Registration.InviteExpiration')); if ($Expires > time()) { $FormPostValues['DateExpires'] = Gdn_Format::toDateTime($Expires); } } $FormPostValues['Code'] = $this->GetInvitationCode(); // Validate the form posted values if ($this->validate($FormPostValues, true) === true) { $Fields = $this->Validation->ValidationFields(); // All fields on the form that need to be validated $Email = arrayValue('Email', $Fields, ''); // Make sure this user has a spare invitation to send. $InviteCount = $UserModel->GetInvitationCount($UserID); if ($InviteCount == 0) { $this->Validation->addValidationResult('Email', 'You do not have enough invitations left.'); return false; } // Make sure that the email does not already belong to an account in the application. $TestData = $UserModel->getWhere(array('Email' => $Email)); if ($TestData->numRows() > 0) { $this->Validation->addValidationResult('Email', 'The email you have entered is already related to an existing account.'); return false; } // Make sure that the email does not already belong to an invitation in the application. $TestData = $this->getWhere(array('Email' => $Email)); $DeleteID = false; if ($TestData->numRows() > 0) { if (!$Resend) { $this->Validation->addValidationResult('Email', 'An invitation has already been sent to the email you entered.'); return false; } else { // Mark the old invitation for deletion. $DeleteID = val('InvitationID', $TestData->firstRow(DATASET_TYPE_ARRAY)); } } // Define the fields to be inserted $Fields = $this->Validation->SchemaValidationFields(); // Call the base model for saving $InvitationID = $this->insert($Fields); // Delete an old invitation. if ($InvitationID && $DeleteID) { $this->delete($DeleteID); } // Now that saving has succeeded, update the user's invitation settings if ($InviteCount > 0) { $UserModel->ReduceInviteCount($UserID); } // And send the invitation email if ($SendEmail) { try { $this->send($InvitationID); } catch (Exception $ex) { $this->Validation->addValidationResult('Email', sprintf(t('Although the invitation was created successfully, the email failed to send. The server reported the following error: %s'), strip_tags($ex->getMessage()))); return false; } } return true; } return false; }
/** * * * @param $Row * @param $Result * @param bool $IncludeRole */ protected function _UnpivotPermissionsRow($Row, &$Result, $IncludeRole = false) { $GlobalName = arrayValue('Name', $Row); // Loop through each permission in the row and place them in the correct place in the grid. foreach ($Row as $PermissionName => $Value) { list($Namespace, $Name, $Suffix) = self::SplitPermission($PermissionName); if (empty($Name)) { continue; // was some other column } if ($GlobalName) { $Namespace = $GlobalName; } if (array_key_exists('JunctionTable', $Row) && ($JunctionTable = $Row['JunctionTable'])) { $Key = "{$JunctionTable}/{$Row['JunctionColumn']}/{$Row['JunctionID']}" . ($IncludeRole ? '/' . $Row['RoleID'] : ''); } else { $Key = '_' . $Namespace; } // Check to see if the namespace is in the result. if (!array_key_exists($Key, $Result)) { $Result[$Key] = array('_Columns' => array(), '_Rows' => array(), '_Info' => array('Name' => $Namespace)); } $NamespaceArray =& $Result[$Key]; // Add the names to the columns and rows. $NamespaceArray['_Columns'][$Suffix] = true; $NamespaceArray['_Rows'][$Name] = true; // Augment the value depending on the junction ID. if (substr($Key, 0, 1) === '_') { $PostValue = $PermissionName; } else { $PostValue = $Key . '//' . $PermissionName; } $NamespaceArray[$Name . '.' . $Suffix] = array('Value' => $Value, 'PostValue' => $PostValue); } }
protected function _IndexSql($Columns, $KeyType = FALSE) { // if ($this->TableName() != 'Comment') // return array(); $Result = array(); $Keys = array(); $Prefixes = array('key' => 'FK_', 'index' => 'IX_', 'unique' => 'UX_', 'fulltext' => 'TX_'); $Indexes = array(); // Gather the names of the columns. foreach ($Columns as $ColumnName => $Column) { $ColumnKeyTypes = (array) $Column->KeyType; foreach ($ColumnKeyTypes as $ColumnKeyType) { $Parts = explode('.', $ColumnKeyType, 2); $ColumnKeyType = $Parts[0]; $IndexGroup = GetValue(1, $Parts, ''); if (!$ColumnKeyType || $KeyType && $KeyType != $ColumnKeyType) { continue; } // Don't add a fulltext if we don't support. if ($ColumnKeyType == 'fulltext' && !$this->_SupportsFulltext()) { continue; } $Indexes[$ColumnKeyType][$IndexGroup][] = $ColumnName; } } // Make the multi-column keys into sql statements. foreach ($Indexes as $ColumnKeyType => $IndexGroups) { $CreateType = arrayValue($ColumnKeyType, array('index' => 'index', 'key' => 'key', 'unique' => 'unique index', 'fulltext' => 'fulltext index', 'primary' => 'primary key')); if ($ColumnKeyType == 'primary') { $Result['PRIMARY'] = 'primary key (`' . implode('`, `', $IndexGroups['']) . '`)'; } else { foreach ($IndexGroups as $IndexGroup => $ColumnNames) { $Multi = strlen($IndexGroup) > 0 || in_array($ColumnKeyType, array('unique', 'fulltext')); if ($Multi) { $IndexName = "{$Prefixes[$ColumnKeyType]}{$this->_TableName}" . ($IndexGroup ? '_' . $IndexGroup : ''); $Result[$IndexName] = "{$CreateType} {$IndexName} (`" . implode('`, `', $ColumnNames) . '`)'; } else { foreach ($ColumnNames as $ColumnName) { $IndexName = "{$Prefixes[$ColumnKeyType]}{$this->_TableName}_{$ColumnName}"; $Result[$IndexName] = "{$CreateType} {$IndexName} (`{$ColumnName}`)"; } } } } } return $Result; }
/** * Return true if it is a https request * * @return bool */ public function isHttps() { return arrayValue($_SERVER, "SERVER_PORT") == 443; }
/** * Get/Set a $_SESSION value * Session is hi-jack protected and protected against corrupt session ids * * @param string $key * @param string $value The value to set * @return mixed */ function session($key, $value = null) { if (defined("CHOQ_SESSIONID_CORRUPT") && CHOQ_SESSIONID_CORRUPT) { return; } if (session_id() === "") { # check for session id to be correct # if not skip activating the session $sessionName = session_name(); $sessionId = isset($_COOKIE[$sessionName]) ? $_COOKIE[$sessionName] : null; if ($sessionId !== null && (strlen($sessionId) < 22 || strlen($sessionId) > 40 || preg_match("~[^a-zA-Z0-9,\\-]~i", $sessionId))) { define("CHOQ_SESSIONID_CORRUPT", true); return; } session_start(); $currentUid = md5(req()->getIp()); $savedUid = arrayValue($_SESSION, "__choquid__"); if ($savedUid && $savedUid != $currentUid) { $_SESSION = array(); } $_SESSION["__choquid__"] = $currentUid; } if ($value === null) { return arrayValue($_SESSION, $key); } $_SESSION[$key] = $value; }
</tr> </thead> <tbody> <?php $Alt = FALSE; foreach ($this->MessageData->result() as $Message) { $Message = $this->MessageModel->DefineLocation($Message); $Alt = $Alt ? FALSE : TRUE; ?> <tr id="<?php echo $Message->MessageID; echo $Alt ? '" class="Alt' : ''; ?> "> <td class="Info nowrap"><?php printf(t('%1$s on %2$s'), arrayValue($Message->AssetTarget, $this->_GetAssetData(), 'Custom Location'), arrayValue($Message->Location, $this->_GetLocationData(), 'Custom Page')); if (val('CategoryID', $Message) && ($Category = CategoryModel::categories($Message->CategoryID))) { echo '<div>' . anchor($Category['Name'], CategoryUrl($Category)); if (val('IncludeSubcategories', $Message)) { echo ' ' . t('and subcategories'); } echo '</div>'; } ?> <div> <strong><?php echo $Message->Enabled == '1' ? t('Enabled') : t('Disabled'); ?> </strong> <?php echo anchor(t('Edit'), '/dashboard/message/edit/' . $Message->MessageID, 'EditMessage SmallButton');
/** * Load the View */ public function onLoad() { needRole(null, true); # OPML if (get("opml")) { $categories = user()->getCategories(); $opml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><opml></opml>'); $opml->addAttribute("version", "1.0"); $head = $opml->addChild("head"); $head->addChild("title", "Subscriptions from nReeda"); $body = $opml->addChild("body"); foreach ($categories as $category) { $cat = $body->addChild("outline"); $cat->addAttribute("title", $category->name); $cat->addAttribute("text", $category->name); $feeds = $category->feeds; if ($feeds) { foreach ($feeds as $feed) { $f = $cat->addChild("outline"); $f->addAttribute("type", "rss"); $f->addAttribute("text", $feed->getCustomName($category)); $f->addAttribute("title", $feed->getCustomName($category)); $f->addAttribute("xmlUrl", $feed->url); } } } $data = $opml->asXML(); CHOQ_OutputManager::cleanAllBuffers(); header("Content-type: application/octet-stream"); header("Content-Disposition: filename=\"nreeda.opml\""); echo $data; die; } # textfile if (get("file")) { $categories = user()->getCategories(); $lines = array(); foreach ($categories as $category) { $feeds = $category->feeds; if ($feeds) { foreach ($feeds as $feed) { $lines[] = $feed->url; } } } $data = implode("\n", $lines); CHOQ_OutputManager::cleanAllBuffers(); header("Content-type: application/octet-stream"); header("Content-Disposition: filename=\"nreeda.txt\""); echo $data; die; } # Import if (isset($_FILES["file"]["tmp_name"])) { $data = file_get_contents($_FILES["file"]["tmp_name"]); if (strpos($data, "<?xml") === false || strpos($data, "</opml>") === false) { $event = RDR_Import::importFromFile($_FILES["file"]["tmp_name"]); if ($event->type == RDR_Event::TYPE_FILE_OK) { RDR_Import::updateAllFeeds(); } v("message", $event->getText()); } else { $event = RDR_Import::importFromOPML($_FILES["file"]["tmp_name"]); if ($event->type == RDR_Event::TYPE_OPML_OK) { RDR_Import::updateAllFeeds(); } v("message", $event->getText()); } } if (post("new") && trim(post("val"))) { RDR_Category::get(post("val")); redirect(url()->getUri(), 302); } if (req()->isAjax()) { $categories = user()->getCategories(); $feeds = user()->getFeeds(); if (post("action") == "edit" && post("val")) { if (isset($categories[post("category")])) { $category = $categories[post("category")]; if (post("feed")) { $feed = arrayValue($feeds, post("feed")); if ($feed) { $feed->setCustomName($category, post("val")); $category->store(); } } else { $category->name = post("val"); $category->store(); } } } if (post("action") == "move") { if (isset($categories[post("categoryOld")])) { $categoryOld = $categories[post("categoryOld")]; $categoryNew = $categories[post("categoryNew")]; if (post("feed")) { $feed = arrayValue($feeds, post("feed")); if ($feed) { $name = $feed->getCustomName($categoryOld); $categoryOld->remove("feedsData", $feed->getId() . "-name"); $categoryOld->remove("feeds", $feed->getId()); $categoryOld->store(); $feed->setCustomName($categoryNew, $name); $categoryNew->add("feeds", $feed); $categoryNew->store(); } } } } if (post("action") == "delete") { if (isset($categories[post("category")])) { $category = $categories[post("category")]; if (post("feed")) { $feed = arrayValue($feeds, post("feed")); if ($feed) { $category->remove("feedsData", $feed->getId() . "-name"); $category->remove("feeds", $feed); $category->store(); } } else { $category->delete(); } } } RDR_Cleanup::cleanupFeeds(); RDR_Cleanup::cleanupFlags(); user()->updateNewsCache(); return; } view("RDR_BasicFrame", array("view" => $this)); }
/** * Adds information to the definition list that causes the app to "phone * home" and see if there are upgrades available. * * Currently added to the dashboard only. Nothing renders with this method. * It is public so it can be added by plugins. */ public function addUpdateCheck() { if (c('Garden.NoUpdateCheck')) { return; } // Check to see if the application needs to phone-home for updates. Doing // this here because this method is always called when admin pages are // loaded regardless of the application loading them. $UpdateCheckDate = Gdn::config('Garden.UpdateCheckDate', ''); if ($UpdateCheckDate == '' || !IsTimestamp($UpdateCheckDate) || $UpdateCheckDate < strtotime("-1 day")) { $UpdateData = array(); // Grab all of the plugins & versions $Plugins = Gdn::pluginManager()->availablePlugins(); foreach ($Plugins as $Plugin => $Info) { $Name = arrayValue('Name', $Info, $Plugin); $Version = arrayValue('Version', $Info, ''); if ($Version != '') { $UpdateData[] = array('Name' => $Name, 'Version' => $Version, 'Type' => 'Plugin'); } } // Grab all of the applications & versions $ApplicationManager = Gdn::factory('ApplicationManager'); $Applications = $ApplicationManager->availableApplications(); foreach ($Applications as $Application => $Info) { $Name = arrayValue('Name', $Info, $Application); $Version = arrayValue('Version', $Info, ''); if ($Version != '') { $UpdateData[] = array('Name' => $Name, 'Version' => $Version, 'Type' => 'Application'); } } // Grab all of the themes & versions $ThemeManager = new Gdn_ThemeManager(); $Themes = $ThemeManager->availableThemes(); foreach ($Themes as $Theme => $Info) { $Name = arrayValue('Name', $Info, $Theme); $Version = arrayValue('Version', $Info, ''); if ($Version != '') { $UpdateData[] = array('Name' => $Name, 'Version' => $Version, 'Type' => 'Theme'); } } // Dump the entire set of information into the definition list (jQuery // will pick it up and ping the VanillaForums.org server with this info). $this->addDefinition('UpdateChecks', Gdn_Format::serialize($UpdateData)); } }
/** * Inserts or updates the discussion via form values. * * Events: BeforeSaveDiscussion, AfterSaveDiscussion. * * @since 2.0.0 * @access public * * @param array $FormPostValues Data sent from the form model. * @return int $DiscussionID Unique ID of the discussion. */ public function save($FormPostValues) { $Session = Gdn::session(); // Define the primary key in this model's table. $this->defineSchema(); // Add & apply any extra validation rules: $this->Validation->applyRule('Body', 'Required'); $this->Validation->addRule('MeAction', 'function:ValidateMeAction'); $this->Validation->applyRule('Body', 'MeAction'); $MaxCommentLength = Gdn::config('Vanilla.Comment.MaxLength'); if (is_numeric($MaxCommentLength) && $MaxCommentLength > 0) { $this->Validation->SetSchemaProperty('Body', 'Length', $MaxCommentLength); $this->Validation->applyRule('Body', 'Length'); } // Validate category permissions. $CategoryID = val('CategoryID', $FormPostValues); if ($CategoryID > 0) { $Category = CategoryModel::categories($CategoryID); if ($Category && !$Session->checkPermission('Vanilla.Discussions.Add', true, 'Category', val('PermissionCategoryID', $Category))) { $this->Validation->addValidationResult('CategoryID', 'You do not have permission to post in this category'); } } // Get the DiscussionID from the form so we know if we are inserting or updating. $DiscussionID = arrayValue('DiscussionID', $FormPostValues, ''); // See if there is a source ID. if (val('SourceID', $FormPostValues)) { $DiscussionID = $this->SQL->getWhere('Discussion', arrayTranslate($FormPostValues, array('Source', 'SourceID')))->value('DiscussionID'); if ($DiscussionID) { $FormPostValues['DiscussionID'] = $DiscussionID; } } elseif (val('ForeignID', $FormPostValues)) { $DiscussionID = $this->SQL->getWhere('Discussion', array('ForeignID' => $FormPostValues['ForeignID']))->value('DiscussionID'); if ($DiscussionID) { $FormPostValues['DiscussionID'] = $DiscussionID; } } $Insert = $DiscussionID == '' ? true : false; $this->EventArguments['Insert'] = $Insert; if ($Insert) { unset($FormPostValues['DiscussionID']); // If no categoryid is defined, grab the first available. if (!val('CategoryID', $FormPostValues) && !c('Vanilla.Categories.Use')) { $FormPostValues['CategoryID'] = val('CategoryID', CategoryModel::DefaultCategory(), -1); } $this->AddInsertFields($FormPostValues); // The UpdateUserID used to be required. Just add it if it still is. if (!$this->Schema->GetProperty('UpdateUserID', 'AllowNull', true)) { $FormPostValues['UpdateUserID'] = $FormPostValues['InsertUserID']; } // $FormPostValues['LastCommentUserID'] = $Session->UserID; $FormPostValues['DateLastComment'] = $FormPostValues['DateInserted']; } else { // Add the update fields. $this->AddUpdateFields($FormPostValues); } // Set checkbox values to zero if they were unchecked if (ArrayValue('Announce', $FormPostValues, '') === false) { $FormPostValues['Announce'] = 0; } if (ArrayValue('Closed', $FormPostValues, '') === false) { $FormPostValues['Closed'] = 0; } if (ArrayValue('Sink', $FormPostValues, '') === false) { $FormPostValues['Sink'] = 0; } // Prep and fire event $this->EventArguments['FormPostValues'] =& $FormPostValues; $this->EventArguments['DiscussionID'] = $DiscussionID; $this->fireEvent('BeforeSaveDiscussion'); // Validate the form posted values $this->validate($FormPostValues, $Insert); $ValidationResults = $this->validationResults(); // If the body is not required, remove it's validation errors. $BodyRequired = c('Vanilla.DiscussionBody.Required', true); if (!$BodyRequired && array_key_exists('Body', $ValidationResults)) { unset($ValidationResults['Body']); } if (count($ValidationResults) == 0) { // If the post is new and it validates, make sure the user isn't spamming if (!$Insert || !$this->CheckForSpam('Discussion')) { // Get all fields on the form that relate to the schema $Fields = $this->Validation->SchemaValidationFields(); // Get DiscussionID if one was sent $DiscussionID = intval(val('DiscussionID', $Fields, 0)); // Remove the primary key from the fields for saving. unset($Fields['DiscussionID']); $StoredCategoryID = false; if ($DiscussionID > 0) { // Updating $Stored = $this->getID($DiscussionID, DATASET_TYPE_OBJECT); // Block Format change if we're forcing the formatter. if (c('Garden.ForceInputFormatter')) { unset($Fields['Format']); } // Clear the cache if necessary. $CacheKeys = array(); if (val('Announce', $Stored) != val('Announce', $Fields)) { $CacheKeys[] = $this->GetAnnouncementCacheKey(); $CacheKeys[] = $this->GetAnnouncementCacheKey(val('CategoryID', $Stored)); } if (val('CategoryID', $Stored) != val('CategoryID', $Fields)) { $CacheKeys[] = $this->GetAnnouncementCacheKey(val('CategoryID', $Fields)); } foreach ($CacheKeys as $CacheKey) { Gdn::cache()->Remove($CacheKey); } self::SerializeRow($Fields); $this->SQL->put($this->Name, $Fields, array($this->PrimaryKey => $DiscussionID)); setValue('DiscussionID', $Fields, $DiscussionID); LogModel::LogChange('Edit', 'Discussion', (array) $Fields, $Stored); if (val('CategoryID', $Stored) != val('CategoryID', $Fields)) { $StoredCategoryID = val('CategoryID', $Stored); } } else { // Inserting. if (!val('Format', $Fields) || c('Garden.ForceInputFormatter')) { $Fields['Format'] = c('Garden.InputFormatter', ''); } if (c('Vanilla.QueueNotifications')) { $Fields['Notified'] = ActivityModel::SENT_PENDING; } // Check for spam. $Spam = SpamModel::IsSpam('Discussion', $Fields); if ($Spam) { return SPAM; } // Check for approval $ApprovalRequired = CheckRestriction('Vanilla.Approval.Require'); if ($ApprovalRequired && !val('Verified', Gdn::session()->User)) { LogModel::insert('Pending', 'Discussion', $Fields); return UNAPPROVED; } // Create discussion $this->SerializeRow($Fields); $DiscussionID = $this->SQL->insert($this->Name, $Fields); $Fields['DiscussionID'] = $DiscussionID; // Update the cache. if ($DiscussionID && Gdn::cache()->activeEnabled()) { $CategoryCache = array('LastDiscussionID' => $DiscussionID, 'LastCommentID' => null, 'LastTitle' => Gdn_Format::text($Fields['Name']), 'LastUserID' => $Fields['InsertUserID'], 'LastDateInserted' => $Fields['DateInserted'], 'LastUrl' => DiscussionUrl($Fields)); CategoryModel::SetCache($Fields['CategoryID'], $CategoryCache); // Clear the cache if necessary. if (val('Announce', $Fields)) { Gdn::cache()->Remove($this->GetAnnouncementCacheKey(val('CategoryID', $Fields))); } } // Update the user's discussion count. $InsertUser = Gdn::userModel()->getID($Fields['InsertUserID']); $this->UpdateUserDiscussionCount($Fields['InsertUserID'], val('CountDiscussions', $InsertUser, 0) > 100); // Mark the user as participated. $this->SQL->replace('UserDiscussion', array('Participated' => 1), array('DiscussionID' => $DiscussionID, 'UserID' => val('InsertUserID', $Fields))); // Assign the new DiscussionID to the comment before saving. $FormPostValues['IsNewDiscussion'] = true; $FormPostValues['DiscussionID'] = $DiscussionID; // Do data prep. $DiscussionName = arrayValue('Name', $Fields, ''); $Story = arrayValue('Body', $Fields, ''); $NotifiedUsers = array(); $UserModel = Gdn::userModel(); $ActivityModel = new ActivityModel(); if (val('Type', $FormPostValues)) { $Code = 'HeadlineFormat.Discussion.' . $FormPostValues['Type']; } else { $Code = 'HeadlineFormat.Discussion'; } $HeadlineFormat = t($Code, '{ActivityUserID,user} started a new discussion: <a href="{Url,html}">{Data.Name,text}</a>'); $Category = CategoryModel::categories(val('CategoryID', $Fields)); $Activity = array('ActivityType' => 'Discussion', 'ActivityUserID' => $Fields['InsertUserID'], 'HeadlineFormat' => $HeadlineFormat, 'RecordType' => 'Discussion', 'RecordID' => $DiscussionID, 'Route' => DiscussionUrl($Fields), 'Data' => array('Name' => $DiscussionName, 'Category' => val('Name', $Category))); // Allow simple fulltext notifications if (c('Vanilla.Activity.ShowDiscussionBody', false)) { $Activity['Story'] = $Story; } // Notify all of the users that were mentioned in the discussion. $Usernames = GetMentions($DiscussionName . ' ' . $Story); $Usernames = array_unique($Usernames); // Use our generic Activity for events, not mentions $this->EventArguments['Activity'] = $Activity; // Notifications for mentions foreach ($Usernames as $Username) { $User = $UserModel->GetByUsername($Username); if (!$User) { continue; } // Check user can still see the discussion. if (!$UserModel->GetCategoryViewPermission($User->UserID, val('CategoryID', $Fields))) { continue; } $Activity['HeadlineFormat'] = t('HeadlineFormat.Mention', '{ActivityUserID,user} mentioned you in <a href="{Url,html}">{Data.Name,text}</a>'); $Activity['NotifyUserID'] = val('UserID', $User); $ActivityModel->Queue($Activity, 'Mention'); } // Notify everyone that has advanced notifications. if (!c('Vanilla.QueueNotifications')) { try { $Fields['DiscussionID'] = $DiscussionID; $this->NotifyNewDiscussion($Fields, $ActivityModel, $Activity); } catch (Exception $Ex) { throw $Ex; } } // Throw an event for users to add their own events. $this->EventArguments['Discussion'] = $Fields; $this->EventArguments['NotifiedUsers'] = $NotifiedUsers; $this->EventArguments['MentionedUsers'] = $Usernames; $this->EventArguments['ActivityModel'] = $ActivityModel; $this->fireEvent('BeforeNotification'); // Send all notifications. $ActivityModel->SaveQueue(); } // Get CategoryID of this discussion $Discussion = $this->getID($DiscussionID, DATASET_TYPE_OBJECT); $CategoryID = val('CategoryID', $Discussion, false); // Update discussion counter for affected categories. if ($Insert || $StoredCategoryID) { $this->IncrementNewDiscussion($Discussion); } if ($StoredCategoryID) { $this->UpdateDiscussionCount($StoredCategoryID); } // Fire an event that the discussion was saved. $this->EventArguments['FormPostValues'] = $FormPostValues; $this->EventArguments['Fields'] = $Fields; $this->EventArguments['DiscussionID'] = $DiscussionID; $this->fireEvent('AfterSaveDiscussion'); } } return $DiscussionID; }
public function testDecribesActualTypeInMismatchMessage() { $this->assertMismatchDescription('was null', arrayValue(), null); $this->assertMismatchDescription('was a string "foo"', arrayValue(), 'foo'); }
/** * Attempt to syncronize user data from remote system into Dashboard. * * @access public * @since 2.0.? * @author Tim Gunter * * @param object $Authenticator * @param array $UserInfo * @param array $Payload */ public function syncScreen($Authenticator, $UserInfo, $Payload) { $this->addJsFile('entry.js'); $this->View = 'handshake'; $this->HandshakeScheme = $Authenticator->getAuthenticationSchemeAlias(); $this->Form->setModel($this->UserModel); $this->Form->addHidden('ClientHour', date('Y-m-d H:00')); // Use the server's current hour as a default $this->Form->addHidden('Target', $this->target()); $PreservedKeys = array('UserKey', 'Token', 'Consumer', 'Email', 'Name', 'Gender', 'HourOffset'); $UserID = 0; $Target = $this->target(); if ($this->Form->isPostBack() === true) { $FormValues = $this->Form->formValues(); if (ArrayValue('StopLinking', $FormValues)) { $AuthResponse = Gdn_Authenticator::AUTH_ABORTED; $UserEventData = array_merge(array('UserID' => $UserID, 'Payload' => $Payload), $UserInfo); Gdn::authenticator()->trigger($AuthResponse, $UserEventData); $Authenticator->deleteCookie(); Gdn::request()->withRoute('DefaultController'); return Gdn::dispatcher()->dispatch(); } elseif (ArrayValue('NewAccount', $FormValues)) { $AuthResponse = Gdn_Authenticator::AUTH_CREATED; // Try and synchronize the user with the new username/email. $FormValues['Name'] = $FormValues['NewName']; $FormValues['Email'] = $FormValues['NewEmail']; $UserID = $this->UserModel->synchronize($UserInfo['UserKey'], $FormValues); $this->Form->setValidationResults($this->UserModel->validationResults()); } else { $AuthResponse = Gdn_Authenticator::AUTH_SUCCESS; // Try and sign the user in. $PasswordAuthenticator = Gdn::authenticator()->authenticateWith('password'); $PasswordAuthenticator->hookDataField('Email', 'SignInEmail'); $PasswordAuthenticator->hookDataField('Password', 'SignInPassword'); $PasswordAuthenticator->fetchData($this->Form); $UserID = $PasswordAuthenticator->authenticate(); if ($UserID < 0) { $this->Form->addError('ErrorPermission'); } elseif ($UserID == 0) { $this->Form->addError('ErrorCredentials'); Logger::event('signin_failure', Logger::WARNING, '{username} failed to sign in. Invalid credentials.'); } if ($UserID > 0) { $Data = $FormValues; $Data['UserID'] = $UserID; $Data['Email'] = arrayValue('SignInEmail', $FormValues, ''); $UserID = $this->UserModel->synchronize($UserInfo['UserKey'], $Data); } } if ($UserID > 0) { // The user has been created successfully, so sign in now // Finalize the link between the forum user and the foreign userkey $Authenticator->finalize($UserInfo['UserKey'], $UserID, $UserInfo['ConsumerKey'], $UserInfo['TokenKey'], $Payload); $UserEventData = array_merge(array('UserID' => $UserID, 'Payload' => $Payload), $UserInfo); Gdn::authenticator()->trigger($AuthResponse, $UserEventData); /// ... and redirect them appropriately $Route = $this->redirectTo(); if ($Route !== false) { redirect($Route); } } else { // Add the hidden inputs back into the form. foreach ($FormValues as $Key => $Value) { if (in_array($Key, $PreservedKeys)) { $this->Form->addHidden($Key, $Value); } } } } else { $Id = Gdn::authenticator()->getIdentity(true); if ($Id > 0) { // The user is signed in so we can just go back to the homepage. redirect($Target); } $Name = $UserInfo['UserName']; $Email = $UserInfo['UserEmail']; // Set the defaults for a new user. $this->Form->setFormValue('NewName', $Name); $this->Form->setFormValue('NewEmail', $Email); // Set the default for the login. $this->Form->setFormValue('SignInEmail', $Email); $this->Form->setFormValue('Handshake', 'NEW'); // Add the handshake data as hidden fields. $this->Form->addHidden('Name', $Name); $this->Form->addHidden('Email', $Email); $this->Form->addHidden('UserKey', $UserInfo['UserKey']); $this->Form->addHidden('Token', $UserInfo['TokenKey']); $this->Form->addHidden('Consumer', $UserInfo['ConsumerKey']); } $this->setData('Name', arrayValue('Name', $this->Form->HiddenInputs)); $this->setData('Email', arrayValue('Email', $this->Form->HiddenInputs)); $this->render(); }
/** * Check whether a user has access to view discussions in a particular category. * * @since 2.0.18 * @example $UserModel->GetCategoryViewPermission($UserID, $CategoryID). * * @param $Sender UserModel. * @return bool Whether user has permission. */ public function userModel_GetCategoryViewPermission_Create($Sender) { static $PermissionModel = null; $UserID = arrayValue(0, $Sender->EventArguments, ''); $CategoryID = arrayValue(1, $Sender->EventArguments, ''); $Permission = val(2, $Sender->EventArguments, 'Vanilla.Discussions.View'); if ($UserID && $CategoryID) { if ($PermissionModel === null) { $PermissionModel = new PermissionModel(); } $Category = CategoryModel::categories($CategoryID); if ($Category) { $PermissionCategoryID = $Category['PermissionCategoryID']; } else { $PermissionCategoryID = -1; } $Result = $PermissionModel->GetUserPermissions($UserID, $Permission, 'Category', 'PermissionCategoryID', 'CategoryID', $PermissionCategoryID); return val($Permission, val(0, $Result), false) ? true : false; } return false; }
/** * Synchronizes the user based on a given UserKey. * * @param string $UserKey A string that uniquely identifies this user. * @param array $Data Information to put in the user table. * @return int The ID of the user. */ public function synchronize($UserKey, $Data) { $UserID = 0; $Attributes = arrayValue('Attributes', $Data); if (is_string($Attributes)) { $Attributes = @unserialize($Attributes); } if (!is_array($Attributes)) { $Attributes = array(); } // If the user didnt log in, they won't have a UserID yet. That means they want a new // account. So create one for them. if (!isset($Data['UserID']) || $Data['UserID'] <= 0) { // Prepare the user data. $UserData['Name'] = $Data['Name']; $UserData['Password'] = RandomString(16); $UserData['Email'] = arrayValue('Email', $Data, '*****@*****.**'); $UserData['Gender'] = strtolower(substr(ArrayValue('Gender', $Data, 'u'), 0, 1)); $UserData['HourOffset'] = arrayValue('HourOffset', $Data, 0); $UserData['DateOfBirth'] = arrayValue('DateOfBirth', $Data, ''); $UserData['CountNotifications'] = 0; $UserData['Attributes'] = $Attributes; $UserData['InsertIPAddress'] = Gdn::request()->ipAddress(); if ($UserData['DateOfBirth'] == '') { $UserData['DateOfBirth'] = '1975-09-16'; } // Make sure there isn't another user with this username. if ($this->ValidateUniqueFields($UserData['Name'], $UserData['Email'])) { if (!BanModel::CheckUser($UserData, $this->Validation, true)) { throw permissionException('Banned'); } // Insert the new user. $this->AddInsertFields($UserData); $UserID = $this->_Insert($UserData); } if ($UserID) { $NewUserRoleIDs = $this->NewUserRoleIDs(); // Save the roles. $Roles = val('Roles', $Data, false); if (empty($Roles)) { $Roles = $NewUserRoleIDs; } $this->SaveRoles($UserID, $Roles, false); } } else { $UserID = $Data['UserID']; } // Synchronize the transientkey from the external user data source if it is present (eg. WordPress' wpnonce). if (array_key_exists('TransientKey', $Attributes) && $Attributes['TransientKey'] != '' && $UserID > 0) { $this->SetTransientKey($UserID, $Attributes['TransientKey']); } return $UserID; }
</tr> <tr class="<?php echo ($Upgrade ? 'More ' : '') . $RowClass; ?> "> <td class="Info"><?php $ToggleText = array_key_exists($PluginName, $this->EnabledPlugins) ? 'Disable' : 'Enable'; echo anchor(t($ToggleText), '/settings/plugins/' . $this->Filter . '/' . $PluginName . '/' . $Session->TransientKey(), $ToggleText . 'Addon SmallButton'); if ($SettingsUrl != '') { echo anchor(t('Settings'), $SettingsUrl, 'SmallButton'); } ?> </td> <td class="Alt Info"><?php $RequiredApplications = arrayValue('RequiredApplications', $PluginInfo, false); $RequiredPlugins = arrayValue('RequiredPlugins', $PluginInfo, false); $Info = ''; if ($Version != '') { $Info = sprintf(t('Version %s'), $Version); } if (is_array($RequiredApplications) || is_array($RequiredPlugins)) { if ($Info != '') { $Info .= '<span>|</span>'; } $Info .= t('Requires: '); } $i = 0; if (is_array($RequiredApplications)) { if ($i > 0) { $Info .= ', '; }
private function runnerDeciderScanWithForceDecision($runner) { $this->setUpTables(); $this->setUpRepo(); $jobId = 42; $licenseRef1 = $this->licenseDao->getLicenseByShortName("GPL-3.0")->getRef(); $licenseRef2 = $this->licenseDao->getLicenseByShortName("3DFX")->getRef(); $agentLicId = $this->licenseDao->getLicenseByShortName("Adaptec")->getRef()->getId(); $addedLicenses = array($licenseRef1, $licenseRef2); assertThat($addedLicenses, not(arrayContaining(null))); $agentId = 5; $pfile = 4; $this->dbManager->queryOnce("INSERT INTO license_file (fl_pk,rf_fk,pfile_fk,agent_fk) VALUES(12222,{$agentLicId},{$pfile},{$agentId})"); $itemTreeBounds = $this->uploadDao->getItemTreeBounds($itemId = 23); assertThat($this->agentLicenseEventProcessor->getScannerEvents($itemTreeBounds), is(not(emptyArray()))); $eventId1 = $this->clearingDao->insertClearingEvent($itemId, $userId = 2, $groupId = 3, $licenseRef1->getId(), false); $eventId2 = $this->clearingDao->insertClearingEvent($itemId, 5, $groupId, $licenseRef2->getId(), true); $this->dbManager->queryOnce("UPDATE clearing_event SET job_fk={$jobId}"); $addedEventIds = array($eventId1, $eventId2); list($success, $output, $retCode) = $runner->run($uploadId = 2, $userId, $groupId, $jobId, $args = "-k1"); $this->assertTrue($success, 'cannot run runner'); $this->assertEquals($retCode, 0, 'decider failed: ' . $output); assertThat($this->getHeartCount($output), equalTo(1)); $uploadBounds = $this->uploadDao->getParentItemBounds($uploadId); $decisions = $this->clearingDao->getFileClearingsFolder($uploadBounds, $groupId); assertThat($decisions, is(arrayWithSize(1))); /** @var ClearingDecision $deciderMadeDecision */ $deciderMadeDecision = $decisions[0]; $eventIds = array(); foreach ($deciderMadeDecision->getClearingEvents() as $event) { $eventIds[] = $event->getEventId(); } assertThat($eventIds, arrayValue($addedEventIds[0])); assertThat($eventIds, arrayValue($addedEventIds[1])); assertThat($eventIds, arrayWithSize(1 + count($addedEventIds))); $this->rmRepo(); }