/** * Looks through the root Garden directory for valid applications and * returns them as an associative array of "Application Name" => * "Application Info Array". It also adds a "Folder" definition to the * Application Info Array for each application. */ public function AvailableApplications() { if (!is_array($this->_AvailableApplications)) { $ApplicationInfo = array(); $AppFolders = Gdn_FileSystem::Folders(PATH_APPLICATIONS); // Get an array of all application folders $ApplicationAboutFiles = Gdn_FileSystem::FindAll(PATH_APPLICATIONS, 'settings' . DS . 'about.php', $AppFolders); // Now look for about files within them. // Include them all right here and fill the application info array $ApplicationCount = count($ApplicationAboutFiles); for ($i = 0; $i < $ApplicationCount; ++$i) { include $ApplicationAboutFiles[$i]; // Define the folder name for the newly added item foreach ($ApplicationInfo as $ApplicationName => $Info) { if (array_key_exists('Folder', $ApplicationInfo[$ApplicationName]) === FALSE) { $Folder = substr($ApplicationAboutFiles[$i], strlen(PATH_APPLICATIONS)); if (substr($Folder, 0, 1) == DS) { $Folder = substr($Folder, 1); } $Folder = substr($Folder, 0, strpos($Folder, DS)); $ApplicationInfo[$ApplicationName]['Folder'] = $Folder; } } } $this->_AvailableApplications = $ApplicationInfo; } return $this->_AvailableApplications; }
function __autoload($ClassName) { // echo $ClassName; if (class_exists('HTMLPurifier_Bootstrap', FALSE) && HTMLPurifier_Bootstrap::autoload($ClassName)) { return true; } if (!class_exists('Gdn_FileSystem', 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_mappings.php', 'Library', PATH_APPLICATIONS, $ApplicationWhiteList, 'models' . DS . $LibraryFileName); } if ($LibraryPath === FALSE) { $LibraryPath = Gdn_FileSystem::FindByMapping('library_mappings.php', 'Library', PATH_LIBRARY, array('core', 'database', 'vendors' . DS . 'phpmailer', 'vendors' . DS . 'htmlpurifier'), $LibraryFileName); } // If it still hasn't been found, check for modules if ($LibraryPath === FALSE) { $LibraryPath = Gdn_FileSystem::FindByMapping('library_mappings.php', 'Library', PATH_APPLICATIONS, $ApplicationWhiteList, 'modules' . DS . $LibraryFileName); } if ($LibraryPath !== FALSE) { include_once $LibraryPath; } }
/** * Looks through the themes directory for valid themes and returns them as * an associative array of "Theme Name" => "Theme Info Array". It also adds * a "Folder" definition to the Theme Info Array for each. */ public function AvailableThemes() { if (!is_array($this->_AvailableThemes)) { $ThemeInfo = array(); $ThemeFolders = Gdn_FileSystem::Folders(PATH_THEMES); $ThemeAboutFiles = Gdn_FileSystem::FindAll(PATH_THEMES, 'about.php', $ThemeFolders); // Include them all right here and fill the theme info array $ThemeCount = is_array($ThemeAboutFiles) ? count($ThemeAboutFiles) : 0; for ($i = 0; $i < $ThemeCount; ++$i) { include $ThemeAboutFiles[$i]; // Define the folder name for the newly added item foreach ($ThemeInfo as $ThemeName => $Info) { if (array_key_exists('Folder', $ThemeInfo[$ThemeName]) === FALSE) { $Folder = substr($ThemeAboutFiles[$i], strlen(PATH_THEMES)); if (substr($Folder, 0, 1) == DS) { $Folder = substr($Folder, 1); } $Folder = substr($Folder, 0, strpos($Folder, DS)); $ThemeInfo[$ThemeName]['Folder'] = $Folder; // Add the screenshot. $ScreenshotPath = SafeGlob(PATH_THEMES . "/{$Folder}/screenshot.*", array('gif', 'jpg', 'png')); if (count($ScreenshotPath) > 0) { $ScreenshotPath = $ScreenshotPath[0]; $ThemeInfo[$ThemeName]['ScreenshotUrl'] = Asset(str_replace(PATH_ROOT, '', $ScreenshotPath)); } } } } $this->_AvailableThemes = $ThemeInfo; } return $this->_AvailableThemes; }
/** * Looks through the themes directory for valid themes and returns them as * an associative array of "Theme Name" => "Theme Info Array". It also adds * a "Folder" definition to the Theme Info Array for each. */ public function AvailableThemes() { if (!is_array($this->_AvailableThemes)) { $ThemeInfo = array(); $ThemeFolders = Gdn_FileSystem::Folders(PATH_THEMES); $ThemeAboutFiles = Gdn_FileSystem::FindAll(PATH_THEMES, 'about.php', $ThemeFolders); // Include them all right here and fill the theme info array $ThemeCount = is_array($ThemeAboutFiles) ? count($ThemeAboutFiles) : 0; for ($i = 0; $i < $ThemeCount; ++$i) { include $ThemeAboutFiles[$i]; // Define the folder name for the newly added item foreach ($ThemeInfo as $ThemeName => $Info) { if (array_key_exists('Folder', $ThemeInfo[$ThemeName]) === FALSE) { $Folder = substr($ThemeAboutFiles[$i], strlen(PATH_THEMES)); if (substr($Folder, 0, 1) == DS) { $Folder = substr($Folder, 1); } $Folder = substr($Folder, 0, strpos($Folder, DS)); $ThemeInfo[$ThemeName]['Folder'] = $Folder; } } } $this->_AvailableThemes = $ThemeInfo; } return $this->_AvailableThemes; }
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; } }
/** * * * @param string $ID * @param string $ServeFile */ public function index($ID = '', $ServeFile = '0') { $this->addJsFile('jquery.js'); // Define the item being downloaded if (strtolower($ID) == 'vanilla') { $ID = 'vanilla-core'; } $UrlFilename = Gdn::request()->filename(); $PathInfo = pathinfo($UrlFilename); $Ext = val('extension', $PathInfo); if ($Ext == 'zip') { $ServeFile = '1'; $ID = $Ext = val('filename', $PathInfo); } // Find the requested addon $this->Addon = $this->AddonModel->getSlug($ID, true); $this->setData('Addon', $this->Addon); if (!is_array($this->Addon) || !val('File', $this->Addon)) { $this->Addon = array('Name' => 'Not Found', 'Version' => 'undefined', 'File' => ''); } else { $AddonID = $this->Addon['AddonID']; if ($ServeFile != '1') { $this->addJsFile('get.js'); } if ($ServeFile == '1') { // Record this download $this->Database->sql()->insert('Download', array('AddonID' => $AddonID, 'DateInserted' => Gdn_Format::toDateTime(), 'RemoteIp' => @$_SERVER['REMOTE_ADDR'])); $this->AddonModel->setProperty($AddonID, 'CountDownloads', $this->Addon['CountDownloads'] + 1); if (val('Slug', $this->Addon)) { $Filename = $this->Addon['Slug']; } else { $Filename = "{$this->Addon['Name']}-{$this->Addon['Version']}"; } $Filename = Gdn_Format::url($Filename) . '.zip'; $File = $this->Addon['File']; $Url = Gdn_Upload::url($File); Gdn_FileSystem::serveFile($Url, $Filename); } } $this->addModule('AddonHelpModule'); $this->render(); }
/** * Save the provided library's data to the on disk location. * * @param string $CacheName name of cache library * @return void */ public static function SaveCache($CacheName) { if (!array_key_exists($CacheName, Gdn_LibraryMap::$_Caches)) { return FALSE; } $FileName = Gdn_LibraryMap::$_Caches[$CacheName]['ondisk']; $CacheContents = "<?php if (!defined('APPLICATION')) exit();\n" . "Gdn_LibraryMap::PrepareCache('{$CacheName}',"; Gdn_LibraryMap::RecurseArrayStr(NULL, Gdn_LibraryMap::$_Caches[$CacheName]['cache'], $CacheContents); $CacheContents .= ");"; try { Gdn_FileSystem::SaveFile(PATH_CACHE . DS . $FileName, $CacheContents); } catch (Exception $e) { } }
/** * Search the garden/locale folder for other locale sources that are * available. Returns an array of locale names. * * @return array */ public function GetAvailableLocaleSources() { return Gdn_FileSystem::Folders(PATH_APPLICATIONS . DS . 'garden' . DS . 'locale'); }
/** * Copy file or folder from source to destination * * It can do recursive copy as well and is very smart * It recursively creates the dest file or directory path if there weren't exists * Situtaions : * - Src:/home/test/file.txt ,Dst:/home/test/b ,Result:/home/test/b -> If source was file copy file.txt name with b as name to destination * - Src:/home/test/file.txt ,Dst:/home/test/b/ ,Result:/home/test/b/file.txt -> If source was file Creates b directory if does not exsits and copy file.txt into it * - Src:/home/test ,Dst:/home/ ,Result:/home/test/** -> If source was directory copy test directory and all of its content into dest * - Src:/home/test/ ,Dst:/home/ ,Result:/home/**-> if source was direcotry copy its content to dest * - Src:/home/test ,Dst:/home/test2 ,Result:/home/test2/** -> if source was directoy copy it and its content to dest with test2 as name * - Src:/home/test/ ,Dst:/home/test2 ,Result:->/home/test2/** if source was directoy copy it and its content to dest with test2 as name * * @author Sina Salek - http://sina.salek.ws/en/contact * @param $source //file or folder * @param $dest ///file or folder * @param $options //folderPermission,filePermission * @return boolean */ public static function copy($source, $dest, $options = array('folderPermission' => 0755, 'filePermission' => 0755)) { $result = false; if (is_file($source)) { if ($dest[strlen($dest) - 1] == '/') { if (!file_exists($dest)) { cmfcDirectory::makeAll($dest, $options['folderPermission'], true); } $__dest = $dest . "/" . basename($source); } else { $__dest = $dest; } $result = copy($source, $__dest); chmod($__dest, $options['filePermission']); } elseif (is_dir($source)) { if ($dest[strlen($dest) - 1] == '/') { if ($source[strlen($source) - 1] == '/') { //Copy only contents } else { //Change parent itself and its contents $dest = $dest . basename($source); @mkdir($dest); chmod($dest, $options['filePermission']); } } else { if ($source[strlen($source) - 1] == '/') { //Copy parent directory with new name and all its content @mkdir($dest, $options['folderPermission']); chmod($dest, $options['filePermission']); } else { //Copy parent directory with new name and all its content @mkdir($dest, $options['folderPermission']); chmod($dest, $options['filePermission']); } } $dirHandle = opendir($source); while ($file = readdir($dirHandle)) { if ($file != "." && $file != "..") { if (!is_dir($source . "/" . $file)) { $__dest = $dest . "/" . $file; } else { $__dest = $dest . "/" . $file; } $result = Gdn_FileSystem::copy($source . "/" . $file, $__dest, $options); } } closedir($dirHandle); } else { $result = false; } return $result; }
protected function _GetKeyPath($Key, $Flags = 0) { $KeyHash = $this->_HashKey($Key); $SplitValue = intval('0x' . substr($KeyHash, 0, 8), 16); $TargetFolder = (string) ($SplitValue % Gdn_Filecache::OPT_MOD_SPLIT); $Container = $this->_GetContainer($KeyHash); if ($Container === Gdn_Cache::CACHEOP_FAILURE) { return $this->Failure("Trying to fetch a container for hash '{$KeyHash}' but got back CACHEOP_FAILURE instead"); } $CacheLocation = $Container[Gdn_Cache::CONTAINER_LOCATION]; $SplitCacheLocation = CombinePaths(array($CacheLocation, $TargetFolder)); $Flags = $Flags & Gdn_Filecache::O_CREATE ? Gdn_FileSystem::O_CREATE | Gdn_FileSystem::O_WRITE : 0; $CacheLocationOK = Gdn_FileSystem::CheckFolderR($SplitCacheLocation, $Flags); if (!$CacheLocationOK) { return $this->Failure("Computed cache folder '{$SplitCacheLocation}' could not be found, or created."); } $CacheFile = rtrim(CombinePaths(array($SplitCacheLocation, $KeyHash)), '/'); return array_merge($Container, array(Gdn_Filecache::CONTAINER_CACHEFILE => $CacheFile)); }
public function EnsureDefinitionFile() { $Path = $this->LocalePath . '/definitions.php'; if (file_exists($Path)) { unlink($Path); } $Contents = $this->GetFileHeader() . self::FormatInfoArray('$LocaleInfo', $this->GetInfoArray()); Gdn_FileSystem::SaveFile($Path, $Contents); }
/** * Saves all settings in $Group to $File. * * @param string $File The full path to the file where the Settings should be saved. * @param string $Group The name of the settings group to be saved to the $File. * @param boolean $RequireSourceFile Should $File be required to exist in order to save? If true, then values * from this file will be merged into the settings array before it is saved. * If false, the values in the settings array will overwrite any values * existing in the file (if it exists). * @return boolean */ public function Save($File = '', $Group = '', $RequireSourceFile = TRUE) { if ($File == '') { $File = $this->_File; } if ($File == '') { trigger_error(ErrorMessage('You must specify a file path to be saved.', 'Configuration', 'Save'), E_USER_ERROR); } if (!is_writable($File)) { throw new Exception(sprintf(T("Unable to write to config file '%s' when saving."), $File)); } if ($Group == '') { $Group = $this->CurrentGroup; } if ($Group == '') { $Group = 'Configuration'; } $Data =& $this->_SaveData; $this->_Sort($Data); // Check for the case when the configuration is the group. if (is_array($Data) && count($Data) == 1 && array_key_exists($Group, $Data)) { $Data = $Data[$Group]; } // Do a sanity check on the config save. if ($File == PATH_LOCAL_CONF . '/config.php') { if (!isset($Data['Database'])) { if ($Pm = Gdn::PluginManager()) { $Pm->EventArguments['Data'] = $Data; $Pm->EventArguments['Backtrace'] = debug_backtrace(); $Pm->FireEvent('ConfigError'); } $this->_SaveData = array(); $this->_File = ''; return FALSE; } } $NewLines = array(); $NewLines[] = "<?php if (!defined('APPLICATION')) exit();"; $LastName = ''; foreach ($Data as $Name => $Value) { // Write a newline to seperate sections. if ($LastName != $Name && is_array($Value)) { $NewLines[] = ''; $NewLines[] = '// ' . $Name; } $Line = "\$" . $Group . "['" . $Name . "']"; FormatArrayAssignment($NewLines, $Line, $Value); } // Record who made the change and when if (is_array($NewLines)) { $Session = Gdn::Session(); $User = $Session->UserID > 0 && is_object($Session->User) ? $Session->User->Name : 'Unknown'; $NewLines[] = ''; $NewLines[] = '// Last edited by ' . $User . ' (' . RemoteIp() . ')' . Gdn_Format::ToDateTime(); } $FileContents = FALSE; if ($NewLines !== FALSE) { $FileContents = implode("\n", $NewLines); } if ($FileContents === FALSE) { trigger_error(ErrorMessage('Failed to define configuration file contents.', 'Configuration', 'Save'), E_USER_ERROR); } $FileKey = sprintf(self::CONFIG_FILE_CACHE_KEY, $File); if ($this->Caching() && Gdn::Cache()->Type() == Gdn_Cache::CACHE_TYPE_MEMORY && Gdn::Cache()->ActiveEnabled()) { $CachedConfigData = Gdn::Cache()->Store($FileKey, $Data, array(Gdn_Cache::FEATURE_NOPREFIX => TRUE)); } // Infrastructure deployment. Use old method. if (PATH_LOCAL_CONF != PATH_CONF) { $Result = Gdn_FileSystem::SaveFile($File, $FileContents, LOCK_EX); } else { $TmpFile = tempnam(PATH_CONF, 'config'); $Result = FALSE; if (file_put_contents($TmpFile, $FileContents) !== FALSE) { chmod($TmpFile, 0775); $Result = rename($TmpFile, $File); } } if ($Result && function_exists('apc_delete_file')) { // This fixes a bug with some configurations of apc. @apc_delete_file($File); } // Clear out the save data array $this->_SaveData = array(); $this->_File = ''; return $Result; }
/** * Save the provided library's data to the on disk location. * * @param string $CacheName name of cache library * @return void */ public static function SaveCache($CacheName) { if ($CacheName != 'locale') { return; } if (!array_key_exists($CacheName, self::$Caches)) { return FALSE; } $UseCache = Gdn::Cache()->Type() == Gdn_Cache::CACHE_TYPE_MEMORY && Gdn::Cache()->ActiveEnabled(); if ($UseCache) { $CacheKey = sprintf(Gdn_LibraryMap::CACHE_CACHE_NAME_FORMAT, $CacheName); $Stored = Gdn::Cache()->Store($CacheKey, self::$Caches[$CacheName]['cache']); } else { $FileName = self::$Caches[$CacheName]['ondisk']; $CacheContents = ""; foreach (self::$Caches[$CacheName]['cache'] as $SectionTitle => $SectionData) { $CacheContents .= "[{$SectionTitle}]\n"; foreach ($SectionData as $StoreKey => $StoreValue) { $CacheContents .= "{$StoreKey} = \"{$StoreValue}\"\n"; } } try { Gdn_FileSystem::SaveFile(PATH_CACHE . DS . $FileName, $CacheContents, LOCK_EX); } catch (Exception $e) { } } }
/** * Save the provided library's data to the on disk location. * * @param string $CacheName name of cache library * @return void */ public static function saveCache($CacheName) { if ($CacheName != 'locale') { return; } if (!array_key_exists($CacheName, self::$Caches)) { return false; } $UseCache = Gdn::cache()->type() == Gdn_Cache::CACHE_TYPE_MEMORY && Gdn::cache()->activeEnabled(); if ($UseCache) { $CacheKey = sprintf(Gdn_LibraryMap::CACHE_CACHE_NAME_FORMAT, $CacheName); $Stored = Gdn::cache()->store($CacheKey, self::$Caches[$CacheName]['cache']); } else { $FileName = self::$Caches[$CacheName]['ondisk']; $CacheContents = ""; foreach (self::$Caches[$CacheName]['cache'] as $SectionTitle => $SectionData) { $CacheContents .= "[{$SectionTitle}]\n"; foreach ($SectionData as $StoreKey => $StoreValue) { $CacheContents .= "{$StoreKey} = \"{$StoreValue}\"\n"; } } try { // Fix slashes to get around parse_ini_file issue that drops off \ when loading network file. $CacheContents = str_replace("\\", "/", $CacheContents); Gdn_FileSystem::saveFile(PATH_CACHE . DS . $FileName, $CacheContents, LOCK_EX); } catch (Exception $e) { } } }
/** * Remove the plugin folder. * * @param string $PluginFolder * @return void */ private function _RemovePluginFolder($PluginFolder) { Gdn_FileSystem::RemoveFolder(PATH_PLUGINS . DS . $PluginFolder); }
/** * * * @param DiscussionController $Sender */ public function discussionController_download_create($Sender) { if (!$this->CanDownload) { throw PermissionException("File could not be streamed: Access is denied"); } list($MediaID) = $Sender->RequestArgs; $Media = $this->mediaModel()->getID($MediaID); if (!$Media) { return; } $Filename = Gdn::request()->filename(); if (!$Filename || $Filename == 'default') { $Filename = $Media->Name; } $DownloadPath = combinePaths(array(MediaModel::pathUploads(), val('Path', $Media))); if (in_array(strtolower(pathinfo($Filename, PATHINFO_EXTENSION)), array('bmp', 'gif', 'jpg', 'jpeg', 'png'))) { $ServeMode = 'inline'; } else { $ServeMode = 'attachment'; } $Served = false; $this->EventArguments['DownloadPath'] = $DownloadPath; $this->EventArguments['ServeMode'] = $ServeMode; $this->EventArguments['Media'] = $Media; $this->EventArguments['Served'] =& $Served; $this->fireEvent('BeforeDownload'); if (!$Served) { return Gdn_FileSystem::serveFile($DownloadPath, $Filename, $Media->Type, $ServeMode); throw new Exception('File could not be streamed: missing file (' . $DownloadPath . ').'); } exit; }
private function PrepareCache($LocaleName = False) { if ($LocaleName === False) { $LocaleName = $this->_Locale->Current(); } $EnabledApplications = Gdn::Config('EnabledApplications', array()); $EnabledPlugins = Gdn::Config('EnabledPlugins', array()); $LocaleSources = array(); // Get application-based locale special definition files // 2.0.0+ (TODO: REMOVE) $ApplicationLocaleSources = Gdn_FileSystem::FindAll(PATH_APPLICATIONS, CombinePaths(array('locale', $LocaleName, 'distinctions.php')), $EnabledApplications); if ($ApplicationLocaleSources !== False) { if (C('Debug')) { Deprecated("Move all application's locale distinctions.php files to [applicationname]/locale/[localename].custom.php, distinctions.php filenames"); } $LocaleSources = array_merge($LocaleSources, $ApplicationLocaleSources); } // 2.0.11+ (TODO: REMOVE) $ApplicationLocaleSources = Gdn_FileSystem::FindAll(PATH_APPLICATIONS, CombinePaths(array('locale', $LocaleName . '.distinct.php')), $EnabledApplications); if ($ApplicationLocaleSources !== False) { if (C('Debug')) { Deprecated("Rename all application's locale [localename].distinct.php files to [localename].custom.php, [localename].distinct.php filenames"); } $LocaleSources = array_merge($LocaleSources, $ApplicationLocaleSources); } // 2.0.18+ $ApplicationLocaleSources = Gdn_FileSystem::FindAll(PATH_APPLICATIONS, CombinePaths(array('locale', $LocaleName . '.custom.php')), $EnabledApplications); if ($ApplicationLocaleSources !== False) { $LocaleSources = array_merge($LocaleSources, $ApplicationLocaleSources); } // Get plugin-based locale special definition files // 2.0.0+ (TODO: REMOVE) $PluginLocaleSources = Gdn_FileSystem::FindAll(PATH_PLUGINS, CombinePaths(array('locale', $LocaleName, 'distinctions.php')), $EnabledPlugins); if ($PluginLocaleSources !== False) { if (C('Debug')) { Deprecated("Move all plugin's locale distinctions.php files to [pluginname]/locale/[localename].custom.php, distinctions.php filenames"); } $LocaleSources = array_merge($LocaleSources, $PluginLocaleSources); } // 2.0.11+ (TODO: REMOVE) $PluginLocaleSources = Gdn_FileSystem::FindAll(PATH_PLUGINS, CombinePaths(array('locale', $LocaleName . '.distinct.php')), $EnabledPlugins); if ($PluginLocaleSources !== False) { if (C('Debug')) { Deprecated("Rename all plugin's locale [localename].distinct.php files to [localename].custom.php, [localename].distinct.php filenames"); } $LocaleSources = array_merge($LocaleSources, $PluginLocaleSources); } // 2.0.18+ $PluginLocaleSources = Gdn_FileSystem::FindAll(PATH_PLUGINS, CombinePaths(array('locale', $LocaleName . '.custom.php')), $EnabledPlugins); if ($PluginLocaleSources !== False) { $LocaleSources = array_merge($LocaleSources, $PluginLocaleSources); } // Get theme-based locale special definition files. $Theme = Gdn::Config('Garden.Theme'); if ($Theme) { // 2.0.11+, TODO: REMOVE $ThemeLocalePath = PATH_THEMES . "/{$Theme}/locale/{$LocaleName}.distinct.php"; if (file_exists($ThemeLocalePath)) { $LocaleSources[] = $ThemeLocalePath; if (C('Debug')) { Deprecated("Rename file to {$LocaleName}.custom.php, {$LocaleName}.distinct.php filename"); } } // 2.0.18+ $ThemeLocalePath = PATH_THEMES . "/{$Theme}/locale/{$LocaleName}.distinct.php"; if (file_exists($ThemeLocalePath)) { $LocaleSources[] = $ThemeLocalePath; } } // Get locale-based locale special definition files. $EnabledLocales = Gdn::Config('EnabledLocales'); if (is_array($EnabledLocales)) { foreach ($EnabledLocales as $Key => $Locale) { if ($Locale != $LocaleName) { continue; } // Grab all of the files in the locale's folder (subdirectory custom) $Paths = glob(PATH_ROOT . "/locales/{$Key}/custom/*.php"); if (is_array($Paths)) { foreach ($Paths as $Path) { $LocaleSources[] = $Path; } } } } $PhpLocaleName = var_export($LocaleName, True); $PhpLocaleSources = var_export($LocaleSources, True); $PhpArrayCode = "\n\$_[{$PhpLocaleName}] = {$PhpLocaleSources};"; $CacheFile = PATH_CACHE . '/customtranslation_map.ini'; if (!file_exists($CacheFile)) { $PhpArrayCode = '<?php' . $PhpArrayCode; } file_put_contents($CacheFile, $PhpArrayCode, FILE_APPEND | LOCK_EX); }
public function Shutdown() { if (!GetValue('dirty', $this->MapInfo)) { return FALSE; } if (!GetValue('save', $this->MapInfo)) { return FALSE; } if (!sizeof($this->Map)) { return FALSE; } $MapName = GetValue('name', $this->MapInfo); $FileName = GetValue('ondisk', $this->MapInfo); $MapContents = ''; foreach ($this->Map as $SplitTopic => $TopicFiles) { $MapContents .= "[{$SplitTopic}]\n"; foreach ($TopicFiles as $ClassName => $Location) { $MapContents .= "{$ClassName} = \"{$Location}\"\n"; } } try { Gdn_FileSystem::SaveFile($FileName, $MapContents, LOCK_EX); } catch (Exception $e) { return FALSE; } return TRUE; }
/** * DiscussionController_Download_Create function. * * @access public * @param mixed $Sender * @return void */ public function DiscussionController_Download_Create($Sender) { if (!$this->IsEnabled()) { return; } if (!$this->CanDownload) { throw new PermissionException("File could not be streamed: Access is denied"); } list($MediaID) = $Sender->RequestArgs; $Media = $this->MediaModel()->GetID($MediaID); if (!$Media) { return; } $Filename = Gdn::Request()->Filename(); if (!$Filename) { $Filename = $Media->Name; } $DownloadPath = CombinePaths(array(MediaModel::PathUploads(), GetValue('Path', $Media))); if (in_array(strtolower(pathinfo($Filename, PATHINFO_EXTENSION)), array('bmp', 'gif', 'jpg', 'jpeg', 'png'))) { $ServeMode = 'inline'; } else { $ServeMode = 'attachment'; } $this->EventArguments['Media'] = $Media; $this->FireEvent('BeforeDownload'); return Gdn_FileSystem::ServeFile($DownloadPath, $Filename, '', $ServeMode); throw new Exception('File could not be streamed: missing file (' . $DownloadPath . ').'); exit; }
/** * Check an addon's file to extract the addon information out of it. * * @param string $Path The path to the file. * @param bool $Fix Whether or not to fix files that have been zipped incorrectly. * @return array An array of addon information. */ public static function AnalyzeAddon($Path, $Fix = FALSE, $ThrowError = TRUE) { $Result = array(); // Extract the zip file so we can make sure it has appropriate information. $Zip = NULL; if (class_exists('ZipArchive', FALSE)) { $Zip = new ZipArchive(); $ZipOpened = $Zip->open($Path); if ($ZipOpened !== TRUE) { $Zip = NULL; } } if (!$Zip) { require_once PATH_LIBRARY . "/vendors/pclzip/class.pclzipadapter.php"; $Zip = new PclZipAdapter(); $ZipOpened = $Zip->open($Path); } if ($ZipOpened !== TRUE) { if ($ThrowError) { $Errors = array(ZIPARCHIVE::ER_EXISTS => 'ER_EXISTS', ZIPARCHIVE::ER_INCONS => 'ER_INCONS', ZIPARCHIVE::ER_INVAL => 'ER_INVAL', ZIPARCHIVE::ER_MEMORY => 'ER_MEMORY', ZIPARCHIVE::ER_NOENT => 'ER_NOENT', ZIPARCHIVE::ER_NOZIP => 'ER_NOZIP', ZIPARCHIVE::ER_OPEN => 'ER_OPEN', ZIPARCHIVE::ER_READ => 'ER_READ', ZIPARCHIVE::ER_SEEK => 'ER_SEEK'); throw new Exception(T('Could not open addon file. Addons must be zip files.') . ' (' . $Path . ' ' . GetValue($ZipOpened, $Errors, 'Unknown Error') . ')' . $Worked, 400); } return FALSE; } $Entries = array(); for ($i = 0; $i < $Zip->numFiles; $i++) { $Entries[] = $Zip->statIndex($i); } // Figure out which system files to delete. $Deletes = array(); foreach ($Entries as $Index => $Entry) { $Name = $Entry['name']; $Delete = strpos($Name, '__MACOSX') !== FALSE | strpos($Name, '.DS_Store') !== FALSE | strpos($Name, 'thumbs.db') !== FALSE | strpos($Name, '.gitignore') !== FALSE; if ($Delete) { $Deletes[] = $Entry; unset($Entries[$Index]); } } // Get a folder ready for checking the addon. $FolderPath = dirname($Path) . '/' . basename($Path, '.zip') . '/'; if (file_exists($FolderPath)) { Gdn_FileSystem::RemoveFolder($FolderPath); } // Figure out what kind of addon this is. $Root = ''; $NewRoot = ''; $Addon = FALSE; foreach ($Entries as $Entry) { $Name = '/' . ltrim($Entry['name'], '/'); $Filename = basename($Name); $Folder = substr($Name, 0, -strlen($Filename)); $NewRoot = ''; // Check to see if the entry is a plugin file. if ($Filename == 'default.php' || StringEndsWith($Filename, '.plugin.php')) { if (count(explode('/', $Folder)) > 3) { // The file is too deep to be a plugin file. continue; } // This could be a plugin file, but we have to examine its info array. $Zip->extractTo($FolderPath, $Entry['name']); $FilePath = CombinePaths(array($FolderPath, $Name)); $Info = self::ParseInfoArray($FilePath, 'PluginInfo'); Gdn_FileSystem::RemoveFolder(dirname($FilePath)); if (!is_array($Info) || !count($Info)) { continue; } // Check to see if the info array conforms to a plugin spec. $Key = key($Info); $Info = $Info[$Key]; $Root = trim($Folder, '/'); $Valid = TRUE; // Make sure the key matches the folder name. if ($Root && strcasecmp($Root, $Key) != 0) { $Result[] = "{$Name}: The plugin's key is not the same as its folder name."; $Valid = FALSE; } else { $NewRoot = $Root; } if (!GetValue('Description', $Info)) { $Result[] = $Name . ': ' . sprintf(T('ValidateRequired'), T('Description')); $Valid = FALSE; } if (!GetValue('Version', $Info)) { $Result[] = $Name . ': ' . sprintf(T('ValidateRequired'), T('Version')); $Valid = FALSE; } if ($Valid) { // The plugin was confirmed. $Addon = array('AddonKey' => $Key, 'AddonTypeID' => ADDON_TYPE_PLUGIN, 'Name' => GetValue('Name', $Info) ? $Info['Name'] : $Key, 'Description' => $Info['Description'], 'Version' => $Info['Version'], 'Path' => $Path); break; } continue; } // Check to see if the entry is an application file. if (StringEndsWith($Name, '/settings/about.php')) { if (count(explode('/', $Folder)) > 4) { $Result[] = "{$Name}: The application's info array was not in the correct location."; // The file is too deep to be a plugin file. continue; } // This could be a plugin file, but we have to examine its info array. $Zip->extractTo($FolderPath, $Entry['name']); $FilePath = CombinePaths(array($FolderPath, $Name)); $Info = self::ParseInfoArray($FilePath, 'ApplicationInfo'); Gdn_FileSystem::RemoveFolder(dirname($FilePath)); if (!is_array($Info) || !count($Info)) { $Result[] = "{$Name}: The application's info array could not be parsed."; continue; } $Key = key($Info); $Info = $Info[$Key]; $Root = trim(substr($Name, 0, -strlen('/settings/about.php')), '/'); $Valid = TRUE; // Make sure the key matches the folder name. if ($Root && strcasecmp($Root, $Key) != 0) { $Result[] = "{$Name}: The application's key is not the same as its folder name."; $Valid = FALSE; } else { $NewRoot = $Root; } if (!GetValue('Description', $Info)) { $Result[] = $Name . ': ' . sprintf(T('ValidateRequired'), T('Description')); $Valid = FALSE; } if (!GetValue('Version', $Info)) { $Result[] = $Name . ': ' . sprintf(T('ValidateRequired'), T('Version')); $Valid = FALSE; } if ($Valid) { // The application was confirmed. $Addon = array('AddonKey' => $Key, 'AddonTypeID' => ADDON_TYPE_APPLICATION, 'Name' => GetValue('Name', $Info) ? $Info['Name'] : $Key, 'Description' => $Info['Description'], 'Version' => $Info['Version'], 'Path' => $Path); break; } continue; } // Check to see if the entry is a theme file. if (StringEndsWith($Name, '/about.php')) { if (count(explode('/', $Folder)) > 3) { // The file is too deep to be a plugin file. continue; } // This could be a theme file, but we have to examine its info array. $Zip->extractTo($FolderPath, $Entry['name']); $FilePath = CombinePaths(array($FolderPath, $Name)); $Info = self::ParseInfoArray($FilePath, 'ThemeInfo'); Gdn_FileSystem::RemoveFolder(dirname($FilePath)); if (!is_array($Info) || !count($Info)) { continue; } $Key = key($Info); $Info = $Info[$Key]; $Valid = TRUE; $Root = trim(substr($Name, 0, -strlen('/about.php')), '/'); // Make sure the theme is at least one folder deep. if (strlen($Root) == 0) { $Result[] = $Name . ': The theme must be in a folder.'; $Valid = FALSE; } if (!GetValue('Description', $Info)) { $Result[] = $Name . ': ' . sprintf(T('ValidateRequired'), T('Description')); $Valid = FALSE; } if (!GetValue('Version', $Info)) { $Result[] = $Name . ': ' . sprintf(T('ValidateRequired'), T('Version')); $Valid = FALSE; } if ($Valid) { // The application was confirmed. $Addon = array('AddonKey' => $Key, 'AddonTypeID' => ADDON_TYPE_THEME, 'Name' => GetValue('Name', $Info) ? $Info['Name'] : $Key, 'Description' => $Info['Description'], 'Version' => $Info['Version'], 'Path' => $Path); break; } } if (StringEndsWith($Name, '/definitions.php')) { if (count(explode('/', $Folder)) > 3) { // The file is too deep to be a plugin file. continue; } // This could be a locale pack, but we have to examine its info array. $Zip->extractTo($FolderPath, $Entry['name']); $FilePath = CombinePaths(array($FolderPath, $Name)); $Info = self::ParseInfoArray($FilePath, 'LocaleInfo'); Gdn_FileSystem::RemoveFolder(dirname($FilePath)); if (!is_array($Info) || !count($Info)) { continue; } $Key = key($Info); $Info = $Info[$Key]; $Valid = TRUE; $Root = trim(substr($Name, 0, -strlen('/definitions.php')), '/'); // Make sure the locale is at least one folder deep. if ($Root != $Key) { $Result[] = $Name . ': The locale pack\'s key must be the same as its folder name.'; $Valid = FALSE; } if (!GetValue('Locale', $Info)) { $Result[] = $Name . ': ' . sprintf(T('ValidateRequired'), T('Locale')); $Valud = FALSE; } elseif (strcasecmp($Info['Locale'], $Key) == 0) { $Result[] = $Name . ': ' . T('The locale\'s key cannot be the same as the name of the locale.'); $Valid = FALSE; } if (!GetValue('Description', $Info)) { $Result[] = $Name . ': ' . sprintf(T('ValidateRequired'), T('Description')); $Valid = FALSE; } if (!GetValue('Version', $Info)) { $Result[] = $Name . ': ' . sprintf(T('ValidateRequired'), T('Version')); $Valid = FALSE; } if ($Valid) { // The locale pack was confirmed. $Addon = array('AddonKey' => $Key, 'AddonTypeID' => ADDON_TYPE_LOCALE, 'Name' => GetValue('Name', $Info) ? $Info['Name'] : $Key, 'Description' => $Info['Description'], 'Version' => $Info['Version'], 'Path' => $Path); break; } } // Check to see if the entry is a core file. if (StringEndsWith($Name, '/index.php')) { if (count(explode('/', $Folder)) != 3) { // The file is too deep to be the core's index.php continue; } // This could be a theme file, but we have to examine its info array. $Zip->extractTo($FolderPath, $Entry['name']); $FilePath = CombinePaths(array($FolderPath, $Name)); // Get the version number from the core. $Version = self::ParseCoreVersion($FilePath); if (!$Version) { continue; } // The application was confirmed. $Addon = array('AddonKey' => 'vanilla', 'AddonTypeID' => ADDON_TYPE_CORE, 'Name' => 'Vanilla', 'Description' => 'Vanilla is an open-source, standards-compliant, multi-lingual, fully extensible discussion forum for the web. Anyone who has web-space that meets the requirements can download and use Vanilla for free!', 'Version' => $Version, 'Path' => $Path); $Info = array(); break; } } if ($Addon) { // Add the requirements. $Requirements = ArrayTranslate($Info, array('RequiredApplications' => 'Applications', 'RequiredPlugins' => 'Plugins', 'RequiredThemes' => 'Themes')); foreach ($Requirements as $Type => $Items) { if (!is_array($Items)) { unset($Requirements[$Type]); } } $Addon['Requirements'] = serialize($Requirements); $Addon['Checked'] = TRUE; $UploadsPath = PATH_ROOT . '/uploads/'; if (StringBeginsWith($Addon['Path'], $UploadsPath)) { $Addon['File'] = substr($Addon['Path'], strlen($UploadsPath)); } if ($Fix) { // Delete extraneous files. foreach ($Deletes as $Delete) { $Zip->deleteName($Delete['name']); } } } $Zip->close(); if (file_exists($FolderPath)) { Gdn_FileSystem::RemoveFolder($FolderPath); } if ($Addon) { $Addon['MD5'] = md5_file($Path); return $Addon; } else { if ($ThrowError) { $Msg = implode("\n", $Result); throw new Exception($Msg, 400); } else { return FALSE; } } }
/** * Search the garden/locale folder for other locale sources that are * available. Returns an array of locale names. * * @return array */ public function getAvailableLocaleSources() { return Gdn_FileSystem::Folders(PATH_APPLICATIONS . '/dashboard/locale'); }
if ($SkipTranslated) { if ($T != T($Code)) { continue; } } $Code = var_export($Code, True); $T = var_export($T, True); $FileContent .= "\n\$Definition[{$Code}] = {$T};"; } } if ($FileContent == '') { continue; } $FileContent = "<?php\n// Date: " . date('r') . " " . $FileContent; $File = $Directory . '/' . strtolower(pathinfo($File, PATHINFO_BASENAME)); Gdn_FileSystem::SaveFile($File, $FileContent); } /** * Undocumented * * @param string $File, path to file. * @return array $Result. */ function GetTranslationFromFile($File) { $Result = array(); $Content = file_get_contents($File); if (!$Content) { return $Result; } $AllTokens = token_get_all($Content);
/** * Searches through the /cache/controller_mappings.php file for the requested * controller. If it doesn't find it, it searches through the entire * application's folders for the requested controller. If it finds the * controller, it adds the mapping to /cache/controller_mappings.php so it * won't need to search again. If it doesn't find the controller file * anywhere, it throws a fatal error. * * @param boolean $ThrowErrorOnFailure * @todo $ThrowErrorOnFailure needs a description. */ private function _FetchController($ThrowErrorOnFailure = FALSE) { $ControllerWhiteList = $this->EnabledApplicationFolders(); // Don't include it if it's already been included if (!class_exists($this->ControllerName())) { $PathParts = array('controllers'); if ($this->_ControllerFolder != '') { $PathParts[] = $this->_ControllerFolder; } $PathParts[] = strtolower($this->_ControllerName) . '.php'; $ControllerFileName = CombinePaths($PathParts); // Force the mapping to search in the app folder if it was in the request if ($this->_ApplicationFolder != '' && InArrayI($this->_ApplicationFolder, $ControllerWhiteList)) { // Limit the white list to the specified application folder $ControllerWhiteList = array($this->_ApplicationFolder); } $ControllerPath = Gdn_FileSystem::FindByMapping('controller_mappings.php', 'Controller', PATH_APPLICATIONS, $ControllerWhiteList, $ControllerFileName); if ($ControllerPath !== FALSE) { // Strip the "Application Folder" from the controller path (this is // used by the controller for various purposes. ie. knowing which // application to search in for a view file). $this->_ApplicationFolder = explode(DS, str_replace(PATH_APPLICATIONS . DS, '', $ControllerPath)); $this->_ApplicationFolder = $this->_ApplicationFolder[0]; // Load the application's master controller if (!class_exists($this->_ApplicationFolder . 'Controller')) { include CombinePaths(array(PATH_APPLICATIONS, $this->_ApplicationFolder, 'controllers', 'appcontroller.php')); } // Now load the library (no need to check for existence - couldn't // have made it here if it didn't exist). include $ControllerPath; } } if (!class_exists($this->ControllerName())) { if ($ThrowErrorOnFailure === TRUE) { if (ForceBool(Gdn::Config('Garden.Debug'))) { trigger_error(ErrorMessage('Controller not found: ' . $this->ControllerName(), 'Dispatcher', '_FetchController'), E_USER_ERROR); } else { // Return a 404 message list($this->_ApplicationFolder, $this->_ControllerName, $this->_ControllerMethod) = explode('/', $this->Routes['Default404']); $ControllerFileName = CombinePaths(array('controllers', strtolower($this->_ControllerName) . '.php')); $ControllerPath = Gdn_FileSystem::FindByMapping('controller_mappings.php', 'Controller', PATH_APPLICATIONS, $ControllerWhiteList, $ControllerFileName); include CombinePaths(array(PATH_APPLICATIONS, $this->_ApplicationFolder, 'controllers', 'appcontroller.php')); include $ControllerPath; } } return FALSE; } else { return TRUE; } }
/** * Returns the location of the view for this module in the filesystem. * * @param string $View * @param string $ApplicationFolder * @return array */ public function FetchViewLocation($View = '', $ApplicationFolder = '') { if ($View == '') { $View = strtolower($this->Name()); } if (substr($View, -6) == 'module') { $View = substr($View, 0, -6); } if (substr($View, 0, 4) == 'gdn_') { $View = substr($View, 4); } if ($ApplicationFolder == '') { $ApplicationFolder = strtolower($this->_ApplicationFolder); } $ThemeFolder = strtolower($this->_ThemeFolder); // Views come from one of four places: $ViewPaths = array(); // 1. An explicitly defined path to a view if (strpos($View, DS) !== FALSE) { $ViewPaths[] = $View; } if ($ThemeFolder != '') { // 1. Application-specific theme view. eg. /path/to/application/themes/theme_name/app_name/views/modules/ $ViewPaths[] = CombinePaths(array(PATH_THEMES, $ThemeFolder, $ApplicationFolder, 'views', 'modules', $View . '.php')); // 2. Garden-wide theme view. eg. /path/to/application/themes/theme_name/views/modules/ $ViewPaths[] = CombinePaths(array(PATH_THEMES, $ThemeFolder, 'views', 'modules', $View . '.php')); } // 3. Application default. eg. /path/to/application/app_name/views/controller_name/ $ViewPaths[] = CombinePaths(array(PATH_APPLICATIONS, $ApplicationFolder, 'views', 'modules', $View . '.php')); // 4. Garden default. eg. /path/to/application/garden/views/modules/ $ViewPaths[] = CombinePaths(array(PATH_APPLICATIONS, 'garden', 'views', 'modules', $View . '.php')); $ViewPath = Gdn_FileSystem::Exists($ViewPaths); if ($ViewPath === FALSE) { trigger_error(ErrorMessage('Could not find a `' . $View . '` view for the `' . $this->Name() . '` module in the `' . $ApplicationFolder . '` application.', get_class($this), 'FetchView'), E_USER_ERROR); } return $ViewPath; }
/** * Returns the location of the view for this module in the filesystem. * * @param string $View * @param string $ApplicationFolder * @return array */ public function fetchViewLocation($View = '', $ApplicationFolder = '') { if ($View == '') { $View = strtolower($this->name()); } if (substr($View, -6) == 'module') { $View = substr($View, 0, -6); } if (substr($View, 0, 4) == 'gdn_') { $View = substr($View, 4); } if ($ApplicationFolder == '') { $ApplicationFolder = strpos($this->_ApplicationFolder, '/') ? $this->_ApplicationFolder : strtolower($this->_ApplicationFolder); } $ThemeFolder = $this->_ThemeFolder; $ViewPath = null; // Try to use Gdn_Controller's FetchViewLocation if (Gdn::controller() instanceof Gdn_Controller) { try { $ViewPath = Gdn::controller()->fetchViewLocation($View, 'modules', $ApplicationFolder); } catch (Exception $Ex) { } } if (!$ViewPath) { $ViewPaths = array(); // 1. An explicitly defined path to a view if (strpos($View, '/') !== false) { $ViewPaths[] = $View; } // 2. A theme if ($ThemeFolder != '') { // a. Application-specific theme view. eg. /path/to/application/themes/theme_name/app_name/views/modules/ $ViewPaths[] = CombinePaths(array(PATH_THEMES, $ThemeFolder, $ApplicationFolder, 'views', 'modules', $View . '.php')); // b. Garden-wide theme view. eg. /path/to/application/themes/theme_name/views/modules/ $ViewPaths[] = CombinePaths(array(PATH_THEMES, $ThemeFolder, 'views', 'modules', $View . '.php')); } // 3. Application default. eg. /path/to/application/app_name/views/controller_name/ if ($this->_ApplicationFolder) { $ViewPaths[] = CombinePaths(array(PATH_APPLICATIONS, $ApplicationFolder, 'views', 'modules', $View . '.php')); } else { $ViewPaths[] = dirname($this->path()) . "/../views/modules/{$View}.php"; } // 4. Garden default. eg. /path/to/application/dashboard/views/modules/ $ViewPaths[] = CombinePaths(array(PATH_APPLICATIONS, 'dashboard', 'views', 'modules', $View . '.php')); $ViewPath = Gdn_FileSystem::exists($ViewPaths); } if ($ViewPath === false) { throw new Exception(ErrorMessage('Could not find a `' . $View . '` view for the `' . $this->Name() . '` module in the `' . $ApplicationFolder . '` application.', get_class($this), 'FetchView'), E_USER_ERROR); } return $ViewPath; }
/** * Save the provided library's data to the on disk location. * * @param string $CacheName name of cache library * @return void */ public static function SaveCache($CacheName) { if ($CacheName != 'locale') { return; } if (!array_key_exists($CacheName, self::$_Caches)) { return FALSE; } $FileName = self::$_Caches[$CacheName]['ondisk']; $CacheContents = ""; foreach (self::$_Caches[$CacheName]['cache'] as $SectionTitle => $SectionData) { $CacheContents .= "[{$SectionTitle}]\n"; foreach ($SectionData as $StoreKey => $StoreValue) { $CacheContents .= "{$StoreKey} = \"{$StoreValue}\"\n"; } } try { Gdn_FileSystem::SaveFile(PATH_LOCAL_CACHE . DS . $FileName, $CacheContents, LOCK_EX); } catch (Exception $e) { } }
/** * * * @param $Path * @param $InfoPaths * @param bool $TmpPath * @param bool $ThrowError * @return array|bool * @throws Exception */ protected static function _GetInfoZip($Path, $InfoPaths, $TmpPath = false, $ThrowError = true) { // Extract the zip file so we can make sure it has appropriate information. $Zip = null; if (class_exists('ZipArchive', false)) { $Zip = new ZipArchive(); $ZipOpened = $Zip->open($Path); if ($ZipOpened !== true) { $Zip = null; } } if (!$Zip) { require_once PATH_LIBRARY . "/vendors/pclzip/class.pclzipadapter.php"; $Zip = new PclZipAdapter(); $ZipOpened = $Zip->open($Path); } if ($ZipOpened !== true) { if ($ThrowError) { $Errors = array(ZIPARCHIVE::ER_EXISTS => 'ER_EXISTS', ZIPARCHIVE::ER_INCONS => 'ER_INCONS', ZIPARCHIVE::ER_INVAL => 'ER_INVAL', ZIPARCHIVE::ER_MEMORY => 'ER_MEMORY', ZIPARCHIVE::ER_NOENT => 'ER_NOENT', ZIPARCHIVE::ER_NOZIP => 'ER_NOZIP', ZIPARCHIVE::ER_OPEN => 'ER_OPEN', ZIPARCHIVE::ER_READ => 'ER_READ', ZIPARCHIVE::ER_SEEK => 'ER_SEEK'); throw new Exception(t('Could not open addon file. Addons must be zip files.') . ' (' . $Path . ' ' . GetValue($ZipOpened, $Errors, 'Unknown Error') . ')' . $Worked, 400); } return false; } if ($TmpPath === false) { $TmpPath = dirname($Path) . '/' . basename($Path, '.zip') . '/'; } if (file_exists($TmpPath)) { Gdn_FileSystem::RemoveFolder($TmpPath); } $Result = array(); for ($i = 0; $i < $Zip->numFiles; $i++) { $Entry = $Zip->statIndex($i); if (preg_match('#(\\.\\.[\\/])#', $Entry['name'])) { throw new Gdn_UserException("Invalid path in zip file: " . htmlspecialchars($Entry['name'])); } $Name = '/' . ltrim($Entry['name'], '/'); foreach ($InfoPaths as $InfoPath) { $Preg = '`(' . str_replace(array('.', '*'), array('\\.', '.*'), $InfoPath) . ')$`'; if (preg_match($Preg, $Name, $Matches)) { $Base = trim(substr($Name, 0, -strlen($Matches[1])), '/'); if (strpos($Base, '/') !== false) { continue; // file nested too deep. } if (!file_exists($TmpPath)) { mkdir($TmpPath, 0777, true); } $Zip->extractTo($TmpPath, $Entry['name']); $Result[] = array('Name' => $Matches[1], 'Path' => $TmpPath . rtrim($Entry['name'], '/'), 'Base' => $Base); } } } return $Result; }
/** * Parse an addon's README file. * * @param string $Path The base path to search from. * @return string */ protected function parseReadme($Path) { $ReadmePaths = array('/readme', '/README', '/readme.md', '/README.md', '/readme.txt', '/README.txt'); $Description = ''; // Get the list of potential files to analyze. $Entries = UpdateModel::findFiles($Path, $ReadmePaths); if ($Entries === false) { return ''; } foreach ($Entries as $Entry) { $ReadMeContents = file_get_contents($Entry['Path']); $Description = Gdn_Format::markdown($ReadMeContents); } $FolderPath = substr($Path, 0, -4); Gdn_FileSystem::removeFolder($FolderPath); return $Description; }
function write_ini_file($File, $Data) { $String = write_ini_string($Data); Gdn_FileSystem::SaveFile($File, $String); }
/** * Overwrites Yaga configurations, dumps Yaga db tables, inserts data via the * model, and copies uploaded files to the server * * @param stdClass The info object read in from the archive * @param array Which tables should be overwritten * @return bool Pass/Fail on the import being executed. Errors can exist on the * form with a passing return value. */ protected function _ImportData($Info, $Include) { if (!$Info) { return FALSE; } // Import Configs $Configs = unserialize(file_get_contents(PATH_UPLOADS . DS . 'import' . DS . 'yaga' . DS . $Info->Config)); $Configurations = $this->_NestedToDotNotation($Configs, 'Yaga'); foreach ($Configurations as $Name => $Value) { SaveToConfig($Name, $Value); } // Import model data foreach ($Include as $Key => $Value) { if ($Value) { $Data = unserialize(file_get_contents(PATH_UPLOADS . DS . 'import' . DS . 'yaga' . DS . $Info->{$Key})); Gdn::SQL()->EmptyTable($Key); $ModelName = $Key . 'Model'; $Model = Yaga::$ModelName(); foreach ($Data as $Datum) { $Model->Insert((array) $Datum); } $this->SetData($Key . 'Count', $Model->GetCount()); } } // Import uploaded files if (Gdn_FileSystem::Copy(PATH_UPLOADS . DS . 'import' . DS . 'yaga' . DS . 'images' . DS . 'uploads' . DS, PATH_UPLOADS . DS) === FALSE) { $this->Form->AddError(T('Yaga.Error.TransportCopy')); } return TRUE; }