Gets the global dispatcher object.
public static dispatcher ( ) : Gdn_Dispatcher | ||
return | Gdn_Dispatcher |
/** * * * @param $SliceName * @param array $Arguments * @return Gdn_Slice */ public function slice($SliceName, $Arguments = array()) { $CurrentPath = Gdn::request()->path(); $ExplodedPath = explode('/', $CurrentPath); switch ($this instanceof Gdn_IPlugin) { case true: $ReplacementIndex = 2; break; case false: $ReplacementIndex = 1; break; } if ($ExplodedPath[0] == strtolower(Gdn::dispatcher()->application()) && $ExplodedPath[1] == strtolower(Gdn::dispatcher()->controller())) { $ReplacementIndex++; } $ExplodedPath[$ReplacementIndex] = $SliceName; $SlicePath = implode('/', $ExplodedPath); return Gdn::Slice($SlicePath); }
/** * Application Gateway. * * @copyright 2009-2015 Vanilla Forums Inc. * @license http://www.opensource.org/licenses/gpl-2.0.php GNU GPL v2 * @package Core * @since 2.0 */ if (PHP_VERSION_ID < 50400) { die("Vanilla requires PHP 5.4 or greater."); } define('APPLICATION', 'Vanilla'); define('APPLICATION_VERSION', '2.2.100.8'); // Report and track all errors. error_reporting(E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR); ini_set('display_errors', 0); ini_set('track_errors', 1); ob_start(); // Define the constants we need to get going. define('DS', '/'); define('PATH_ROOT', getcwd()); // Include the bootstrap to configure the framework. require_once PATH_ROOT . '/bootstrap.php'; // Create and configure the dispatcher. $Dispatcher = Gdn::dispatcher(); $EnabledApplications = Gdn::ApplicationManager()->EnabledApplicationFolders(); $Dispatcher->EnabledApplicationFolders($EnabledApplications); $Dispatcher->PassProperty('EnabledApplications', $EnabledApplications); // Process the request. $Dispatcher->start(); $Dispatcher->dispatch();
/** * * * @param $Path * @param bool $Post * @return mixed * @throws Gdn_UserException */ public function api($Path, $Post = false) { // Build the url. $Url = 'https://graph.facebook.com/' . ltrim($Path, '/'); $AccessToken = $this->accessToken(); if (!$AccessToken) { throw new Gdn_UserException("You don't have a valid Facebook connection."); } if (strpos($Url, '?') === false) { $Url .= '?'; } else { $Url .= '&'; } $Url .= 'access_token=' . urlencode($AccessToken); $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_URL, $Url); if ($Post !== false) { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $Post); trace(" POST {$Url}"); } else { trace(" GET {$Url}"); } $Response = curl_exec($ch); $HttpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $ContentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); curl_close($ch); Gdn::controller()->setJson('Type', $ContentType); if (strpos($ContentType, 'javascript') !== false) { $Result = json_decode($Response, true); if (isset($Result['error'])) { Gdn::dispatcher()->passData('FacebookResponse', $Result); throw new Gdn_UserException($Result['error']['message']); } } else { $Result = $Response; } return $Result; }
/** * * * @return string */ public static function pagename() { $Application = Gdn::dispatcher()->application(); $Controller = Gdn::dispatcher()->controller(); switch ($Controller) { case 'discussions': case 'discussion': case 'post': return 'discussions'; case 'inbox': return 'inbox'; case 'activity': return 'activity'; case 'profile': $Args = Gdn::dispatcher()->controllerArguments(); if (!sizeof($Args) || sizeof($Args) && $Args[0] == Gdn::session()->UserID) { return 'profile'; } break; } return 'unknown'; }
/** * Render an exception as the sole output. * * @param Exception $Ex The exception to render. */ public function renderException($Ex) { if ($this->deliveryMethod() == DELIVERY_METHOD_XHTML) { try { // Pick our route. switch ($Ex->getCode()) { case 401: $route = 'DefaultPermission'; break; case 404: $route = 'Default404'; break; default: $route = '/home/error'; } // Redispatch to our error handler. if (is_a($Ex, 'Gdn_UserException')) { // UserExceptions provide more info. Gdn::dispatcher()->passData('Code', $Ex->getCode())->passData('Exception', $Ex->getMessage())->passData('Message', $Ex->getMessage())->passData('Trace', $Ex->getTraceAsString())->passData('Url', url())->passData('Breadcrumbs', $this->Data('Breadcrumbs', array()))->dispatch($route); } elseif (in_array($Ex->getCode(), array(401, 404))) { // Default forbidden & not found codes. Gdn::dispatcher()->passData('Message', $Ex->getMessage())->passData('Url', url())->dispatch($route); } else { // I dunno! Barf. Gdn_ExceptionHandler($Ex); } } catch (Exception $Ex2) { Gdn_ExceptionHandler($Ex); } return; } // Make sure the database connection is closed before exiting. $this->finalize(); $this->sendHeaders(); $Code = $Ex->getCode(); $Data = array('Code' => $Code, 'Exception' => $Ex->getMessage(), 'Class' => get_class($Ex)); if (debug()) { if ($Trace = trace()) { // Clear passwords from the trace. array_walk_recursive($Trace, function (&$Value, $Key) { if (in_array(strtolower($Key), array('password'))) { $Value = '***'; } }); $Data['Trace'] = $Trace; } if (!is_a($Ex, 'Gdn_UserException')) { $Data['StackTrace'] = $Ex->getTraceAsString(); } $Data['Data'] = $this->Data; } // Try cleaning out any notices or errors. if (ob_get_level()) { ob_clean(); } if ($Code >= 400 && $Code <= 505) { safeHeader("HTTP/1.0 {$Code}", true, $Code); } else { safeHeader('HTTP/1.0 500', true, 500); } switch ($this->deliveryMethod()) { case DELIVERY_METHOD_JSON: if (($Callback = $this->Request->getValueFrom(Gdn_Request::INPUT_GET, 'callback', false)) && $this->allowJSONP()) { safeHeader('Content-Type: application/javascript; charset=' . C('Garden.Charset', 'utf-8'), true); // This is a jsonp request. exit($Callback . '(' . json_encode($Data) . ');'); } else { safeHeader('Content-Type: application/json; charset=' . C('Garden.Charset', 'utf-8'), true); // This is a regular json request. exit(json_encode($Data)); } break; // case DELIVERY_METHOD_XHTML: // Gdn_ExceptionHandler($Ex); // break; // case DELIVERY_METHOD_XHTML: // Gdn_ExceptionHandler($Ex); // break; case DELIVERY_METHOD_XML: safeHeader('Content-Type: text/xml; charset=' . C('Garden.Charset', 'utf-8'), true); array_map('htmlspecialchars', $Data); exit("<Exception><Code>{$Data['Code']}</Code><Class>{$Data['Class']}</Class><Message>{$Data['Exception']}</Message></Exception>"); break; default: safeHeader('Content-Type: text/plain; charset=' . C('Garden.Charset', 'utf-8'), true); exit($Ex->getMessage()); } }
/** * Attempt to syncronize user data from remote system into Dashboard. * * @access public * @since 2.0.? * @author Tim Gunter * * @param object $Authenticator * @param array $UserInfo * @param array $Payload */ public function syncScreen($Authenticator, $UserInfo, $Payload) { $this->addJsFile('entry.js'); $this->View = 'handshake'; $this->HandshakeScheme = $Authenticator->getAuthenticationSchemeAlias(); $this->Form->setModel($this->UserModel); $this->Form->addHidden('ClientHour', date('Y-m-d H:00')); // Use the server's current hour as a default $this->Form->addHidden('Target', $this->target()); $PreservedKeys = array('UserKey', 'Token', 'Consumer', 'Email', 'Name', 'Gender', 'HourOffset'); $UserID = 0; $Target = $this->target(); if ($this->Form->isPostBack() === true) { $FormValues = $this->Form->formValues(); if (val('StopLinking', $FormValues)) { $AuthResponse = Gdn_Authenticator::AUTH_ABORTED; $UserEventData = array_merge(array('UserID' => $UserID, 'Payload' => $Payload), $UserInfo); Gdn::authenticator()->trigger($AuthResponse, $UserEventData); $Authenticator->deleteCookie(); Gdn::request()->withRoute('DefaultController'); return Gdn::dispatcher()->dispatch(); } elseif (val('NewAccount', $FormValues)) { $AuthResponse = Gdn_Authenticator::AUTH_CREATED; // Try and synchronize the user with the new username/email. $FormValues['Name'] = $FormValues['NewName']; $FormValues['Email'] = $FormValues['NewEmail']; $UserID = $this->UserModel->synchronize($UserInfo['UserKey'], $FormValues); $this->Form->setValidationResults($this->UserModel->validationResults()); } else { $AuthResponse = Gdn_Authenticator::AUTH_SUCCESS; // Try and sign the user in. $PasswordAuthenticator = Gdn::authenticator()->authenticateWith('password'); $PasswordAuthenticator->hookDataField('Email', 'SignInEmail'); $PasswordAuthenticator->hookDataField('Password', 'SignInPassword'); $PasswordAuthenticator->fetchData($this->Form); $UserID = $PasswordAuthenticator->authenticate(); if ($UserID < 0) { $this->Form->addError('ErrorPermission'); } elseif ($UserID == 0) { $this->Form->addError('ErrorCredentials'); Logger::event('signin_failure', Logger::WARNING, '{username} failed to sign in. Invalid credentials.'); } if ($UserID > 0) { $Data = $FormValues; $Data['UserID'] = $UserID; $Data['Email'] = val('SignInEmail', $FormValues, ''); $UserID = $this->UserModel->synchronize($UserInfo['UserKey'], $Data); } } if ($UserID > 0) { // The user has been created successfully, so sign in now // Finalize the link between the forum user and the foreign userkey $Authenticator->finalize($UserInfo['UserKey'], $UserID, $UserInfo['ConsumerKey'], $UserInfo['TokenKey'], $Payload); $UserEventData = array_merge(array('UserID' => $UserID, 'Payload' => $Payload), $UserInfo); Gdn::authenticator()->trigger($AuthResponse, $UserEventData); /// ... and redirect them appropriately $Route = $this->redirectTo(); if ($Route !== false) { redirect($Route); } } else { // Add the hidden inputs back into the form. foreach ($FormValues as $Key => $Value) { if (in_array($Key, $PreservedKeys)) { $this->Form->addHidden($Key, $Value); } } } } else { $Id = Gdn::authenticator()->getIdentity(true); if ($Id > 0) { // The user is signed in so we can just go back to the homepage. redirect($Target); } $Name = $UserInfo['UserName']; $Email = $UserInfo['UserEmail']; // Set the defaults for a new user. $this->Form->setFormValue('NewName', $Name); $this->Form->setFormValue('NewEmail', $Email); // Set the default for the login. $this->Form->setFormValue('SignInEmail', $Email); $this->Form->setFormValue('Handshake', 'NEW'); // Add the handshake data as hidden fields. $this->Form->addHidden('Name', $Name); $this->Form->addHidden('Email', $Email); $this->Form->addHidden('UserKey', $UserInfo['UserKey']); $this->Form->addHidden('Token', $UserInfo['TokenKey']); $this->Form->addHidden('Consumer', $UserInfo['ConsumerKey']); } $this->setData('Name', val('Name', $this->Form->HiddenInputs)); $this->setData('Email', val('Email', $this->Form->HiddenInputs)); $this->render(); }
<?php if (!defined('APPLICATION')) { exit; } // User. Gdn::FactoryInstall(Gdn::AliasUserModel, 'UserModel'); // Permissions. Gdn::FactoryInstall(Gdn::AliasPermissionModel, 'PermissionModel'); // Roles. Gdn::FactoryInstall('RoleModel', 'RoleModel'); // Head. Gdn::FactoryInstall('Head', 'HeadModule'); // Menu. Gdn::FactoryInstall('Menu', 'MenuModule'); Gdn::dispatcher()->PassProperty('Menu', Gdn::Factory('Menu'));
/** * Create a new not found exception. This is a convenience function that will create an exception with a standard message. * * @param string $Code The translation code of the type of object that wasn't found. * @return Exception */ function notFoundException($RecordType = 'Page') { Gdn::dispatcher()->passData('RecordType', $RecordType)->passData('Description', sprintf(T('The %s you were looking for could not be found.'), strtolower($RecordType))); return new Gdn_UserException(sprintf(T('%s not found.'), T($RecordType)), 404); }
/** * Set new password for current user. * * @since 2.0.0 * @access public */ public function password() { $this->permission('Garden.SignIn.Allow'); // Don't allow password editing if using SSO Connect ONLY. // This is for security. We encountered the case where a customer charges // for membership using their external application and use SSO to let // their customers into Vanilla. If you allow those people to change their // password in Vanilla, they will then be able to log into Vanilla using // Vanilla's login form regardless of the state of their membership in the // external app. if (c('Garden.Registration.Method') == 'Connect') { Gdn::dispatcher()->dispatch('DefaultPermission'); exit; } Gdn::userModel()->addPasswordStrength($this); // Get user data and set up form $this->getUserInfo(); $this->Form->setModel($this->UserModel); $this->addDefinition('Username', $this->User->Name); if ($this->Form->authenticatedPostBack() === true) { $this->Form->setFormValue('UserID', $this->User->UserID); $this->UserModel->defineSchema(); // $this->UserModel->Validation->AddValidationField('OldPassword', $this->Form->formValues()); // No password may have been set if they have only signed in with a connect plugin if (!$this->User->HashMethod || $this->User->HashMethod == "Vanilla") { $this->UserModel->Validation->applyRule('OldPassword', 'Required'); $this->UserModel->Validation->applyRule('OldPassword', 'OldPassword', 'Your old password was incorrect.'); } $this->UserModel->Validation->applyRule('Password', 'Required'); $this->UserModel->Validation->applyRule('Password', 'Strength'); $this->UserModel->Validation->applyRule('Password', 'Match'); if ($this->Form->save()) { $this->informMessage(sprite('Check', 'InformSprite') . t('Your password has been changed.'), 'Dismissable AutoDismiss HasSprite'); $this->Form->clearInputs(); Logger::event('password_change', Logger::INFO, '{InsertName} changed password.'); } else { Logger::event('password_change_failure', Logger::INFO, '{InsertName} failed to change password.', array('Error' => $this->Form->errorString())); } } $this->title(t('Change My Password')); $this->_setBreadcrumbs(t('Change My Password'), '/profile/password'); $this->render(); }
/** * * * @param $Sender * @param bool|false $PocketID * @return mixed * @throws Gdn_UserException */ protected function _addEdit($Sender, $PocketID = false) { $Form = new Gdn_Form(); $PocketModel = new Gdn_Model('Pocket'); $Form->setModel($PocketModel); $Sender->ConditionModule = new ConditionModule($Sender); $Sender->Form = $Form; if ($Form->authenticatedPostBack()) { // Save the pocket. if ($PocketID !== false) { $Form->setFormValue('PocketID', $PocketID); } // Convert the form data into a format digestable by the database. $Repeat = $Form->getFormValue('RepeatType'); switch ($Repeat) { case Pocket::REPEAT_EVERY: $PocketModel->Validation->applyRule('EveryFrequency', 'Integer'); $PocketModel->Validation->applyRule('EveryBegin', 'Integer'); $Frequency = $Form->getFormValue('EveryFrequency', 1); if (!$Frequency || !validateInteger($Frequency) || $Frequency < 1) { $Frequency = 1; } $Repeat .= ' ' . $Frequency; if ($Form->getFormValue('EveryBegin', 1) > 1) { $Repeat .= ',' . $Form->getFormValue('EveryBegin'); } break; case Pocket::REPEAT_INDEX: $PocketModel->Validation->addRule('IntegerArray', 'function:ValidateIntegerArray'); $PocketModel->Validation->applyRule('Indexes', 'IntegerArray'); $Indexes = explode(',', $Form->getFormValue('Indexes', '')); $Indexes = array_map('trim', $Indexes); $Repeat .= ' ' . implode(',', $Indexes); break; default: break; } $Form->setFormValue('Repeat', $Repeat); $Form->setFormValue('Sort', 0); $Form->setFormValue('Format', 'Raw'); $Condition = Gdn_Condition::toString($Sender->ConditionModule->conditions(true)); $Form->setFormValue('Condition', $Condition); if ($Form->getFormValue('Ad', 0)) { $Form->setFormValue('Type', Pocket::TYPE_AD); } else { $Form->setFormValue('Type', Pocket::TYPE_DEFAULT); } $Saved = $Form->save(); if ($Saved) { $Sender->StatusMessage = t('Your changes have been saved.'); $Sender->RedirectUrl = url('settings/pockets'); } } else { if ($PocketID !== false) { // Load the pocket. $Pocket = $PocketModel->getWhere(array('PocketID' => $PocketID))->firstRow(DATASET_TYPE_ARRAY); if (!$Pocket) { return Gdn::dispatcher()->dispatch('Default404'); } // Convert some of the pocket data into a format digestable by the form. list($RepeatType, $RepeatFrequency) = Pocket::parseRepeat($Pocket['Repeat']); $Pocket['RepeatType'] = $RepeatType; $Pocket['EveryFrequency'] = GetValue(0, $RepeatFrequency, 1); $Pocket['EveryBegin'] = GetValue(1, $RepeatFrequency, 1); $Pocket['Indexes'] = implode(',', $RepeatFrequency); $Pocket['Ad'] = $Pocket['Type'] == Pocket::TYPE_AD; $Sender->ConditionModule->conditions(Gdn_Condition::fromString($Pocket['Condition'])); $Form->setData($Pocket); } else { // Default the repeat. $Form->setFormValue('RepeatType', Pocket::REPEAT_ONCE); } } $Sender->Form = $Form; $Sender->setData('Locations', $this->Locations); $Sender->setData('LocationsArray', $this->getLocationsArray()); $Sender->setData('Pages', array('' => '(' . T('All') . ')', 'activity' => 'activity', 'comments' => 'comments', 'dashboard' => 'dashboard', 'discussions' => 'discussions', 'inbox' => 'inbox', 'profile' => 'profile')); return $Sender->render('AddEdit', '', 'plugins/Pockets'); }
/** * Alias /addons to /addon. */ public function index() { Gdn::dispatcher()->dispatch('/addon'); }
/** * * * @param RootController $Sender * @param $Args */ public function rootController_sso_handler($Sender, $Args) { $Provider = $Args['DefaultProvider']; if (val('AuthenticationSchemeAlias', $Provider) !== 'jsconnect') { return; } // The default provider is jsconnect so let's redispatch there. $Get = ['client_id' => val('AuthenticationKey', $Provider), 'target' => val('Target', $Args, '/')]; $Url = '/entry/jsconnect?' . http_build_query($Get); Gdn::request()->pathAndQuery($Url); Gdn::dispatcher()->dispatch(); $Args['Handled'] = true; }