Esempio n. 1
0
 /**
  * test fnmatch
  */
 public function testFnmatchExtended()
 {
     // Valid
     $this->assertTrue(fnmatch('/foo/bar/zoo', '/foo/bar/zoo'));
     $this->assertTrue(fnmatch('/foo/?ar/zoo', '/foo/bar/zoo'));
     $this->assertTrue(fnmatch('/foo/*/zoo', '/foo/bar/zoo'));
     $this->assertTrue(fnmatch('/foo/b*/zoo', '/foo/bar/zoo'));
     $this->assertTrue(fnmatch('/foo/bar*/zoo', '/foo/bar/zoo'));
     $this->assertTrue(fnmatch('/foo/bar/#', '/foo/bar/22'));
     $this->assertTrue(fnmatch('/foo/bar/?#', '/foo/bar/a22'));
     $this->assertTrue(fnmatch('/foo/**', '/foo/bar/zoo'));
     $this->assertTrue(fnmatch('/foo/**', '/foo/'));
     $this->assertTrue(fnmatch('/foo/**', '/foo'));
     $this->assertTrue(fnmatch('/foo/{bar,baz}/zoo', '/foo/bar/zoo'));
     $this->assertTrue(fnmatch('/foo/{12,89}/zoo', '/foo/12/zoo'));
     $this->assertTrue(fnmatch('/foo/[bc]ar/zoo', '/foo/bar/zoo'));
     $this->assertTrue(fnmatch('/foo/[a-c]ar/zoo', '/foo/bar/zoo'));
     // Invalid
     $this->assertFalse(fnmatch('/foo/qux/zoo', '/foo/bar/zoo'));
     $this->assertFalse(fnmatch('/foo/?a/zoo', '/foo/bar/zoo'));
     $this->assertFalse(fnmatch('/foo/*/zoo', '/foo/zoo'));
     $this->assertFalse(fnmatch('/foo/bar/#', '/foo/bar/n00'));
     $this->assertFalse(fnmatch('/foo/bar/?#', '/foo/bar/2'));
     $this->assertFalse(fnmatch('/foo/**', '/foobar/zoo'));
     $this->assertFalse(fnmatch('/foo/{bar,baz}/zoo', '/foo/{bar,baz}/zoo'));
     $this->assertFalse(fnmatch('/foo/{12,89}/zoo', '/foo/1289/zoo'));
     $this->assertFalse(fnmatch('/foo/[bc]ar/zoo', '/foo/dar/zoo'));
     $this->assertFalse(fnmatch('/foo/[d-q]ar/zoo', '/foo/bar/zoo'));
 }
Esempio n. 2
0
 public function run()
 {
     if (fnmatch('*cli*', php_sapi_name())) {
         $dir = Config::get('dir.schedules', APPLICATION_PATH . DS . 'schedules');
         if (is_dir($dir)) {
             Timer::start();
             Cli::show("Start of execution", 'COMMENT');
             $files = glob($dir . DS . '*.php');
             foreach ($files as $file) {
                 require_once $file;
                 $object = str_replace('.php', '', Arrays::last(explode(DS, $file)));
                 $class = 'Thin\\' . ucfirst(Inflector::camelize($object . '_schedule'));
                 $instance = lib('app')->make($class);
                 $methods = get_class_methods($instance);
                 Cli::show("Start schedule '{$object}'", 'COMMENT');
                 foreach ($methods as $method) {
                     $when = $this->getWhen($instance, $method);
                     $isDue = $this->isDue($object, $method, $when);
                     if (true === $isDue) {
                         Cli::show("Execution of {$object}->{$method}", 'INFO');
                         $instance->{$method}();
                     } else {
                         Cli::show("No need to execute {$object}->{$method}", 'QUESTION');
                     }
                 }
             }
             Cli::show("Time of execution [" . Timer::get() . " s.]", 'SUCCESS');
             Cli::show("end of execution", 'COMMENT');
         }
     }
 }
 protected function processFiles($path)
 {
     $files = glob($path . "/{,.}*", GLOB_BRACE);
     foreach ($files as $file) {
         $is_ok = true;
         if (preg_match('#/\\.\\.?$#', $file)) {
             $is_ok = false;
         } else {
             $short = preg_replace("#^{$this->root}/#", '', $file);
         }
         if ($is_ok) {
             foreach ($this->excludes as $exclude) {
                 if (fnmatch("{$this->root}/{$exclude}", $file)) {
                     $this->log("Ignore " . (is_dir($file) ? 'dir ' : 'file') . " {$short} \t\t[{$exclude}]");
                     $is_ok = false;
                     break;
                 }
             }
         }
         // for files that need to avoid exclude patterns -- only one so far
         if (!$is_ok) {
             if (preg_match('#/.htaccess$#', $file)) {
                 $this->log("Butnot " . (is_dir($file) ? 'dir ' : 'file') . " {$short}");
                 $is_ok = true;
             }
         }
         if ($is_ok) {
             if (++$this->count % $this->reopen_interval == $this->reopen_interval - 1) {
                 $this->reopen();
                 // to stop annoying file handle exhaustion bug
             }
             $is_dist = preg_match('#\\.dist$#', $file) == 1;
             if ($is_dist) {
                 $short = preg_replace('#\\.dist$#', '', $short);
             }
             if (is_dir($file)) {
                 $this->log("Adding dir  {$short}");
                 // double space makes it line up
                 if ($is_dist) {
                     throw new sfException("Cannot use .dist suffixed directories yet");
                 }
                 $this->zip->addEmptyDir($short);
                 $this->processFiles($file);
             } else {
                 $this->log("Adding file {$short}" . ($is_dist ? " from {$short}.dist" : ''));
                 $entry_exists = $this->zip->locateName($short) !== FALSE;
                 if ($entry_exists) {
                     if ($is_dist) {
                         $this->log("{$short} already exists -- replaced with {$short}.dist.", true);
                     } else {
                         throw new sfException("{$short} already exists in archive!");
                     }
                 }
                 if ($this->zip->addFile($file, $short) == FALSE) {
                     throw new sfException("Couldn't add -- probably too many open files");
                 }
             }
         }
     }
 }
Esempio n. 4
0
/**
 * Recursive remove dir
 *
 * @param string $path
 * @param array $exclude
 * @param bool $remove
 * @return void
 */
function w3_rmdir($path, $exclude = array(), $remove = true)
{
    $dir = @opendir($path);
    if ($dir) {
        while (($entry = @readdir($dir)) !== false) {
            if ($entry == '.' || $entry == '..') {
                continue;
            }
            foreach ($exclude as $mask) {
                if (fnmatch($mask, basename($entry))) {
                    continue 2;
                }
            }
            $full_path = $path . DIRECTORY_SEPARATOR . $entry;
            if (@is_dir($full_path)) {
                w3_rmdir($full_path, $exclude);
            } else {
                @unlink($full_path);
            }
        }
        @closedir($dir);
        if ($remove) {
            @rmdir($path);
        }
    }
}
Esempio n. 5
0
 public function ls()
 {
     $pattern = null;
     $dir = null;
     $args = func_get_args();
     $lst = array();
     switch (count($args)) {
         case 0:
             $dir = getcwd();
         case 1:
             $dir = $this->app->path($args[0]);
             break;
         case 2:
             $pattern = $args[0];
             $dir = $this->app->path($args[1]);
             break;
         default:
             return $lst;
     }
     if (!$dir || !file_exists($dir)) {
         return $lst;
     }
     foreach (new \DirectoryIterator($dir) as $file) {
         if ($file->isDot()) {
             continue;
         }
         if ($pattern && !fnmatch($pattern, $file->getBasename())) {
             continue;
         }
         $lst[] = new \SplFileObject($file->getRealPath());
     }
     return $lst;
 }
Esempio n. 6
0
function myglob($glob, $recursive = false)
{
    $pattern = basename($glob);
    $path = dirname($glob);
    if ($path == DIRECTORY_SEPARATOR) {
        return array(".");
    }
    if (!is_readable($path)) {
        return array();
    }
    $handle = opendir($path);
    if ($handle === false) {
        return array();
    }
    $list = array();
    while (false !== ($file = readdir($handle))) {
        if ($file == ".") {
            continue;
        }
        if ($file == "..") {
            continue;
        }
        if (is_file(dirname($glob) . DIRECTORY_SEPARATOR . $file) && fnmatch($pattern, $file)) {
            $list[] = $path . DIRECTORY_SEPARATOR . $file;
        }
        if (is_dir(dirname($glob) . DIRECTORY_SEPARATOR . $file) && $recursive) {
            $res = myglob(dirname($glob) . DIRECTORY_SEPARATOR . $file . DIRECTORY_SEPARATOR . basename($glob), $recursive);
            $list = array_merge($list, $res);
        }
    }
    closedir($handle);
    natsort($list);
    return $list;
}
 public function formatErrors(Validator $validator)
 {
     $repeatedAttendee = false;
     $emptyNames = false;
     $errors = $validator->errors()->all();
     foreach ($errors as $index => $error) {
         if (fnmatch('The selected user id.* is invalid.', $error)) {
             // Removes from array; can still iterate through array with foreach
             unset($errors[$index]);
             $repeatedAttendee = true;
         } else {
             if (fnmatch('The name.* field is required.', $error)) {
                 unset($errors[$index]);
                 $emptyNames = true;
             }
         }
     }
     // Pushes more descriptive error message onto array
     if ($repeatedAttendee) {
         array_push($errors, 'The same attendee has been entered in the attendance list more than once.');
     }
     if ($emptyNames) {
         array_push($errors, 'One of the names of the listed attendees has not been provided.');
     }
     return $errors;
 }
 /**
  * Handles request in order to authenticate.
  *
  * @param \AppserverIo\Psr\Servlet\Http\HttpServletRequestInterface  $servletRequest  The request instance
  * @param \AppserverIo\Psr\Servlet\Http\HttpServletResponseInterface $servletResponse The response instance
  *
  * @return boolean TRUE if the authentication has been successful, else FALSE
  *
  * @throws \Exception
  */
 public function handleRequest(HttpServletRequestInterface $servletRequest, HttpServletResponseInterface $servletResponse)
 {
     // iterate over all servlets and return the matching one
     /**
      * @var string $urlPattern
      * @var \AppserverIo\Http\Authentication\AuthenticationInterface $authenticationAdapter
      */
     foreach ($this->authenticationAdapters as $urlPattern => $authenticationAdapter) {
         // we'll match our URI against the URL pattern
         if (fnmatch($urlPattern, $servletRequest->getServletPath() . $servletRequest->getPathInfo())) {
             // the URI pattern matches, init the adapter and try to authenticate
             // check if auth header is not set in coming request headers
             if (!$servletRequest->hasHeader(Protocol::HEADER_AUTHORIZATION)) {
                 // send header for challenge authentication against client
                 $servletResponse->addHeader(HttpProtocol::HEADER_WWW_AUTHENTICATE, $authenticationAdapter->getAuthenticateHeader());
             }
             // initialize the adapter with the current request
             $authenticationAdapter->init($servletRequest->getHeader(HttpProtocol::HEADER_AUTHORIZATION), $servletRequest->getMethod());
             // try to authenticate the request
             $authenticated = $authenticationAdapter->authenticate();
             if (!$authenticated) {
                 // send header for challenge authentication against client
                 $servletResponse->addHeader(HttpProtocol::HEADER_WWW_AUTHENTICATE, $authenticationAdapter->getAuthenticateHeader());
             }
             return $authenticated;
         }
     }
     // we did not find an adapter for that URI pattern, no authentication required then
     return true;
 }
Esempio n. 9
0
 public function onRoute(MvcEvent $e)
 {
     $serviceManager = $e->getApplication()->getServiceManager();
     $routeMatchName = $e->getRouteMatch()->getMatchedRouteName();
     if (strpos($routeMatchName, '.rest.') !== false || strpos($routeMatchName, '.rpc.') !== false) {
         return;
     }
     $config = $serviceManager->get('Config');
     $identityGuards = $config['zource_guard']['identity'];
     $needsIdentity = null;
     foreach ($identityGuards as $guard => $needed) {
         if (fnmatch($guard, $routeMatchName)) {
             $needsIdentity = $needed;
             break;
         }
     }
     if ($needsIdentity === null) {
         throw new RuntimeException(sprintf('The identity guard "%s" has not been configured.', $routeMatchName));
     }
     if (!$needsIdentity) {
         return;
     }
     $authenticationService = $serviceManager->get('Zend\\Authentication\\AuthenticationService');
     if ($authenticationService->hasIdentity()) {
         return;
     }
     $returnUrl = $e->getRouter()->assemble([], ['name' => $routeMatchName, 'force_canonical' => true, 'query' => $e->getRequest()->getUri()->getQuery()]);
     $url = $e->getRouter()->assemble([], ['name' => 'login', 'query' => ['redir' => $returnUrl]]);
     $response = new Response();
     $response->setStatusCode(Response::STATUS_CODE_302);
     $response->getHeaders()->addHeaderLine('Location: ' . $url);
     return $response;
 }
Esempio n. 10
0
 public static function passes(\Modules\Models\Modules $module, $route = null, $options = array())
 {
     // if this ruleset is ignored, return null
     if (!in_array($module->{'assignment.routes.method'}, array('include', 'exclude'))) {
         return null;
     }
     if (is_null($route) || $route == '*') {
         return true;
     }
     $match = false;
     // get the list of urls to match $route against
     // if any of them match, return true
     $patterns = (array) $module->{'assignment.routes.list'};
     if (empty($patterns)) {
         $match = true;
     }
     foreach ($patterns as $pattern) {
         if (fnmatch($pattern, $route)) {
             $match = true;
         }
     }
     switch ($module->{'assignment.routes.method'}) {
         case "exclude":
             $passes = $match ? false : true;
             break;
         default:
             $passes = $match;
             break;
     }
     return $passes;
 }
Esempio n. 11
0
 /**
  * A safe empowered glob().
  *
  * Function glob() is prohibited on some server (probably in safe mode)
  * (Message "Warning: glob() has been disabled for security reasons in
  * (script) on line (line)") for security reasons as stated on:
  * http://seclists.org/fulldisclosure/2005/Sep/0001.html
  *
  * safe_glob() intends to replace glob() using readdir() & fnmatch() instead.
  * Supported flags: GLOB_MARK, GLOB_NOSORT, GLOB_ONLYDIR
  * Additional flags: GLOB_NODIR, GLOB_PATH, GLOB_NODOTS, GLOB_RECURSE
  * (not original glob() flags)
  *
  * @author BigueNique AT yahoo DOT ca
  * @updates
  * - 080324 Added support for additional flags: GLOB_NODIR, GLOB_PATH,
  *   GLOB_NODOTS, GLOB_RECURSE
  */
 function safe_glob($pattern, $flags = 0)
 {
     $split = explode('/', str_replace('\\', '/', $pattern));
     $mask = array_pop($split);
     $path = implode('/', $split);
     if (($dir = @opendir($path)) !== false) {
         $glob = array();
         while (($file = readdir($dir)) !== false) {
             // Recurse subdirectories (GLOB_RECURSE); speedup: no need to sort the intermediate results
             if ($flags & GLOB_RECURSE && is_dir($file) && !in_array($file, array('.', '..'))) {
                 $glob = array_merge($glob, array_prepend(safe_glob($path . '/' . $file . '/' . $mask, $flags | GLOB_NOSORT), $flags & GLOB_PATH ? '' : $file . '/'));
             }
             // Match file mask
             if (fnmatch($mask, $file)) {
                 if ((!($flags & GLOB_ONLYDIR) || is_dir($path . '/' . $file)) && (!($flags & GLOB_NODIR) || !is_dir($path . '/' . $file)) && (!($flags & GLOB_NODOTS) || !in_array($file, array('.', '..')))) {
                     $glob[] = ($flags & GLOB_PATH ? $path . '/' : '') . $file . ($flags & GLOB_MARK && is_dir($path . '/' . $file) ? '/' : '');
                 }
             }
         }
         closedir($dir);
         if (!($flags & GLOB_NOSORT)) {
             sort($glob);
         }
         return $glob;
     } else {
         return false;
     }
 }
 public static function uniquify($filePath)
 {
     //$filePath = '/www/sites/vladsch/database/migrations/2015_10_17_030224_*_create_license_agent_versions_table.php';
     $base_path = dirname($filePath);
     $filename = substr($filePath, strlen($base_path) + 1);
     $pos = strpos($filename, '*');
     $name = substr($filename, 0, $pos + 1);
     assert($pos !== false, "pattern '*' must exist in {$filePath}");
     $maxMatch = 0;
     if ($handle = opendir($base_path)) {
         while (false !== ($entry = readdir($handle))) {
             if (fnmatch($name, $entry, FNM_PERIOD)) {
                 // this one matches, lets extract the stuff matched by *
                 if (preg_match('/(\\d+)/', substr($entry, $pos + 1), $matches)) {
                     $found = $matches[1];
                     //print("Found $entry : value $found\n");
                     if ($maxMatch < $found) {
                         $maxMatch = intval($found);
                     }
                 }
             }
         }
         closedir($handle);
     }
     $maxMatch = sprintf("%02d", $maxMatch + 1);
     return str_replace('*', $maxMatch, $filePath);
 }
Esempio n. 13
0
 public function __construct($configFiles, $env = '@')
 {
     $this->config = new \stdClass();
     if (!is_array($configFiles)) {
         $configFiles = [$configFiles];
     }
     foreach ($configFiles as $configFile) {
         if (!file_exists($configFile)) {
             throw new ConfigException('Configuration file not found: ' . $configFile);
         }
         $config = parse_ini_file($configFile, true);
         if (!$config || !is_array($config['@'])) {
             throw new ConfigException('Configuration file failed to parse: ' . $configFile);
         }
         $this->addValues($config['@']);
         if (isset($config[$env])) {
             $config = [$env => $config[$env]];
         }
         foreach ($config as $key => $value) {
             if (fnmatch($key, $env)) {
                 $this->addValues($value);
             }
         }
     }
     $this->config = $this->recursiveArrayToObject($this->config);
 }
 /**
  * Load a client configuration as a service in the container. A client can use multiple servers
  *
  * @param ContainerInterface $container  The container
  * @param string             $alias      Alias of the client
  * @param array              $config     Base config of the client
  * @param array              $servers    List of available servers as describe in the config file
  * @param boolean            $baseEvents Register base events
  *
  * @throws InvalidConfigurationException
  * @return string the service name
  */
 protected function loadClient($container, $alias, array $config, array $servers, $baseEvents)
 {
     $usedServers = [];
     $events = $config['events'];
     $matchedServers = [];
     if ($config['servers'][0] == 'all') {
         // Use all servers
         $matchedServers = array_keys($servers);
     } else {
         // Use only declared servers
         foreach ($config['servers'] as $serverAlias) {
             // Named server
             if (array_key_exists($serverAlias, $servers)) {
                 $matchedServers[] = $serverAlias;
                 continue;
             }
             // Search matchning server config name
             $found = false;
             foreach (array_keys($servers) as $key) {
                 if (fnmatch($serverAlias, $key)) {
                     $matchedServers[] = $key;
                     $found = true;
                 }
             }
             // No server found
             if (!$found) {
                 throw new InvalidConfigurationException(sprintf('M6WebStatsd client %s used server %s which is not defined in the servers section', $alias, $serverAlias));
             }
         }
     }
     // Matched server congurations
     foreach ($matchedServers as $serverAlias) {
         $usedServers[] = ['address' => $servers[$serverAlias]['address'], 'port' => $servers[$serverAlias]['port']];
     }
     // Add the statsd client configured
     $serviceId = $alias == 'default' ? 'm6_statsd' : 'm6_statsd.' . $alias;
     $definition = new Definition('M6Web\\Bundle\\StatsdBundle\\Client\\Client');
     $definition->setScope(ContainerInterface::SCOPE_CONTAINER);
     $definition->addArgument($usedServers);
     if (isset($config['to_send_limit'])) {
         $definition->addMethodCall('setToSendLimit', array($config['to_send_limit']));
     }
     foreach ($events as $eventName => $eventConfig) {
         $definition->addTag('kernel.event_listener', ['event' => $eventName, 'method' => 'handleEvent']);
         $definition->addMethodCall('addEventToListen', [$eventName, $eventConfig]);
     }
     $container->setDefinition($serviceId, $definition);
     // Add the statsd client listener
     $serviceListenerId = $serviceId . '.listener';
     $definition = new Definition('M6Web\\Bundle\\StatsdBundle\\Statsd\\Listener');
     $definition->addArgument(new Reference($serviceId));
     $definition->addArgument(new Reference('event_dispatcher'));
     $definition->addTag('kernel.event_listener', ['event' => 'kernel.terminate', 'method' => 'onKernelTerminate', 'priority' => -100]);
     if ($baseEvents) {
         $definition->addTag('kernel.event_listener', ['event' => 'kernel.terminate', 'method' => 'onKernelTerminateEvents', 'priority' => 0]);
         $definition->addTag('kernel.event_listener', ['event' => 'kernel.exception', 'method' => 'onKernelException', 'priority' => 0]);
     }
     $container->setDefinition($serviceListenerId, $definition);
     return $serviceId;
 }
Esempio n. 15
0
 function _clean($path, $remove = false)
 {
     $dir = @opendir($path);
     if ($dir) {
         while (($entry = @readdir($dir)) !== false) {
             if ($entry == '.' || $entry == '..') {
                 continue;
             }
             if (substr($entry, -4) === '.old') {
                 continue;
             }
             foreach ($this->_exclude as $mask) {
                 if (fnmatch($mask, basename($entry))) {
                     continue 2;
                 }
             }
             $full_path = $path . DIRECTORY_SEPARATOR . $entry;
             if (@is_dir($full_path)) {
                 $this->_clean($full_path);
             } elseif (!$this->is_valid($full_path)) {
                 $old_entry_path = $full_path . '.old';
                 $this->processed_count++;
                 if (!@rename($full_path, $old_entry_path)) {
                     // if we can delete old entry - do second attempt to store in old-entry file
                     if (@unlink($old_entry_path)) {
                         @rename($full_path, $old_entry_path);
                     }
                 }
             }
         }
         @closedir($dir);
     }
 }
Esempio n. 16
0
 /**
  * listen to write event.
  */
 public static function write_hook($params)
 {
     if (\OCP\App::isEnabled('files_versions')) {
         $path = $params[\OC\Files\Filesystem::signal_param_path];
         $user = \OCP\User::getUser();
         $excluded = false;
         $excludes = \OCP\Config::getSystemValue('files_versions_excludes', NULL);
         if (isset($excludes) && array_key_exists($user, $excludes)) {
             $user_excludes = $excludes[$user];
             foreach ($user_excludes as &$pat) {
                 if (fnmatch($pat, $path)) {
                     // TODO: Not certain if logging of the files names and patters is allowed.
                     \OCP\Util::writeLog('files_versions', "write_hook: user='******', path='" . $path . "' matched to '" . $pat . "', excluding!", \OCP\Util::INFO);
                     $excluded = true;
                     break;
                 }
             }
             unset($pat);
         }
         if ($excluded) {
             return;
         }
         if ($path != '') {
             Storage::store($path);
         }
     }
 }
Esempio n. 17
0
 private function generate_table($tbl)
 {
     $conf = $this->tblconf[$tbl];
     $key = $conf['key'];
     unset($conf['key']);
     $indices = array();
     if (isset($conf['index'])) {
         $indices = explode(' ', $conf['index']);
         unset($conf['index']);
     }
     $k = $this->get_key_field($tbl);
     $sql = "CREATE TABLE `{$tbl}` ( `{$k}` " . $this->generate_type($key, true) . ', ';
     foreach ($conf as $key => $type) {
         if (fnmatch($key, 'field.*')) {
             $key = substr($key, 6);
             $sql .= "`{$key}` " . $this->generate_type($type, false) . ", ";
         }
     }
     $sql = substr($sql, 0, -2);
     $sql .= ' )';
     $this->conn->query($sql);
     foreach ($indices as $index) {
         $sql = "CREATE UNIQUE INDEX `{$tbl}" . "_{$index}` ON `{$tbl}`(`{$index}`)";
         $this->conn->query($sql);
     }
 }
 /**
  * @param  \Kbrw\RiakBundle\Model\Cluster\Cluster $cluster
  * @return array<string>
  */
 public function buckets($cluster, $ignore = "_rsid_*")
 {
     $bucketNames = array();
     $request = $this->getClient($cluster->getGuzzleClientProviderService(), $this->getConfig($cluster, "true"))->get();
     $this->logger->debug("[GET] '" . $request->getUrl() . "'");
     try {
         $response = $request->send();
         $extra = array("method" => "GET");
         if ($response->getStatusCode() === 200) {
             $ts = microtime(true);
             $content = json_decode($response->getBody(true));
             $extra["deserialization_time"] = microtime(true) - $ts;
             if (isset($content)) {
                 foreach ($content->{"buckets"} as $bucketName) {
                     if (!fnmatch($ignore, $bucketName)) {
                         $bucketNames[] = $bucketName;
                     }
                 }
             }
         }
         $this->logResponse($response, $extra);
     } catch (CurlException $e) {
         $this->logger->err("Riak is unavailable" . $e->getMessage());
         throw new RiakUnavailableException();
     } catch (\Exception $e) {
         $this->logger->err("Error while getting buckets" . $e->getMessage());
     }
     return $bucketNames;
 }
Esempio n. 19
0
 /**
  * @param string $event
  * @param array  $params
  * @param string $context
  */
 public function trigger($event, $params = [], $context = '')
 {
     if (empty($this->events[$event])) {
         return;
     }
     $queue = new \SplPriorityQueue();
     foreach ($this->events[$event] as $index => $action) {
         $queue->insert($index, $action['prio']);
     }
     $queue->top();
     while ($queue->valid()) {
         $index = $queue->current();
         if (!empty($context)) {
             $contexts = explode(',', $this->events[$event][$index]['contexts']);
             $current_context = false;
             foreach ($contexts as $route) {
                 if (fnmatch(trim($route), $context)) {
                     $current_context = true;
                     break;
                 }
             }
         } else {
             $current_context = true;
         }
         if ($current_context && is_callable($this->events[$event][$index]['fn'])) {
             if (call_user_func_array($this->events[$event][$index]['fn'], $params) === false) {
                 break;
             }
         }
         $queue->next();
     }
 }
Esempio n. 20
0
 public function sendFile($file)
 {
     $lastmod = filemtime($file);
     if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
         $ifmod = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
         if ($ifmod >= $lastmod) {
             header('Not Modified', true, 304);
             return;
         }
     }
     $ct = null;
     // Apply content type
     foreach (['*.css' => 'text/css', '*.js' => 'text/javascript'] as $ptn => $ct) {
         if (fnmatch($ptn, $file)) {
             $ctype = $ct;
         }
     }
     // If no match, try to determine
     if (empty($ctype)) {
         $ctype = mime_content_type($file);
     }
     // Set headers
     header('Content-Type: ' . $ctype);
     header('Content-Length: ' . filesize($file));
     header('Last-Modified: ' . gmdate('D, d M Y H:i:s \\G\\M\\T', $lastmod));
     $this->contentlength = filesize($file);
     readfile($file);
     return;
 }
Esempio n. 21
0
 public function __construct()
 {
     chdir(dirname(__DIR__));
     foreach ($this->binaries as $name => $path) {
         if (getenv(strtoupper("ion_{$name}_exec"))) {
             $this->binaries[$name] = getenv(strtoupper("ion_{$name}_exec"));
         }
     }
     set_exception_handler(function (\Throwable $exception) {
         $this->line(get_class($exception) . ": " . $exception->getMessage() . " in " . $exception->getFile() . ":" . $exception->getLine() . "\n" . $exception->getTraceAsString() . "\n");
         exit(1);
     });
     if ($this->isMacOS()) {
         if (fnmatch('1*.*.*', php_uname("r"))) {
             $this->cflags[] = "-arch x86_64 -mmacosx-version-min=10.5";
         } else {
             $this->cflags[] = "-arch x86_64 -arch ppc -arch ppc64";
         }
     }
     if ($this->isLinux()) {
         $this->nproc = intval(`nproc`) - 1;
     } elseif ($this->isMacOS() || $this->isBSD()) {
         $this->nproc = intval(`sysctl -n hw.ncpu`) - 1;
     }
     if ($this->nproc < 1) {
         $this->nproc = 1;
     }
     if (!PHP_ZTS) {
         //            $this->event_confugure[] = "--disable-thread-support";
     }
 }
Esempio n. 22
0
 public function scanForPartials()
 {
     $templates = [];
     $filespec = '/*';
     $basedir = $this->basedir . $filespec;
     $path[] = $basedir;
     while (count($path) != 0) {
         $search = array_shift($path);
         foreach (glob($search) as $item) {
             if (is_dir($item)) {
                 $path[] = $item . $filespec;
             } elseif (is_file($item)) {
                 if (fnmatch("_*.html", basename($item))) {
                     $templates[] = $item;
                 }
             }
         }
     }
     foreach ($templates as $template) {
         $namespace = $this->getNamespace($template);
         if (!array_key_exists($namespace, $this->_partials)) {
             $this->_partials[$namespace] = $this->extractPartial(file_get_contents($template));
         }
     }
 }
Esempio n. 23
0
 function isFileOK($file, $checkPatterns = false)
 {
     $fOK = true;
     $file = JFile::stripExt($file) . '.' . strtolower(JFile::getExt($file));
     if ($checkPatterns) {
         $fOK = false;
         foreach ($this->permittedFilePatterns as $p) {
             if (fnmatch($p, $file)) {
                 $fOK = true;
                 break;
             }
         }
     }
     if ($fOK) {
         foreach ($this->excludedDirs as $dir => $flag) {
             if (!$flag) {
                 continue;
             }
             if ($this->_inDir($file, $dir)) {
                 $fOK = false;
                 break;
             }
         }
     }
     if ($fOK) {
         // if the file was excluded
         if (isset($this->excludedFiles[$file]) && $this->excludedFiles[$file]) {
             $fOK = false;
         }
     }
     return $fOK;
 }
Esempio n. 24
0
 /**
  * @ignore
  */
 public static function fromFileScan($uPattern)
 {
     $tSep = quotemeta(DIRECTORY_SEPARATOR);
     $tPos = strrpos($uPattern, $tSep);
     if ($tSep !== '/' && $tPos === false) {
         $tSep = '/';
         $tPos = strrpos($uPattern, $tSep);
     }
     if ($tPos !== false) {
         $tPattern = substr($uPattern, $tPos + strlen($tSep));
         $tPath = substr($uPattern, 0, $tPos + strlen($tSep));
     } else {
         $tPath = $uPattern;
         $tPattern = "";
     }
     $tTemp = new static();
     $tHandle = new \DirectoryIterator($tPath);
     $tPatExists = strlen($uPattern) > 0;
     for (; $tHandle->valid(); $tHandle->next()) {
         if (!$tHandle->isFile()) {
             continue;
         }
         $tFile = $tHandle->current();
         if ($tPatExists && !fnmatch($tPattern, $tFile)) {
             continue;
         }
         $tTemp->add(simplexml_load_file($tPath . $tFile));
     }
     return $tTemp;
 }
Esempio n. 25
0
function array_matches($have, $should, $name = 'array')
{
    $ret = true;
    if (is_array($have)) {
        foreach ($should as $key => $value) {
            if (!array_key_exists($key, $have)) {
                log_msg('Missing: ' . $key);
                $ret = false;
            } else {
                if (is_array($value) && is_array($have[$key])) {
                    $ret &= array_matches($have[$key], $value);
                } else {
                    if (is_array($value) || is_array($have[$key])) {
                        log_msg('Type mismatch: ' . $key);
                        $ret = false;
                    } else {
                        if (!fnmatch($value, $have[$key])) {
                            log_msg("Failed comparison: {$key}={$have[$key]} (expected {$value})");
                            $ret = false;
                        }
                    }
                }
            }
        }
    } else {
        log_msg('Not an array: ' . $name);
        $ret = false;
    }
    return $ret;
}
Esempio n. 26
0
 public function config($subcommand)
 {
     $n = func_num_args();
     $subcommand = strtolower($subcommand);
     if ($subcommand === 'get') {
         if ($n !== 2) {
             throw new InvalidArgumentException('ERR Wrong number of arguments for CONFIG get');
         }
         $pattern = func_get_arg(1);
         $ret = array();
         foreach ($this->getConfig() as $name => $value) {
             if (fnmatch($pattern, $name)) {
                 $ret[] = $name;
                 $ret[] = $value;
             }
         }
         return $ret;
     } elseif ($subcommand === 'set') {
         if ($n !== 3) {
             throw new InvalidArgumentException('ERR Wrong number of arguments for CONFIG set');
         }
         $this->getConfig()->set(func_get_arg(1), func_get_arg(2));
         return true;
     }
     throw new InvalidArgumentException('ERR CONFIG subcommand must be one of GET, SET');
 }
Esempio n. 27
0
 public function trackHit()
 {
     // Don't track bot or crawler requests
     if (!Grav::instance()['browser']->isHuman()) {
         return;
     }
     /** @var Page $page */
     $page = Grav::instance()['page'];
     $relative_url = str_replace(Grav::instance()['base_url_relative'], '', $page->url());
     // Don't track error pages or pages that have no route
     if ($page->template() == 'error' || !$page->route()) {
         return;
     }
     // Make sure no 'widcard-style' ignore matches this url
     foreach ((array) $this->config->get('plugins.admin.popularity.ignore') as $ignore) {
         if (fnmatch($ignore, $relative_url)) {
             return;
         }
     }
     // initial creation if it doesn't exist
     if (!file_exists($this->data_path)) {
         mkdir($this->data_path);
         $this->flushPopularity();
     }
     // Update the data we want to track
     $this->updateDaily();
     $this->updateMonthly();
     $this->updateTotals($page->route());
     $this->updateVisitors(Grav::instance()['uri']->ip());
 }
Esempio n. 28
0
function php_get_browser($agent = NULL)
{
    $agent = $agent ? $agent : $_SERVER['HTTP_USER_AGENT'];
    $yu = array();
    $q_s = array("#\\.#", "#\\*#", "#\\?#");
    $q_r = array("\\.", ".*", ".?");
    $brows = parse_ini_file("php_browscap.ini", true);
    foreach ($brows as $k => $t) {
        if (fnmatch($k, $agent)) {
            $yu['browser_name_pattern'] = $k;
            $pat = preg_replace($q_s, $q_r, $k);
            $yu['browser_name_regex'] = strtolower("^{$pat}\$");
            foreach ($brows as $g => $r) {
                if ($t['Parent'] == $g) {
                    foreach ($brows as $a => $b) {
                        if ($r['Parent'] == $a) {
                            $yu = array_merge($yu, $b, $r, $t);
                            foreach ($yu as $d => $z) {
                                $l = strtolower($d);
                                $hu[$l] = $z;
                            }
                        }
                    }
                }
            }
            break;
        }
    }
    return $hu;
}
Esempio n. 29
0
 public function __construct($configFile, $env = '@')
 {
     $this->config = new \stdClass();
     if (!file_exists($configFile)) {
         throw new ConfigException('Configruation file not found: ' . $configFile);
     }
     $config = json_decode(file_get_contents($configFile));
     if ($config === null) {
         $msg = 'Configruation file failed to parse: ' . $configFile . ', with error: ' . json_last_error_msg();
         throw new ConfigException($msg);
     }
     if (!isset($config->{'@'})) {
         throw new ConfigException('Missing "@" section in parsed config: ' . $configFile);
     }
     // If modules is defined, copy to own variable
     if (isset($config->__modules__)) {
         $this->modules = $config->__modules__;
     }
     // Att default values to config
     $this->addValue('tmpConfig', $config->{'@'}, $this);
     if (isset($config->{$env})) {
         $config = [$env => $config->{$env}];
     }
     foreach ($config as $key => $value) {
         if (fnmatch($key, $env)) {
             $this->addValue('tmpConfig', $value, $this);
         }
     }
     $this->loadConfigModules();
     $this->addValue('config', $this->tmpConfig, $this);
     unset($this->tmpConfig);
 }
 /**
  * {@inheritdoc}
  */
 public function getFilesList($exclude = false)
 {
     $fileslist = array();
     $iterator = new \RecursiveDirectoryIterator($this->path, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::UNIX_PATHS);
     if ((is_string($exclude) || is_array($exclude)) && !empty($exclude)) {
         $iterator = new \RecursiveCallbackFilterIterator($iterator, function ($current) use($exclude) {
             if ($current->isDir()) {
                 return true;
             }
             $subpath = substr($current->getPathName(), strlen($this->path) + 1);
             foreach ((array) $exclude as $pattern) {
                 if ($pattern[0] == '!' ? !fnmatch(substr($pattern, 1), $subpath) : fnmatch($pattern, $subpath)) {
                     return false;
                 }
             }
             return true;
         });
     }
     $iterator = new \RecursiveIteratorIterator($iterator);
     foreach ($iterator as $file) {
         $pathname = substr($file->getPathName(), strlen($this->path));
         $filename = $file->getBasename();
         $dirname = dirname($pathname);
         $fileslist[$dirname][$filename] = substr($pathname, 1);
     }
     return $fileslist;
 }