public function Comment() { $Session = Gdn::Session(); $this->Form->SetModel($this->ActivityModel); $NewActivityID = 0; if ($this->Form->AuthenticatedPostBack()) { $Body = $this->Form->GetValue('Body', ''); $ActivityID = $this->Form->GetValue('ActivityID', ''); if ($Body != '' && is_numeric($ActivityID) && $ActivityID > 0) { $NewActivityID = $this->ActivityModel->Add($Session->UserID, 'ActivityComment', $Body, '', $ActivityID, '', TRUE); } } // Redirect back to the sending location if this isn't an ajax request if ($this->_DeliveryType === DELIVERY_TYPE_ALL) { Redirect($this->Form->GetValue('Return', Gdn_Url::WebRoot())); } else { // Load the newly added comment $this->Comment = $this->ActivityModel->GetID($NewActivityID); $this->Comment->ActivityType .= ' Hidden'; // Hide it so jquery can reveal it // Set it in the appropriate view $this->View = 'comment'; // And render $this->Render(); } }
/** * Manage the current ranks and add new ones */ public function Settings() { $this->Permission('Yaga.Ranks.Manage'); $this->AddSideMenu('rank/settings'); $this->Title(T('Yaga.Ranks.Manage')); // Get list of ranks from the model and pass to the view $this->SetData('Ranks', $this->RankModel->Get()); if ($this->Form->IsPostBack() == TRUE) { // Handle the photo upload $Upload = new Gdn_Upload(); $TmpImage = $Upload->ValidateUpload('PhotoUpload', FALSE); if ($TmpImage) { // Generate the target image name $TargetImage = $Upload->GenerateTargetName(PATH_UPLOADS); $ImageBaseName = pathinfo($TargetImage, PATHINFO_BASENAME); // Save the uploaded image $Parts = $Upload->SaveAs($TmpImage, 'yaga' . DS . $ImageBaseName); $RelativeUrl = StringBeginsWith($Parts['Url'], Gdn_Url::WebRoot(TRUE), TRUE, TRUE); SaveToConfig('Yaga.Ranks.Photo', $RelativeUrl); if (C('Yaga.Ranks.Photo') == $Parts['SaveName']) { $this->InformMessage(T('Yaga.Rank.PhotoUploaded')); } } } include_once $this->FetchViewLocation('helper_functions', 'rank'); $this->Render(); }
private function BuildPager($Sender, $Total) { $Sanitized = $this->ValidateInputs(); //get offset $GETString = '?' . Gdn_Url::QueryString() . '&tar=srch'; //use this to providea link back to search - be sure to append the '&tar=srch' to tell to load the main search page $GETString = str_replace('p=search&', 'search?', $GETString); //echo $GETString; die; $Limit = $this->Settings['Admin']->LimitResultsPage; $Offset = ($Sanitized['Offset'] - 1) * $Limit; //limit per page $Pos = strpos($GETString, '&pg=' . $_GET['pg']); if (!$Pos == FALSE) { //$Url = substr($GETString, 0, $Pos); //strip the page number if it exists $Url = str_replace('&pg=' . GetIncomingValue('pg'), '', $GETString); //strip the page number if it exists $Url = str_replace('&tar=srch', '', $Url); //don't want to load adv search page when clicking page numbers } else { $Url = str_replace('&tar=srch', '', $GETString); } //don't want to load adv search page when clicking page numbers $PagerFactory = new Gdn_PagerFactory(); $Sender->Pager = $PagerFactory->GetPager('Pager', $Sender); $Sender->Pager->MoreCode = '>'; $Sender->Pager->LessCode = '<'; $Sender->Pager->ClientID = 'Pager'; $Sender->Pager->Configure($Offset, $Limit, $Total, $Url . '&pg=%1$s'); //echo $Url; die; $Sender->SetData('GETString', $GETString); }
private function insert_oa_login($caption, $element, $callback_uri) { $providers = implode(',', array_map(function ($p) { return "'" . $p . "'"; }, C(self::CONFIG_PREFIX . 'Providers', array()))); $host = Gdn_Url::webRoot(TRUE); return "<h4 class='login-title'>{$caption}</h4>\r\n\t\t\t\t<div class='oneall_social_login_providers' id='{$element}'></div>\r\n\t\t\t\t<!-- OneAll Social Login : http://www.oneall.com //-->\r\n\t\t\t\t<script type='text/javascript'>\r\n\t\t\t\t\t// <![CDATA[\r\n\t\t\t\t\tvar _oneall = _oneall || [];\r\n\t\t\t\t\t_oneall.push(['social_login', 'set_providers', [{$providers}]]);\r\n\t\t\t\t\t_oneall.push(['social_login', 'set_callback_uri', '{$host}{$callback_uri}']);\r\n\t\t\t\t\t_oneall.push(['social_login', 'set_custom_css_uri', (('https:' == document.location.protocol) ? 'https://secure' : 'http://public') + '.oneallcdn.com/css/api/socialize/themes/wordpress/default.css']);\r\n\t\t\t\t\t_oneall.push(['social_login', 'do_render_ui', '{$element}']);\r\n\t\t\t\t\t// ]]>\r\n\t\t\t\t</script>"; }
public function ActivityController_Render_Before(&$Sender) { $Session = Gdn::Session(); if (!$Session->CheckPermission('Plugins.Privacy.Activity')) { if (!$Session->IsValid()) { Redirect(Gdn::Authenticator()->SignInUrl(Gdn_Url::Request())); } else { Redirect(Gdn::Config('Routes.DefaultPermission')); } } }
public function Check($Type = '', $Name = '') { if ($Type != '' && $Name != '') { $this->AddItem($Type, $Name); } if (count($this->_Items) > 0) { // TODO: Use garden update check url instead of this: $UpdateUrl = Url('/lussumo/update', TRUE, TRUE); $Host = Gdn_Url::Host(); $Path = CombinePaths(array(Gdn_Url::WebRoot(), 'lussumo', 'update'), '/'); $Port = 80; /* $UpdateUrl = Gdn::Config('Garden.UpdateCheckUrl', ''); $UpdateUrl = parse_url($UpdateUrl); $Host = ArrayValue('host', $UpdateUrl, 'www.lussumo.com'); $Path = ArrayValue('path', $UpdateUrl, '/'); $Port = ArrayValue('port', $UpdateUrl, '80'); */ $Path .= '?Check=' . urlencode(Format::Serialize($this->_Items)); $Locale = Gdn::Config('Garden.Locale', 'Undefined'); $Referer = Gdn_Url::WebRoot(TRUE); if ($Referer === FALSE) { $Referer = 'Undefined'; } $Timeout = 10; $Response = ''; // Connect to the update server. $Pointer = @fsockopen($Host, '80', $ErrorNumber, $Error, $Timeout); if (!$Pointer) { throw new Exception(sprintf(Gdn::Translate('Encountered an error when attempting to connect to the update server (%1$s): [%2$s] %3$s'), $UpdateUrl, $ErrorNumber, $Error)); } else { // send the necessary headers to get the file fputs($Pointer, "GET {$Path} HTTP/1.0\r\n" . "Host: {$Host}\r\n" . "User-Agent: Lussumo Garden/1.0\r\n" . "Accept: */*\r\n" . "Accept-Language: " . $Locale . "\r\n" . "Accept-Charset: utf-8;\r\n" . "Keep-Alive: 300\r\n" . "Connection: keep-alive\r\n" . "Referer: {$Referer}\r\n\r\n"); // Retrieve the response from the remote server while ($Line = fread($Pointer, 4096)) { $Response .= $Line; } fclose($Pointer); // Remove response headers $Response = substr($Response, strpos($Response, "\r\n\r\n") + 4); } $Result = Format::Unserialize($Response); // print_r($Result); if (is_array($Result)) { $this->_Items = $Result; } else { $Result = FALSE; } return $Result; } }
/* Copyright 2008, 2009 Mark O'Sullivan This file is part of Garden. Garden is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Garden is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Garden. If not, see <http://www.gnu.org/licenses/>. Contact Mark O'Sullivan at mark [at] lussumo [dot] com */ // Report and track all errors. error_reporting(E_ALL); ini_set('display_errors', 'on'); ini_set('track_errors', 1); ob_start(); // 1. Define the constants we need to get going. define('APPLICATION', 'Garden'); define('APPLICATION_VERSION', '1.0'); define('DS', DIRECTORY_SEPARATOR); define('PATH_ROOT', dirname(__FILE__)); // 2. Include the header. require_once PATH_ROOT . DS . 'bootstrap.php'; // 3. Start the application. if (strpos(Gdn_Url::Request(), 'gardensetup') === FALSE) { Gdn::Session()->Start(Gdn::Authenticator()); } $Dispatcher = Gdn::Dispatcher(); $EnabledApplications = Gdn::Config('EnabledApplications'); $Dispatcher->EnabledApplicationFolders($EnabledApplications); $Dispatcher->PassProperty('EnabledApplications', $EnabledApplications); $Dispatcher->Routes = Gdn::Config('Routes'); // Process the request. $Dispatcher->Dispatch();
/** * Checks whether the current request url matches an item's link url. * * @param array $item The item to check. * @return bool Whether the current request url matches an item's link url. */ protected function isActive($item) { if (empty($this->highlightRoute)) { $highlightRoute = Gdn_Url::request(true); } else { $highlightRoute = url($this->highlightRoute); } return val('url', $item) && trim(url(val('url', $item)), '/') == trim($highlightRoute, '/'); }
/** * Returns the xhtml for the opening of the form (the form tag and all * hidden elements). * * @param array $Attributes An associative array of attributes for the form tag. Here is a list of * "special" attributes and their default values: * * Attribute Options Default * ---------------------------------------- * method get,post post * action [any url] [The current url] * ajax TRUE,FALSE FALSE * * @return string * * @todo check that missing DataObject parameter */ public function Open($Attributes = FALSE) { $Return = '<form'; if ($this->InputPrefix != '') { $Return .= $this->_IDAttribute($this->InputPrefix, $Attributes); } // Method $MethodFromAttributes = ArrayValueI('method', $Attributes); $this->Method = $MethodFromAttributes === FALSE ? $this->Method : $MethodFromAttributes; // Action $ActionFromAttributes = ArrayValueI('action', $Attributes); if ($this->Action == '') { $this->Action = Url(Gdn_Url::Request()); } $this->Action = $ActionFromAttributes === FALSE ? $this->Action : $ActionFromAttributes; $Return .= ' method="' . $this->Method . '"' . ' action="' . $this->Action . '"' . $this->_AttributesToString($Attributes) . ">\n"; // Postback Key - don't allow it to be posted in the url (prevents csrf attacks & hijacks) if ($this->Method != "get") { $Session = Gdn::Session(); $Return .= $this->Hidden('TransientKey', array('value' => $Session->TransientKey())); // Also add a honeypot if Forms.HoneypotName has been defined $HoneypotName = Gdn::Config('Garden.Forms.HoneypotName'); if ($HoneypotName) { $Return .= $this->Hidden($HoneypotName, array('Name' => $HoneypotName, 'style' => "display: none;")); } } // Render all other hidden inputs that have been defined $Return .= $this->GetHidden(); return $Return; }
function WriteActivityComment($Comment, &$Sender, &$Session) { $Author = UserBuilder($Comment, 'Activity'); $PhotoAnchor = UserPhoto($Author, 'Photo'); $CssClass = 'Item ActivityComment Condensed ' . $Comment->ActivityType; if ($PhotoAnchor != '') { $CssClass .= ' HasPhoto'; } ?> <li id="Activity_<?php echo $Comment->ActivityID; ?> " class="<?php echo $CssClass; ?> "> <?php if ($PhotoAnchor != '') { ?> <div class="Author Photo"><?php echo $PhotoAnchor; ?> </div> <?php } ?> <div class="ItemContent ActivityComment"> <?php echo UserAnchor($Author, 'Title Name'); ?> <div class="Excerpt"><?php echo Gdn_Format::Display($Comment->Story); ?> </div> <div class="Meta"> <span class="DateCreated"><?php echo Gdn_Format::Date($Comment->DateInserted); ?> </span> <?php if ($Session->UserID == $Comment->InsertUserID || $Session->CheckPermission('Garden.Activity.Delete')) { echo Anchor(T('Delete'), 'dashboard/activity/delete/' . $Comment->ActivityID . '/' . $Session->TransientKey() . '?Return=' . urlencode(Gdn_Url::Request()), 'DeleteComment'); } ?> </div> </div> </li> <?php }
/** * * * @param string $HighlightRoute * @return string * @throws Exception */ public function toString($HighlightRoute = '') { if ($HighlightRoute == '') { $HighlightRoute = $this->_HighlightRoute; } if ($HighlightRoute == '') { $HighlightRoute = Gdn_Url::Request(); } $this->fireEvent('BeforeToString'); $Username = ''; $UserID = ''; $Session_TransientKey = ''; $Session = Gdn::session(); $Admin = false; if ($Session->isValid() === true) { $UserID = $Session->User->UserID; $Username = $Session->User->Name; $Session_TransientKey = $Session->TransientKey(); $Admin = $Session->User->Admin > 0 ? true : false; } $Menu = ''; if (count($this->Items) > 0) { // Apply the menu group sort if present... if (is_array($this->Sort)) { $Items = array(); $Count = count($this->Sort); for ($i = 0; $i < $Count; ++$i) { $Group = $this->Sort[$i]; if (array_key_exists($Group, $this->Items)) { $Items[$Group] = $this->Items[$Group]; unset($this->Items[$Group]); } } foreach ($this->Items as $Group => $Links) { $Items[$Group] = $Links; } } else { $Items = $this->Items; } foreach ($Items as $GroupName => $Links) { $ItemCount = 0; $LinkCount = 0; $OpenGroup = false; $Group = ''; foreach ($Links as $Key => $Link) { $CurrentLink = false; $ShowLink = false; $RequiredPermissions = array_key_exists('Permission', $Link) ? $Link['Permission'] : false; if ($RequiredPermissions !== false && !is_array($RequiredPermissions)) { $RequiredPermissions = explode(',', $RequiredPermissions); } // Show if there are no permissions or the user has ANY of the specified permissions or the user is admin $ShowLink = $Admin || $RequiredPermissions === false || Gdn::session()->checkPermission($RequiredPermissions, false); if ($ShowLink === true) { if ($ItemCount == 1) { $Group .= '<ul>'; $OpenGroup = true; } elseif ($ItemCount > 1) { $Group .= "</li>\r\n"; } $Url = val('Url', $Link); if (substr($Link['Text'], 0, 1) === '\\') { $Text = substr($Link['Text'], 1); } else { $Text = str_replace('{Username}', $Username, $Link['Text']); } $Attributes = val('Attributes', $Link, array()); $AnchorAttributes = val('AnchorAttributes', $Link, array()); if ($Url !== false) { $Url = url(str_replace(array('{Username}', '{UserID}', '{Session_TransientKey}'), array(urlencode($Username), $UserID, $Session_TransientKey), $Link['Url'])); $CurrentLink = $Url == url($HighlightRoute); $CssClass = val('class', $Attributes, ''); if ($CurrentLink) { $Attributes['class'] = $CssClass . ' Highlight'; } $Group .= '<li' . Attribute($Attributes) . '><a' . Attribute($AnchorAttributes) . ' href="' . $Url . '">' . $Text . '</a>'; ++$LinkCount; } else { $Group .= '<li' . Attribute($Attributes) . '>' . $Text; } ++$ItemCount; } } if ($OpenGroup === true) { $Group .= "</li>\r\n</ul>\r\n"; } if ($Group != '' && $LinkCount > 0) { $Menu .= $Group . "</li>\r\n"; } } if ($Menu != '') { $Menu = '<ul id="' . $this->HtmlId . '"' . ($this->CssClass != '' ? ' class="' . $this->CssClass . '"' : '') . '>' . $Menu . '</ul>'; } } return $Menu; }
public function ToString($HighlightRoute = '') { if ($HighlightRoute == '') { $HighlightRoute = $this->_HighlightRoute; } if ($HighlightRoute == '') { $HighlightRoute = Gdn_Url::Request(); } $HighlightUrl = Url($HighlightRoute); // Apply a sort to the items if given. if (is_array($this->Sort)) { $Sort = array_flip($this->Sort); foreach ($this->Items as $Group => &$Item) { if (isset($Sort[$Group])) { $Item['Sort'] = $Sort[$Group]; } else { $Item['_Sort'] += count($Sort); } foreach ($Item['Links'] as $Url => &$Link) { if (isset($Sort[$Url])) { $Link['Sort'] = $Sort[$Url]; } elseif (isset($Sort[$Link['Text']])) { $Link['Sort'] = $Sort[$Link['Text']]; } else { $Link['_Sort'] += count($Sort); } } } } // Sort the groups. $this->_Compare($this->Items); uasort($this->Items, array($this, '_Compare')); // Sort the items within the groups. foreach ($this->Items as &$Item) { $this->_Compare($Item['Links']); uasort($Item['Links'], array($this, '_Compare')); // Highlight the group. if (GetValue('Url', $Item) && Url($Item['Url']) == $HighlightUrl) { $Item['Attributes']['class'] = ConcatSep(' ', GetValue('class', $Item['Attributes']), 'Active'); } // Hightlight the correct item in the group. foreach ($Item['Links'] as &$Link) { if (GetValue('Url', $Link) && Url($Link['Url']) == $HighlightUrl) { $Link['Attributes']['class'] = ConcatSep(' ', GetValue('class', $Link['Attributes']), 'Active'); $Item['Attributes']['class'] = ConcatSep(' ', GetValue('class', $Item['Attributes']), 'Active'); } } } return parent::ToString(); }
/** * Create an admin user account. * * @param array $FormPostValues */ public function saveAdminUser($FormPostValues) { $UserID = 0; // Add & apply any extra validation rules: $Name = val('Name', $FormPostValues, ''); $FormPostValues['Email'] = val('Email', $FormPostValues, strtolower($Name . '@' . Gdn_Url::host())); $FormPostValues['ShowEmail'] = '0'; $FormPostValues['TermsOfService'] = '1'; $FormPostValues['DateOfBirth'] = '1975-09-16'; $FormPostValues['DateLastActive'] = Gdn_Format::toDateTime(); $FormPostValues['DateUpdated'] = Gdn_Format::toDateTime(); $FormPostValues['Gender'] = 'u'; $FormPostValues['Admin'] = '1'; $this->addInsertFields($FormPostValues); if ($this->validate($FormPostValues, true) === true) { $Fields = $this->Validation->schemaValidationFields(); // Only fields that are present in the schema // Insert the new user $UserID = $this->insertInternal($Fields, ['NoConfirmEmail' => true, 'Setup' => true]); if ($UserID > 0) { $ActivityModel = new ActivityModel(); $ActivityModel->save(['ActivityUserID' => $UserID, 'ActivityType' => 'Registration', 'HeadlineFormat' => t('HeadlineFormat.Registration', '{ActivityUserID,You} joined.'), 'Story' => t('Welcome Aboard!')], false, ['GroupBy' => 'ActivityTypeID']); } $this->saveRoles($UserID, [16], false); } return $UserID; }
/** * Use curl or fsock to make a request to a remote server. * * @param string $Url The full url to the page being requested (including http://). * @param integer $Timeout How long to allow for this request. * Default Garden.SocketTimeout or 1, 0 to never timeout. * @param boolean $FollowRedirects Whether or not to follow 301 and 302 redirects. Defaults false. * @return string Returns the response body. */ function proxyRequest($Url, $Timeout = false, $FollowRedirects = false) { $OriginalTimeout = $Timeout; if ($Timeout === false) { $Timeout = c('Garden.SocketTimeout', 1.0); } $UrlParts = parse_url($Url); $Scheme = GetValue('scheme', $UrlParts, 'http'); $Host = GetValue('host', $UrlParts, ''); $Port = GetValue('port', $UrlParts, $Scheme == 'https' ? '443' : '80'); $Path = GetValue('path', $UrlParts, ''); $Query = GetValue('query', $UrlParts, ''); // Get the cookie. $Cookie = ''; $EncodeCookies = c('Garden.Cookie.Urlencode', true); foreach ($_COOKIE as $Key => $Value) { if (strncasecmp($Key, 'XDEBUG', 6) == 0) { continue; } if (strlen($Cookie) > 0) { $Cookie .= '; '; } $EValue = $EncodeCookies ? urlencode($Value) : $Value; $Cookie .= "{$Key}={$EValue}"; } $Response = ''; if (function_exists('curl_init')) { //$Url = $Scheme.'://'.$Host.$Path; $Handler = curl_init(); curl_setopt($Handler, CURLOPT_URL, $Url); curl_setopt($Handler, CURLOPT_PORT, $Port); curl_setopt($Handler, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($Handler, CURLOPT_HEADER, 1); curl_setopt($Handler, CURLOPT_USERAGENT, val('HTTP_USER_AGENT', $_SERVER, 'Vanilla/2.0')); curl_setopt($Handler, CURLOPT_RETURNTRANSFER, 1); if ($Cookie != '') { curl_setopt($Handler, CURLOPT_COOKIE, $Cookie); } if ($Timeout > 0) { curl_setopt($Handler, CURLOPT_TIMEOUT, $Timeout); } // TIM @ 2010-06-28: Commented this out because it was forcing all requests with parameters to be POST. //Same for the $Url above // //if ($Query != '') { // curl_setopt($Handler, CURLOPT_POST, 1); // curl_setopt($Handler, CURLOPT_POSTFIELDS, $Query); //} $Response = curl_exec($Handler); $Success = true; if ($Response == false) { $Success = false; $Response = ''; throw new Exception(curl_error($Handler)); } curl_close($Handler); } elseif (function_exists('fsockopen')) { $Referer = Gdn_Url::WebRoot(true); // Make the request $Pointer = @fsockopen($Host, $Port, $ErrorNumber, $Error, $Timeout); if (!$Pointer) { throw new Exception(sprintf(T('Encountered an error while making a request to the remote server (%1$s): [%2$s] %3$s'), $Url, $ErrorNumber, $Error)); } stream_set_timeout($Pointer, $Timeout); if (strlen($Cookie) > 0) { $Cookie = "Cookie: {$Cookie}\r\n"; } $HostHeader = $Host . ($Port != 80 ? ":{$Port}" : ''); $Header = "GET {$Path}?{$Query} HTTP/1.1\r\n" . "Host: {$HostHeader}\r\n" . "User-Agent: " . val('HTTP_USER_AGENT', $_SERVER, 'Vanilla/2.0') . "\r\n" . "Accept: */*\r\n" . "Accept-Charset: utf-8;\r\n" . "Referer: {$Referer}\r\n" . "Connection: close\r\n"; if ($Cookie != '') { $Header .= $Cookie; } $Header .= "\r\n"; // Send the headers and get the response fputs($Pointer, $Header); while ($Line = fread($Pointer, 4096)) { $Response .= $Line; } @fclose($Pointer); $Bytes = strlen($Response); $Response = trim($Response); $Success = true; $StreamInfo = stream_get_meta_data($Pointer); if (GetValue('timed_out', $StreamInfo, false) === true) { $Success = false; $Response = "Operation timed out after {$Timeout} seconds with {$Bytes} bytes received."; } } else { throw new Exception(T('Encountered an error while making a request to the remote server: Your PHP configuration does not allow curl or fsock requests.')); } if (!$Success) { return $Response; } $ResponseHeaderData = trim(substr($Response, 0, strpos($Response, "\r\n\r\n"))); $Response = trim(substr($Response, strpos($Response, "\r\n\r\n") + 4)); $ResponseHeaderLines = explode("\n", trim($ResponseHeaderData)); $Status = array_shift($ResponseHeaderLines); $ResponseHeaders = array(); $ResponseHeaders['HTTP'] = trim($Status); /* get the numeric status code. * - trim off excess edge whitespace, * - split on spaces, * - get the 2nd element (as a single element array), * - pop the first (only) element off it... * - return that. */ $Status = trim($Status); $Status = explode(' ', $Status); $Status = array_slice($Status, 1, 1); $Status = array_pop($Status); $ResponseHeaders['StatusCode'] = $Status; foreach ($ResponseHeaderLines as $Line) { $Line = explode(':', trim($Line)); $Key = trim(array_shift($Line)); $Value = trim(implode(':', $Line)); $ResponseHeaders[$Key] = $Value; } if ($FollowRedirects) { $Code = GetValue('StatusCode', $ResponseHeaders, 200); if (in_array($Code, array(301, 302))) { if (array_key_exists('Location', $ResponseHeaders)) { $Location = absoluteSource(GetValue('Location', $ResponseHeaders), $Url); return ProxyRequest($Location, $OriginalTimeout, $FollowRedirects); } } } return $Response; }
/** * Returns the Request part of the current url. ie. "/controller/action/" in * "http://localhost/garden/index.php/controller/action/". * * @param boolean $WithWebRoot * @param boolean $WithDomain * @param boolean $RemoveSyndication * @return string */ public static function Request($WithWebRoot = FALSE, $WithDomain = FALSE, $RemoveSyndication = FALSE) { $Return = ''; // TODO: Test this on various platforms/browsers. Very breakable. // Try PATH_INFO $Request = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : @getenv('PATH_INFO'); if ($Request) { $Return = $Request; } // Try ORIG_PATH_INFO if (!$Return) { $Request = isset($_SERVER['ORIG_PATH_INFO']) ? $_SERVER['ORIG_PATH_INFO'] : @getenv('ORIG_PATH_INFO'); if ($Request != '') { $Return = $Request; } } // Try with PHP_SELF if (!$Return) { $PhpSelf = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : @getenv('PHP_SELF'); $ScriptName = isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : @getenv('SCRIPT_NAME'); if ($PhpSelf && $ScriptName) { $Return = substr($PhpSelf, strlen($ScriptName)); } } $Return = trim($Return, '/'); if (strcasecmp(substr($Return, 0, 9), 'index.php') == 0) { $Return = substr($Return, 9); } $Return = trim($Return, '/'); if ($RemoveSyndication) { $Prefix = strtolower(substr($Return, 0, strpos($Return, '/'))); if ($Prefix == 'rss') { $Return = substr($Return, 4); } else { if ($Prefix == 'atom') { $Return = substr($Return, 5); } } } if ($WithWebRoot) { $WebRoot = Gdn_Url::WebRoot($WithDomain); if (substr($WebRoot, -1, 1) != '/') { $WebRoot .= '/'; } $Return = $WebRoot . $Return; } return $Return; }
/** * Allows the configuration of basic setup information in Garden. This * should not be functional after the application has been set up. */ public function Configure($RedirectUrl = '') { $Config = Gdn::Factory(Gdn::AliasConfig); // Create a model to save configuration settings $Validation = new Gdn_Validation(); $ConfigurationModel = new Gdn_ConfigurationModel($Validation); $ConfigurationModel->SetField(array('Garden.Locale', 'Garden.Title', 'Garden.RewriteUrls', 'Garden.WebRoot', 'Garden.Cookie.Salt', 'Garden.Cookie.Domain', 'Database.Name', 'Database.Host', 'Database.User', 'Database.Password')); // Set the models on the forms. $this->Form->SetModel($ConfigurationModel); // Load the locales for the locale dropdown // $Locale = Gdn::Locale(); // $AvailableLocales = $Locale->GetAvailableLocaleSources(); // $this->LocaleData = array_combine($AvailableLocales, $AvailableLocales); // If seeing the form for the first time... if (!$this->Form->IsPostback()) { // Force the webroot using our best guesstimates $ConfigurationModel->Data['Database.Host'] = 'localhost'; $this->Form->SetData($ConfigurationModel->Data); } else { // Define some validation rules for the fields being saved $ConfigurationModel->Validation->ApplyRule('Database.Name', 'Required', 'You must specify the name of the database in which you want to set up Vanilla.'); // Let's make some user-friendly custom errors for database problems $DatabaseHost = $this->Form->GetFormValue('Database.Host', '~~Invalid~~'); $DatabaseName = $this->Form->GetFormValue('Database.Name', '~~Invalid~~'); $DatabaseUser = $this->Form->GetFormValue('Database.User', '~~Invalid~~'); $DatabasePassword = $this->Form->GetFormValue('Database.Password', '~~Invalid~~'); $ConnectionString = GetConnectionString($DatabaseName, $DatabaseHost); try { $Connection = new PDO($ConnectionString, $DatabaseUser, $DatabasePassword); } catch (PDOException $Exception) { switch ($Exception->getCode()) { case 1044: $this->Form->AddError(T('The database user you specified does not have permission to access the database. Have you created the database yet? The database reported: <code>%s</code>'), strip_tags($Exception->getMessage())); break; case 1045: $this->Form->AddError(T('Failed to connect to the database with the username and password you entered. Did you mistype them? The database reported: <code>%s</code>'), strip_tags($Exception->getMessage())); break; case 1049: $this->Form->AddError(T('It appears as though the database you specified does not exist yet. Have you created it yet? Did you mistype the name? The database reported: <code>%s</code>'), strip_tags($Exception->getMessage())); break; case 2005: $this->Form->AddError(T("Are you sure you've entered the correct database host name? Maybe you mistyped it? The database reported: <code>%s</code>"), strip_tags($Exception->getMessage())); break; default: $this->Form->AddError(sprintf(T('ValidateConnection'), strip_tags($Exception->getMessage()))); break; } } $ConfigurationModel->Validation->ApplyRule('Garden.Title', 'Required'); $ConfigurationFormValues = $this->Form->FormValues(); if ($ConfigurationModel->Validate($ConfigurationFormValues) !== TRUE || $this->Form->ErrorCount() > 0) { // Apply the validation results to the form(s) $this->Form->SetValidationResults($ConfigurationModel->ValidationResults()); } else { $Host = array_shift(explode(':', Gdn::Request()->RequestHost())); $Domain = Gdn::Request()->Domain(); // Set up cookies now so that the user can be signed in. $ConfigurationFormValues['Garden.Cookie.Salt'] = RandomString(10); $ConfigurationFormValues['Garden.Cookie.Domain'] = strpos($Host, '.') === FALSE ? '' : $Host; // Don't assign the domain if it is a non .com domain as that will break cookies. $ConfigurationModel->Save($ConfigurationFormValues); // If changing locale, redefine locale sources: $NewLocale = 'en-CA'; // $this->Form->GetFormValue('Garden.Locale', FALSE); if ($NewLocale !== FALSE && Gdn::Config('Garden.Locale') != $NewLocale) { $ApplicationManager = new Gdn_ApplicationManager(); $PluginManager = Gdn::Factory('PluginManager'); $Locale = Gdn::Locale(); $Locale->Set($NewLocale, $ApplicationManager->EnabledApplicationFolders(), $PluginManager->EnabledPluginFolders(), TRUE); } // Set the instantiated config object's db params and make the database use them (otherwise it will use the default values from conf/config-defaults.php). $Config->Set('Database.Host', $ConfigurationFormValues['Database.Host']); $Config->Set('Database.Name', $ConfigurationFormValues['Database.Name']); $Config->Set('Database.User', $ConfigurationFormValues['Database.User']); $Config->Set('Database.Password', $ConfigurationFormValues['Database.Password']); $Config->ClearSaveData(); Gdn::FactoryInstall(Gdn::AliasDatabase, 'Gdn_Database', PATH_LIBRARY . DS . 'database' . DS . 'class.database.php', Gdn::FactorySingleton, array(Gdn::Config('Database'))); // Install db structure & basic data. $Database = Gdn::Database(); $Drop = FALSE; // Gdn::Config('Garden.Version') === FALSE ? TRUE : FALSE; $Explicit = FALSE; try { include PATH_APPLICATIONS . DS . 'dashboard' . DS . 'settings' . DS . 'structure.php'; } catch (Exception $ex) { $this->Form->AddError(strip_tags($ex->getMessage())); } if ($this->Form->ErrorCount() > 0) { return FALSE; } // Create the administrative user $UserModel = Gdn::UserModel(); $UserModel->DefineSchema(); $UserModel->Validation->ApplyRule('Name', 'Username', self::UsernameError); $UserModel->Validation->ApplyRule('Name', 'Required', T('You must specify an admin username.')); $UserModel->Validation->ApplyRule('Password', 'Required', T('You must specify an admin password.')); $UserModel->Validation->ApplyRule('Password', 'Match'); $UserModel->Validation->ApplyRule('Email', 'Email'); if (!$UserModel->SaveAdminUser($ConfigurationFormValues)) { $this->Form->SetValidationResults($UserModel->ValidationResults()); } else { // The user has been created successfully, so sign in now $Authenticator = Gdn::Authenticator(); $AuthUserID = $Authenticator->Authenticate(array('Email' => $this->Form->GetValue('Email'), 'Password' => $this->Form->GetValue('Password'), 'RememberMe' => TRUE)); } if ($this->Form->ErrorCount() > 0) { return FALSE; } // Assign some extra settings to the configuration file if everything succeeded. $ApplicationInfo = array(); include CombinePaths(array(PATH_APPLICATIONS . DS . 'dashboard' . DS . 'settings' . DS . 'about.php')); // Detect rewrite abilities try { $Query = Gdn::Request()->Domain() . Gdn::Request()->WebRoot() . "entry"; $Results = ProxyHead($Query, array(), 1); $CanRewrite = FALSE; if (in_array(ArrayValue('StatusCode', $Results, 404), array(200, 302)) && ArrayValue('X-Garden-Version', $Results, 'None') != 'None') { $CanRewrite = TRUE; } } catch (Exception $e) { // cURL and fsockopen arent supported... guess? $CanRewrite = function_exists('apache_get_modules') && in_array('mod_rewrite', apache_get_modules()) ? TRUE : FALSE; } SaveToConfig(array('Garden.Version' => ArrayValue('Version', GetValue('Dashboard', $ApplicationInfo, array()), 'Undefined'), 'Garden.WebRoot' => Gdn_Url::WebRoot(), 'Garden.RewriteUrls' => $CanRewrite, 'Garden.Domain' => $Domain, 'Garden.CanProcessImages' => function_exists('gd_info'), 'EnabledPlugins.GettingStarted' => 'GettingStarted', 'EnabledPlugins.HTMLPurifier' => 'HtmlPurifier')); } } return $this->Form->ErrorCount() == 0 ? TRUE : FALSE; }
/** * Undocumented method. * * @todo Method DefinitionList() needs a description. */ public function DefinitionList() { $Session = Gdn::Session(); if (!array_key_exists('TransportError', $this->_Definitions)) { $this->_Definitions['TransportError'] = Gdn::Translate('A fatal error occurred while processing the request.<br />The server returned the following response: %s'); } if (!array_key_exists('TransientKey', $this->_Definitions)) { $this->_Definitions['TransientKey'] = $Session->TransientKey(); } if (!array_key_exists('WebRoot', $this->_Definitions)) { $this->_Definitions['WebRoot'] = Gdn_Url::WebRoot(TRUE); } if (!array_key_exists('ConfirmHeading', $this->_Definitions)) { $this->_Definitions['ConfirmHeading'] = Gdn::Translate('Confirm'); } if (!array_key_exists('ConfirmText', $this->_Definitions)) { $this->_Definitions['ConfirmText'] = Gdn::Translate('Are you sure you want to do that?'); } if (!array_key_exists('Okay', $this->_Definitions)) { $this->_Definitions['Okay'] = Gdn::Translate('Okay'); } if (!array_key_exists('Cancel', $this->_Definitions)) { $this->_Definitions['Cancel'] = Gdn::Translate('Cancel'); } $Return = '<!-- Various definitions for Javascript //--> <div id="Definitions" style="display: none;"> '; foreach ($this->_Definitions as $Term => $Definition) { $Return .= '<input type="hidden" id="' . $Term . '" value="' . $Definition . '" />' . "\n"; } return $Return . '</div>'; }
$Gdn_Config = Gdn::Factory(Gdn::AliasConfig); /// Configuration Defaults. $Gdn_Config->Load(PATH_CONF . DS . 'config-defaults.php', 'Use'); // Load the custom configurations so that we know what apps are enabled. $Gdn_Config->Load(PATH_CONF . DS . 'config.php', 'Use'); /// Load the configurations for the installed items. $Gdn_EnabledApplications = Gdn::Config('EnabledApplications', array()); foreach ($Gdn_EnabledApplications as $ApplicationName => $ApplicationFolder) { $Gdn_Config->Load(PATH_APPLICATIONS . DS . $ApplicationFolder . DS . 'settings' . DS . 'configuration.php', 'Use'); } /// Load the custom configurations again so that application setting defaults are overridden. $Gdn_Config->Load(PATH_CONF . DS . 'config.php', 'Use'); unset($Gdn_Config); // Redirect to the setup screen if Garden hasn't been installed yet. if (!Gdn::Config('Garden.Installed', FALSE) && strpos(Gdn_Url::Request(), 'gardensetup') === FALSE) { header('location: ' . CombinePaths(array(Gdn_Url::WebRoot(TRUE), 'index.php/garden/gardensetup'), '/')); exit; } /// Install some of the services. // Default database. Gdn::FactoryInstall(Gdn::AliasDatabase, 'Gdn_Database', PATH_LIBRARY . DS . 'database' . DS . 'class.database.php', Gdn::FactorySingleton, array('Database')); // Database drivers. Gdn::FactoryInstall('MySQLDriver', 'Gdn_MySQLDriver', PATH_LIBRARY . DS . 'database' . DS . 'class.mysql.driver.php', Gdn::FactoryInstance); Gdn::FactoryInstall('MySQLStructure', 'Gdn_MySQLStructure', PATH_LIBRARY . DS . 'database' . DS . 'class.mysql.structure.php', Gdn::FactoryInstance); // Identity, Authenticator & Session. Gdn::FactoryInstall('Identity', 'Gdn_CookieIdentity', PATH_LIBRARY_CORE . DS . 'class.cookieidentity.php'); $AuthType = Gdn::Config('Garden.Authenticator.Type', 'Password'); Gdn::FactoryInstall(Gdn::AliasAuthenticator, 'Gdn_' . $AuthType . 'Authenticator', PATH_LIBRARY_CORE . DS . 'class.' . strtolower($AuthType) . 'authenticator.php', Gdn::FactorySingleton, array('Garden.Authenticator')); Gdn::FactoryInstall(Gdn::AliasSession, 'Gdn_Session', PATH_LIBRARY_CORE . DS . 'class.session.php'); // Dispatcher. Gdn::FactoryInstall(Gdn::AliasDispatcher, 'Gdn_Dispatcher', PATH_LIBRARY_CORE . DS . 'class.dispatcher.php', Gdn::FactorySingleton);
function WriteActivityComment($Comment, &$Sender, &$Session) { ?> <li id="Activity_<?php echo $Comment->ActivityID; ?> " class="<?php echo $Comment->ActivityType; ?> "><?php if ($Comment->ActivityPhoto != '') { if ($Comment->InsertUserID == $Session->UserID) { echo '<a href="' . Url('/garden/profile/' . urlencode($Comment->ActivityName)) . '">' . $Sender->Html->Image('uploads/n' . $Comment->ActivityPhoto) . '</a>'; } else { echo $Sender->Html->Image('uploads/n' . $Comment->ActivityPhoto); } } ?> <h3><?php echo $Session->UserID == $Comment->InsertUserID || $Session->CheckPermission('Garden.Activity.Delete') ? Anchor('Delete', 'garden/activity/delete/' . $Comment->ActivityID . '/' . $Session->TransientKey() . '?Return=' . urlencode(Gdn_Url::Request()), 'Delete') : ''; ?> <strong><?php echo Format::ActivityHeadline($Comment, $Sender->ProfileUserID); ?> <em><?php echo Format::Date($Comment->DateInserted); ?> </em></strong></h3> <blockquote><?php echo Format::Display($Comment->Story); ?> </blockquote> </li> <?php }
protected static function GetGroupName($FilePath) { static $WebRootLength; if (is_null($WebRootLength)) { $WebRootLength = strlen(Gdn_Url::WebRoot()); } $GroupName = GetValue(1, explode('/', substr($FilePath, $WebRootLength))); return $GroupName; }
/** * Parses the query string looking for supplied request parameters. Places * anything useful into this object's Controller properties. * * @param int $FolderDepth * @todo $folderDepth needs a description. */ protected function _AnalyzeRequest($FolderDepth = 2) { // Here are some examples of what this method could/would receive: // /application/controllergroup/controller/method/argn // /controllergroup/controller/method/argn // /application/controllergroup/controller/argn // /controllergroup/controller/argn // /controllergroup/controller // /application/controller/method/argn // /controller/method/argn // /application/controller/argn // /controller/argn // /controller // Clear the slate $this->_ApplicationFolder = ''; $this->_ControllerFolder = ''; $this->_ControllerName = ''; $this->_ControllerMethod = 'index'; $this->_ControllerMethodArgs = array(); // Retrieve and parse the request if ($this->Request == '') { $this->Request = Gdn_Url::Request(); $Prefix = strtolower(substr($this->Request, 0, strpos($this->Request, '/'))); switch ($Prefix) { case 'rss': $this->_SyndicationMethod = SYNDICATION_RSS; $this->Request = substr($this->Request, 4); break; case 'atom': $this->_SyndicationMethod = SYNDICATION_ATOM; $this->Request = substr($this->Request, 5); break; default: $this->_SyndicationMethod = SYNDICATION_NONE; break; } } if ($this->Request == '') { $this->Request = $this->Routes['DefaultController']; } // Check for re-routing // Is there a literal match? if (isset($this->Routes[$this->Request])) { $this->Request = $this->Routes[$this->Request]; } else { // Check for other matching custom routes foreach ($this->Routes as $Route => $Destination) { // Check for wild-cards $Route = str_replace(array(':alphanum', ':num'), array('.+', '[0-9]+'), $Route); // Check for a match if (preg_match('#^' . $Route . '$#', $this->Request)) { // Do we have a back-reference? if (strpos($Destination, '$') !== FALSE && strpos($this->Request, '(') !== FALSE) { $Destination = preg_replace('#^' . $Route . '$#', $Destination, $this->Request); } $this->Request = $Destination; } } } $Parts = explode('/', $this->Request); $Length = count($Parts); if ($Length == 1 || $FolderDepth <= 0) { $FolderDepth = 0; $this->_ControllerName = $Parts[0]; $this->_MapParts($Parts, 0); $this->_FetchController(TRUE); // Throw an error if this fails because there's nothing else to check } else { if ($Length == 2) { // Force a depth of 1 because only one of the two url parts can be a folder. $FolderDepth = 1; } } if ($FolderDepth == 2) { // print_r($Parts); // echo $Parts[1]; $this->_ApplicationFolder = $Parts[0]; $this->_ControllerFolder = $Parts[1]; $this->_MapParts($Parts, 2); if (!$this->_FetchController()) { // echo '<div>Failed. AppFolder: '.$this->_ApplicationFolder.'; Cont Folder: '.$this->_ControllerFolder.'; Cont: '.$this->_ControllerName.';</div>'; $this->_AnalyzeRequest(1); } } else { if ($FolderDepth == 1) { // Try the application folder first $Found = FALSE; if (in_array($Parts[0], $this->EnabledApplicationFolders())) { // Check to see if the first part is an application $this->_ApplicationFolder = $Parts[0]; $this->_MapParts($Parts, 1); $Found = $this->_FetchController(); } if (!$Found) { // echo '<div>Failed. AppFolder: '.$this->_ApplicationFolder.'; Cont Folder: '.$this->_ControllerFolder.'; Cont: '.$this->_ControllerName.';</div>'; // Check to see if the first part is a controller folder $this->_ApplicationFolder = ''; $this->_ControllerFolder = $Parts[0]; $this->_MapParts($Parts, 1); if (!$this->_FetchController()) { // echo '<div>Failed. AppFolder: '.$this->_ApplicationFolder.'; Cont Folder: '.$this->_ControllerFolder.'; Cont: '.$this->_ControllerName.';</div>'; $this->_AnalyzeRequest(0); } } } } }
// This header is redundantly set in the controller. //header('X-Garden-Version: '.APPLICATION.' '.APPLICATION_VERSION); Gdn::FactoryInstall(Gdn::AliasCache, 'Gdn_Cache', CombinePaths(array(PATH_LIBRARY_CORE, 'class.cache.php')), Gdn::FactoryRealSingleton, 'Initialize'); // Default request object Gdn::FactoryInstall(Gdn::AliasRequest, 'Gdn_Request', PATH_LIBRARY . DS . 'core' . DS . 'class.request.php', Gdn::FactoryRealSingleton, 'Create'); Gdn::Request()->FromEnvironment(); /// Load the configurations for the installed items. $Gdn_EnabledApplications = Gdn::Config('EnabledApplications', array()); foreach ($Gdn_EnabledApplications as $ApplicationName => $ApplicationFolder) { $Gdn_Config->Load(PATH_APPLICATIONS . DS . $ApplicationFolder . DS . 'settings' . DS . 'configuration.php', 'Use'); } /// Load the custom configurations again so that application setting defaults are overridden. $Gdn_Config->Load(PATH_CONF . DS . 'config.php', 'Use'); unset($Gdn_Config); // Redirect to the setup screen if Dashboard hasn't been installed yet. if (!Gdn::Config('Garden.Installed', FALSE) && strpos(Gdn_Url::Request(), 'setup') === FALSE) { header('location: ' . Gdn::Request()->Url('dashboard/setup', TRUE)); exit; } /// Install some of the services. // Default database. Gdn::FactoryInstall(Gdn::AliasDatabase, 'Gdn_Database', PATH_LIBRARY . DS . 'database' . DS . 'class.database.php', Gdn::FactorySingleton, array('Database')); // Database drivers. Gdn::FactoryInstall('MySQLDriver', 'Gdn_MySQLDriver', PATH_LIBRARY . DS . 'database' . DS . 'class.mysql.driver.php', Gdn::FactoryInstance); Gdn::FactoryInstall('MySQLStructure', 'Gdn_MySQLStructure', PATH_LIBRARY . DS . 'database' . DS . 'class.mysql.structure.php', Gdn::FactoryInstance); // Form class Gdn::FactoryInstall('Form', 'Gdn_Form', PATH_LIBRARY . DS . 'core' . DS . 'class.form.php', Gdn::FactoryInstance); // Identity, Authenticator & Session. Gdn::FactoryInstall('Identity', 'Gdn_CookieIdentity', PATH_LIBRARY_CORE . DS . 'class.cookieidentity.php'); Gdn::FactoryInstall(Gdn::AliasSession, 'Gdn_Session', PATH_LIBRARY_CORE . DS . 'class.session.php'); Gdn::FactoryInstall(Gdn::AliasAuthenticator, 'Gdn_Auth', PATH_LIBRARY_CORE . DS . 'class.auth.php', Gdn::FactorySingleton);
public function SendPasswordEmail($UserID, $Password) { $Session = Gdn::Session(); $Sender = $this->Get($Session->UserID); $User = $this->Get($UserID); $AppTitle = Gdn::Config('Garden.Title'); $Email = new Gdn_Email(); $Email->Subject(sprintf(T('[%s] Password Reset'), $AppTitle)); $Email->To($User->Email); //$Email->From($Sender->Email, $Sender->Name); $Email->Message(sprintf(T('EmailPassword'), $User->Name, $Sender->Name, $AppTitle, Gdn_Url::WebRoot(TRUE), $Password, $User->Email)); $Email->Send(); }
public function RemoteSignOutUrl() { $Session = Gdn::Session(); $Url = sprintf($this->_SignOutUrl, urlencode(Gdn_Url::Request())); $Url = str_replace('{Session_TransientKey}', $Session->TransientKey(), $Url); return $Url; }
public function DiscussionController_BeforeDiscussion_Handler(&$Sender) { echo sprintf($this->Code, Gdn_Url::Request(true, true, true)); }
* default config and the general and error functions. More control is possible * here, but some things have already been loaded and are immutable. */ if (file_exists(PATH_CONF . '/bootstrap.early.php')) { require_once PATH_CONF . '/bootstrap.early.php'; } Gdn::config()->caching(true); debug(c('Debug', false)); setHandlers(); /** * Installer Redirect * * If Garden is not yet installed, force the request to /dashboard/setup and * begin installation. */ if (Gdn::config('Garden.Installed', false) === false && strpos(Gdn_Url::request(), 'setup') === false) { safeHeader('Location: ' . Gdn::request()->url('dashboard/setup', true)); exit; } /** * Extension Managers * * Now load the Addon, Application, Theme and Plugin managers into the Factory, and * process the application-specific configuration defaults. */ // ApplicationManager Gdn::factoryInstall(Gdn::AliasApplicationManager, 'Gdn_ApplicationManager', '', Gdn::FactorySingleton, [Gdn::addonManager()]); // ThemeManager Gdn::factoryInstall(Gdn::AliasThemeManager, 'Gdn_ThemeManager', '', Gdn::FactorySingleton, [Gdn::addonManager()]); // PluginManager Gdn::factoryInstall(Gdn::AliasPluginManager, 'Gdn_PluginManager', '', Gdn::FactorySingleton, [Gdn::addonManager()]);
function Url($Destination = '', $WithDomain = FALSE, $RemoveSyndication = FALSE) { // Cache the rewrite urls config setting in this object. static $RewriteUrls = NULL; if (is_null($RewriteUrls)) { $RewriteUrls = ForceBool(Gdn::Config('Garden.RewriteUrls', FALSE)); } $Prefix = substr($Destination, 0, 7); if (in_array($Prefix, array('http://', 'https:/'))) { return $Destination; } else { if ($Destination == '#' || $Destination == '') { if ($WithDomain) { return Gdn_Url::Request(TRUE, TRUE, $RemoveSyndication) . $Destination; } else { return '/' . Gdn_Url::Request(TRUE, FALSE, $RemoveSyndication) . $Destination; } } else { $Paths = array(); if (!$WithDomain) { $Paths[] = '/'; } $Paths[] = Gdn_Url::WebRoot($WithDomain); if (!$RewriteUrls) { $Paths[] = 'index.php'; } $Paths[] = $Destination; return CombinePaths($Paths, '/'); } } }
/** * Undocumented method. * * @todo Method DefinitionList() needs a description. */ public function DefinitionList() { $Session = Gdn::Session(); $Return = '<!-- Various Definitions for Javascript //--> <ul id="Definitions" style="display: none;"> <li id="TransportError">' . Gdn::Translate('A fatal error occurred while processing the request.<br />The server returned the following response: %s') . '</li> <li id="TransientKey">' . $Session->TransientKey() . '</li> <li id="WebRoot">' . Gdn_Url::WebRoot(TRUE) . '</li> <li id="ConfirmText">' . Gdn::Translate('Are you sure you want to proceed?') . '</li> <li id="Okay">' . Gdn::Translate('Okay') . '</li> <li id="Cancel">' . Gdn::Translate('Cancel') . '</li> '; foreach ($this->_Definitions as $Term => $Definition) { $Return .= '<li id="' . $Term . '">' . $Definition . '</li>'; } return $Return . '</ul>'; }
/** * Takes the path to an asset (image, js file, css file, etc) and prepends the webroot. */ function SmartAsset($Destination = '', $WithDomain = FALSE, $AddVersion = FALSE) { $Destination = str_replace('\\', '/', $Destination); if (substr($Destination, 0, 7) == 'http://' || substr($Destination, 0, 8) == 'https://') { $Result = $Destination; } else { $Parts = array(Gdn_Url::WebRoot($WithDomain), $Destination); if (!$WithDomain) { array_unshift($Parts, '/'); } $Result = CombinePaths($Parts, '/'); } if ($AddVersion) { if (strpos($Result, '?') === FALSE) { $Result .= '?'; } else { $Result .= '&'; } // Figure out which version to put after the asset. $Version = APPLICATION_VERSION; if (preg_match('`^/([^/]+)/([^/]+)/`', $Destination, $Matches)) { $Type = $Matches[1]; $Key = $Matches[2]; static $ThemeVersion = NULL; switch ($Type) { case 'plugins': $PluginInfo = Gdn::PluginManager()->GetPluginInfo($Key); $Version = GetValue('Version', $PluginInfo, $Version); break; case 'themes': if ($ThemeVersion === NULL) { $ThemeInfo = Gdn::ThemeManager()->GetThemeInfo(Theme()); if ($ThemeInfo !== FALSE) { $ThemeVersion = GetValue('Version', $ThemeInfo, $Version); } else { $ThemeVersion = $Version; } } $Version = $ThemeVersion; break; } } $Result .= 'v=' . urlencode($Version); } return $Result; }
/** * A custom error handler that displays much more, very useful information when * errors are encountered in Garden. * * @param int The level of the error raised. * @param string The error message. * @param string The filename that the error was raised in. * @param string The line number the error was raised at. * @param string An array of every variable that existed in the scope the error was triggered in. */ function ErrorHandler($ErrorNumber, $Message, $File, $Line, $Arguments) { // Ignore errors that have a @ before them (ie. @function();) if (error_reporting() == 0) { return FALSE; } // Clean the output buffer in case an error was encountered in-page. @ob_end_clean(); header('Content-Type: text/html; charset=utf-8'); $SenderMessage = $Message; $SenderObject = 'PHP'; $SenderMethod = 'ErrorHandler'; $SenderCode = FALSE; $MessageInfo = explode('|', $Message); $MessageCount = count($MessageInfo); if ($MessageCount == 4) { list($SenderMessage, $SenderObject, $SenderMethod, $SenderCode) = $MessageInfo; } else { if ($MessageCount == 3) { list($SenderMessage, $SenderObject, $SenderMethod) = $MessageInfo; } } $SenderMessage = strip_tags($SenderMessage); $Master = FALSE; // The parsed master view $CssPath = FALSE; // The web-path to the css file $ErrorLines = FALSE; // The lines near the error's line # $DeliveryType = DELIVERY_TYPE_ALL; if (array_key_exists('DeliveryType', $_POST)) { $DeliveryType = $_POST['DeliveryType']; } else { if (array_key_exists('DeliveryType', $_GET)) { $DeliveryType = $_GET['DeliveryType']; } } // Make sure all of the required custom functions and variables are defined. $PanicError = FALSE; // Should we just dump a message and forget about the master view? if (!defined('DS')) { $PanicError = TRUE; } if (!defined('PATH_ROOT')) { $PanicError = TRUE; } if (!defined('APPLICATION')) { define('APPLICATION', 'Garden'); } if (!defined('APPLICATION_VERSION')) { define('APPLICATION_VERSION', 'Unknown'); } $WebRoot = class_exists('Url', FALSE) ? Gdn_Url::WebRoot() : ''; // Try and rollback a database transaction. if (class_exists('Gdn', FALSE)) { $Database = Gdn::Database(); if (is_object($Database)) { $Database->RollbackTransaction(); } } if ($PanicError === FALSE) { // See if we can get the file that caused the error if (is_string($File) && is_numeric($ErrorNumber)) { $ErrorLines = @file($File); } // If this error was encountered during an ajax request, don't bother gettting the css or theme files if ($DeliveryType == DELIVERY_TYPE_ALL) { $CssPaths = array(); // Potential places where the css can be found in the filesystem. $MasterViewPaths = array(); $MasterViewName = 'error.master.php'; $MasterViewCss = 'error.css'; if (class_exists('Gdn', FALSE)) { $CurrentTheme = ''; // The currently selected theme $CurrentTheme = Gdn::Config('Garden.Theme', ''); $MasterViewName = Gdn::Config('Garden.Errors.MasterView', $MasterViewName); $MasterViewCss = substr($MasterViewName, 0, strpos($MasterViewName, '.')); if ($MasterViewCss == '') { $MasterViewCss = 'error'; } $MasterViewCss .= '.css'; if ($CurrentTheme != '') { // Look for CSS in the theme folder: $CssPaths[] = PATH_THEMES . DS . $CurrentTheme . DS . 'design' . DS . $MasterViewCss; // Look for Master View in the theme folder: $MasterViewPaths[] = PATH_THEMES . DS . $CurrentTheme . DS . 'views' . DS . $MasterViewName; } } // Look for CSS in the garden design folder. $CssPaths[] = PATH_APPLICATIONS . DS . 'garden' . DS . 'design' . DS . $MasterViewCss; // Look for Master View in the garden view folder. $MasterViewPaths[] = PATH_APPLICATIONS . DS . 'garden' . DS . 'views' . DS . $MasterViewName; $CssPath = FALSE; $Count = count($CssPaths); for ($i = 0; $i < $Count; ++$i) { if (file_exists($CssPaths[$i])) { $CssPath = $CssPaths[$i]; break; } } if ($CssPath !== FALSE) { $CssPath = str_replace(array(PATH_ROOT, DS), array('', '/'), $CssPath); $CssPath = ($WebRoot == '' ? '' : '/' . $WebRoot) . $CssPath; } $MasterViewPath = FALSE; $Count = count($MasterViewPaths); for ($i = 0; $i < $Count; ++$i) { if (file_exists($MasterViewPaths[$i])) { $MasterViewPath = $MasterViewPaths[$i]; break; } } if ($MasterViewPath !== FALSE) { include $MasterViewPath; $Master = TRUE; } } } if ($DeliveryType != DELIVERY_TYPE_ALL) { // This is an ajax request, so dump an error that is more eye-friendly in the debugger echo 'FATAL ERROR IN: ', $SenderObject, '.', $SenderMethod, "();\n\"" . $SenderMessage . "\"\n"; if ($SenderCode != '') { echo htmlentities($SenderCode, ENT_COMPAT, 'UTF-8') . "\n"; } if (is_array($ErrorLines) && $Line > -1) { echo "LOCATION: ", $File, "\n"; } $LineCount = count($ErrorLines); $Padding = strlen($Line + 5); for ($i = 0; $i < $LineCount; ++$i) { if ($i > $Line - 6 && $i < $Line + 4) { if ($i == $Line - 1) { echo '>>'; } echo '> ' . str_pad($i + 1, $Padding, " ", STR_PAD_LEFT), ': ', str_replace(array("\n", "\r"), array('', ''), $ErrorLines[$i]), "\n"; } } $Backtrace = debug_backtrace(); if (is_array($Backtrace)) { echo "BACKTRACE:\n"; $BacktraceCount = count($Backtrace); for ($i = 0; $i < $BacktraceCount; ++$i) { if (array_key_exists('file', $Backtrace[$i])) { $File = $Backtrace[$i]['file'] . ' ' . $Backtrace[$i]['line']; } echo '[' . $File . ']', ' ', array_key_exists('class', $Backtrace[$i]) ? $Backtrace[$i]['class'] : 'PHP', array_key_exists('type', $Backtrace[$i]) ? $Backtrace[$i]['type'] : '::', $Backtrace[$i]['function'], '();', "\n"; } } } else { // If the master view wasn't found, assume a panic state and dump the error. if ($Master === FALSE) { echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-ca"> <head> <title>Fatal Error</title> </head> <body> <h1>Fatal Error in ', $SenderObject, '.', $SenderMethod, '();</h1> <h2>', $SenderMessage, "</h2>\n"; if ($SenderCode != '') { echo '<code>', htmlentities($SenderCode, ENT_COMPAT, 'UTF-8'), "</code>\n"; } if (is_array($ErrorLines) && $Line > -1) { echo '<h3><strong>The error occurred on or near:</strong> ', $File, '</h3> <pre>'; $LineCount = count($ErrorLines); $Padding = strlen($Line + 4); for ($i = 0; $i < $LineCount; ++$i) { if ($i > $Line - 6 && $i < $Line + 4) { echo str_pad($i, $Padding, " ", STR_PAD_LEFT), ': ', htmlentities($ErrorLines[$i], ENT_COMPAT, 'UTF-8'); } } echo "</pre>\n"; } echo '<h2>Need Help?</h2> <p>If you are a user of this website, you can report this message to a website administrator.</p> <p>If you are an administrator of this website, you can get help at the <a href="http://vanillaforums.org/discussions/" target="_blank">Vanilla Community Forums</a>.</p> <h2>Additional information for support personnel:</h2> <ul> <li><strong>Application:</strong> ', APPLICATION, '</li> <li><strong>Application Version:</strong> ', APPLICATION_VERSION, '</li> <li><strong>PHP Version:</strong> ', PHP_VERSION, '</li> <li><strong>Operating System:</strong> ', PHP_OS, "</li>\n"; if (array_key_exists('HTTP_REFERER', $_SERVER)) { echo '<li><strong>Referer:</strong> ', $_SERVER['HTTP_REFERER'], "</li>\n"; } if (array_key_exists('HTTP_USER_AGENT', $_SERVER)) { echo '<li><strong>User Agent:</strong> ', $_SERVER['HTTP_USER_AGENT'], "</li>\n"; } if (array_key_exists('REQUEST_URI', $_SERVER)) { echo '<li><strong>Request Uri:</strong> ', $_SERVER['REQUEST_URI'], "</li>\n"; } echo '</ul> </body> </html>'; } } // Attempt to log an error message no matter what. LogMessage($File, $Line, $SenderObject, $SenderMethod, $SenderMessage, $SenderCode); exit; }