/** * Override the default dashboard page with the new stats one. */ public function Gdn_Dispatcher_BeforeDispatch_Handler($Sender) { $Enabled = C('Garden.Analytics.Enabled', TRUE); if ($Enabled && !Gdn::PluginManager()->HasNewMethod('SettingsController', 'Index')) { Gdn::PluginManager()->RegisterNewMethod('VanillaStatsPlugin', 'StatsDashboard', 'SettingsController', 'Index'); } }
public function GetPluginFolder($Absolute = TRUE) { $Folder = GetValue('Folder', Gdn::PluginManager()->GetPluginInfo(get_class($this), Gdn_PluginManager::ACCESS_CLASSNAME)); $PathParts = array($Folder); array_unshift($PathParts, $Absolute ? PATH_PLUGINS : 'plugins'); return implode(DS, $PathParts); }
/** * Remove plugins that are not mobile friendly! */ public function Gdn_Dispatcher_AfterAnalyzeRequest_Handler($Sender) { // Remove plugins so they don't mess up layout or functionality. if (in_array($Sender->Application(), array('vanilla', 'dashboard', 'conversations'))) { Gdn::PluginManager()->RemoveMobileUnfriendlyPlugins(); } }
/** * Is the application/plugin/theme removable? * * @param string $Type self::TYPE_APPLICATION or self::TYPE_PLUGIN or self::TYPE_THEME * @param string $Name * @return boolean */ public static function IsRemovable($Type, $Name) { switch ($Type) { case self::TYPE_APPLICATION: $ApplicationManager = Gdn::Factory('ApplicationManager'); if ($IsRemovable = !array_key_exists($Name, $ApplicationManager->EnabledApplications())) { $ApplicationInfo = ArrayValue($Name, $ApplicationManager->AvailableApplications(), array()); $ApplicationFolder = ArrayValue('Folder', $ApplicationInfo, ''); $IsRemovable = IsWritable(PATH_APPLICATIONS . DS . $ApplicationFolder); } break; case self::TYPE_PLUGIN: if ($IsRemovable = !array_key_exists($Name, Gdn::PluginManager()->EnabledPlugins)) { $PluginInfo = ArrayValue($Name, Gdn::PluginManager()->AvailablePlugins(), FALSE); $PluginFolder = ArrayValue('Folder', $PluginInfo, FALSE); $IsRemovable = IsWritable(PATH_PLUGINS . DS . $PluginFolder); } break; case self::TYPE_THEME: // TODO $IsRemovable = FALSE; break; } return $IsRemovable; }
/** * Set user's preferred locale. * * Moved event from AppStart to AfterAnalyzeRequest to allow Embed to set P3P header first. */ public function Gdn_Dispatcher_AfterAnalyzeRequest_Handler($Sender) { // Set user preference if ($TempLocale = $this->GetAlternateLocale()) { Gdn::Locale()->Set($TempLocale, Gdn::ApplicationManager()->EnabledApplicationFolders(), Gdn::PluginManager()->EnabledPluginFolders()); } }
/** Remove plugins that are not mobile friendly! */ public function Gdn_Dispatcher_AfterAnalyzeRequest_Handler($Sender) { // Remove plugins so they don't mess up layout or functionality. if (in_array($Sender->Application(), array('vanilla', 'conversations')) || $Sender->Application() == 'dashboard' && in_array($Sender->Controller(), array('Activity', 'Profile', 'Search'))) { Gdn::PluginManager()->RemoveMobileUnfriendlyPlugins(); } SaveToConfig('Garden.Format.EmbedSize', '240x135', FALSE); }
/** * Reload the locale system */ public function Refresh() { $LocalName = $this->Current(); $ApplicationWhiteList = Gdn::ApplicationManager()->EnabledApplicationFolders(); $PluginWhiteList = Gdn::PluginManager()->EnabledPluginFolders(); $ForceRemapping = TRUE; $this->Set($LocalName, $ApplicationWhiteList, $PluginWhiteList, $ForceRemapping); }
protected function RenderNsfw(&$Sender) { if (!$this->RenderNsfw || Gdn::PluginManager()->CheckPlugin('NBBC')) { return; } $FormatBody =& $Sender->EventArguments['Object']->FormatBody; $FormatBody = preg_replace('`<div>\\s*(\\[/?nsfw\\])\\s*</div>`', '$1', $FormatBody); $FormatBody = preg_replace_callback("/(\\[nsfw(?:=(?:")?([\\d\\w_',.? ]+)(?:")?)?\\])/siu", array($this, 'NsfwCallback'), $FormatBody); $FormatBody = str_ireplace('[/nsfw]', '</div></div>', $FormatBody); }
public function __construct() { parent::__construct(); if (Gdn::PluginManager()->CheckPlugin('Reactions') && C('Plugins.QnA.Reactions', TRUE)) { $this->Reactions = TRUE; } if (Gdn::ApplicationManager()->CheckApplication('Reputation') && C('Plugins.QnA.Badges', TRUE)) { $this->Badges = TRUE; } }
protected function RenderSpoilers(&$Sender) { if (!$this->RenderSpoilers || Gdn::PluginManager()->CheckPlugin('NBBC')) { return; } $FormatBody =& $Sender->EventArguments['Object']->FormatBody; // Fix a wysiwyg but where spoilers $FormatBody = preg_replace('`<div>\\s*(\\[/?spoiler\\])\\s*</div>`', '$1', $FormatBody); $FormatBody = preg_replace_callback("/(\\[spoiler(?:=(?:")?([\\d\\w_',.? ]+)(?:")?)?\\])/siu", array($this, 'SpoilerCallback'), $FormatBody); $FormatBody = str_ireplace('[/spoiler]', '</div></div>', $FormatBody); }
function Gdn_Autoload($ClassName) { if (!class_exists('Gdn_FileSystem', FALSE)) { return false; } if (!class_exists('Gdn_LibraryMap', FALSE)) { return false; } if (!class_exists('Gdn', FALSE)) { return false; } if (substr($ClassName, 0, 4) === 'Gdn_') { $LibraryFileName = 'class.' . strtolower(substr($ClassName, 4)) . '.php'; } else { $LibraryFileName = 'class.' . strtolower($ClassName) . '.php'; } if (!is_null($ApplicationManager = Gdn::Factory('ApplicationManager'))) { $ApplicationWhiteList = Gdn::Factory('ApplicationManager')->EnabledApplicationFolders(); } else { $ApplicationWhiteList = NULL; } $LibraryPath = FALSE; // If this is a model, look in the models folder(s) if (strtolower(substr($ClassName, -5)) == 'model') { $LibraryPath = Gdn_FileSystem::FindByMapping('library', PATH_APPLICATIONS, $ApplicationWhiteList, 'models' . DS . $LibraryFileName); } if (Gdn::PluginManager() instanceof Gdn_PluginManager) { // Look for plugin files. if ($LibraryPath === FALSE) { $PluginFolders = Gdn::PluginManager()->EnabledPluginFolders(); $LibraryPath = Gdn_FileSystem::FindByMapping('library', PATH_PLUGINS, $PluginFolders, $LibraryFileName); } // Look harder for plugin files. if ($LibraryPath === FALSE) { $LibraryPath = Gdn_FileSystem::FindByMapping('plugin', FALSE, FALSE, $ClassName); } } // Look for the class in the applications' library folders. if ($LibraryPath === FALSE) { $LibraryPath = Gdn_FileSystem::FindByMapping('library', PATH_APPLICATIONS, $ApplicationWhiteList, "library/{$LibraryFileName}"); } // Look for the class in the core. if ($LibraryPath === FALSE) { $LibraryPath = Gdn_FileSystem::FindByMapping('library', PATH_LIBRARY, array('core', 'database', 'vendors' . DS . 'phpmailer'), $LibraryFileName); } // If it still hasn't been found, check for modules if ($LibraryPath === FALSE) { $LibraryPath = Gdn_FileSystem::FindByMapping('library', PATH_APPLICATIONS, $ApplicationWhiteList, 'modules' . DS . $LibraryFileName); } if ($LibraryPath !== FALSE) { include_once $LibraryPath; } }
public function EnabledLocalePacks($GetInfo = FALSE) { $Result = (array) C('EnabledLocales', array()); if ($GetInfo) { foreach ($Result as $Key => $Locale) { $InfoPath = PATH_ROOT . "/locales/{$Key}/definitions.php"; if (file_exists($InfoPath)) { $LocaleInfo = Gdn::PluginManager()->ScanPluginFile($InfoPath, 'LocaleInfo'); $Result[$Key] = current($LocaleInfo); } else { unset($Result[$Key]); } } } return $Result; }
/** * * * @since 2.0.18 * @access public * @return array Category IDs. */ public static function CategoryWatch() { $Categories = self::Categories(); $AllCount = count($Categories); $Watch = array(); foreach ($Categories as $CategoryID => $Category) { if ($Category['PermsDiscussionsView'] && $Category['Following'] && !GetValue('HideAllDiscussions', $Category)) { $Watch[] = $CategoryID; } } Gdn::PluginManager()->EventArguments['CategoryIDs'] =& $Watch; Gdn::PluginManager()->FireEvent('CategoryWatch'); if ($AllCount == count($Watch)) { return TRUE; } return $Watch; }
/** * If passed path leads to an image, return size * * @param string $Path Path to file. * @return array [0] => Height, [1] => Width. */ public static function GetImageSize($Path) { // Static FireEvent for intercepting non-local files. $Sender = new stdClass(); $Sender->Returns = array(); $Sender->EventArguments = array(); $Sender->EventArguments['Path'] =& $Path; $Sender->EventArguments['Parsed'] = Gdn_Upload::Parse($Path); Gdn::PluginManager()->CallEventHandlers($Sender, 'Gdn_Upload', 'CopyLocal'); if (!in_array(strtolower(pathinfo($Path, PATHINFO_EXTENSION)), array('gif', 'jpg', 'jpeg', 'png'))) { return array(0, 0); } $ImageSize = @getimagesize($Path); if (is_array($ImageSize)) { if (!in_array($ImageSize[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) { return array(0, 0); } return array($ImageSize[0], $ImageSize[1]); } return array(0, 0); }
/** * Returns the url prefix for a given type. * If there is a plugin that wants to store uploads at a different location or in a different way then they register themselves by subscribing to the Gdn_Upload_GetUrls_Handler event. * After that they will be available here. * * @param string $Type The type of upload to get the prefix for. * @return string The url prefix. */ public static function Urls($Type = NULL) { static $Urls = NULL; if ($Urls === NULL) { $Urls = array('' => Asset('/uploads', TRUE)); $Sender = new stdClass(); $Sender->Returns = array(); $Sender->EventArguments = array(); $Sender->EventArguments['Urls'] =& $Urls; Gdn::PluginManager()->CallEventHandlers($Sender, 'Gdn_Upload', 'GetUrls'); } if ($Type === NULL) { return $Urls; } if (isset($Urls[$Type])) { return $Urls[$Type]; } return FALSE; }
/** * Used to extend any method * * There are two types of extended method calls: * 1. Declared: The method was declared with the lowercase "x" prefix and called without it. * ie. Declaration: public function xMethodName() {} * Call: $Object->MethodName(); * * 2. Called: The method was declared without the lowercase "x" prefix and called with it. * ie. Declaration: public function MethodName() {} * Call: $Object->xMethodName(); * * Note: Plugins will always refer to the method name without the "x" * regardless of the type. So, $ReferenceMethodName is declared below without * the "x". * * * @param string $MethodName * @param array $Arguments * @return mixed * */ public function __call($MethodName, $Arguments) { // Define a return variable. $Return = FALSE; // Was this method declared, or called? if (substr($MethodName, 0, 1) == 'x') { // Declared $ActualMethodName = substr($MethodName, 1); // Remove the x prefix $ReferenceMethodName = $ActualMethodName; // No x prefix } else { // Called $ActualMethodName = 'x' . $MethodName; // Add the x prefix $ReferenceMethodName = $MethodName; // No x prefix } // Make sure that $ActualMethodName exists before continuing: if (!method_exists($this, $ActualMethodName)) { // Make sure that a plugin is not handling the call if (!Gdn::PluginManager()->HasNewMethod($this->ClassName, $ReferenceMethodName)) { trigger_error(ErrorMessage('The "' . $this->ClassName . '" object does not have a "' . $ActualMethodName . '" method.', $this->ClassName, $ActualMethodName), E_USER_ERROR); } } // Make sure the arguments get passed in the same way whether firing a custom event or a magic one. $this->EventArguments = $Arguments; // Call the "Before" event handlers Gdn::PluginManager()->CallEventHandlers($this, $this->ClassName, $ReferenceMethodName, 'Before'); // Call this object's method if (Gdn::PluginManager()->HasMethodOverride($this->ClassName, $ReferenceMethodName)) { // The method has been overridden $this->HandlerType = HANDLER_TYPE_OVERRIDE; $Return = Gdn::PluginManager()->CallMethodOverride($this, $this->ClassName, $ReferenceMethodName); } else { if (Gdn::PluginManager()->HasNewMethod($this->ClassName, $ReferenceMethodName)) { $this->HandlerType = HANDLER_TYPE_NEW; $Return = Gdn::PluginManager()->CallNewMethod($this, $this->ClassName, $ReferenceMethodName); } else { // The method has not been overridden $Count = count($Arguments); if ($Count == 0) { $Return = $this->{$ActualMethodName}(); } else { if ($Count == 1) { $Return = $this->{$ActualMethodName}($Arguments[0]); } else { if ($Count == 2) { $Return = $this->{$ActualMethodName}($Arguments[0], $Arguments[1]); } else { if ($Count == 3) { $Return = $this->{$ActualMethodName}($Arguments[0], $Arguments[1], $Arguments[2]); } else { if ($Count == 4) { $Return = $this->{$ActualMethodName}($Arguments[0], $Arguments[1], $Arguments[2], $Arguments[3]); } else { $Return = $this->{$ActualMethodName}($Arguments[0], $Arguments[1], $Arguments[2], $Arguments[3], $Arguments[4]); } } } } } } } // Call the "After" event handlers Gdn::PluginManager()->CallEventHandlers($this, $this->ClassName, $MethodName, 'After'); return $Return; }
public function Structure($AppName = 'all', $CaptureOnly = '1', $Drop = '0', $Explicit = '0') { $this->Permission('Garden.Settings.Manage'); $Files = array(); $AppName = $AppName == '' ? 'all': $AppName; if ($AppName == 'all') { // Load all application structure files. $ApplicationManager = new Gdn_ApplicationManager(); $Apps = $ApplicationManager->EnabledApplications(); $AppNames = ConsolidateArrayValuesByKey($Apps, 'Folder'); foreach ($AppNames as $AppName) { $Files[] = CombinePaths(array(PATH_APPLICATIONS, $AppName, 'settings', 'structure.php'), DS); } $AppName = 'all'; } else { // Load that specific application structure file. $Files[] = CombinePaths(array(PATH_APPLICATIONS, $AppName, 'settings', 'structure.php'), DS); } $Validation = new Gdn_Validation(); $Database = Gdn::Database(); $Drop = $Drop == '0' ? FALSE : TRUE; $Explicit = $Explicit == '0' ? FALSE : TRUE; $CaptureOnly = !($CaptureOnly == '0'); $Structure = Gdn::Structure(); $Structure->CaptureOnly = $CaptureOnly; $SQL = Gdn::SQL(); $SQL->CaptureModifications = $CaptureOnly; $this->SetData('CaptureOnly', $Structure->CaptureOnly); $this->SetData('Drop', $Drop); $this->SetData('Explicit', $Explicit); $this->SetData('ApplicationName', $AppName); $this->SetData('Status', ''); $FoundStructureFile = FALSE; foreach ($Files as $File) { if (file_exists($File)) { $FoundStructureFile = TRUE; try { include($File); } catch (Exception $Ex) { $this->Form->AddError($Ex); } } } // Run the structure of all of the plugins. $Plugins = Gdn::PluginManager()->EnabledPlugins(); foreach ($Plugins as $PluginKey => $Plugin) { $PluginInstance = Gdn::PluginManager()->GetPluginInstance($PluginKey, Gdn_PluginManager::ACCESS_PLUGINNAME); if (method_exists($PluginInstance, 'Structure')) $PluginInstance->Structure(); } if (property_exists($Structure->Database, 'CapturedSql')) $this->SetData('CapturedSql', (array)$Structure->Database->CapturedSql); else $this->SetData('CapturedSql', array()); if ($this->Form->ErrorCount() == 0 && !$CaptureOnly && $FoundStructureFile) $this->SetData('Status', 'The structure was successfully executed.'); $this->AddSideMenu('dashboard/settings/configure'); $this->AddCssFile('admin.css'); $this->SetData('Title', T('Database Structure Upgrades')); $this->Render(); }
public function Plugins($Filter = '', $PluginName = '', $TransientKey = '') { $this->AddJsFile('addons.js'); $this->Title(T('Plugins')); $Session = Gdn::Session(); $PluginName = $Session->ValidateTransientKey($TransientKey) ? $PluginName : ''; if (!in_array($Filter, array('enabled', 'disabled'))) { $Filter = 'all'; } $this->Filter = $Filter; $this->Permission('Garden.Plugins.Manage'); $this->AddSideMenu('dashboard/settings/plugins'); // Retrieve all available plugins from the plugins directory $this->EnabledPlugins = Gdn::PluginManager()->EnabledPlugins; self::SortAddons($this->EnabledPlugins); $this->AvailablePlugins = Gdn::PluginManager()->AvailablePlugins(); self::SortAddons($this->AvailablePlugins); // Loop through all of the available plugins and mark them if they have an update available // Retrieve the list of plugins that require updates from the config file $RequiredUpdates = Gdn_Format::Unserialize(Gdn::Config('Garden.RequiredUpdates', '')); if (is_array($RequiredUpdates)) { foreach ($RequiredUpdates as $UpdateInfo) { if (is_object($UpdateInfo)) { $UpdateInfo = Gdn_Format::ObjectAsArray($UpdateInfo); } $NewVersion = ArrayValue('Version', $UpdateInfo, ''); $Name = ArrayValue('Name', $UpdateInfo, ''); $Type = ArrayValue('Type', $UpdateInfo, ''); foreach ($this->AvailablePlugins as $Plugin => $Info) { $CurrentName = ArrayValue('Name', $Info, $Plugin); if ($CurrentName == $Name && $Type == 'Plugin') { $Info['NewVersion'] = $NewVersion; $this->AvailablePlugins[$Plugin] = $Info; } } } } if ($PluginName != '') { try { $this->EventArguments['PluginName'] = $PluginName; if (array_key_exists($PluginName, $this->EnabledPlugins) === TRUE) { Gdn::PluginManager()->DisablePlugin($PluginName); $this->FireEvent('AfterDisablePlugin'); } else { $Validation = new Gdn_Validation(); if (!Gdn::PluginManager()->EnablePlugin($PluginName, $Validation)) { $this->Form->SetValidationResults($Validation->Results()); } $this->EventArguments['Validation'] = $Validation; $this->FireEvent('AfterEnablePlugin'); } } catch (Exception $e) { $this->Form->AddError(strip_tags($e->getMessage())); } if ($this->Form->ErrorCount() == 0) { Redirect('/settings/plugins/' . $this->Filter); } } $this->Render(); }
public function Media() { if ($this->_Media === NULL) { try { $I = Gdn::PluginManager()->GetPluginInstance('FileUploadPlugin', Gdn_PluginManager::ACCESS_CLASSNAME); $M = $I->MediaCache(); } catch (Exception $Ex) { $M = array(); } $Media = array(); foreach ($M as $Key => $Data) { foreach ($Data as $Row) { $Media[$Row->MediaID] = $Row; } } $this->_Media = $Media; } return $this->_Media; }
/** * Allows the configuration of basic setup information in Garden. This * should not be functional after the application has been set up. * * @since 2.0.0 * @access public * @param string $RedirectUrl Where to send user afterward. */ public function Configure($RedirectUrl = '') { // 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', 'Garden.Registration.ConfirmEmail', 'Garden.Email.SupportName')); // 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. $ExistingSalt = C('Garden.Cookie.Salt', FALSE); $ConfigurationFormValues['Garden.Cookie.Salt'] = $ExistingSalt ? $ExistingSalt : RandomString(10); $ConfigurationFormValues['Garden.Cookie.Domain'] = ''; // Don't set this to anything by default. # Tim - 2010-06-23 // Additional default setup values. $ConfigurationFormValues['Garden.Registration.ConfirmEmail'] = TRUE; $ConfigurationFormValues['Garden.Email.SupportName'] = $ConfigurationFormValues['Garden.Title']; $ConfigurationModel->Save($ConfigurationFormValues, TRUE); // 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(); $Locale = Gdn::Locale(); $Locale->Set($NewLocale, $ApplicationManager->EnabledApplicationFolders(), Gdn::PluginManager()->EnabledPluginFolders(), TRUE); } // Install db structure & basic data. $Database = Gdn::Database(); $Database->Init(); $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($ex); } if ($this->Form->ErrorCount() > 0) { return FALSE; } // Create the administrative user $UserModel = Gdn::UserModel(); $UserModel->DefineSchema(); $UsernameError = T('UsernameError', 'Username can only contain letters, numbers, underscores, and must be between 3 and 20 characters long.'); $UserModel->Validation->ApplyRule('Name', 'Username', $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 (!($AdminUserID = $UserModel->SaveAdminUser($ConfigurationFormValues))) { $this->Form->SetValidationResults($UserModel->ValidationResults()); } else { // The user has been created successfully, so sign in now. SaveToConfig('Garden.Installed', TRUE, array('Save' => FALSE)); Gdn::Session()->Start($AdminUserID, TRUE); SaveToConfig('Garden.Installed', FALSE, array('Save' => FALSE)); } 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 = ConcatSep('/', Gdn::Request()->Domain(), Gdn::Request()->WebRoot(), 'dashboard/setup'); $Results = ProxyHead($Query, array(), 3); $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.RewriteUrls' => $CanRewrite, 'Garden.CanProcessImages' => function_exists('gd_info'), 'EnabledPlugins.GettingStarted' => 'GettingStarted', 'EnabledPlugins.HtmLawed' => 'HtmLawed')); } } return $this->Form->ErrorCount() == 0 ? TRUE : FALSE; }
include_once $Gdn_Path; } // Include the application's hooks. $Hooks_Path = PATH_APPLICATIONS . DS . $ApplicationFolder . DS . 'settings' . DS . 'class.hooks.php'; if (file_exists($Hooks_Path)) { include_once $Hooks_Path; } } unset($Gdn_EnabledApplications); unset($Gdn_Path); unset($Hooks_Path); // If there is a hooks file in the theme folder, include it. $ThemeName = C('Garden.Theme', 'default'); $ThemeHooks = PATH_THEMES . DS . $ThemeName . DS . 'class.' . strtolower($ThemeName) . 'themehooks.php'; if (file_exists($ThemeHooks)) { include_once $ThemeHooks; } // Set up the plugin manager (doing this early so it has fewer classes to // examine to determine if they are plugins). Gdn::FactoryInstall(Gdn::AliasPluginManager, 'Gdn_PluginManager', PATH_LIBRARY . DS . 'core' . DS . 'class.pluginmanager.php', Gdn::FactorySingleton); Gdn::PluginManager()->IncludePlugins(); Gdn::PluginManager()->RegisterPlugins(); Gdn::FactoryOverwrite($FactoryOverwriteBak); unset($FactoryOverwriteBak); Gdn::Authenticator()->StartAuthenticator(); /// Include a user-defined bootstrap. if (file_exists(PATH_ROOT . DS . 'conf' . DS . 'bootstrap.after.php')) { require_once PATH_ROOT . DS . 'conf' . DS . 'bootstrap.after.php'; } // Include "Render" functions now - this way pluggables and custom confs can override them. require_once PATH_LIBRARY_CORE . DS . 'functions.render.php';
/** * Fetches the location of a view into a string and returns it. Returns * false on failure. * * @param string $View The name of the view to fetch. If not specified, it will use the value * of $this->View. If $this->View is not specified, it will use the value * of $this->RequestMethod (which is defined by the dispatcher class). * @param string $ControllerName The name of the controller that owns the view if it is not $this. * - If the controller name is FALSE then the name of the current controller will be used. * - If the controller name is an empty string then the view will be looked for in the base views folder. * @param string $ApplicationFolder The name of the application folder that contains the requested controller if it is not $this->ApplicationFolder. */ public function FetchViewLocation($View = '', $ControllerName = FALSE, $ApplicationFolder = FALSE, $ThrowError = TRUE) { // Accept an explicitly defined view, or look to the method that was called on this controller if ($View == '') { $View = $this->View; } if ($View == '') { $View = $this->RequestMethod; } if ($ControllerName === FALSE) { $ControllerName = $this->ControllerName; } // Munge the controller folder onto the controller name if it is present. if ($this->ControllerFolder != '') { $ControllerName = $this->ControllerFolder . DS . $ControllerName; } if (StringEndsWith($ControllerName, 'controller', TRUE)) { $ControllerName = substr($ControllerName, 0, -10); } if (strtolower(substr($ControllerName, 0, 4)) == 'gdn_') { $ControllerName = substr($ControllerName, 4); } if (!$ApplicationFolder) { $ApplicationFolder = $this->ApplicationFolder; } //$ApplicationFolder = strtolower($ApplicationFolder); $ControllerName = strtolower($ControllerName); if (strpos($View, DS) === FALSE) { // keep explicit paths as they are. $View = strtolower($View); } // If this is a syndication request, append the method to the view if ($this->SyndicationMethod == SYNDICATION_ATOM) { $View .= '_atom'; } else { if ($this->SyndicationMethod == SYNDICATION_RSS) { $View .= '_rss'; } } $LocationName = ConcatSep('/', strtolower($ApplicationFolder), $ControllerName, $View); $ViewPath = ArrayValue($LocationName, $this->_ViewLocations, FALSE); if ($ViewPath === FALSE) { // Define the search paths differently depending on whether or not we are in a plugin or application. $ApplicationFolder = trim($ApplicationFolder, '/'); if (StringBeginsWith($ApplicationFolder, 'plugins/')) { $KeyExplode = explode('/', $ApplicationFolder); $PluginName = array_pop($KeyExplode); $PluginInfo = Gdn::PluginManager()->GetPluginInfo($PluginName); $BasePath = GetValue('SearchPath', $PluginInfo); $ApplicationFolder = GetValue('Folder', $PluginInfo); } else { $BasePath = PATH_APPLICATIONS; $ApplicationFolder = strtolower($ApplicationFolder); } $SubPaths = array(); // Define the subpath for the view. // The $ControllerName used to default to '' instead of FALSE. // This extra search is added for backwards-compatibility. if (strlen($ControllerName) > 0) { $SubPaths[] = "views/{$ControllerName}/{$View}"; } else { $SubPaths[] = "views/{$View}"; $SubPaths[] = "views/{$this->ControllerName}/{$View}"; } // Views come from one of four places: $ViewPaths = array(); foreach ($SubPaths as $SubPath) { // 1. An explicitly defined path to a view if (strpos($View, DS) !== FALSE) { $ViewPaths[] = $View; } if ($this->Theme) { // 2. Application-specific theme view. eg. /path/to/application/themes/theme_name/app_name/views/controller_name/ $ViewPaths[] = PATH_THEMES . "/{$this->Theme}/{$ApplicationFolder}/{$SubPath}.*"; // $ViewPaths[] = CombinePaths(array(PATH_THEMES, $this->Theme, $ApplicationFolder, 'views', $ControllerName, $View . '.*')); // 3. Garden-wide theme view. eg. /path/to/application/themes/theme_name/views/controller_name/ $ViewPaths[] = PATH_THEMES . "/{$this->Theme}/{$SubPath}.*"; //$ViewPaths[] = CombinePaths(array(PATH_THEMES, $this->Theme, 'views', $ControllerName, $View . '.*')); } // 4. Application/plugin default. eg. /path/to/application/app_name/views/controller_name/ $ViewPaths[] = "{$BasePath}/{$ApplicationFolder}/{$SubPath}.*"; //$ViewPaths[] = CombinePaths(array(PATH_APPLICATIONS, $ApplicationFolder, 'views', $ControllerName, $View . '.*')); } // Find the first file that matches the path. $ViewPath = FALSE; foreach ($ViewPaths as $Glob) { $Paths = SafeGlob($Glob); if (is_array($Paths) && count($Paths) > 0) { $ViewPath = $Paths[0]; break; } } //$ViewPath = Gdn_FileSystem::Exists($ViewPaths); $this->_ViewLocations[$LocationName] = $ViewPath; } // echo '<div>['.$LocationName.'] RETURNS ['.$ViewPath.']</div>'; if ($ViewPath === FALSE && $ThrowError) { trigger_error(ErrorMessage("Could not find a '{$View}' view for the '{$ControllerName}' controller in the '{$ApplicationFolder}' application.", $this->ClassName, 'FetchViewLocation'), E_USER_ERROR); } return $ViewPath; }
/** * Gets the shortname of the currently active cache * * This method retrieves the name of the active cache according to the config file. * It fires an event thereafter, allowing that value to be overridden * by loaded plugins. * * @return string shortname of current auto active cache */ public static function ActiveCache() { /* * There is a catch 22 with caching the config file. We need * an external way to define the cache layer before needing it * in the config. */ if (defined('CACHE_METHOD_OVERRIDE')) { $ActiveCache = CACHE_METHOD_OVERRIDE; } else { $ActiveCache = C('Cache.Method', FALSE); } // This should only fire when cache is loading automatically if (!func_num_args() && Gdn::PluginManager() instanceof Gdn_PluginManager) { Gdn::PluginManager()->EventArguments['ActiveCache'] =& $ActiveCache; Gdn::PluginManager()->FireEvent('BeforeActiveCache'); } return $ActiveCache; }
/** * Parses the query string looking for supplied request parameters. Places * anything useful into this object's Controller properties. * * @param int $FolderDepth */ protected function AnalyzeRequest(&$Request) { // Here is the basic format of a request: // [/application]/controller[/method[.json|.xml]]/argn|argn=valn // Here are some examples of what this method could/would receive: // /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(); $this->Request = $Request->Path(FALSE); $PathAndQuery = $Request->PathAndQuery(); $MatchRoute = Gdn::Router()->MatchRoute($PathAndQuery); // We have a route. Take action. if ($MatchRoute !== FALSE) { switch ($MatchRoute['Type']) { case 'Internal': $Request->PathAndQuery($MatchRoute['FinalDestination']); $this->Request = $Request->Path(FALSE); break; case 'Temporary': header("HTTP/1.1 302 Moved Temporarily"); header("Location: " . Url($MatchRoute['FinalDestination'])); exit; break; case 'Permanent': header("HTTP/1.1 301 Moved Permanently"); header("Location: " . Url($MatchRoute['FinalDestination'])); exit; break; case 'NotAuthorized': header("HTTP/1.1 401 Not Authorized"); $this->Request = $MatchRoute['FinalDestination']; break; case 'NotFound': header("HTTP/1.1 404 Not Found"); $this->Request = $MatchRoute['FinalDestination']; break; case 'Test': $Request->PathAndQuery($MatchRoute['FinalDestination']); $this->Request = $Request->Path(FALSE); decho($MatchRoute, 'Route'); decho(array('Path' => $Request->Path(), 'Get' => $Request->Get()), 'Request'); die; } } switch ($Request->OutputFormat()) { case 'rss': $this->_SyndicationMethod = SYNDICATION_RSS; break; case 'atom': $this->_SyndicationMethod = SYNDICATION_ATOM; break; case 'default': default: $this->_SyndicationMethod = SYNDICATION_NONE; break; } if ($this->Request == '') { $DefaultController = Gdn::Router()->GetRoute('DefaultController'); $this->Request = $DefaultController['Destination']; } $Parts = explode('/', str_replace('\\', '/', $this->Request)); /** * The application folder is either the first argument or is not provided. The controller is therefore * either the second argument or the first, depending on the result of the previous statement. Check that. */ try { // if the 1st argument is a valid application, check if it has a controller matching the 2nd argument if (in_array($Parts[0], $this->EnabledApplicationFolders())) { $this->FindController(1, $Parts); } // if no match, see if the first argument is a controller $this->FindController(0, $Parts); // 3] See if there is a plugin trying to create a root method. list($MethodName, $DeliveryMethod) = $this->_SplitDeliveryMethod(GetValue(0, $Parts), TRUE); if ($MethodName && Gdn::PluginManager()->HasNewMethod('RootController', $MethodName, TRUE)) { $this->_DeliveryMethod = $DeliveryMethod; $Parts[0] = $MethodName; $Parts = array_merge(array('root'), $Parts); $this->FindController(0, $Parts); } throw new GdnDispatcherControllerNotFoundException(); } catch (GdnDispatcherControllerFoundException $e) { switch ($this->_DeliveryMethod) { case DELIVERY_METHOD_JSON: case DELIVERY_METHOD_XML: $this->_DeliveryType = DELIVERY_TYPE_DATA; break; case DELIVERY_METHOD_TEXT: $this->_DeliveryType = DELIVERY_TYPE_VIEW; break; case DELIVERY_METHOD_XHTML: break; default: $this->_DeliveryMethod = DELIVERY_METHOD_XHTML; break; } return TRUE; } catch (GdnDispatcherControllerNotFoundException $e) { $this->EventArguments['Handled'] = FALSE; $Handled =& $this->EventArguments['Handled']; $this->FireEvent('NotFound'); if (!$Handled) { header("HTTP/1.1 404 Not Found"); $Request->WithRoute('Default404'); return $this->AnalyzeRequest($Request); } } }
/** * Defines & retrieves the view and master view. Renders all content within * them to the screen. * * @param string $View * @param string $ControllerName * @param string $ApplicationFolder * @param string $AssetName The name of the asset container that the content should be rendered in. * @todo $View, $ControllerName, and $ApplicationFolder need correct variable types and descriptions. */ public function xRender($View = '', $ControllerName = FALSE, $ApplicationFolder = FALSE, $AssetName = 'Content') { // Remove the deliver type and method from the query string so they don't corrupt calls to Url. $this->Request->SetValueOn(Gdn_Request::INPUT_GET, 'DeliveryType', NULL); $this->Request->SetValueOn(Gdn_Request::INPUT_GET, 'DeliveryMethod', NULL); Gdn::PluginManager()->CallEventHandlers($this, $this->ClassName, $this->RequestMethod, 'Render'); if ($this->_DeliveryType == DELIVERY_TYPE_NONE) { return; } // Handle deprecated StatusMessage values that may have been added by plugins $this->InformMessage($this->StatusMessage); // If there were uncontrolled errors above the json data, wipe them out // before fetching it (otherwise the json will not be properly parsed // by javascript). if ($this->_DeliveryMethod == DELIVERY_METHOD_JSON) { ob_clean(); $this->ContentType('application/json'); $this->SetHeader('X-Content-Type-Options', 'nosniff'); } if ($this->_DeliveryMethod == DELIVERY_METHOD_TEXT) { $this->ContentType('text/plain'); } // Send headers to the browser $this->SendHeaders(); // Make sure to clear out the content asset collection if this is a syndication request if ($this->SyndicationMethod !== SYNDICATION_NONE) { $this->Assets['Content'] = ''; } // Define the view if (!in_array($this->_DeliveryType, array(DELIVERY_TYPE_BOOL, DELIVERY_TYPE_DATA))) { $View = $this->FetchView($View, $ControllerName, $ApplicationFolder); // Add the view to the asset container if necessary if ($this->_DeliveryType != DELIVERY_TYPE_VIEW) { $this->AddAsset($AssetName, $View, 'Content'); } } // Redefine the view as the entire asset contents if necessary if ($this->_DeliveryType == DELIVERY_TYPE_ASSET) { $View = $this->GetAsset($AssetName); } else { if ($this->_DeliveryType == DELIVERY_TYPE_BOOL) { // Or as a boolean if necessary $View = TRUE; if (property_exists($this, 'Form') && is_object($this->Form)) { $View = $this->Form->ErrorCount() > 0 ? FALSE : TRUE; } } } if ($this->_DeliveryType == DELIVERY_TYPE_MESSAGE && $this->Form) { $View = $this->Form->Errors(); } if ($this->_DeliveryType == DELIVERY_TYPE_DATA) { $ExitRender = $this->RenderData(); if ($ExitRender) { return; } } if ($this->_DeliveryMethod == DELIVERY_METHOD_JSON) { // Format the view as JSON with some extra information about the // success status of the form so that jQuery knows what to do // with the result. if ($this->_FormSaved === '') { // Allow for override $this->_FormSaved = property_exists($this, 'Form') && $this->Form->ErrorCount() == 0 ? TRUE : FALSE; } $this->SetJson('FormSaved', $this->_FormSaved); $this->SetJson('DeliveryType', $this->_DeliveryType); $this->SetJson('Data', base64_encode($View instanceof Gdn_IModule ? $View->ToString() : $View)); $this->SetJson('InformMessages', $this->_InformMessages); $this->SetJson('ErrorMessages', $this->_ErrorMessages); $this->SetJson('RedirectUrl', $this->RedirectUrl); // Make sure the database connection is closed before exiting. $this->Finalize(); if (!check_utf8($this->_Json['Data'])) { $this->_Json['Data'] = utf8_encode($this->_Json['Data']); } $Json = json_encode($this->_Json); // Check for jsonp call. if (($Callback = $this->Request->Get('callback', FALSE)) && $this->AllowJSONP()) { $Json = $Callback . '(' . $Json . ')'; } $this->_Json['Data'] = $Json; exit($this->_Json['Data']); } else { if (count($this->_InformMessages) > 0 && $this->SyndicationMethod === SYNDICATION_NONE) { $this->AddDefinition('InformMessageStack', base64_encode(json_encode($this->_InformMessages))); } if ($this->RedirectUrl != '' && $this->SyndicationMethod === SYNDICATION_NONE) { $this->AddDefinition('RedirectUrl', $this->RedirectUrl); } if ($this->_DeliveryMethod == DELIVERY_METHOD_XHTML && Debug()) { $this->AddModule('TraceModule'); } // Render if ($this->_DeliveryType == DELIVERY_TYPE_BOOL) { echo $View ? 'TRUE' : 'FALSE'; } else { if ($this->_DeliveryType == DELIVERY_TYPE_ALL) { // Add definitions to the page if ($this->SyndicationMethod === SYNDICATION_NONE) { $this->AddAsset('Foot', $this->DefinitionList()); } // Render $this->RenderMaster(); } else { if ($View instanceof Gdn_IModule) { $View->Render(); } else { echo $View; } } } } }
/** * 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; }
/** * Takes the path to an asset (image, js file, css file, etc) and prepends the web root. * * @param string $Destination The subpath of the asset. * @param bool|string $WithDomain Whether or not to include the domain in the final URL. * @param bool $AddVersion Whether or not to add a cache-busting version querystring parameter to the URL. * @return string Returns the URL of the asset. */ function smartAsset($Destination = '', $WithDomain = false, $AddVersion = false) { $Destination = str_replace('\\', '/', $Destination); if (IsUrl($Destination)) { $Result = $Destination; } else { $Result = Gdn::Request()->UrlDomain($WithDomain) . Gdn::Request()->AssetRoot() . '/' . ltrim($Destination, '/'); } 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; }
/** * Analyzes the supplied query string and decides how to dispatch the request. */ public function Dispatch($ImportRequest = NULL, $Permanent = TRUE) { if ($ImportRequest && is_string($ImportRequest)) { $ImportRequest = Gdn_Request::Create()->FromEnvironment()->WithURI($ImportRequest); } if (is_a($ImportRequest, 'Gdn_Request') && $Permanent) { Gdn::Request($ImportRequest); } $Request = is_a($ImportRequest, 'Gdn_Request') ? $ImportRequest : Gdn::Request(); if (Gdn::Config('Garden.UpdateMode', FALSE)) { if (!Gdn::Session()->CheckPermission('Garden.Settings.GlobalPrivs')) { // Updatemode, and this user is not root admin $Request->WithURI(Gdn::Router()->GetDestination('UpdateMode')); } } $this->FireEvent('BeforeDispatch'); $this->_AnalyzeRequest($Request); // Send user to login page if this is a private community if (C('Garden.PrivateCommunity') && $this->ControllerName() != 'EntryController' && !Gdn::Session()->IsValid()) { Redirect(Gdn::Authenticator()->SignInUrl($this->Request)); exit; } /* echo "<br />Gdn::Request thinks: ".Gdn::Request()->Path(); echo "<br />Gdn::Request also suggests: output=".Gdn::Request()->OutputFormat().", filename=".Gdn::Request()->Filename(); echo '<br />Request: '.$this->Request; echo '<br />App folder: '.$this->_ApplicationFolder; echo '<br />Controller folder: '.$this->_ControllerFolder; echo '<br />ControllerName: '.$this->_ControllerName; echo '<br />ControllerMethod: '.$this->_ControllerMethod; */ $ControllerName = $this->ControllerName(); if ($ControllerName != '' && class_exists($ControllerName)) { // Create it and call the appropriate method/action $Controller = new $ControllerName(); // Pass along any assets if (is_array($this->_AssetCollection)) { foreach ($this->_AssetCollection as $AssetName => $Assets) { foreach ($Assets as $Asset) { $Controller->AddAsset($AssetName, $Asset); } } } // Instantiate Imported & Uses classes $Controller->GetImports(); // Pass in the syndication method $Controller->SyndicationMethod = $this->_SyndicationMethod; // Pass along the request $Controller->SelfUrl = $this->Request; // Pass along any objects foreach ($this->_PropertyCollection as $Name => $Mixed) { $Controller->{$Name} = $Mixed; } // Set up a default controller method in case one isn't defined. $ControllerMethod = str_replace('_', '', $this->_ControllerMethod); $Controller->OriginalRequestMethod = $ControllerMethod; // Take enabled plugins into account, as well $PluginManagerHasReplacementMethod = Gdn::PluginManager()->HasNewMethod($this->ControllerName(), $this->_ControllerMethod); if (!$PluginManagerHasReplacementMethod && ($this->_ControllerMethod == '' || !method_exists($Controller, $ControllerMethod))) { // Check to see if there is an 'x' version of the method. if (method_exists($Controller, 'x' . $ControllerMethod)) { // $PluginManagerHasReplacementMethod = TRUE; $ControllerMethod = 'x' . $ControllerMethod; } else { if ($this->_ControllerMethod != '') { array_unshift($this->_ControllerMethodArgs, $this->_ControllerMethod); } $this->_ControllerMethod = 'Index'; $ControllerMethod = 'Index'; $PluginManagerHasReplacementMethod = Gdn::PluginManager()->HasNewMethod($this->ControllerName(), $this->_ControllerMethod); } } // Pass in the querystring values $Controller->ApplicationFolder = $this->_ApplicationFolder; $Controller->Application = $this->EnabledApplication(); $Controller->ControllerFolder = $this->_ControllerFolder; $Controller->RequestMethod = $this->_ControllerMethod; $Controller->RequestArgs = $this->_ControllerMethodArgs; $Controller->Request = $Request; $Controller->DeliveryType($Request->GetValue('DeliveryType', '')); $Controller->DeliveryMethod($Request->GetValue('DeliveryMethod', '')); $Controller->Initialize(); // Call the requested method on the controller - error out if not defined. if ($PluginManagerHasReplacementMethod || method_exists($Controller, $ControllerMethod)) { // call_user_func_array is too slow!! //call_user_func_array(array($Controller, $ControllerMethod), $this->_ControllerMethodArgs); if ($PluginManagerHasReplacementMethod) { Gdn::PluginManager()->CallNewMethod($Controller, $Controller->ControllerName, $ControllerMethod); } else { $Args = $this->_ControllerMethodArgs; $Count = count($Args); if ($Count == 0) { $Controller->{$ControllerMethod}(); } else { if ($Count == 1) { $Controller->{$ControllerMethod}($Args[0]); } else { if ($Count == 2) { $Controller->{$ControllerMethod}($Args[0], $Args[1]); } else { if ($Count == 3) { $Controller->{$ControllerMethod}($Args[0], $Args[1], $Args[2]); } else { if ($Count == 4) { $Controller->{$ControllerMethod}($Args[0], $Args[1], $Args[2], $Args[3]); } else { if ($Count == 5) { $Controller->{$ControllerMethod}($Args[0], $Args[1], $Args[2], $Args[3], $Args[4]); } else { if ($Count == 6) { $Controller->{$ControllerMethod}($Args[0], $Args[1], $Args[2], $Args[3], $Args[4], $Args[5]); } else { if ($Count == 7) { $Controller->{$ControllerMethod}($Args[0], $Args[1], $Args[2], $Args[3], $Args[4], $Args[5], $Args[6]); } else { if ($Count == 8) { $Controller->{$ControllerMethod}($Args[0], $Args[1], $Args[2], $Args[3], $Args[4], $Args[5], $Args[6], $Args[7]); } else { if ($Count == 9) { $Controller->{$ControllerMethod}($Args[0], $Args[1], $Args[2], $Args[3], $Args[4], $Args[5], $Args[6], $Args[7], $Args[8]); } else { $Controller->{$ControllerMethod}($Args[0], $Args[1], $Args[2], $Args[3], $Args[4], $Args[5], $Args[6], $Args[7], $Args[8], $Args[9]); } } } } } } } } } } } } else { Gdn::Request()->WithRoute('Default404'); return $this->Dispatch(); } } }
/** * Handle toggling this version of embedding on and off. Take care of disabling the other version of embed (the old plugin). * @param type $Toggle * @param type $TransientKey * @return boolean */ private function Toggle($Toggle = '', $TransientKey = '') { if (in_array($Toggle, array('enable', 'disable')) && Gdn::Session()->ValidateTransientKey($TransientKey)) { if ($Toggle == 'enable' && array_key_exists('embedvanilla', Gdn::PluginManager()->EnabledPlugins())) { throw new Gdn_UserException('You must disable the "Embed Vanilla" plugin before continuing.'); } // Do the toggle SaveToConfig('Garden.Embed.Allow', $Toggle == 'enable' ? TRUE : FALSE); return TRUE; } return FALSE; }
public function RunStructure($AddonCode = NULL, $Explicit = FALSE, $Drop = FALSE) { // Get the structure files for all of the enabled applications. $ApplicationManager = new Gdn_ApplicationManager(); $Apps = $ApplicationManager->EnabledApplications(); $AppNames = ConsolidateArrayValuesByKey($Apps, 'Folder'); $Paths = array(); foreach ($Apps as $Key => $AppInfo) { $Path = PATH_APPLICATIONS . "/{$AppInfo['Folder']}/settings/structure.php"; if (file_exists($Path)) { $Paths[] = $Path; } Gdn::ApplicationManager()->RegisterPermissions($Key, $this->Validation); } // Execute the structures. $Database = Gdn::Database(); $SQL = Gdn::SQL(); $Structure = Gdn::Structure(); foreach ($Paths as $Path) { include $Path; } // Execute the structures for all of the plugins. $PluginManager = Gdn::PluginManager(); $Registered = $PluginManager->RegisteredPlugins(); foreach ($Registered as $ClassName => $Enabled) { if (!$Enabled) { continue; } try { $Plugin = $PluginManager->GetPluginInstance($ClassName, Gdn_PluginManager::ACCESS_CLASSNAME); if (method_exists($Plugin, 'Structure')) { Trace("{$ClassName}->Structure()"); $Plugin->Structure(); } } catch (Exception $Ex) { // Do nothing, plugin wouldn't load/structure. if (Debug()) { throw $Ex; } } } }