/** * Renders an asset from the controller. * * @param array The parameters passed into the function. * The parameters that can be passed to this function are as follows. * - <b>name</b>: The name of the asset. * - <b>tag</b>: The type of tag to wrap the asset in. * - <b>id</b>: The id of the tag if different than the name. * @param Smarty The smarty object rendering the template. * @return The rendered asset. */ function smarty_function_asset($Params, &$Smarty) { $Name = ArrayValue('name', $Params); $Tag = ArrayValue('tag', $Params, ''); $Id = ArrayValue('id', $Params, $Name); $Class = ArrayValue('class', $Params, ''); if ($Class != '') { $Class = ' class="' . $Class . '"'; } $Controller = $Smarty->get_template_vars('Controller'); // Get the asset from the controller. $Asset = $Controller->GetAsset($Name); if (!is_string($Asset)) { ob_start(); $Asset->Render(); $Asset = ob_get_contents(); ob_end_clean(); } if (!empty($Tag)) { $Result = '<' . $Tag . ' id="' . $Id . '"' . $Class . '>' . $Asset . '</' . $Tag . '>'; } else { $Result = $Asset; } return $Result; }
/** * Returns the path to the application's dispatcher. Optionally with the * domain prepended. * ie. http://domain.com/[web_root]/index.php/request * * @param boolean $WithDomain Should it include the domain with the WebRoot? Default is FALSE. * @return string */ public static function WebRoot($WithDomain = FALSE) { static $WebRoot = NULL; if (is_null($WebRoot)) { // Attempt to get the webroot from the configuration array $WebRoot = Gdn::Config('Garden.WebRoot'); // Attempt to get the webroot from the server if ($WebRoot === FALSE) { $WebRoot = explode('/', ArrayValue('PHP_SELF', $_SERVER, '')); // Look for index.php to figure out where the web root is. $Key = array_search('index.php', $WebRoot); if ($Key !== FALSE) { $WebRoot = implode('/', array_slice($WebRoot, 0, $Key)); } else { $WebRoot = ''; } } } if (is_string($WebRoot) && $WebRoot != '') { // Strip forward slashes from the beginning of webroot return ($WithDomain ? Gdn_Url::Domain() : '') . preg_replace('/(^\\/+)/', '', $WebRoot); } else { return $WithDomain ? Gdn_Url::Domain() : ''; } }
/** * Renders an asset from the controller. * * @param array The parameters passed into the function. * The parameters that can be passed to this function are as follows. * - <b>name</b>: The name of the asset. * - <b>tag</b>: The type of tag to wrap the asset in. * - <b>id</b>: The id of the tag if different than the name. * @param Smarty The smarty object rendering the template. * @return The rendered asset. */ function smarty_function_asset($Params, &$Smarty) { $Name = ArrayValue('name', $Params); $Tag = ArrayValue('tag', $Params, ''); $Id = ArrayValue('id', $Params, $Name); $Class = ArrayValue('class', $Params, ''); if ($Class != '') { $Class = ' class="' . $Class . '"'; } $Controller = $Smarty->Controller; $Controller->EventArguments['AssetName'] = $Name; $Result = ''; ob_start(); $Controller->FireEvent('BeforeRenderAsset'); $Result .= ob_get_clean(); $Asset = $Controller->GetAsset($Name); if (!is_string($Asset)) { $Asset->AssetName = $Name; $Asset = $Asset->ToString(); } if (!empty($Tag)) { $Result .= '<' . $Tag . ' id="' . $Id . '"' . $Class . '>' . $Asset . '</' . $Tag . '>'; } else { $Result .= $Asset; } ob_start(); $Controller->FireEvent('AfterRenderAsset'); $Result .= ob_get_clean(); return $Result; }
public function Base_Render_Before(&$Sender) { $ConfigItem = C('WhosOnline.Location.Show', 'every'); $Controller = $Sender->ControllerName; $Application = $Sender->ApplicationFolder; $Session = Gdn::Session(); // Check if its visible to users if (C('WhosOnline.Hide', TRUE) && !$Session->IsValid()) { return; } $ShowOnController = array(); switch ($ConfigItem) { case 'every': $ShowOnController = array('discussioncontroller', 'categoriescontroller', 'discussionscontroller', 'profilecontroller', 'activitycontroller'); break; case 'discussion': default: $ShowOnController = array('discussioncontroller', 'discussionscontroller', 'categoriescontroller'); } if (!InArrayI($Controller, $ShowOnController)) { return; } $UserMetaData = $this->GetUserMeta($Session->UserID, '%'); include_once PATH_PLUGINS . DS . 'WhosOnline' . DS . 'class.whosonlinemodule.php'; $WhosOnlineModule = new WhosOnlineModule($Sender); $WhosOnlineModule->GetData(ArrayValue('Plugin.WhosOnline.Invisible', $UserMetaData)); $Sender->AddModule($WhosOnlineModule); $Sender->AddJsFile('/plugins/WhosOnline/whosonline.js'); $Frequency = C('WhosOnline.Frequency', 4); if (!is_numeric($Frequency)) { $Frequency = 4; } $Sender->AddDefinition('WhosOnlineFrequency', $Frequency); }
/** * Renames a column in $this->Table(). * * @param string $OldName The name of the column to be renamed. * @param string $NewName The new name for the column being renamed. * @param string $TableName * @return boolean * @todo $TableName needs a description. */ public function RenameColumn($OldName, $NewName, $TableName = '') { if ($TableName != '') $this->_TableName = $TableName; // Get the schema for this table $OldPrefix = $this->Database->DatabasePrefix; $this->Database->DatabasePrefix = $this->_DatabasePrefix; $Schema = $this->Database->SQL()->FetchTableSchema($this->_TableName); $this->Database->DatabasePrefix = $OldPrefix; // Get the definition for this column $OldColumn = ArrayValue($OldName, $Schema); $NewColumn = ArrayValue($NewName, $Schema); // Make sure that one column, or the other exists if (!$OldColumn && !$NewColumn) throw new Exception(sprintf(T('The `%1$s` column does not exist.'),$OldName)); // Make sure the new column name isn't already taken if ($OldColumn && $NewColumn) throw new Exception(sprintf(T('You cannot rename the `%1$s` column to `%2$s` because that column already exists.'), $OldName, $NewName)); // Rename the column // The syntax for renaming a column is: // ALTER TABLE tablename CHANGE COLUMN oldname newname originaldefinition; if (!$this->Query('alter table `'.$this->_TableName.'` change column `'.$OldName.'` `'.$NewName.'` '.$this->_DefineColumn($OldColumn))) throw new Exception(sprintf(T('Failed to rename table `%1$s` to `%2$s`.'), $OldName, $NewName)); return TRUE; }
function smarty_function_anchor($Params, &$Smarty) { $Text = ArrayValue('text', $Params, ''); $Destination = ArrayValue('destination', $Params, ''); $CssClass = ArrayValue('class', $Params, ''); return Anchor($Text, $Destination, $CssClass); }
/** * 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 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->AddInsertFields($FormPostValues); // Validate the form posted values $MessageID = FALSE; if ($this->Validate($FormPostValues)) { $Fields = $this->Validation->SchemaValidationFields(); // All fields on the form that relate to the schema $MessageID = $this->SQL->Insert($this->Name, $Fields); $ConversationID = ArrayValue('ConversationID', $Fields, 0); // Update the conversation's DateUpdated field $this->SQL->Update('Conversation')->Set('DateUpdated', Format::ToDateTime())->Set('UpdateUserID', $Session->UserID)->Where('ConversationID', $ConversationID)->Put(); // NOTE: INCREMENTING COUNTS INSTEAD OF GETTING ACTUAL COUNTS COULD // BECOME A PROBLEM. WATCH FOR IT. // Update the message counts for all users in the conversation $this->SQL->Update('UserConversation')->Set('CountMessages', 'CountMessages + 1', FALSE)->Where('ConversationID', $ConversationID)->Put(); $this->SQL->Update('UserConversation')->Set('CountNewMessages', 'CountNewMessages + 1', FALSE)->Where('ConversationID', $ConversationID)->Where('UserID <>', $Session->UserID)->Put(); // Update the CountUnreadConversations count on each user related to the discussion. $this->UpdateCountUnreadConversations($ConversationID, $Session->UserID); // Update the userconversation records to reflect the most recently // added message for all users other than the one that added the // message (otherwise they would see their name/message on the // conversation list instead of the person they are conversing with). $this->SQL->Update('UserConversation')->Set('LastMessageID', $MessageID)->Where('ConversationID', $ConversationID)->Where('UserID <>', $Session->UserID)->Put(); } return $MessageID; }
protected function _AttachBadge(&$Sender) { $badge = ArrayValue($Sender->EventArguments['Author']->UserID, $Sender->Data('Plugin-Badge-Counts')); if ($badge > 0) { $icon = file_exists('plugins/TopPosters/badges/' . $badge . '.png') ? $badge . '.png' : 'medal-icon.png'; echo '<span><img src="' . str_replace("index.php?p=", "", Gdn::Request()->Domain() . Url('plugins/TopPosters/badges/' . $icon)) . '" style="width:16px;height:16px;vertical-align:middle"></span>'; } }
/** * Takes a route and prepends the web root (expects "/controller/action/params" as $Destination). * * @param array The parameters passed into the function. * The parameters that can be passed to this function are as follows. * - <b>dest</b>: The destination of the url. * - <b>domain</b>: Whether or not to add the domain to the url. * - <b>removeSyndication</b>: Whether or not to remove any syndication from the url. * @param Smarty The smarty object rendering the template. * @return The url. */ function smarty_function_url($Params, &$Smarty) { $Destination = ArrayValue('dest', $Params, ''); $WithDomain = ArrayValue('domain', $Params, FALSE); $RemoveSyndication = ArrayValue('removeSyndication', $Params, FALSE); $Result = Url($Destination, $WithDomain, $RemoveSyndication); return $Result; }
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'); $MaxCommentLength = Gdn::Config('Vanilla.Comment.MaxLength'); if (is_numeric($MaxCommentLength) && $MaxCommentLength > 0) { $this->Validation->SetSchemaProperty('Body', 'Length', $MaxCommentLength); $this->Validation->ApplyRule('Body', 'Length'); } // Get the DraftID from the form so we know if we are inserting or updating. $DraftID = ArrayValue('DraftID', $FormPostValues, ''); $Insert = $DraftID == '' ? TRUE : FALSE; // Remove the discussionid from the form value collection if it's empty if (array_key_exists('DiscussionID', $FormPostValues) && $FormPostValues['DiscussionID'] == '') { unset($FormPostValues['DiscussionID']); } if ($Insert) { // If no categoryid is defined, grab the first available. if (ArrayValue('CategoryID', $FormPostValues) === FALSE) { $FormPostValues['CategoryID'] = $this->SQL->Get('Category', '', '', 1)->FirstRow()->CategoryID; } } // Add the update fields because this table's default sort is by DateUpdated (see $this->Get()). $this->AddInsertFields($FormPostValues); $this->AddUpdateFields($FormPostValues); // Remove checkboxes from the fields if they were unchecked if (ArrayValue('Announce', $FormPostValues, '') === FALSE) { unset($FormPostValues['Announce']); } if (ArrayValue('Closed', $FormPostValues, '') === FALSE) { unset($FormPostValues['Closed']); } if (ArrayValue('Sink', $FormPostValues, '') === FALSE) { unset($FormPostValues['Sink']); } // Validate the form posted values if ($this->Validate($FormPostValues, $Insert)) { $Fields = $this->Validation->SchemaValidationFields(); // All fields on the form that relate to the schema $DraftID = intval(ArrayValue('DraftID', $Fields, 0)); // If the post is new and it validates, make sure the user isn't spamming if ($DraftID > 0) { // Update the draft $Fields = RemoveKeyFromArray($Fields, 'DraftID'); // Remove the primary key from the fields for saving $this->SQL->Put($this->Name, $Fields, array($this->PrimaryKey => $DraftID)); } else { // Insert the draft unset($Fields['DraftID']); $DraftID = $this->SQL->Insert($this->Name, $Fields); $this->UpdateUser($Session->UserID); } } return $DraftID; }
public function Gdn_HandshakeAuthenticator_AfterGetHandshakeData_Handler(&$Sender) { $HandshakeData = ArrayValue('HandshakeData', $Sender->EventArguments); if (is_array($HandshakeData)) { // var_dump($HandshakeData); // exit(); // Do something based on the data returned from the handshake... } }
public function Edit($RouteIndex = FALSE) { $this->Permission('Garden.Routes.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(); }
/** * Special function automatically run upon clicking 'Enable' on your application. * Change the word 'skeleton' anywhere you see it. */ public function Setup() { // You need to manually include structure.php here for it to get run at install. include(PATH_APPLICATIONS . DS . 'skeleton' . DS . 'settings' . DS . 'structure.php'); // This just gets the version number and stores it in the config file. Good practice but optional. $ApplicationInfo = array(); include(CombinePaths(array(PATH_APPLICATIONS . DS . 'skeleton' . DS . 'settings' . DS . 'about.php'))); $Version = ArrayValue('Version', ArrayValue('Skeleton', $ApplicationInfo, array()), 'Undefined'); SaveToConfig('Skeleton.Version', $Version); }
public function Save($FormPostValues, $UserModel) { $Session = Gdn::Session(); $UserID = $Session->UserID; // 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); $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)); if ($TestData->NumRows() > 0) { $this->Validation->AddValidationResult('Email', 'An invitation has already been sent to the email you entered.'); return FALSE; } // Define the fields to be inserted $Fields = $this->Validation->SchemaValidationFields(); // Call the base model for saving $InvitationID = $this->Insert($Fields); // Now that saving has succeeded, update the user's invitation settings if ($InviteCount > 0) { $UserModel->ReduceInviteCount($UserID); } // And send the invitation email 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; }
/** * Returns the unique id assigned to the user in the database, 0 if the * username/password combination weren't found, or -1 if the user does not * have permission to sign in. * * @param string $Email The email address (or unique username) assigned to the user in the database. * @param string $Password The password assigned to the user in the database. * @return int The UserID of the authenticated user or 0 if one isn't found. */ public function Authenticate($Email = '', $Password = '') { if (!$Email || !$Password) { // We werent given parameters, check if they exist in our DataSource if ($this->CurrentStep() != Gdn_Authenticator::MODE_VALIDATE) return Gdn_Authenticator::AUTH_INSUFFICIENT; // Get the values from the DataSource $Email = $this->GetValue('Email'); $Password = $this->GetValue('Password'); $PersistentSession = $this->GetValue('RememberMe'); $ClientHour = $this->GetValue('ClientHour'); } else { $PersistentSession = FALSE; $ClientHour = 0; } $UserID = 0; // Retrieve matching username/password values $UserModel = Gdn::Authenticator()->GetUserModel(); $UserData = $UserModel->ValidateCredentials($Email, 0, $Password); if ($UserData !== FALSE) { // Get ID $UserID = $UserData->UserID; // Get Sign-in permission $SignInPermission = $UserData->Admin == '1' ? TRUE : FALSE; if ($SignInPermission === FALSE && !$UserData->Banned) { $PermissionModel = Gdn::Authenticator()->GetPermissionModel(); foreach($PermissionModel->GetUserPermissions($UserID) as $Permissions) { $SignInPermission |= ArrayValue('Garden.SignIn.Allow', $Permissions, FALSE); } } // Update users Information $UserID = $SignInPermission ? $UserID : -1; if ($UserID > 0) { // Create the session cookie $this->SetIdentity($UserID, $PersistentSession); // Update some information about the user... $UserModel->UpdateLastVisit($UserID, $UserData->Attributes, $ClientHour); Gdn::Authenticator()->Trigger(Gdn_Authenticator::AUTH_SUCCESS); $this->FireEvent('Authenticated'); } else { Gdn::Authenticator()->Trigger(Gdn_Authenticator::AUTH_DENIED); } } return $UserID; }
public function GetHandshakeData() { if (is_array($this->_HandshakeData)) { return $this->_HandshakeData; } $UrlParts = parse_url($this->AuthenticateUrl); $Host = $UrlParts['host']; $Port = ArrayValue('port', $UrlParts, '80'); $Path = $UrlParts['path']; $Referer = Gdn_Url::WebRoot(TRUE); // Make a request to the authenticated Url to see if we are logged in. $Pointer = @fsockopen($Host, $Port, $ErrorNumber, $Error); if (!$Pointer) { throw new Exception(sprintf(Gdn::Translate('Encountered an error when attempting to authenticate handshake (%1$s): [%2$s] %3$s'), $this->AuthenticateUrl, $ErrorNumber, $Error)); } // Get the cookie. $Cookie = ''; foreach ($_COOKIE as $Key => $Value) { if (strncasecmp($Key, 'XDEBUG', 6) == 0) { continue; } if (strlen($Cookie) > 0) { $Cookie .= '; '; } $Cookie .= $Key . '=' . urlencode($Value); } if (strlen($Cookie) > 0) { $Cookie = "Cookie: {$Cookie}\r\n"; } // Send the necessary headers to get the file fputs($Pointer, "GET {$Path} HTTP/1.0\r\n" . "Host: {$Host}\r\n" . "User-Agent: Vanilla/1.0\r\n" . "Accept: */*\r\n" . "Accept-Charset: utf-8;\r\n" . "Keep-Alive: 300\r\n" . "Connection: keep-alive\r\n" . "Referer: {$Referer}\r\n" . $Cookie . "\r\n"); // Retrieve the response from the remote server $Response = ''; $InBody = FALSE; while ($Line = fread($Pointer, 4096)) { $Response .= $Line; } fclose($Pointer); // Remove response headers $Response = trim(substr($Response, strpos($Response, "\r\n\r\n") + 4)); switch ($this->Encoding) { case 'json': $Result = json_decode($Response, TRUE); break; case 'ini': default: $Result = parse_ini_string($Response); break; } $this->_HandshakeData = $Result; return $Result; }
public function Init($Config = NULL) { if (is_null($Config)) { $Config = Gdn::Config('Garden.Cookie'); } elseif (is_string($Config)) { $Config = Gdn::Config($Config); } $DefaultConfig = Gdn::Config('Garden.Cookie'); $this->CookieName = ArrayValue('Name', $Config, $DefaultConfig['Name']); $this->CookiePath = ArrayValue('Path', $Config, $DefaultConfig['Path']); $this->CookieDomain = ArrayValue('Domain', $Config, $DefaultConfig['Domain']); $this->CookieHashMethod = ArrayValue('HashMethod', $Config, $DefaultConfig['HashMethod']); $this->CookieSalt = ArrayValue('Salt', $Config, $DefaultConfig['Salt']); }
public function CheckUniqueURI($Value = Null) { if (is_null($Value)) { return True; } if (is_array($Value)) { $Value = ArrayValue('URI', $Value); } $Data = $this->GetRequestUri($Value); if ($Data == False) { return True; } return False; }
/** * Includes a file in template. Handy for adding html files to tpl files * * @param array The parameters passed into the function. * The parameters that can be passed to this function are as follows. * - <b>name</b>: The name of the file. * @param Smarty The smarty object rendering the template. * @return The rendered asset. */ function smarty_function_include_file($Params, &$Smarty) { $Name = ltrim(ArrayValue('name', $Params), '/'); if (strpos($Name, '..') !== false) { return '<!-- Error, moving up directory path not allowed -->'; } if (IsUrl($Name)) { return '<!-- Error, urls are not allowed -->'; } $filename = rtrim($Smarty->template_dir, '/') . '/' . $Name; if (!file_exists($filename)) { return '<!-- Error, file does not exist -->'; } return file_get_contents($filename); }
public function Setup() { // Got Setup? $Database = Gdn::Database(); $Config = Gdn::Factory(Gdn::AliasConfig); $Drop = C('Skeleton.Version') === FALSE ? TRUE : FALSE; $Explicit = TRUE; $Validation = new Gdn_Validation(); // This is going to be needed by structure.php to validate permission names include PATH_APPLICATIONS . DS . 'skeleton' . DS . 'settings' . DS . 'structure.php'; $ApplicationInfo = array(); include CombinePaths(array(PATH_APPLICATIONS . DS . 'skeleton' . DS . 'settings' . DS . 'about.php')); $Version = ArrayValue('Version', ArrayValue('Skeleton', $ApplicationInfo, array()), 'Undefined'); SaveToConfig('Skeleton.Version', $Version); }
public function GetRoute($Route) { if (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'])); }
public function Save($FormPostValues) { // Define the primary key in this model's table. $this->DefineSchema(); // Add & apply any extra validation rules: $this->Validation->ApplyRule('Body', 'Required'); $this->Validation->ApplyRule('ReplyCommentID', 'Required'); // Add/define extra fields for saving $ReplyCommentID = intval(ArrayValue('ReplyCommentID', $FormPostValues, 0)); $Discussion = $this->SQL->Select('c.DiscussionID, d.Name, d.CategoryID')->From('Comment c')->Join('Discussion d', 'd.DiscussionID = c.DiscussionID')->Where('c.CommentID', $ReplyCommentID)->Get()->FirstRow(); if (is_object($Discussion)) { $FormPostValues['DiscussionID'] = $Discussion->DiscussionID; } $CommentID = ArrayValue('CommentID', $FormPostValues); $Insert = $CommentID === FALSE ? TRUE : FALSE; if ($Insert) { $this->AddInsertFields($FormPostValues); // Check for spam $this->CheckForSpam('Comment'); // Comments and replies use the same spam check rules } else { $this->AddUpdateFields($FormPostValues); } // Validate the form posted values if ($this->Validation->Validate($FormPostValues, $Insert)) { $Fields = $this->Validation->SchemaValidationFields(); $Fields = RemoveKeyFromArray($Fields, $this->PrimaryKey); $Session = Gdn::Session(); // Make sure there are no reply drafts. if ($Insert === FALSE) { $this->SQL->Put($this->Name, $Fields, array('CommentID' => $CommentID)); } else { $CommentID = $this->SQL->Insert($this->Name, $Fields); $this->UpdateReplyCount($ReplyCommentID); // Report user-comment activity $this->RecordActivity($ReplyCommentID, $Session->UserID, $CommentID); } // Index the comment. $Search = Gdn::Factory('SearchModel'); if (!is_null($Search)) { // Index the discussion. $Document = array('TableName' => 'Comment', 'PrimaryID' => $CommentID, 'PermissionJunctionID' => $Discussion->CategoryID, 'Title' => $Discussion->Name, 'Summary' => $Fields['Body'], 'Url' => '/discussion/comment/' . $ReplyCommentID . '/#Comment_' . $CommentID, 'InsertUserID' => $Session->UserID); $Search->Index($Document); } } return $CommentID; }
public function EnableTheme($ThemeName) { // 1. Make sure that the theme's requirements are met $ApplicationManager = new Gdn_ApplicationManager(); $EnabledApplications = $ApplicationManager->EnabledApplications(); $AvailableThemes = $this->AvailableThemes(); $NewThemeInfo = ArrayValue($ThemeName, $AvailableThemes, array()); $RequiredApplications = ArrayValue('RequiredApplications', $NewThemeInfo, FALSE); CheckRequirements($ThemeName, $RequiredApplications, $EnabledApplications, 'application'); // Applications // 5. Set the theme $ThemeFolder = ArrayValue('Folder', $NewThemeInfo, ''); if ($ThemeFolder == '') { throw new Exception(Gdn::Translate('The theme folder was not properly defined.')); } else { SaveToConfig('Garden.Theme', $ThemeFolder); } return TRUE; }
public function Query($Sql, $InputParameters = NULL, $Options = array()) { $Trace = debug_backtrace(); $Method = ''; foreach ($Trace as $Info) { $Class = GetValue('class', $Info, ''); if ($Class === '' || StringEndsWith($Class, 'Model', TRUE) || StringEndsWith($Class, 'Plugin', TRUE)) { $Type = ArrayValue('type', $Info, ''); $Method = $Class . $Type . $Info['function'] . '(' . self::FormatArgs($Info['args']) . ')'; break; } } // Save the query for debugging // echo '<br />adding to queries: '.$Sql; $Query = array('Sql' => $Sql, 'Parameters' => $InputParameters, 'Method' => $Method); $SaveQuery = TRUE; if (isset($Options['Cache'])) { $CacheKeys = (array) $Options['Cache']; $Cache = array(); $AllSet = TRUE; foreach ($CacheKeys as $CacheKey) { $Value = Gdn::Cache()->Get($CacheKey); $CacheValue = $Value !== Gdn_Cache::CACHEOP_FAILURE; $AllSet &= $CacheValue; $Cache[$CacheKey] = $CacheValue; } $SaveQuery = !$AllSet; $Query['Cache'] = $Cache; } // Start the Query Timer $TimeStart = Now(); $Result = parent::Query($Sql, $InputParameters, $Options); $Query = array_merge($this->LastInfo, $Query); // Aggregate the query times $TimeEnd = Now(); $this->_ExecutionTime += $TimeEnd - $TimeStart; if ($SaveQuery && !StringBeginsWith($Sql, 'set names')) { $Query['Time'] = $TimeEnd - $TimeStart; $this->_Queries[] = $Query; } return $Result; }
protected function GetUserEmails($FormValues) { $SQL = Gdn::SQL(); $UserModel = Gdn::UserModel(); if (ArrayValue('SendMeOnly', $FormValues)) { $Session = Gdn::Session(); $UserID = GetValueR('User.UserID', $Session); $User = $UserModel->Get($UserID); $Result[$User->Email] = $User->Name; return $Result; } $Roles = ArrayValue('Roles', $FormValues); if (is_array($Roles) && count($Roles) > 0) { $DataSet = $SQL->Select('u.Name, u.Email')->From('UserRole r')->Join('User u', 'u.UserID = r.UserID')->WhereIn('r.RoleID', $Roles)->Get(); } else { $DataSet = $SQL->Select('u.Name, u.Email')->From('User u')->Get(); } $Result = ConsolidateArrayValuesByKey($DataSet->ResultArray(), 'Email', 'Name'); return $Result; }
/** * Setup the application. * * The methods in setup controllers should not call "Render". Rendering will * be handled by the controller that initiated the setup. This method should * return a boolean value indicating success. * * @return bool True on successful setup */ public function Index() { $Database = Gdn::Database(); $Config = Gdn::Factory(Gdn::AliasConfig); $Drop = Gdn::Config('Conversations.Version') === FALSE ? TRUE : FALSE; $Explicit = TRUE; $Validation = new Gdn_Validation(); // This is going to be needed by structure.php to validate permission names try { include PATH_APPLICATIONS . DS . 'conversations' . DS . 'settings' . DS . 'structure.php'; } catch (Exception $ex) { $this->Form->AddError(strip_tags($ex->getMessage())); } if ($this->Form->ErrorCount() == 0) { $ApplicationInfo = array(); include CombinePaths(array(PATH_APPLICATIONS . DS . 'conversations' . DS . 'settings' . DS . 'about.php')); $Version = ArrayValue('Version', ArrayValue('Conversations', $ApplicationInfo, array()), 'Undefined'); SaveToConfig('Conversations.Version', $Version); } return $this->Form->ErrorCount() > 0 ? FALSE : TRUE; }
/** * Renders an asset from the controller. * * @param array The parameters passed into the function. * The parameters that can be passed to this function are as follows. * - <b>name</b>: The name of the asset. * - <b>tag</b>: The type of tag to wrap the asset in. * - <b>id</b>: The id of the tag if different than the name. * @param Smarty The smarty object rendering the template. * @return The rendered asset. */ function smarty_function_asset($Params, &$Smarty) { $Name = ArrayValue('name', $Params); $Tag = ArrayValue('tag', $Params, ''); $Id = ArrayValue('id', $Params, $Name); $Class = ArrayValue('class', $Params, ''); if ($Class != '') { $Class = ' class="' . $Class . '"'; } $Controller = $Smarty->Controller; // Get the asset from the controller. $Asset = $Controller->GetAsset($Name); if (!is_string($Asset)) { $Asset = $Asset->ToString(); } if (!empty($Tag)) { $Result = '<' . $Tag . ' id="' . $Id . '"' . $Class . '>' . $Asset . '</' . $Tag . '>'; } else { $Result = $Asset; } return $Result; }
/** * @todo Put the query debugging logic into the debug plugin. * 1. Create a subclass of this object where Query() does the debugging stuff. * 2. Install that class to Gdn to override the database. */ public function Query($Sql, $InputParameters = NULL) { $Trace = debug_backtrace(); $Method = ''; foreach ($Trace as $Info) { $Class = ArrayValue('class', $Info, ''); if ($Class === '' || strlen($Class) > 5 && substr_compare($Class, 'Model', -5, 5, FALSE) == 0) { $Type = ArrayValue('type', $Info, ''); $Method = $Class . $Type . $Info['function'] . '(' . self::FormatArgs($Info['args']) . ')'; } } // Save the query for debugging // echo '<br />adding to queries: '.$Sql; $this->_Queries[] = array('Sql' => $Sql, 'Parameters' => $InputParameters, 'Method' => $Method); // Start the Query Timer $TimeStart = list($sm, $ss) = explode(' ', microtime()); $Result = parent::Query($Sql, $InputParameters); // Aggregate the query times $TimeEnd = list($em, $es) = explode(' ', microtime()); $this->_ExecutionTime += $em + $es - ($sm + $ss); $this->_QueryTimes[] = $em + $es - ($sm + $ss); return $Result; }
function LingvoTranslate($Word, $Options = array()) { LoadPhpQuery(); static $Result, $LanguageCode; if (is_null($LanguageCode)) { $LanguageCode = LocaleLanguageCode(); } $ResetCache = ArrayValue('ResetCache', $Options, False); $From = ArrayValue('From', $Options, $LanguageCode); $To = ArrayValue('To', $Options, $LanguageCode); if (!isset($Result[$Word]) || $ResetCache) { $Direction = $From . '-' . $To; $Url = 'http://lingvo.abbyyonline.com/en/' . $Direction . '/' . rawurlencode($Word); $Doc = PhpQuery::NewDocumentFile($Url); /*$Translation = Pq('div.card-short > span.Bold')->Text(); if($Translation != ''){ $Translation = preg_replace('/\n/', '', $Translation); if(!preg_match('/^[а-я ]+$/iu', $Translation)){ $Translation = Pq('span.translation:eq(0)')->Text(); } }*/ Pq('span.translation:eq(0)')->Children()->Remove(); $Translation = Pq('span.translation:eq(0)')->Text(); $Translation = trim($Translation); $Result[$Word] = $Translation; } return $Result[$Word]; }