function siteLibAutoloader($className) { $paths = $GLOBALS['libDirs']; // If the className has Module in it then use the modules dir if (defined('MODULES_DIR') && preg_match("/(.*)WebModule/", $className, $bits)) { $paths[] = MODULES_DIR . '/' . strtolower($bits[1]); } // use the site lib dir if it's been defined if (defined('SITE_LIB_DIR')) { $paths[] = SITE_LIB_DIR; } $paths[] = LIB_DIR; foreach ($paths as $path) { $file = realpath_exists("$path/$className.php"); if ($file) { //error_log("Autoloader found $file for $className"); include($file); return; } } return; }
function _outputTypeFile($matches) { $file = $matches[3]; $prefix = ''; $bits = explode("/", $file); if (count($bits) > 1) { $file = array_pop($bits); $prefix = trim(implode("/", $bits), "/") . '/'; } $platform = Kurogo::deviceClassifier()->getPlatform(); $pagetype = Kurogo::deviceClassifier()->getPagetype(); $browser = Kurogo::deviceClassifier()->getBrowser(); $testDirs = array(THEME_DIR, SHARED_THEME_DIR, SITE_APP_DIR, SHARED_APP_DIR, APP_DIR); $testFiles = array("{$prefix}{$pagetype}-{$platform}-{$browser}/{$file}", "{$prefix}{$pagetype}-{$platform}/{$file}", "{$prefix}{$pagetype}/{$file}", "{$prefix}{$file}"); foreach ($testDirs as $dir) { //do not assume dirs have value set if ($dir) { $dir .= '/' . $matches[1] . $matches[2]; foreach ($testFiles as $file) { Kurogo::log(LOG_DEBUG, "Looking for {$dir}/{$file}", 'index'); if ($file = realpath_exists("{$dir}/{$file}")) { _outputFile($file); } } } } _404(); }
function _outputTypeFile($matches) { $file = $matches[3]; $platform = Kurogo::deviceClassifier()->getPlatform(); $pagetype = Kurogo::deviceClassifier()->getPagetype(); $testDirs = array( THEME_DIR.'/'.$matches[1].$matches[2], SITE_DIR.'/'.$matches[1].$matches[2], APP_DIR.'/'.$matches[1].$matches[2], ); $testFiles = array( "$pagetype-$platform/$file", "$pagetype/$file", "$file", ); foreach ($testDirs as $dir) { foreach ($testFiles as $file) { if ($file = realpath_exists("$dir/$file")) { _outputFile($file); } } } _404(); }
/** * This function defines a autoloader that is run when a class needs to be instantiated but the corresponding * file has not been loaded. Files MUST be named with the same name as its class * currently it will search: * 1. If the className has Module in it, it will search the MODULES_DIR * 2. The SITE_LIB_DIR (keep in mind that some files may manually include the LIB_DIR class * 3. The LIB_DIR * */ function siteLibAutoloader($className) { $paths = array(); // If the className has Authentication at the end try the authentication dir if (preg_match("/(Authentication)$/", $className, $bits)) { if (defined('SITE_LIB_DIR')) { $paths[] = SITE_LIB_DIR . "/" . $bits[1]; } $paths[] = LIB_DIR . "/" . $bits[1]; } // If the className has Module in it then use the modules dir if (defined('MODULES_DIR') && preg_match("/(.*)WebModule/", $className, $bits)) { $paths[] = MODULES_DIR . '/' . strtolower($bits[1]); } // use the site lib dir if it's been defined if (defined('SITE_LIB_DIR')) { $paths[] = SITE_LIB_DIR; } $paths[] = LIB_DIR; foreach ($paths as $path) { $file = realpath_exists("$path/$className.php"); if ($file) { //error_log("Autoloader found $file for $className"); include $file; return; } } return; }
public function parseFile($filename) { if (strpos($filename, '.zip') !== false) { if (!class_exists('ZipArchive')) { throw new KurogoException("class ZipArchive (php-zip) not available"); } $zip = new ZipArchive(); $zip->open($filename); // locate valid shapefile components $shapeNames = array(); for ($i = 0; $i < $zip->numFiles; $i++) { if (preg_match('/(.+)\\.(shp|dbf|prj)$/', $zip->getNameIndex($i), $matches)) { $shapeName = $matches[1]; $extension = $matches[2]; if (!isset($shapeNames[$shapeName])) { $shapeNames[$shapeName] = array(); } $shapeNames[$shapeName][] = $extension; } } $this->dbfParser = new DBase3FileParser(); foreach ($shapeNames as $shapeName => $extensions) { if (in_array('dbf', $extensions) && in_array('shp', $extensions)) { $this->setContents($zip->getFromName("{$shapeName}.shp")); $contents = $zip->getFromName("{$shapeName}.dbf"); if (!$contents) { throw new KurogoDataException("could not read {$shapeName}.dbf"); } $this->dbfParser->setContents($zip->getFromName("{$shapeName}.dbf")); $this->dbfParser->setup(); if (in_array('prj', $extensions)) { $prjData = $zip->getFromName("{$shapeName}.prj"); $this->mapProjection = new MapProjection($prjData); } $this->doParse(); } } } elseif (realpath_exists("{$filename}.shp") && realpath_exists("{$filename}.dbf")) { $this->setFilename("{$filename}.shp"); $this->dbfParser = new DBase3FileParser(); $this->dbfParser->setFilename("{$filename}.dbf"); $this->dbfParser->setup(); $prjFile = $filename . '.prj'; if (realpath_exists($prjFile)) { $prjData = file_get_contents($prjFile); $this->mapProjection = new MapProjection($prjData); } $this->doParse(); } else { throw new KurogoDataException("Cannot find {$filename}"); } return $this->features; }
protected function retrieveResponse() { $response = $this->initResponse(); if (strpos($this->fileStem, '.zip') !== false) { if (!class_exists('ZipArchive')) { throw new KurogoException("class ZipArchive (php-zip) not available"); } $response->setContext('zipped', true); $zip = new ZipArchive(); if (strpos($this->fileStem, 'http') === 0 || strpos($this->fileStem, 'ftp') === 0) { $tmpFile = Kurogo::tempFile(); copy($this->fileStem, $tmpFile); $zip->open($tmpFile); } else { $zip->open($this->fileStem); } // locate valid shapefile components $shapeNames = array(); for ($i = 0; $i < $zip->numFiles; $i++) { if (preg_match('/(.+)\\.(shp|dbf|prj)$/', $zip->getNameIndex($i), $matches)) { $shapeName = $matches[1]; $extension = $matches[2]; if (!isset($shapeNames[$shapeName])) { $shapeNames[$shapeName] = array(); } $shapeNames[$shapeName][] = $extension; } } $responseData = array(); foreach ($shapeNames as $shapeName => $extensions) { if (in_array('dbf', $extensions) && in_array('shp', $extensions)) { $fileData = array('dbf' => $zip->getFromName("{$shapeName}.dbf"), 'shp' => $zip->getFromName("{$shapeName}.shp")); if (in_array('prj', $extensions)) { $prjData = $zip->getFromName("{$shapeName}.prj"); $fileData['projection'] = new MapProjection($prjData); } $responseData[$shapeName] = $fileData; } } $response->setResponse($responseData); } elseif (realpath_exists("{$this->fileStem}.shp") && realpath_exists("{$this->fileStem}.dbf")) { $response->setContext('zipped', false); $response->setContext('shp', "{$this->fileStem}.shp"); $response->setContext('dbf', "{$this->fileStem}.dbf"); if (realpath_exists("{$this->fileStem}.prj")) { $prjData = file_get_contents("{$this->fileStem}.prj"); $response->setContext('projection', new MapProjection($prjData)); } } else { throw new KurogoDataException("Cannot find {$this->fileStem}"); } return $response; }
protected function loadFile($_file, $safe = true) { if (strlen($_file) == 0) { return false; } if (!($file = realpath_exists($_file, $safe))) { return false; } $vars = parse_ini_file($file, false); $this->addVars($vars); $sectionVars = parse_ini_file($file, true); $this->addSectionVars($sectionVars); Kurogo::log(LOG_INFO, "Loaded config file {$file}", 'config'); return $file; }
function buildFileList($checkFiles) { $foundFiles = array(); foreach ($checkFiles['files'] as $entry) { if (is_array($entry)) { $foundFiles = array_merge($foundFiles, buildFileList($entry)); } else if (realpath_exists($entry)) { $foundFiles[] = $entry; } if ($checkFiles['include'] == 'any' && count($foundFiles)) { break; } } return $foundFiles; }
function _outputTypeFile($matches) { $file = $matches[3]; $platform = Kurogo::deviceClassifier()->getPlatform(); $pagetype = Kurogo::deviceClassifier()->getPagetype(); $browser = Kurogo::deviceClassifier()->getBrowser(); $testDirs = array(THEME_DIR . '/' . $matches[1] . $matches[2], SITE_APP_DIR . '/' . $matches[1] . $matches[2], SHARED_APP_DIR . '/' . $matches[1] . $matches[2], APP_DIR . '/' . $matches[1] . $matches[2]); $testFiles = array("{$pagetype}-{$platform}-{$browser}/{$file}", "{$pagetype}-{$platform}/{$file}", "{$pagetype}/{$file}", "{$file}"); foreach ($testDirs as $dir) { foreach ($testFiles as $file) { if ($file = realpath_exists("{$dir}/{$file}")) { _outputFile($file); } } } _404(); }
protected static function generateURL($file, $contents, $subdirectory=null) { $path = AUTOLOAD_FILE_DIR; if (!realpath_exists($path)) { if (!mkdir($path, 0755, true)) { error_log("could not create $path"); return; } } $subPath = $path."/$subdirectory"; if (!realpath_exists($subPath)) { if (!mkdir($subPath, 0755, true)) { error_log("could not create $subPath"); return; } } if (file_put_contents(self::filePath($file, $subdirectory), $contents)) { return self::fullURL($file, $subdirectory); } else { return false; } }
function __construct() { // Load main configuration file $config = ConfigFile::factory('kurogo', 'project', ConfigFile::OPTION_IGNORE_MODE | ConfigFile::OPTION_IGNORE_LOCAL); $this->addConfig($config); define('CONFIG_MODE', $config->getVar('CONFIG_MODE')); define('CONFIG_IGNORE_LOCAL', $config->getVar('CONFIG_IGNORE_LOCAL')); //make sure active site is set if (!$site = $this->getVar('ACTIVE_SITE')) { die("FATAL ERROR: ACTIVE_SITE not set"); } //make sure site_dir is set and is a valid path if (!($siteDir = $this->getVar('SITE_DIR')) || !($siteDir = realpath_exists($siteDir))) { die("FATAL ERROR: Site Directory ". $this->getVar('SITE_DIR') . " not found for site " . $site); } // Set up defines relative to SITE_DIR define('SITE_DIR', $siteDir); define('SITE_KEY', md5($siteDir)); define('SITE_LIB_DIR', SITE_DIR.'/lib'); define('SITE_APP_DIR', SITE_DIR.'/app'); define('SITE_MODULES_DIR', SITE_DIR.'/app/modules'); define('DATA_DIR', SITE_DIR.'/data'); define('CACHE_DIR', SITE_DIR.'/cache'); define('LOG_DIR', SITE_DIR.'/logs'); define('SITE_CONFIG_DIR', SITE_DIR.'/config'); //load in the site config file (required); $config = ConfigFile::factory('site', 'site'); $this->addConfig($config); // Set up theme define if (!$theme = $this->getVar('ACTIVE_THEME')) { die("FATAL ERROR: ACTIVE_THEME not set"); } define('THEME_DIR', SITE_DIR.'/themes/'.$theme); }
protected static function generateURL($file, $contents, $subdirectory = null) { $path = AUTOLOAD_FILE_DIR; if (!realpath_exists($path)) { if (!mkdir($path, 0755, true)) { Kurogo::log(LOG_WARNING, "could not create {$path}", 'data'); return; } } $subPath = $path . "/{$subdirectory}"; if (!realpath_exists($subPath)) { if (!mkdir($subPath, 0755, true)) { Kurogo::log(LOG_WARNING, "could not create {$subPath}", 'data'); return; } } if (file_put_contents(self::filePath($file, $subdirectory), $contents)) { return self::fullURL($file, $subdirectory); } else { return false; } }
public static function factory($id, $type=null) { // when run without a type it will find either $classNames = array( 'web'=>ucfirst($id).'WebModule', 'api'=>ucfirst($id).'APIModule' ); // if we specified a type, include only that type in the array if ($type) { if (isset($classNames[$type])) { $classNames = array($classNames[$type]); } else { throw new Exception("Invalid module type $type"); } } // possible module paths $modulePaths = array( SITE_MODULES_DIR."/$id/Site%s.php"=>"Site%s", SITE_MODULES_DIR."/$id/%s.php"=>"%s", MODULES_DIR."/$id/%s.php"=>"%s", ); //cycle module paths and class names to find a valid module foreach($modulePaths as $path=>$className){ foreach ($classNames as $class) { $className = sprintf($className, $class); $path = sprintf($path, $class); $moduleFile = realpath_exists($path); if ($moduleFile && include_once($moduleFile)) { return new $className(); } } } throw new Exception("Module $id not found"); }
public function __construct($path, $timeout = NULL, $mkdir = FALSE) { if (empty($path)) { throw new KurogoDataException("Invalid path"); } $this->path = $path; if ($mkdir) { if (!file_exists($path)) { if (!@mkdir($path, 0700, true)) { throw new KurogoDataException("Could not create cache folder {$path}"); } } if (!realpath_exists($path)) { throw new KurogoDataException("Path {$path} is not valid for cache"); } } if (!is_writable($path)) { throw new KurogoDataException("Path {$path} is not writable"); } if ($timeout !== NULL) { $this->timeout = $timeout; } }
protected function detectDeviceInternal($user_agent) { Kurogo::log(LOG_INFO, "Detecting device using internal device detection", 'deviceDetection'); if (!$user_agent) { return; } /* * Two things here: * First off, we now have two files which can be used to classify devices, * the master file, usually at LIB_DIR/deviceData.json, and the custom file, * usually located at DATA_DIR/deviceData.json. * * Second, we're still allowing the use of sqlite databases (despite it * being slower and more difficult to update). So, if you specify the * format of the custom file as sqlite, it should still work. */ $master_file = LIB_DIR . "/deviceData.json"; $site_file = Kurogo::getOptionalSiteVar('MOBI_SERVICE_SITE_FILE'); $site_file_format = Kurogo::getOptionalSiteVar('MOBI_SERVICE_SITE_FORMAT', 'json'); if (!($site_file && $site_file_format)) { // We don't have a site-specific file. This means we can only // detect on the master file. $site_file = ""; } if (!empty($site_file) && ($site_file = realpath_exists($site_file))) { switch ($site_file_format) { case 'json': $site_devices = json_decode(file_get_contents($site_file), true); $site_devices = $site_devices['devices']; if (($error_code = json_last_error()) !== JSON_ERROR_NONE) { throw new KurogoConfigurationException("Problem decoding Custom Device Detection File. Error code returned was " . $error_code); } if (($device = $this->checkDevices($site_devices, $user_agent)) !== false) { return $this->translateDevice($device); } break; case 'sqlite': Kurogo::includePackage('db'); try { $db = new db(array('DB_TYPE' => 'sqlite', 'DB_FILE' => $site_file)); $result = $db->query('SELECT * FROM userAgentPatterns WHERE version<=? ORDER BY patternorder,version DESC', array($this->version)); } catch (Exception $e) { Kurogo::log(LOG_ALERT, "Error with internal device detection: " . $e->getMessage(), 'deviceDetection'); if (!in_array('sqlite', PDO::getAvailableDrivers())) { die("SQLite PDO drivers not available. You should switch to external device detection by changing MOBI_SERVICE_USE_EXTERNAL to 1 in " . SITE_CONFIG_DIR . "/site.ini"); } return false; } while ($row = $result->fetch()) { if (preg_match("#" . $row['pattern'] . "#i", $user_agent)) { return $row; } } break; default: throw new KurogoConfigurationException('Unknown format specified for Custom Device Detection File: ' . $site_file_format); } } if (!empty($master_file) && ($master_file = realpath_exists($master_file))) { $master_devices = json_decode(file_get_contents($master_file), true); $master_devices = $master_devices['devices']; if (function_exists('json_last_error') && ($error_code = json_last_error()) !== JSON_ERROR_NONE) { Kurogo::log(LOG_ALERT, "Error with JSON internal device detection: " . $error_code, 'deviceDetection'); die("Problem decoding Device Detection Master File. Error code returned was " . $error_code); } if (($device = $this->checkDevices($master_devices, $user_agent)) !== false) { return $this->translateDevice($device); } } Kurogo::log(LOG_WARNING, "Could not find a match in the internal device detection database for: {$user_agent}", 'deviceDetection'); }
protected function loadFile($_file) { if (!($file = realpath_exists($_file))) { return false; } $this->filepath = $file; $vars = parse_ini_file($file, false); $this->addVars($vars); $sectionVars = parse_ini_file($file, true); $this->addSectionVars($sectionVars); Kurogo::log(LOG_DEBUG, "Loaded config file {$file}", 'config'); return true; }
protected function loadFile($_file) { if (empty($_file)) { return false; } $cacheKey = 'configfile-' . md5($_file); if ($cache = Kurogo::getCache($cacheKey)) { // a little sanity in case we update the structure if (isset($cache['vars'], $cache['sectionVars'], $cache['file'])) { $this->addVars($cache['vars']); $this->addSectionVars($cache['sectionVars']); return $cache['file']; } } if (!($file = realpath_exists($_file))) { return false; } $vars = parse_ini_file($file, false); $this->addVars($vars); $sectionVars = parse_ini_file($file, true); $this->addSectionVars($sectionVars); Kurogo::setCache($cacheKey, array('vars' => $vars, 'sectionVars' => $sectionVars, 'file' => $file)); Kurogo::log(LOG_DEBUG, "Loaded config file {$file}", 'config'); return $file; }
function getMinifyGroupsConfig() { $minifyConfig = array(); $key = $_GET['g']; // // Check for specific file request // if (strpos($key, MIN_FILE_PREFIX) === 0) { // file path relative to either templates or the theme (check theme first) $path = substr($key, strlen(MIN_FILE_PREFIX)); $config = array('include' => 'all', 'files' => array(THEME_DIR . $path, SITE_APP_DIR . $path, APP_DIR . $path)); return array($key => buildFileList($config)); } // // Page request // $pageOnly = isset($_GET['pageOnly']) && $_GET['pageOnly']; // if this is a copied module also pull in files from that module $configModule = isset($_GET['config']) ? $_GET['config'] : ''; list($ext, $module, $page, $pagetype, $platform, $pathHash) = explode('-', $key); $cache = new DiskCache(CACHE_DIR . '/minify', Kurogo::getOptionalSiteVar('MINIFY_CACHE_TIMEOUT', 30), true); $cacheName = "group_{$key}"; if ($configModule) { $cacheName .= "-{$configModule}"; } if ($pageOnly) { $cacheName .= "-pageOnly"; } if ($cache->isFresh($cacheName)) { $minifyConfig = $cache->read($cacheName); } else { $dirs = array(APP_DIR, SITE_APP_DIR, THEME_DIR); if ($pageOnly || ($pagetype == 'tablet' || $platform == 'computer') && in_array($module, array('info', 'admin'))) { // Info module does not inherit from common files $subDirs = array('/modules/' . $module); } else { $subDirs = array('/common', '/modules/' . $module); } if ($configModule) { $subDirs[] = '/modules/' . $configModule; } $checkFiles = array('css' => getCSSFileConfigForDirs($page, $pagetype, $platform, $dirs, $subDirs, $pageOnly), 'js' => getJSFileConfigForDirs($page, $pagetype, $platform, $dirs, $subDirs, $pageOnly)); //error_log(print_r($checkFiles, true)); $minifyConfig[$key] = buildFileList($checkFiles[$ext]); //error_log(__FUNCTION__."($pagetype-$platform) scanned filesystem for $key"); $cache->write($minifyConfig, $cacheName); } // Add minify source object for the theme config.ini if ($ext == 'css') { $themeVarsFile = realpath_exists(THEME_DIR . '/config.ini'); if ($themeVarsFile) { $minifyConfig[$key][] = new Minify_Source(array('id' => 'themeConfigModTimeChecker', 'getContentFunc' => 'minifyThemeConfigModTimeCheckerContent', 'minifier' => '', 'contentType' => Minify::TYPE_CSS, 'lastModified' => filemtime($themeVarsFile))); } } //error_log(__FUNCTION__."($pagetype-$platform) returning: ".print_r($minifyConfig, true)); return $minifyConfig; }
static private function getExtendsFile($name, $template) { $pagetype = Kurogo::deviceClassifier()->getPagetype(); $platform = Kurogo::deviceClassifier()->getPlatform(); $checkDirs = array( 'THEME_DIR' => THEME_DIR, 'SITE_APP_DIR' => SITE_APP_DIR, 'APP_DIR' => APP_DIR, ); foreach ($checkDirs as $type => $dir) { $test = realpath_exists("$dir/$name"); if ($test && !$template->smarty->extendsTrackerSeenFile($test)) { if (Kurogo::getOptionalSiteVar('TEMPLATE_DEBUG')) { error_log(__FUNCTION__."($pagetype-$platform) choosing '$type/$name' for '$name'"); } $template->smarty->extendsTrackerAddFile($test); return $test; } } return false; }
/** * Factory method. Used to instantiate a subclass * @param string $id, the module id to load * @param string $type, the type of module to load (web/api) */ public static function factory($id, $type = null) { if ($id == 'kurogo') { set_exception_handler("exceptionHandlerForError"); } if (!self::isValidModuleName($id)) { throw new KurogoException(Kurogo::getLocalizedString('ERROR_INVALID_MODULE')); } Kurogo::log(LOG_INFO, "Initializing {$type} module {$id}", 'module'); $configModule = $id; $configStore = Kurogo::configStore(); //attempt to load config/$id/module.ini if ($moduleData = $configStore->getOptionalSection('module', 'module', $configModule)) { $id = Kurogo::arrayVal($moduleData, 'id', $configModule); } else { throw new KurogoModuleNotFound(Kurogo::getLocalizedString('ERROR_MODULE_NOT_FOUND', $id)); } // see if the class location has been cached if ($moduleFile = Kurogo::getCache(self::cacheKey($id, $type))) { $className = basename($moduleFile, '.php'); include_once $moduleFile; $module = new $className(); if (is_a($module, KurogoWebBridge::STUB_API_CLASS)) { $module->setID($id); } $module->setConfigModule($configModule); Kurogo::addModuleLib($id); return $module; } // when run without a type it will find either $classNames = array('web' => ucfirst($id) . 'WebModule', 'api' => ucfirst($id) . 'APIModule', 'shell' => ucfirst($id) . 'ShellModule'); // if we specified a type, include only that type in the array if ($type) { if (isset($classNames[$type])) { $classNames = array($classNames[$type]); } else { throw new KurogoException("Invalid module type {$type}"); } } // possible module paths. // 1. Site Folder SiteMODULEIDXXXModule // 2. Site Folder MODULEIDXXXModule // 3. Project folder MODULEIDXXXModule // Note: The PHP class name MUST be the basename of the file path. $modulePaths = array(SITE_MODULES_DIR . "/{$id}/Site%s.php", SITE_MODULES_DIR . "/{$id}/%s.php", SHARED_MODULES_DIR . "/{$id}/Site%s.php", SHARED_MODULES_DIR . "/{$id}/%s.php", MODULES_DIR . "/{$id}/%s.php"); if ($type == 'api' && KurogoWebBridge::moduleHasMediaAssets($configModule)) { $modulePaths[] = LIB_DIR . '/' . KurogoWebBridge::STUB_API_CLASS . ".php"; } //cycle module paths foreach ($modulePaths as $path) { $className = basename($path, '.php'); //cycle class names to find a valid module foreach ($classNames as $class) { $className = sprintf($className, $class); $path = sprintf($path, $class); Kurogo::log(LOG_DEBUG, "Looking for {$path} for {$id}", 'module'); // see if it exists $moduleFile = realpath_exists($path); if ($moduleFile && (include_once $moduleFile)) { //found it $info = new ReflectionClass($className); if (!$info->isAbstract()) { Kurogo::log(LOG_INFO, "Found {$moduleFile} for {$id}", 'module'); $module = new $className(); if (is_a($module, KurogoWebBridge::STUB_API_CLASS)) { $module->setID($id); } $module->setConfigModule($configModule); // cache the location of the class (which also includes the classname) Kurogo::setCache(self::cacheKey($id, $type), $moduleFile); Kurogo::addModuleLib($id); return $module; } Kurogo::log(LOG_NOTICE, "{$class} found at {$moduleFile} is abstract and cannot be used for {$id}", 'module'); return false; } } } Kurogo::log(LOG_NOTICE, "No valid {$type} class found for module {$id}", 'module'); throw new KurogoModuleNotFound(Kurogo::getLocalizedString('ERROR_MODULE_NOT_FOUND', $id)); }
/** * Factory method. Used to instantiate a subclass * @param string $id, the module id to load * @param string $type, the type of module to load (web/api) */ public static function factory($id, $type = null) { Kurogo::log(LOG_INFO, "Initializing {$type} module {$id}", 'module'); $configModule = $id; //attempt to load config/$id/module.ini if ($config = ModuleConfigFile::factory($id, 'module', ModuleConfigFile::OPTION_DO_NOT_CREATE)) { //use the ID parameter if it's present, otherwise use the included id $id = $config->getOptionalVar('id', $id); } elseif (!Kurogo::getOptionalSiteVar('CREATE_DEFAULT_CONFIG', false, 'modules')) { Kurogo::log(LOG_ERR, "Module config file not found for module {$id}", 'module'); throw new KurogoModuleNotFound(Kurogo::getLocalizedString('ERROR_MODULE_NOT_FOUND', $id)); } // see if the class location has been cached if ($moduleFile = Kurogo::getCache(self::cacheKey($id, $type))) { $className = basename($moduleFile, '.php'); include_once $moduleFile; $module = new $className(); $module->setConfigModule($configModule); if ($config) { $module->setConfig('module', $config); } return $module; } // when run without a type it will find either $classNames = array('web' => ucfirst($id) . 'WebModule', 'api' => ucfirst($id) . 'APIModule'); // if we specified a type, include only that type in the array if ($type) { if (isset($classNames[$type])) { $classNames = array($classNames[$type]); } else { throw new KurogoException("Invalid module type {$type}"); } } // possible module paths. // 1. Site Folder SiteMODULEIDXXXModule // 2. Site Folder MODULEIDXXXModule // 3. Project folder MODULEIDXXXModule $modulePaths = array(SITE_MODULES_DIR . "/{$id}/Site%s.php" => "Site%s", SITE_MODULES_DIR . "/{$id}/%s.php" => "%s", MODULES_DIR . "/{$id}/%s.php" => "%s"); //cycle module paths foreach ($modulePaths as $path => $className) { //cycle class names to find a valid module foreach ($classNames as $class) { $className = sprintf($className, $class); $path = sprintf($path, $class); Kurogo::log(LOG_DEBUG, "Looking for {$path} for {$id}", 'module'); // see if it exists $moduleFile = realpath_exists($path); if ($moduleFile && (include_once $moduleFile)) { //found it $info = new ReflectionClass($className); if (!$info->isAbstract()) { Kurogo::log(LOG_INFO, "Found {$moduleFile} for {$id}", 'module'); $module = new $className(); $module->setConfigModule($configModule); if ($config) { $module->setConfig('module', $config); } // cache the location of the class (which also includes the classname) Kurogo::setCache(self::cacheKey($id, $type), $moduleFile); return $module; } Kurogo::log(LOG_NOTICE, "{$class} found at {$moduleFile} is abstract and cannot be used for {$id}", 'module'); return false; } } } Kurogo::log(LOG_ERR, "No valid class found for module {$id}", 'module'); throw new KurogoModuleNotFound(Kurogo::getLocalizedString('ERROR_MODULE_NOT_FOUND', $id)); }
public static function getAllModuleClasses() { $modulePaths = array(SITE_MODULES_DIR, MODULES_DIR); $moduleClasses = array(); $moduleIDs = array(); foreach ($modulePaths as $path) { $moduleFiles = glob($path . "/*/*WebModule.php"); foreach ($moduleFiles as $file) { $moduleFile = realpath_exists($file); if (preg_match("/(Site)?([A-Za-z]+WebModule)\\.php\$/", $file, $bits)) { $className = $bits[1] . $bits[2]; // prevent loading a class twice (i.e. a site overridden class) if (!in_array($className, $moduleClasses)) { if ($moduleFile && (include_once $moduleFile)) { $info = new ReflectionClass($className); if (!$info->isAbstract()) { try { $module = new $className(); $moduleClasses[] = $className; $moduleIDs[] = $module->getID(); } catch (Exception $e) { } } } } } } } $moduleIDs = array_unique($moduleIDs); sort($moduleIDs); return $moduleIDs; }
public function prepareJavascriptTemplate($filename, $repeating = false) { // TODO better way to search for package-specific templates $path = dirname(__FILE__) . '/javascript/' . $filename . '.js'; $path = realpath_exists($path); if ($path) { return new JavascriptTemplate($path, $repeating); } }
protected static function getPathOrDie($path) { $file = realpath_exists($path); if (!$file) { die("Missing config file at '$path'"); } return $file; }
public function setCacheFolder($cacheFolder, $create = false) { $this->cacheFolder = $cacheFolder; if ($create) { $this->createCacheFolderIfNeeded(); } if (!realpath_exists($this->cacheFolder)) { throw new KurogoDataException("Path {$this->cacheFolder} is not valid for cache"); } if (!is_writable($cacheFolder)) { throw new KurogoDataException("Path {$this->cacheFolder} is not writable"); } }
public static function getAvailableMediaInfoForModule($id) { $cacheKey = "webbridge-mediainfo-{$id}"; // use memory cache to make this more efficient $info = Kurogo::getCache($cacheKey); if ($info === false) { $files = array_merge((array) glob(WEB_BRIDGE_DIR . "/*/{$id}.zip"), (array) glob(WEB_BRIDGE_DIR . "/*/{$id}-tablet.zip")); $info = array(); foreach ($files as $file) { $name = basename($file, '.zip'); $dir = realpath(dirname($file)); $parts = explode(DIRECTORY_SEPARATOR, $dir); if (!$parts) { continue; } $platform = end($parts); if (!$platform) { continue; } $key = $platform; if ($name == "{$id}-tablet") { $key .= "-tablet"; } $file = realpath_exists($file); if (!$file) { continue; } $info[$key] = array('url' => FULL_URL_PREFIX . "media/web_bridge/{$platform}/{$name}.zip", 'file' => $file, 'mtime' => filemtime($file), 'md5' => md5_file($file)); } Kurogo::setCache($cacheKey, $info); } return $info ? $info : array(); }
/** * Factory method. Used to instantiate a subclass * @param string $id, the module id to load * @param string $type, the type of module to load (web/api) */ public static function factory($id, $type=null) { // when run without a type it will find either $classNames = array( 'web'=>ucfirst($id).'WebModule', 'api'=>ucfirst($id).'APIModule' ); // if we specified a type, include only that type in the array if ($type) { if (isset($classNames[$type])) { $classNames = array($classNames[$type]); } else { throw new Exception("Invalid module type $type"); } } // possible module paths. // 1. Site Folder SiteMODULEIDXXXModule // 2. Site Folder MODULEIDXXXModule // 3. Project folder MODULEIDXXXModule $modulePaths = array( SITE_MODULES_DIR."/$id/Site%s.php"=>"Site%s", SITE_MODULES_DIR."/$id/%s.php"=>"%s", MODULES_DIR."/$id/%s.php"=>"%s", ); //cycle module paths foreach($modulePaths as $path=>$className){ //cycle class names to find a valid module foreach ($classNames as $class) { $className = sprintf($className, $class); $path = sprintf($path, $class); // see if it exists $moduleFile = realpath_exists($path); if ($moduleFile && include_once($moduleFile)) { //found it $info = new ReflectionClass($className); if (!$info->isAbstract()) { $module = new $className(); return $module; } return false; } } } throw new Exception("Module $id not found"); }
protected function getExtendsFile($name, $template) { $pagetype = Kurogo::deviceClassifier()->getPagetype(); $platform = Kurogo::deviceClassifier()->getPlatform(); $browser = Kurogo::deviceClassifier()->getBrowser(); $checkDirs = array('THEME_DIR' => THEME_DIR, 'SITE_APP_DIR' => SITE_APP_DIR, 'SHARED_APP_DIR' => SHARED_APP_DIR, 'APP_DIR' => APP_DIR); foreach ($checkDirs as $type => $dir) { if ($dir) { $test = realpath_exists("{$dir}/{$name}"); if ($test && !$this->extendsTrackerSeenFile($test)) { Kurogo::log(LOG_DEBUG, __FUNCTION__ . "({$pagetype}-{$platform}-{$browser}) choosing '{$type}/{$name}' for '{$name}'", 'template'); $this->extendsTrackerAddFile($test); return addslashes($test); } } } return false; }
protected function loadFile($_file) { if (!$file = realpath_exists($_file)) { return false; } $this->filepath = $file; $vars = parse_ini_file($file, false); $this->addVars($vars); $sectionVars = parse_ini_file($file, true); $this->addSectionVars($sectionVars); return true; }
/** * */ function Initialize(&$path=null) { // // Constants which cannot be set by config file // define('WEBROOT_DIR', realpath(ROOT_DIR.'/www')); define('LIB_DIR', realpath(ROOT_DIR.'/lib')); define('MASTER_CONFIG_DIR', realpath(ROOT_DIR.'/config')); define('APP_DIR', realpath(ROOT_DIR.'/app')); define('MODULES_DIR', realpath(APP_DIR.'/modules')); define('MIN_FILE_PREFIX', 'file:'); // // Pull in functions to deal with php version differences // require_once(ROOT_DIR.'/lib/compat.php'); // // Set up library autoloader // require_once realpath(LIB_DIR.'/autoloader.php'); spl_autoload_register("siteLibAutoloader"); // // Set up host define for server name and port // $host = $_SERVER['SERVER_NAME']; if (isset($_SERVER['HTTP_HOST']) && strlen($_SERVER['HTTP_HOST'])) { $host = $_SERVER['HTTP_HOST']; } else if (isset($_SERVER['SERVER_PORT'])) { $host .= ":{$_SERVER['SERVER_PORT']}"; } define('SERVER_HOST', $host); // // And a double quote define for ini files (php 5.1 can't escape them) // define('_QQ_', '"'); // // Get URL base // define('DOCUMENT_ROOT', $_SERVER['DOCUMENT_ROOT']); $pathParts = array_values(array_filter(explode(DIRECTORY_SEPARATOR, $_SERVER['REQUEST_URI']))); $testPath = DOCUMENT_ROOT.DIRECTORY_SEPARATOR; $urlBase = '/'; $foundPath = false; if (realpath($testPath) != realpath(WEBROOT_DIR)) { foreach ($pathParts as $dir) { $test = $testPath.$dir.DIRECTORY_SEPARATOR; if (realpath_exists($test)) { $testPath = $test; $urlBase .= $dir.'/'; if (realpath($test) == realpath(WEBROOT_DIR)) { $foundPath = true; break; } } } } define('URL_BASE', $foundPath ? $urlBase : '/'); define('IS_SECURE', isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'); define('FULL_URL_BASE', 'http'.(IS_SECURE ? 's' : '').'://'.$_SERVER['HTTP_HOST'].URL_BASE); define('COOKIE_PATH', URL_BASE); // We are installed under URL_BASE // // Load configuration files // $GLOBALS['siteConfig'] = new SiteConfig(); ini_set('display_errors', $GLOBALS['siteConfig']->getVar('DISPLAY_ERRORS')); if (!ini_get('error_log')) { ini_set('error_log', LOG_DIR . '/php_error.log'); } // // Set timezone // date_default_timezone_set($GLOBALS['siteConfig']->getVar('LOCAL_TIMEZONE')); // // Install exception handlers // require_once realpath(LIB_DIR.'/exceptions.php'); if($GLOBALS['siteConfig']->getVar('PRODUCTION_ERROR_HANDLER_ENABLED')) { set_exception_handler("exceptionHandlerForProduction"); } else { set_exception_handler("exceptionHandlerForDevelopment"); } // Strips out the leading part of the url for sites where // the base is not located at the document root, ie.. /mobile or /m // Also strips off the leading slash (needed by device debug below) if (isset($path)) { // Strip the URL_BASE off the path $baseLen = strlen(URL_BASE); if ($baseLen && strpos($path, URL_BASE) === 0) { $path = substr($path, $baseLen); } } // // Initialize global device classifier // $device = null; $urlPrefix = URL_BASE; $urlDeviceDebugPrefix = '/'; // Check for device classification in url and strip it if present if ($GLOBALS['siteConfig']->getVar('DEVICE_DEBUG') && preg_match(';^device/([^/]+)/(.*)$;', $path, $matches)) { $device = $matches[1]; // layout forced by url $path = $matches[2]; $urlPrefix .= "device/$device/"; $urlDeviceDebugPrefix .= "device/$device/"; } define('URL_DEVICE_DEBUG_PREFIX', $urlDeviceDebugPrefix); define('URL_PREFIX', $urlPrefix); define('FULL_URL_PREFIX', 'http'.(IS_SECURE ? 's' : '').'://'.$_SERVER['HTTP_HOST'].URL_PREFIX); //error_log(__FUNCTION__."(): prefix: $urlPrefix"); //error_log(__FUNCTION__."(): path: $path"); $GLOBALS['deviceClassifier'] = new DeviceClassifier($device); }