private function getRandomBytes($count) { $bytes = ''; if (function_exists('openssl_random_pseudo_bytes') && strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') { // OpenSSL slow on Win $bytes = openssl_random_pseudo_bytes($count); } if ($bytes === '' && @is_readable('/dev/urandom') && ($hRand = @fopen('/dev/urandom', 'rb')) !== FALSE) { $bytes = fread($hRand, $count); fclose($hRand); } if (strlen($bytes) < $count) { $bytes = ''; if ($this->randomState === null) { $this->randomState = microtime(); if (function_exists('getmypid')) { $this->randomState .= getmypid(); } } for ($i = 0; $i < $count; $i += 16) { $this->randomState = md5(microtime() . $this->randomState); if (PHP_VERSION >= '5') { $bytes .= md5($this->randomState, true); } else { $bytes .= pack('H*', md5($this->randomState)); } } $bytes = substr($bytes, 0, $count); } return $bytes; }
/** * Parses YAML into a PHP array. * * The parse method, when supplied with a YAML stream (string or file), * will do its best to convert YAML in a file into a PHP array. * * Usage: * <code> * $array = Yaml::parse('config.yml'); * print_r($array); * </code> * * @param string $input Path to a YAML file or a string containing YAML * * @return array The YAML converted to a PHP array * * @throws \InvalidArgumentException If the YAML is not valid * * @api */ public static function parse($input) { // if input is a file, process it $file = ''; if (strpos($input, "\n") === false && is_file($input)) { if (false === is_readable($input)) { throw new ParseException(sprintf('Unable to parse "%s" as the file is not readable.', $input)); } $file = $input; if (self::$enablePhpParsing) { ob_start(); $retval = (include $file); $content = ob_get_clean(); // if an array is returned by the config file assume it's in plain php form else in YAML $input = is_array($retval) ? $retval : $content; // if an array is returned by the config file assume it's in plain php form else in YAML if (is_array($input)) { return $input; } } else { $input = file_get_contents($file); } } $yaml = new Parser(); try { return $yaml->parse($input); } catch (ParseException $e) { if ($file) { $e->setParsedFile($file); } throw $e; } }
public function __invoke($ctx) { if (isset($ctx['Directory']['path'])) { $path = $ctx['Directory']['path']; } else { $url = $ctx['env']['PATH_INFO']; if (strpos($url, '..') !== false) { return array(403, array('Content-Type', 'text/plain'), 'Forbidden'); } $path = $this->path . $url; } // Sanity checks if (!file_exists($path)) { return array(404, array('Content-Type', 'text/plain'), 'File not found'); } $path = realpath($path); if (false === $path) { // resolving failed. not enough rights for intermediate folder? return array(404, array('Content-Type', 'text/plain'), 'File not found'); } if (strpos($path, $this->path) !== 0) { // gone out of "chroot"? return array(404, array('Content-Type', 'text/plain'), 'File not found'); } if (!is_readable($path)) { return array(403, array('Content-Type', 'text/plain'), 'Forbidden'); } // Only files are served if (is_dir($path)) { return array(403, array('Content-Type', 'text/plain'), 'Forbidden'); } return $this->serve($path); }
/** * Performs a batch insert into a specific table using either LOAD DATA INFILE or plain INSERTs, * as a fallback. On MySQL, LOAD DATA INFILE is 20x faster than a series of plain INSERTs. * * @param string $tableName PREFIXED table name! you must call Common::prefixTable() before passing the table name * @param array $fields array of unquoted field names * @param array $values array of data to be inserted * @param bool $throwException Whether to throw an exception that was caught while trying * LOAD DATA INFILE, or not. * @throws Exception * @return bool True if the bulk LOAD was used, false if we fallback to plain INSERTs */ public static function tableInsertBatch($tableName, $fields, $values, $throwException = false) { $filePath = PIWIK_USER_PATH . '/tmp/assets/' . $tableName . '-' . Common::generateUniqId() . '.csv'; $filePath = SettingsPiwik::rewriteTmpPathWithInstanceId($filePath); $loadDataInfileEnabled = Config::getInstance()->General['enable_load_data_infile']; if ($loadDataInfileEnabled && Db::get()->hasBulkLoader()) { try { $fileSpec = array('delim' => "\t", 'quote' => '"', 'escape' => '\\\\', 'escapespecial_cb' => function ($str) { return str_replace(array(chr(92), chr(34)), array(chr(92) . chr(92), chr(92) . chr(34)), $str); }, 'eol' => "\r\n", 'null' => 'NULL'); // hack for charset mismatch if (!DbHelper::isDatabaseConnectionUTF8() && !isset(Config::getInstance()->database['charset'])) { $fileSpec['charset'] = 'latin1'; } self::createCSVFile($filePath, $fileSpec, $values); if (!is_readable($filePath)) { throw new Exception("File {$filePath} could not be read."); } $rc = self::createTableFromCSVFile($tableName, $fields, $filePath, $fileSpec); if ($rc) { unlink($filePath); return true; } } catch (Exception $e) { Log::info("LOAD DATA INFILE failed or not supported, falling back to normal INSERTs... Error was: %s", $e->getMessage()); if ($throwException) { throw $e; } } } // if all else fails, fallback to a series of INSERTs @unlink($filePath); self::tableInsertBatchIterate($tableName, $fields, $values); return false; }
public static function run(Request $request) { $controlador = $request->getControlador() . "Controller"; $ruta = ROOT . "Controllers" . DS . $controlador . ".php"; $metodo = $request->getMetodo(); if ($metodo == "index.php") { $metodo = "index"; } $argumento = $request->getArgumento(); if (is_readable($ruta)) { require_once $ruta; $mostrar = "Controllers\\" . $controlador; $controlador = new $mostrar(); if (!isset($argumento) || !isset($metodo)) { $datos = call_user_func(array($controlador, $metodo)); } else { $datos = call_user_func_array(array($controlador, $metodo), $argumento); } } //Cargar vista $ruta = ROOT . "Views" . DS . $request->getControlador() . DS . $request->getMetodo() . ".php"; if (is_readable($ruta)) { require_once $ruta; } else { print "No se encontro la ruta"; } }
/** * Load config from file * * @param string $filename * @throws \Exception * * @return void */ public function loadConfig($filename) { if (!is_readable($filename)) { throw new \Exception("Profile configuration file `{$filename}` is not readable or does not exists."); } $this->_config = (new \Magento\Framework\Xml\Parser())->load($filename)->xmlToArray(); }
function autoload($className) { $filename = ABSPATH . "classes/" . $className . ".php"; if (is_readable($filename)) { require_once $filename; } }
/** * Recursively delete an entire directory. * * @since 4.6 * @package all * @param string $directory The dir you want to remove. * @param bool $empty Should the dir remain empty? * @return bool */ function recursive_remove_directory($directory, $empty = false) { if (substr($directory, -1) == '/') { $directory = substr($directory, 0, -1); } if (!file_exists($directory) || !is_dir($directory)) { return false; } elseif (is_readable($directory)) { $handle = opendir($directory); while (false !== ($item = readdir($handle))) { if ($item != '.' && $item != '..') { $path = $directory . '/' . $item; if (is_dir($path)) { recursive_remove_directory($path); } else { unlink($path); } } } closedir($handle); if (!$empty) { if (!rmdir($directory)) { return false; } } } return true; }
function __construct() { global $mysql, $config, $_FPREFIX; $this->Requiremants = new DomDocument(); $config_file = $_FPREFIX . 'includes/requirements.xml'; if (!file_exists($config_file) || !is_readable($config_file)) { $this->error("Cannot read <i>{$config_file}</i> file!", false); } $this->Requiremants->load($config_file); $this->checkSystem(); $this->checkDB(); $this->loadRealms(); if (in_array($_GET['Realm'], $this->Realms)) { $this->Realm = array_search($_GET['Realm'], $this->Realms); } else { foreach ($mysql->Config['char'] as $key => $realm) { if ($realm['default']) { $this->Realm = $key; } } } if (!$this->Realm) { foreach ($mysql->Config['char'] as $key => $realm) { $this->Realm = $key; break; } } $this->server = $config['server_name']; if ($_GET['searchplugin']) { header('Content-type: text/xml'); die($this->getOpenSearchPlugin()); } }
public function install_notice() { $this->generate_key(); if (!is_readable($this->key_file)) { echo ' <div class="error"> <p> I couldn’t find a key file in <strong>' . dirname(__FILE__) . '/expurgate/cache/</strong>. Without one, expurgate won’t work. </p> <p> I tried to create one, but I couldn’t! </p> </div> '; } if (!is_writable($this->cache_dir)) { echo ' <div class="error"> <p> The expurgate cache directory isn’t writable. Please correct this with: </p> <p> chmod 777 ' . dirname(__FILE__) . '/expurgate/cache/ </p> </div> '; } }
/** * @see sfTask */ protected function execute($arguments = array(), $options = array()) { parent::execute($arguments, $options); $projectWebPath = sfConfig::get('sf_web_dir'); $filesystem = new dmFilesystem($this->dispatcher, $this->formatter); foreach (array('dmAdminPlugin', 'dmFrontPlugin') as $plugin) { $this->logSection('plugin', 'Configuring plugin - ' . $plugin); $this->installPluginAssets($plugin, dm::getDir() . '/' . $plugin); } // remove useless doctrine assets if (is_readable($doctrineAssetPath = dmOs::join($projectWebPath, 'sfDoctrinePlugin'))) { if (!is_link($doctrineAssetPath)) { $filesystem->deleteDirContent($doctrineAssetPath); } $filesystem->remove($doctrineAssetPath); } // remove web cache dir $webCacheDir = sfConfig::get('sf_web_dir') . '/cache'; if (is_link($webCacheDir)) { $filesystem->remove($webCacheDir); } // create web cache dir $filesystem->mkdir($webCacheDir); if (!file_exists(dmOs::join($projectWebPath, 'sf'))) { $filesystem->relativeSymlink(realpath(sfConfig::get('sf_symfony_lib_dir') . '/../data/web/sf'), dmOs::join($projectWebPath, 'sf'), true); } }
private function parseIniFile() { $settings = array(); $settingStack = array(); $open_basedir_restriction = ini_get('open_basedir'); if (empty($open_basedir_restriction)) { $settingStack[] = '/etc/dbc.ini'; $settingStack[] = '/usr/local/etc/dbc.ini'; if (function_exists("posix_getpwuid") && function_exists("posix_getuid")) { $userData = posix_getpwuid(posix_getuid()); $settingStack[] = $userData['dir'] . '/.dbc.ini'; } } $settingStack[] = dirname(__FILE__) . '/../dbc.ini'; $settingStack[] = getcwd() . '/dbc.ini'; foreach ($settingStack as $settingsFile) { if (is_readable($settingsFile)) { $settings = array_merge(parse_ini_file($settingsFile, true), $settings); } } //merge with default settings $settings = array_merge($this->settingsData, $settings); if (empty($settings)) { throw new Exception('No settings file found. Aborting.'); } if (!isset($settings['dbConn:standard'])) { throw new Exception('Mandatory "dbConn:standard" is missing in settings file. Aborting.'); } $this->settingsData = $this->parseValues($settings); }
public static function configIsReadable() { if (!is_file(self::$CONFIG_FILE)) { return false; } return is_readable(self::$CONFIG_FILE); }
function isWritable($sFile, $sPrePath = '/../../') { clearstatcache(); $aPathInfo = pathinfo(__FILE__); $sFile = $aPathInfo['dirname'] . '/../../' . $sFile; return is_readable($sFile) && is_writable($sFile); }
function choose_page($page) { if ($page !== "" && $page[0] === "~") { $xpage = Navigation::path_component(0, true); Navigation::set_path("/" . $page . Navigation::path_suffix(1)); $page = Navigation::set_page($xpage ?: "index"); } $i = strlen($page) - 4; if ($i > 0 && substr($page, $i) === ".php") { $page = substr($page, 0, $i); } if ($page === "index") { return null; } if (is_readable($page . ".php") && strpos($page, "/") === false) { return $page . ".php"; } else { if (preg_match(',\\A(?:images|scripts|stylesheets)\\z,', $page)) { $_REQUEST["file"] = $page . Navigation::path(); return "cacheable.php"; } else { Navigation::redirect_site("index"); } } }
/** * Determine if the XML file exists * @return bool */ public function fileExists() { if (file_exists($this->path) && is_readable($this->path)) { return true; } return false; }
/** * Takes a filename and returnes a Stringset representing that file. * @param string $filename * @return Stringset */ public static function fromFile($filename) { if (!is_readable($filename)) { throw new Exception("Unreadable file"); } return self::fromString(file_get_contents($filename)); }
/** * Factory fuction which produces a configuration based on a policy and based * on local system resources. * * @param $policy array: * - enable_ssl: bool; default: TRUE * - verify_peer: bool; default: TRUE * - cafile: string, path to aggregated PEM; overrides any system defaults * - fallback_cafile: string, path to aggregated PEM; used on systems which lack default; set FALSE to disable * - fallback_ttl: int, seconds, the max age of the fallback cafile before it's regarded as stale; default: 5 years * @return CA_Config_Stream */ public static function probe($policy = array()) { if (isset($policy['enable_ssl']) && $policy['enable_ssl'] === FALSE) { return new CA_Config_Stream(FALSE, FALSE, NULL); } $sw = stream_get_wrappers(); if (!extension_loaded('openssl') || !in_array('https', $sw)) { return new CA_Config_Stream(FALSE, FALSE, NULL); } if (isset($policy['verify_peer']) && $policy['verify_peer'] === FALSE) { return new CA_Config_Stream(TRUE, FALSE, NULL); } if (isset($policy['cafile'])) { if (file_exists($policy['cafile']) && is_readable($policy['cafile'])) { return new CA_Config_Stream(TRUE, TRUE, $policy['cafile']); } else { throw new Exception("Certificate Authority file is missing. Please contact the system administrator. See also: " . $policy['cafile']); } } if (!isset($policy['fallback_ttl'])) { $policy['fallback_ttl'] = 5 * 364 * 24 * 60 * 60; } if (!isset($policy['fallback_cafile'])) { $policy['fallback_cafile'] = dirname(__FILE__) . '/cacert.pem'; } if (empty($policy['fallback_cafile']) || !file_exists($policy['fallback_cafile'])) { throw new Exception("Certificate Authority file is required for SSL. Please contact the system administrator."); } elseif (time() > filemtime($policy['fallback_cafile']) + $policy['fallback_ttl']) { throw new Exception("Certificate Authority file is too old. Please contact the system administrator. See also: " . $policy['fallback_cafile']); } else { return new CA_Config_Stream(TRUE, TRUE, $policy['fallback_cafile']); } }
/** * PRNG generator based on security principles * at http://phpsecurity.readthedocs.org/en/latest/Insufficient-Entropy-For-Random-Values.html * * @param mixed $length * @param mixed $strong * @access public * @return void */ public function getBytes($length, $strong = false) { $bytes = ''; if (function_exists('openssl_random_pseudo_bytes') && (version_compare(PHP_VERSION, '5.3.4') >= 0 || strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') ) { $bytes = openssl_random_pseudo_bytes($length, $usable); if (true === $usable) { return $bytes; } } if (function_exists('mcrypt_create_iv') && (version_compare(PHP_VERSION, '5.3.7') >= 0 || strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') ) { $bytes = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM); if ($bytes !== false && strlen($bytes) === $length) { return $bytes; } } $checkAlternatives = (file_exists('/dev/urandom') && is_readable('/dev/urandom')) || class_exists('\\COM', false); if (true === $strong && false === $checkAlternatives) { throw new \Exception( 'Unable to generate sufficiently strong random bytes due to a lack ', 'of sources with sufficient entropy' ); } $generator = $this->getAlternativeGenerator(); return $generator->generate($length); }
/** * Setup */ function __construct() { $ns = e107::getRender(); $pref = e107::getPref(); $mes = e107::getMessage(); $frm = e107::getForm(); $this->backUrl = e_SELF; $core_data = file_get_contents(e_CORE . 'sql/core_sql.php'); $this->tables['core'] = $this->getTables($core_data); $this->sqlLanguageTables = $this->getSqlLanguages(); if (varset($pref['e_sql_list'])) { foreach ($pref['e_sql_list'] as $path => $file) { $filename = e_PLUGIN . $path . '/' . $file . '.php'; if (is_readable($filename)) { $id = str_replace('_sql', '', $file); $data = file_get_contents($filename); $this->tables[$id] = $this->getTables($data); unset($data); } else { $message = str_replace("[x]", $filename, DBVLAN_22); $mes->add($message, E_MESSAGE_WARNING); } } } }
/** * Adds all resources that belong to a locale. * * @param Application $app * @param string $locale * * @return array */ public static function addResources(Application $app, $locale) { // Directories to look for translation file(s) $transDirs = array_unique([$app['resources']->getPath("app/resources/translations/{$locale}"), $app['resources']->getPath("root/app/resources/translations/{$locale}")]); $needsSecondPass = true; $resources = []; foreach ($transDirs as $transDir) { if (!is_dir($transDir) || !is_readable($transDir)) { continue; } $iterator = new \DirectoryIterator($transDir); /** * @var \SplFileInfo $fileInfo */ foreach ($iterator as $fileInfo) { $ext = Lib::getExtension((string) $fileInfo); if (!$fileInfo->isFile() || !in_array($ext, ['yml', 'xlf'], true)) { continue; } list($domain) = explode('.', $fileInfo->getFilename()); $resources[] = [$ext, $fileInfo->getRealPath(), $locale, $domain]; $needsSecondPass = false; } } if ($needsSecondPass && strlen($locale) === 5) { $resources = array_merge($resources, static::addResources($app, substr($locale, 0, 2))); } return $resources; }
/** * 遍历目录内容 * @param string $dirName 目录名 * @param string $exts 读取的文件扩展名 * @param int $son 是否显示子目录 * @param array $list * @return array */ public static function tree($dirName = null, $exts = '', $son = 0, $list = array()) { if (is_null($dirName)) { $dirName = '.'; } $dirPath = self::dirPath($dirName); static $id = 0; if (is_array($exts)) { $exts = implode("|", $exts); } foreach (glob($dirPath . '*') as $v) { $id++; if (is_dir($v) || !$exts || preg_match("/\\.({$exts})/i", $v)) { $list[$id]['name'] = basename($v); $list[$id]['path'] = str_replace("\\", "/", realpath($v)); $list[$id]['type'] = filetype($v); $list[$id]['filemtime'] = filemtime($v); $list[$id]['fileatime'] = fileatime($v); $list[$id]['size'] = is_file($v) ? filesize($v) : self::get_dir_size($v); $list[$id]['iswrite'] = is_writeable($v) ? 1 : 0; $list[$id]['isread'] = is_readable($v) ? 1 : 0; } if ($son) { if (is_dir($v)) { $list = self::tree($v, $exts, $son = 1, $list); } } } return $list; }
/** * Load translation data (XLIFF file reader) * * @param string $locale Locale/Language to add data for, identical with locale identifier, * see Zend_Locale for more information * @param string $filename XLIFF file to add, full path must be given for access * @param array $option OPTIONAL Options to use * @throws Zend_Translation_Exception * @return array */ protected function _loadTranslationData($filename, $locale, array $options = array()) { $this->_data = array(); if (!is_readable($filename)) { require_once 'Zend/Translate/Exception.php'; throw new Zend_Translate_Exception('Translation file \'' . $filename . '\' is not readable.'); } if (empty($options['useId'])) { $this->_useId = false; } else { $this->_useId = true; } $encoding = $this->_findEncoding($filename); $this->_target = $locale; $this->_file = xml_parser_create($encoding); xml_set_object($this->_file, $this); xml_parser_set_option($this->_file, XML_OPTION_CASE_FOLDING, 0); xml_set_element_handler($this->_file, "_startElement", "_endElement"); xml_set_character_data_handler($this->_file, "_contentElement"); if (!xml_parse($this->_file, file_get_contents($filename))) { $ex = sprintf('XML error: %s at line %d', xml_error_string(xml_get_error_code($this->_file)), xml_get_current_line_number($this->_file)); xml_parser_free($this->_file); require_once 'Zend/Translate/Exception.php'; throw new Zend_Translate_Exception($ex); } return $this->_data; }
/** * Load config data. Support php|ini|yml config formats. * * @param string|\SplFileInfo $configFile * @throws ConfigException */ public function loadConfig($configFile) { if (!$configFile instanceof \SplFileInfo) { if (!is_string($configFile)) { throw new ConfigException('Mismatch type of variable.'); } $path = realpath($this->basePath . $configFile); // check basePath at mutation if (strpos($configFile, '..') || !strpos($path, realpath($this->basePath))) { throw new ConfigException('Config file name: ' . $configFile . ' isn\'t correct.'); } if (!is_file($path) || !is_readable($path)) { throw new ConfigException('Config file: ' . $path . ' not found of file isn\'t readable.'); } $configFile = new \SplFileInfo($path); } $path = $configFile->getRealPath(); $ext = $configFile->getExtension(); $key = $configFile->getBasename('.' . $ext); if ('php' === $ext) { $this->data[$key] = (include $path); } elseif ('ini' === $ext) { $this->data[$key] = parse_ini_file($path, true); } elseif ('yml' === $ext) { if (!function_exists('yaml_parse_file')) { throw new ConfigException("Function `yaml_parse_file` isn't supported.\n" . 'http://php.net/manual/en/yaml.requirements.php'); } $this->data[$key] = yaml_parse_file($path); } }
protected function execute(InputInterface $input, OutputInterface $output) { $magento = new Magento($input->getOption('magento-root')); $config_adapter = new ConfigurationAdapter($magento); $yaml = new Parser(); if ($input->getArgument('config-yaml-file')) { $config_yaml_file = $input->getArgument('config-yaml-file'); if (!file_exists($config_yaml_file)) { throw new \Exception("File ({$config_yaml_file}) does not exist"); } if (!is_readable($config_yaml_file)) { throw new \Exception("File ({$config_yaml_file}) is not readable"); } $config_db_yaml = ConfigYaml::build($config_adapter); $config_file_contents = $yaml->parse(file_get_contents($config_yaml_file)); $config_file_yaml = new ConfigYaml($config_file_contents, $input->getOption('env')); $diff = ConfigYaml::compare($config_file_yaml, $config_db_yaml); if (count($diff) > 0) { $db_data = $config_db_yaml->getData(); $file_data = $config_file_yaml->getData(); $diff_count = 0; foreach ($diff as $scope => $scope_data) { foreach ($scope_data as $key => $value) { $diff_count++; $diff_message = sprintf("%s/%s is different (File: %s, DB: %s)", $scope, $key, $this->decorateValue($file_data[$scope][$key]), $this->decorateValue($db_data[$scope][$key])); $output->writeln($diff_message); } } return $diff_count; } else { return 0; } } }
public static function getExtension($host, $addr) { $BBC_IP2EXT_PATH = dirname(__FILE__) . '/../ip2ext/'; // generic extensions which need to be looked up first $gen_ext = array("ac", "aero", "ag", "arpa", "as", "biz", "cc", "cd", "com", "coop", "cx", "edu", "eu", "gb", "gov", "gs", "info", "int", "la", "mil", "ms", "museum", "name", "net", "nu", "org", "pro", "sc", "st", "su", "tc", "tf", "tk", "tm", "to", "tv", "vu", "ws"); // hosts with reliable country extension don't need to be looked up $cnt_ext = array("ad", "ae", "af", "ai", "al", "am", "an", "ao", "aq", "ar", "at", "au", "aw", "az", "ba", "bb", "bd", "be", "bf", "bg", "bh", "bi", "bj", "bm", "bn", "bo", "br", "bs", "bt", "bv", "bw", "by", "bz", "ca", "cf", "cg", "ch", "ci", "ck", "cl", "cm", "cn", "co", "cr", "cs", "cu", "cv", "cy", "cz", "de", "dj", "dk", "dm", "do", "dz", "ec", "ee", "eg", "eh", "er", "es", "et", "fi", "fj", "fk", "fm", "fo", "fr", "ga", "gd", "ge", "gf", "gg", "gh", "gi", "gl", "gm", "gn", "gp", "gq", "gr", "gt", "gu", "gw", "gy", "hk", "hm", "hn", "hr", "ht", "hu", "id", "ie", "il", "im", "in", "io", "iq", "ir", "is", "it", "je", "jm", "jo", "jp", "ke", "kg", "kh", "ki", "km", "kn", "kp", "kr", "kw", "ky", "kz", "lb", "lc", "li", "lk", "lr", "ls", "lt", "lu", "lv", "ly", "ma", "mc", "md", "me", "mg", "mh", "mk", "ml", "mm", "mn", "mo", "mp", "mq", "mr", "mt", "mu", "mv", "mw", "mx", "my", "mz", "na", "nc", "ne", "nf", "ng", "ni", "nl", "no", "np", "nr", "nz", "om", "pa", "pe", "pf", "pg", "ph", "pk", "pl", "pm", "pn", "pr", "ps", "pt", "pw", "py", "qa", "re", "ro", "ru", "rs", "rw", "sa", "sb", "sd", "se", "sg", "sh", "si", "sj", "sk", "sl", "sm", "sn", "so", "sr", "sv", "sy", "sz", "td", "tg", "th", "tj", "tl", "tn", "tp", "tr", "tt", "tw", "tz", "ua", "ug", "uk", "um", "us", "uy", "uz", "va", "vc", "ve", "vg", "vi", "vn", "wf", "ye", "yt", "yu", "za", "zm", "zr", "zw"); $file = $BBC_IP2EXT_PATH . (substr($addr, 0, strpos($addr, ".")) . ".inc"); $ext = strtolower(substr($host, strrpos($host, ".") + 1)); // Don't look up if there's already a country extension if (in_array($ext, $cnt_ext)) { return $ext; } if (!is_readable($file)) { return self::legacy_ext($ext, $gen_ext); } $long = ip2long($addr); $long = sprintf("%u", $long); $fp = fopen($file, "rb"); while (($range = fgetcsv($fp, 32, "|")) !== false) { if ($long >= $range[1] && $long <= $range[1] + $range[2] - 1) { // don't hose our stats if the database returns an unexpected extension $db_ext = in_array($range[0], $cnt_ext) || in_array($range[0], $gen_ext) ? $range[0] : self::legacy_ext($ext, $gen_ext); break; } } fclose($fp); return !empty($db_ext) ? $db_ext : self::legacy_ext($ext, $gen_ext); }
public static function useConfigurationFile($path) { if (is_readable($path)) { $config = json_decode(file_get_contents($path), true); self::$_cachedConfig = array_merge(self::$_cachedConfig, $config); } }
function recursiveRemDir($directory, $empty = FALSE) { if (substr($directory, -1) == '/') { $directory = substr($directory, 0, -1); } if (!file_exists($directory) || !is_dir($directory)) { return FALSE; } elseif (is_readable($directory)) { $handle = opendir($directory); while (FALSE !== ($item = readdir($handle))) { if ($item != '.' && $item != '..') { $path = $directory . '/' . $item; if (is_dir($path)) { Y::recursiveRemDir($path); } else { unlink($path); } } } closedir($handle); if ($empty == FALSE) { if (!rmdir($directory)) { return FALSE; } } } return TRUE; }
/** * Executes the check itselfs * * @return boolean */ public function check() { $this->isFound = file_exists($this->filename); $this->isReadable = is_readable($this->filename); $result = $this->isFound && $this->isReadable; return $result; }
/** * load(): defined by FileLoaderInterface. * * @see FileLoaderInterface::load() * @param string $locale * @param string $filename * @return TextDomain|null * @throws Exception\InvalidArgumentException */ public function load($locale, $filename) { $resolvedIncludePath = stream_resolve_include_path($filename); $fromIncludePath = $resolvedIncludePath !== false ? $resolvedIncludePath : $filename; if (!$fromIncludePath || !is_file($fromIncludePath) || !is_readable($fromIncludePath)) { throw new Exception\InvalidArgumentException(sprintf('Could not find or open file %s for reading', $filename)); } $messages = []; $iniReader = new IniReader(); $messagesNamespaced = $iniReader->fromFile($fromIncludePath); $list = $messagesNamespaced; if (isset($messagesNamespaced['translation'])) { $list = $messagesNamespaced['translation']; } foreach ($list as $message) { if (!is_array($message) || count($message) < 2) { throw new Exception\InvalidArgumentException('Each INI row must be an array with message and translation'); } if (isset($message['message']) && isset($message['translation'])) { $messages[$message['message']] = $message['translation']; continue; } $messages[array_shift($message)] = array_shift($message); } if (!is_array($messages)) { throw new Exception\InvalidArgumentException(sprintf('Expected an array, but received %s', gettype($messages))); } $textDomain = new TextDomain($messages); if (array_key_exists('plural', $messagesNamespaced) && isset($messagesNamespaced['plural']['plural_forms'])) { $textDomain->setPluralRule(PluralRule::fromString($messagesNamespaced['plural']['plural_forms'])); } return $textDomain; }