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(); }
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; } }
/** * 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>'; }
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); $Query = ArrayValue('query', $UrlParts, ''); // 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"; } $Header = "GET {$Path}?{$Query} HTTP/1.1\r\n" . "Host: {$Host}\r\n" . "User-Agent: Vanilla/2.0\r\n" . "Accept: */*\r\n" . "Accept-Charset: utf-8;\r\n" . "Referer: {$Referer}\r\n" . "Connection: close\r\n" . $Cookie . "\r\n\r\n"; // Send the necessary headers to get the file fputs($Pointer, $Header); // echo '<br /><textarea style="height: 400px; width: 700px;">'.$Header.'</textarea>'; // Retrieve the response from the remote server $Response = ''; $InBody = FALSE; while ($Line = fread($Pointer, 4096)) { $Response .= $Line; } fclose($Pointer); // echo '<br /><textarea style="height: 400px; width: 700px;">'.$Response.'</textarea>'; // exit(); // 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; }
<?php if (!defined('APPLICATION')) { exit; } $UserPhotoFirst = C('Vanilla.Comment.UserPhotoFirst', TRUE); $Year = $this->Data('Year'); $Month = $this->Data('Month'); $MonthFirst = $this->Data('MonthFirst'); $MonthLast = $this->Data('MonthLast'); $Domain = Gdn_Url::WebRoot(TRUE); $Events = $this->Data('Events'); $Event = array_shift($Events); $EventDay = $Event['EventCalendarDay']; /* <div class="Tabs HeadingTabs CalendarTabs"> <div class="SubTab"><?php echo date(T('F Y'), $this->Data('MonthFirst'));?></div> </div> */ ?> <h1 class="CalendarDate"> <a href="<?php echo "{$Domain}eventcalendar/{$this->Data('PreviousMonth')}"; ?> ">«</a> <?php echo date(T('F Y'), $this->Data('MonthFirst')); ?> <a href="<?php echo "{$Domain}eventcalendar/{$this->Data('NextMonth')}";
/** * Create table if not exists and create a dbinfo.php file for ajax use */ public function Setup() { $commentsTable = 'GDN_tInfoBar_comments'; $file_dbinfo = $this->GetPluginFolder() . '/dbinfo.php'; $file_globals = $this->GetPluginFolder() . '/globals.js'; $Structure = Gdn::Structure(); $Structure->Query("\n\t\t\tCREATE TABLE IF NOT EXISTS `{$commentsTable}` (\n\t\t\t `id` int(11) NOT NULL AUTO_INCREMENT,\n\t\t\t `context` varchar(256) NOT NULL,\n\t\t\t `wordID` text NOT NULL,\n\t\t\t `user` varchar(60) NOT NULL,\n\t\t\t `text` text NOT NULL,\n\t\t\t PRIMARY KEY (`id`)\n\t\t\t) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=21 ;\n\t\t"); $dbinfo = '<?php $table_comments = "' . $commentsTable . '"; $db_host = \'' . Gdn::Config('Database.Host') . '\'; $db_user = \'' . Gdn::Config('Database.User') . '\'; $db_pass = \'' . Gdn::Config('Database.Password') . '\'; $db_database= \'' . Gdn::Config('Database.Name') . '\'; $con = mysql_connect($db_host, $db_user, $db_pass) or die ("Could not connect to Data Base!"); mysql_select_db($db_database, $con) or die ("Failed to select Data Base"); ?> '; $globals = ' // Some global vars for use in the main.js file var GdnWebRoot = "' . Gdn_Url::WebRoot(true) . '"; var GgnPluginFolder = "' . $this->GetPluginFolder() . '"; '; // if( !file_put_contents($file_dbinfo, $dbinfo)) // exit("Unable to create database info file. Check if you have writing permissions on: <b>".$this->GetPluginFolder()."</b>"); // if( !file_put_contents($file_globals, $globals)) // exit("Unable to create database info file. Check if you have writing permissions on: <b>".$this->GetPluginFolder()."</b>"); // chmod($file_dbinfo, 0777); // chmod($file_globals, 0777); Gdn::Structure()->Table('Discussion')->Column('ArticleID', 'int', NULL)->Column('ItemID', 'varchar(256)', NULL)->Set(); }
/** * 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; }
public function GetWebResource($Filepath) { $WebResource = $this->GetResource($Filepath, FALSE, FALSE); if (Gdn_Url::WebRoot()) { $WebResource = CombinePaths(array(Gdn_Url::WebRoot(), $WebResource)); } return '/' . $WebResource; }
function Asset($Destination = '', $WithDomain = FALSE) { if (substr($Destination, 0, 7) == 'http://') { return $Destination; } else { return CombinePaths(array('/', Gdn_Url::WebRoot($WithDomain), $Destination), '/'); } }
/** * 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); $ConfigFile = PATH_CONF . DS . 'config.php'; // Create a model to save configuration settings $Validation = new Gdn_Validation(); $ConfigurationModel = new Gdn_ConfigurationModel('Configuration', $ConfigFile, $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->AddRule('Connection', 'function:ValidateConnection'); $ConfigurationModel->Validation->ApplyRule('Database.Name', 'Connection'); $ConfigurationModel->Validation->ApplyRule('Garden.Title', 'Required'); $ConfigurationFormValues = $this->Form->FormValues(); if ($ConfigurationModel->Validate($ConfigurationFormValues) !== TRUE) { // Apply the validation results to the form(s) $this->Form->SetValidationResults($ConfigurationModel->ValidationResults()); } else { $Host = Gdn_Url::Host(); $Domain = Gdn_Url::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 . 'garden' . 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', 'Admin username can only contain letters, numbers, and underscores.'); $UserModel->Validation->ApplyRule('Password', 'Required'); $UserModel->Validation->ApplyRule('Password', 'Match'); 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('Name' => $this->Form->GetValue('Name'), '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 . 'garden' . DS . 'settings' . DS . 'about.php')); $Config->Load($ConfigFile, 'Save'); $Config->Set('Garden.Version', ArrayValue('Version', ArrayValue('Garden', $ApplicationInfo, array()), 'Undefined')); $Config->Set('Garden.WebRoot', Gdn_Url::WebRoot()); $Config->Set('Garden.RewriteUrls', function_exists('apache_get_modules') && in_array('mod_rewrite', apache_get_modules()) ? TRUE : FALSE); $Config->Set('Garden.Domain', $Domain); $Config->Set('Garden.CanProcessImages', function_exists('gd_info')); $Config->Set('Garden.Messages.Cache', 'arr:["Garden\\/Settings\\/Index"]'); // Make sure that the "welcome" message is cached for viewing $Config->Set('EnabledPlugins.HTMLPurifier', 'HtmlPurifier'); // Make sure html purifier is enabled so html has a default way of being safely parsed $Config->Save(); } } return $this->Form->ErrorCount() == 0 ? TRUE : FALSE; }
/** * Uses curl or fsock to make a request to a remote server. Returns the * response. * * @param string $Url The full url to the page being requested (including http://) */ function ProxyRequest($Url, $Timeout = FALSE) { if (!$Timeout) { $Timeout = C('Garden.SocketTimeout', 1.0); } $UrlParts = parse_url($Url); $Scheme = GetValue('scheme', $UrlParts, 'http'); $Host = GetValue('host', $UrlParts, ''); $Port = GetValue('port', $UrlParts, '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_HEADER, 0); curl_setopt($Handler, CURLOPT_RETURNTRANSFER, 1); if ($Cookie != '') { curl_setopt($Handler, CURLOPT_COOKIE, $Cookie); } // 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); if ($Response == FALSE) { $Response = curl_error($Handler); } curl_close($Handler); } else { if (function_exists('fsockopen')) { $Referer = Gdn_Url::WebRoot(TRUE); // Make the request $Pointer = @fsockopen($Host, $Port, $ErrorNumber, $Error); 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)); } if (strlen($Cookie) > 0) { $Cookie = "Cookie: {$Cookie}\r\n"; } $HostHeader = $Host . ($Post != 80) ? ":{$Port}" : ''; $Header = "GET {$Path}?{$Query} HTTP/1.1\r\n" . "Host: {$HostHeader}\r\n" . "User-Agent: 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); $Response = trim(substr($Response, strpos($Response, "\r\n\r\n") + 4)); return $Response; } 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.')); } } return $Response; }
public function GetWebResource($Filepath, $WithDomain = FALSE) { $WebResource = $this->GetResource($Filepath, FALSE, FALSE); if ($WithDomain === '/') { return $WebResource; } if (Gdn_Url::WebRoot()) { $WebResource = '/' . CombinePaths(array(Gdn_Url::WebRoot(), $WebResource)); } if ($WithDomain === '//') { $WebResource = '//' . Gdn::Request()->HostAndPort() . $WebResource; } elseif ($WithDomain) { $WebResource = Gdn::Request()->Scheme() . '//' . Gdn::Request()->HostAndPort() . $WebResource; } return $WebResource; }
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; }
/** * 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; }
/** * 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>'; }
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, '/'); } } }
/** * Edit an existing badge or add a new one * * @param int $BadgeID * @throws ForbiddenException if no proper rules are found */ public function Edit($BadgeID = NULL) { $this->Permission('Yaga.Badges.Manage'); $this->AddSideMenu('badge/settings'); $this->Form->SetModel($this->BadgeModel); // Only allow editing if some rules exist if (!RulesController::GetRules()) { throw new Gdn_UserException(T('Yaga.Error.NoRules')); } $Edit = FALSE; if ($BadgeID) { $this->Title(T('Yaga.Badge.Edit')); $this->Badge = $this->BadgeModel->GetByID($BadgeID); $this->Form->AddHidden('BadgeID', $BadgeID); $Edit = TRUE; } else { $this->Title(T('Yaga.Badge.Add')); } if ($this->Form->IsPostBack() == FALSE) { if (property_exists($this, 'Badge')) { // Manually merge the criteria into the badge object $Criteria = (array) unserialize($this->Badge->RuleCriteria); $BadgeArray = (array) $this->Badge; $Data = array_merge($BadgeArray, $Criteria); $this->Form->SetData($Data); } } else { // 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); $this->Form->SetFormValue('Photo', $RelativeUrl); } else { if (!$Edit) { // Use default photo from config if this is a new badge $this->Form->SetFormValue('Photo', C('Yaga.Badges.DefaultPhoto')); } } // Find the rule criteria $FormValues = $this->Form->FormValues(); $Criteria = array(); foreach ($FormValues as $Key => $Value) { if (substr($Key, 0, 7) == '_Rules/') { $RealKey = substr($Key, 7); $Criteria[$RealKey] = $Value; } } // Validate the criteria $RuleClass = new $FormValues['RuleClass'](); $Rule = new $RuleClass(); $Rule->Validate($Criteria, $this->Form); $SerializedCriteria = serialize($Criteria); $this->Form->SetFormValue('RuleCriteria', $SerializedCriteria); if ($this->Form->Save()) { if ($Edit) { $this->InformMessage(T('Yaga.Badge.Updated')); } else { $this->InformMessage(T('Yaga.Badge.Added')); } Redirect('/badge/settings'); } } $this->Render('edit'); }
function Url($Path = '', $WithDomain = FALSE, $RemoveSyndication = FALSE) { $Result = Gdn::Request()->Url($Path, $WithDomain); return $Result; // 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($Path, 0, 7); if (in_array($Prefix, array('http://', 'https:/'))) { return $Path; } if ($Path == '#' || $Path == '') { $Path = Gdn_Url::Request(FALSE, FALSE, $RemoveSyndication) . $Path; } $Paths = array(); if (!$WithDomain) { $Paths[] = '/'; } $Paths[] = Gdn_Url::WebRoot($WithDomain); if (!$RewriteUrls) { $Paths[] = 'index.php'; } $Paths[] = $Path; return CombinePaths($Paths, '/'); }
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 Send($InvitationID) { $Invitation = $this->GetByInvitationID($InvitationID); $Session = Gdn::Session(); if ($Invitation === FALSE) { throw new Exception(Gdn::Translate('ErrorRecordNotFound')); } else { if ($Session->UserID != $Invitation->SenderUserID) { throw new Exception(Gdn::Translate('ErrorPermission')); } else { // Some information for the email $RegistrationUrl = CombinePaths(array(Gdn_Url::WebRoot(TRUE), 'entry', 'register', $Invitation->Code), '/'); $AppTitle = Gdn::Config('Garden.Title'); $Email = new Gdn_Email(); $Email->Subject(sprintf(Gdn::Translate('[%s] Invitation'), $AppTitle)); $Email->To($Invitation->Email); $Email->From($Invitation->SenderEmail, $Invitation->SenderName); $Email->Message(sprintf(Gdn::Translate('EmailInvitation'), $Invitation->SenderName, $AppTitle, $RegistrationUrl)); $Email->Send(); } } }
/** * 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; }
$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);