function scan_dir_files($logsdir, $wildcard, $subdir_wildcard, $write_dir, $dbhost, $dbport, $dbuser, $dbpass, $processid)
{
    if (!file_exists($logsdir)) {
        echo "Dir: " . $logsdir . " does not exist\n";
        exit(1);
    }
    $dirHandle = opendir("{$logsdir}");
    //List files in images directory
    while (($file = readdir($dirHandle)) !== false) {
        $file_list[] = $file;
    }
    closedir($dirHandle);
    $filtered_file_list = preg_grep($wildcard, $file_list);
    if (count($filtered_file_list) > 0) {
        $files_to_retrieve = filter_file_list($filtered_file_list, $processid, $dbhost, $dbport, $dbuser, $dbpass);
        foreach ($files_to_retrieve as $file) {
            echo "Copying " . $file . "\n";
            copy($logsdir . '/' . $file, $write_dir . '/' . $file);
        }
    } else {
        echo "No files to copy from the logs dir(" . $logsdir . ").\n";
    }
    $filtered_subdir_list = preg_grep($subdir_wildcard, $file_list);
    foreach ($filtered_subdir_list as $subdir) {
        if (is_dir($logsdir . "/" . $subdir)) {
            echo "Scanning " . $subdir . "\n";
            scan_dir_files($logsdir . "/" . $subdir, $wildcard, $subdir_wildcard, $write_dir, $dbhost, $dbport, $dbuser, $dbpass, $processid);
        }
    }
}
Example #2
0
 public function getBodyHighlighted($keywords = null, $wordsAround = 5, $tag = '<b>', $delimiter = ' &hellip; ', $maxMatchesNum = NULL)
 {
     if (!is_array($keywords)) {
         $keywords = preg_replace('/<.*>/Uu', '', $keywords);
         $keywords = preg_replace('/\\s+/u', ' ', $keywords);
         $keywords = preg_split('/\\s+/u', $keywords, -1, PREG_SPLIT_NO_EMPTY);
     }
     $tag_close = preg_replace('/<([a-z0-9]+).*>/isx', '</$1>', $tag);
     array_walk($keywords, 'preg_quote');
     $words = preg_split('/\\s+/u', strip_tags($this->data['BODY']), -1, PREG_SPLIT_NO_EMPTY);
     if (!($matched = preg_grep("/(" . join('|', $keywords) . ")/iu", $words))) {
         return false;
     }
     foreach ($matched as $i => $word) {
         $words[$i] = "{$tag}{$words[$i]}{$tag_close}";
     }
     $matches = array();
     $prev = -$wordsAround * 2;
     foreach ($matched as $i => $word) {
         if ($i - $wordsAround > $prev) {
             $start = $i - $wordsAround;
             if ($start < 0) {
                 $start = 0;
             }
             $matches[] = join(' ', array_slice($words, $start, $wordsAround * 2 + 1));
         }
         $prev = $i;
     }
     if ($maxMatchesNum) {
         $matches = array_slice($matches, 0, $maxMatchesNum);
     }
     return join($delimiter, $matches);
 }
 /**
  * {@inheritDoc}
  */
 public function getConfigTreeBuilder()
 {
     $treeBuilder = new TreeBuilder();
     $rootNode = $treeBuilder->root('hearsay_require_js');
     $rootNode->children()->scalarNode('require_js_src')->cannotBeEmpty()->defaultValue('//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.8/require.min.js')->end()->scalarNode('initialize_template')->cannotBeEmpty()->defaultValue('HearsayRequireJSBundle::initialize.html.twig')->end()->scalarNode('base_url')->defaultValue('js')->end()->scalarNode('base_dir')->isRequired()->cannotBeEmpty()->end()->arrayNode('paths')->defaultValue(array())->useAttributeAsKey('path')->normalizeKeys(false)->prototype('array')->beforeNormalization()->ifString()->then(function ($v) {
         return array('location' => $v);
     })->end()->children()->variableNode('location')->isRequired()->cannotBeEmpty()->validate()->always(function ($v) {
         if (!is_string($v) && !is_array($v)) {
             throw new InvalidTypeException();
         }
         $vs = !is_array($v) ? (array) $v : $v;
         $er = preg_grep('~\\.js$~', $vs);
         if ($er) {
             throw new InvalidPathException();
         }
         return $v;
     })->end()->end()->booleanNode('external')->cannotBeEmpty()->defaultFalse()->end()->end()->end()->end()->arrayNode('shim')->defaultValue(array())->useAttributeAsKey('name')->normalizeKeys(false)->prototype('array')->children()->arrayNode('deps')->defaultValue(array())->prototype('scalar')->end()->end()->scalarNode('exports')->end()->end()->end()->end()->arrayNode('options')->defaultValue(array())->useAttributeAsKey('name')->prototype('array')->beforeNormalization()->always(function ($v) {
         return array('value' => $v);
     })->end()->children()->variableNode('value')->isRequired()->end()->end()->end()->end()->arrayNode('optimizer')->children()->scalarNode('path')->isRequired()->cannotBeEmpty()->end()->booleanNode('hide_unoptimized_assets')->defaultFalse()->end()->booleanNode('declare_module_name')->defaultFalse()->end()->arrayNode('exclude')->defaultValue(array())->prototype('scalar')->end()->end()->arrayNode('modules')->defaultValue(array())->useAttributeAsKey('name')->prototype('array')->children()->scalarNode('name')->cannotBeEmpty()->end()->arrayNode('include')->defaultValue(array())->prototype('scalar')->end()->end()->arrayNode('exclude')->defaultValue(array())->prototype('scalar')->end()->end()->end()->end()->end()->arrayNode('options')->defaultValue(array())->useAttributeAsKey('name')->prototype('array')->beforeNormalization()->always(function ($v) {
         return array('value' => $v);
     })->end()->children()->variableNode('value')->isRequired()->end()->end()->end()->end()->scalarNode('timeout')->cannotBeEmpty()->validate()->ifTrue(function ($v) {
         return !(is_int($v) || ctype_digit($v));
     })->thenInvalid('Invalid number of seconds "%s"')->end()->defaultValue(60)->end()->scalarNode('almond_path')->defaultFalse()->end()->end()->end()->end();
     return $treeBuilder;
 }
Example #4
0
function df_browse_cache()
{
    global $db, $prefix;
    $cached = array('config' => array(), 'themes' => array(), 'modules' => array());
    $dir = str_replace(BASEDIR . 'cache/', '', glob(BASEDIR . 'cache/*.{php,inc}', GLOB_BRACE));
    # get all configuration files
    # core files should have its own formatting
    # all cached files should be lower case
    # modules configuration files should go under the module files list, not under core config list
    $pattern = array('/^(a_|bb_|config_|installer)([a-z\\-_]+[^\\.])\\.php/i');
    $replace = array('$1$2');
    $tmp = preg_replace($pattern, $replace, preg_grep('/^(a_|bb_|config_|installer_)/i', $dir));
    foreach ($tmp as $key => $file) {
        $GLOBALS['cpgtpl']->assign_block_vars('config', array('S_FILE' => $file));
    }
    $tmp = array_unique(preg_replace('/^tpl_([a-z0-9\\-_]+)_[a-z0-9\\-_].*+/i', '$1', preg_grep('/^tpl_/i', $dir)));
    foreach ($tmp as $key => $file) {
        $GLOBALS['cpgtpl']->assign_block_vars('themes', array('S_FILE' => $file));
    }
    //$Module = new Module;
    //$modules = implode('|', arrayRebuild($Module->list, array('title')));
    $modules = array();
    $result = $db->sql_query('SELECT title FROM ' . $prefix . '_modules');
    while ($row = $db->sql_fetchrow($result, SQL_NUM)) {
        $modules[] = $row[0];
    }
    $db->free_result($result);
    $modules = implode('|', $modules);
    $tmp = array_unique(preg_replace('/^(' . $modules . ')_.*/i', '$1', preg_grep('/^(' . $modules . ')/i', $dir)));
    foreach ($tmp as $key => $file) {
        $GLOBALS['cpgtpl']->assign_block_vars('modules', array('S_FILE' => $file, 'U_DEL' => URL::admin("cache&amp;module={$file}&amp;delete")));
    }
    unset($dir, $modules, $tmp);
}
 /**
  * Return all available sets
  * @return array
  */
 public function getAvailableSetFiles()
 {
     $strDir = TL_ROOT . '/web/bundles/contaoddadvancedclasses/sets/';
     $arrFiles = preg_grep('~\\.(json)$~', scandir($strDir));
     $arrFiles = array_combine($arrFiles, $arrFiles);
     return $arrFiles;
 }
Example #6
0
 function buildAttributes()
 {
     $this->fieldnames = array();
     $this->attributes = array();
     $email = null;
     // First let's find the email field.
     // First we'll check to see if any fields have been explicitly
     // flagged as email address fields.
     foreach ($this->table->fields(false, true) as $field) {
         if (@$field['email']) {
             $email = $field['name'];
             break;
         }
     }
     if (!isset($email)) {
         // Next lets see if any of the fields actually contain the word
         // email in the name
         $candidates = preg_grep('/(email)/i', array_keys($this->table->fields()));
         foreach ($candidates as $candidate) {
             if ($this->table->isChar($candidate)) {
                 $email = $candidate;
                 break;
             }
         }
     }
     if (isset($email)) {
         $field =& $this->table->getField($email);
         $this->attributes['email'] =& $field;
         unset($field);
         $this->fieldnames['email'] = $email;
     }
     return true;
 }
Example #7
0
function wpcf7_akismet_submitted_params()
{
    $params = array('author' => '', 'author_email' => '', 'author_url' => '');
    $content = '';
    $fes = wpcf7_scan_shortcode();
    foreach ($fes as $fe) {
        if (!isset($fe['name']) || !isset($_POST[$fe['name']])) {
            continue;
        }
        $value = $_POST[$fe['name']];
        if (is_array($value)) {
            $value = implode(', ', wpcf7_array_flatten($value));
        }
        $value = trim($value);
        $options = (array) $fe['options'];
        if (preg_grep('%^akismet:author$%', $options)) {
            $params['author'] = trim($params['author'] . ' ' . $value);
        } elseif (preg_grep('%^akismet:author_email$%', $options)) {
            if ('' == $params['author_email']) {
                $params['author_email'] = $value;
            }
        } elseif (preg_grep('%^akismet:author_url$%', $options)) {
            if ('' == $params['author_url']) {
                $params['author_url'] = $value;
            }
        }
        $content = trim($content . "\n\n" . $value);
    }
    $params = array_filter($params);
    if (!$params) {
        return false;
    }
    $params['content'] = $content;
    return $params;
}
Example #8
0
 /**
  * Handle the match
  */
 function handle($match, $state, $pos, &$handler)
 {
     switch ($state) {
         case DOKU_LEXER_ENTER:
             $data = strtolower(trim(substr($match, strpos($match, ' '), -1)));
             return array($state, $data);
         case DOKU_LEXER_UNMATCHED:
             // check if $match is a == header ==
             $headerMatch = preg_grep('/([ \\t]*={2,}[^\\n]+={2,}[ \\t]*(?=))/msSi', array($match));
             if (empty($headerMatch)) {
                 $handler->_addCall('cdata', array($match), $pos);
             } else {
                 // if it's a == header ==, use the core header() renderer
                 // (copied from core header() in inc/parser/handler.php)
                 $title = trim($match);
                 $level = 7 - strspn($title, '=');
                 if ($level < 1) {
                     $level = 1;
                 }
                 $title = trim($title, '=');
                 $title = trim($title);
                 $handler->_addCall('header', array($title, $level, $pos), $pos);
             }
             return false;
         case DOKU_LEXER_EXIT:
             return array($state, '');
     }
     return false;
 }
Example #9
0
 public static function fast_array_key_filter($array, $pattern)
 {
     $pattern = '/' . preg_quote($pattern) . '/';
     $keys = preg_grep($pattern, array_keys($array));
     $retArray = array_flip($keys);
     return array_intersect_key($array, $retArray);
 }
Example #10
0
/**
 * viewdirtree()
 *
 * @param mixed $dir
 * @param mixed $currentpath
 * @return
 */
function viewdirtree($dir, $currentpath)
{
    global $array_dirname, $global_config, $module_file;
    $pattern = !empty($dir) ? '/^(' . nv_preg_quote($dir) . ')\\/([^\\/]+)$/' : '/^([^\\/]+)$/';
    $_dirlist = preg_grep($pattern, array_keys($array_dirname));
    $content = '';
    foreach ($_dirlist as $_dir) {
        $check_allow_upload_dir = nv_check_allow_upload_dir($_dir);
        if (!empty($check_allow_upload_dir)) {
            $class_li = ($_dir == $currentpath or strpos($currentpath, $_dir . '/') !== false) ? 'open collapsable' : 'expandable';
            $style_color = $_dir == $currentpath ? ' style="color:red"' : '';
            $tree = array();
            $tree['class1'] = $class_li;
            $tree['class2'] = nv_set_dir_class($check_allow_upload_dir) . ' pos' . nv_string_to_filename($dir);
            $tree['style'] = $style_color;
            $tree['title'] = $_dir;
            $tree['titlepath'] = basename($_dir);
            $content2 = viewdirtree($_dir, $currentpath);
            $xtpl = new XTemplate('foldlist.tpl', NV_ROOTDIR . '/themes/' . $global_config['module_theme'] . '/modules/' . $module_file);
            $xtpl->assign('DIRTREE', $tree);
            if (empty($content2)) {
                $content2 = '<li class="hide">&nbsp;</li>';
            }
            if (!empty($content2)) {
                $xtpl->assign('TREE_CONTENT', $content2);
                $xtpl->parse('tree.tree_content');
            }
            $xtpl->parse('tree');
            $content .= $xtpl->text('tree');
        }
    }
    return $content;
}
Example #11
0
 public static function render_instance(BlockInstance $instance, $editing = false)
 {
     global $THEME;
     $configdata = $instance->get('configdata');
     if (!isset($configdata['license'])) {
         return '';
     }
     $licensetype = reset(preg_grep('/^([a-z\\-]+)$/', array($configdata['license'])));
     if (isset($configdata['version'])) {
         $licenseversion = get_string('version' . $configdata['version'], 'blocktype.creativecommons');
     } else {
         $licenseversion = get_string('version30', 'blocktype.creativecommons');
     }
     $licenseurl = "http://creativecommons.org/licenses/{$licensetype}/{$licenseversion}/";
     $view = $instance->get_view();
     $workname = '<span rel="dc:type" href="http://purl.org/dc/dcmitype/Text" property="dc:title">' . $view->display_title(true, false, false) . '</span>';
     $authorurl = $view->owner_link();
     $authorname = hsc($view->formatted_owner());
     $licensename = get_string('cclicensename', 'blocktype.creativecommons', get_string($licensetype, 'blocktype.creativecommons'), $licenseversion);
     $licenselink = '<a rel="license" href="' . $licenseurl . '">' . $licensename . '</a>';
     $attributionlink = '<a rel="cc:attributionURL" property="cc:attributionName" href="' . $authorurl . '">' . $authorname . '</a>';
     $licensestatement = get_string('cclicensestatement', 'blocktype.creativecommons', $workname, $attributionlink, $licenselink);
     $permissionlink = '<a rel="cc:morePermissions" href="' . $authorurl . '">' . $authorname . '</a>';
     $otherpermissions = get_string('otherpermissions', 'blocktype.creativecommons', $permissionlink);
     $smarty = smarty_core();
     $smarty->assign('licenseurl', $licenseurl);
     $smarty->assign('licenselogo', $THEME->get_image_url($licensetype . '-3_0', 'blocktype/creativecommons'));
     $smarty->assign('licensestatement', $licensestatement);
     $smarty->assign('otherpermissions', $otherpermissions);
     return $smarty->fetch('blocktype:creativecommons:statement.tpl');
 }
Example #12
0
 /**
  * Standard modular run function for OcCLE hooks.
  *
  * @param  array	The options with which the command was called
  * @param  array	The parameters with which the command was called
  * @param  object  A reference to the OcCLE filesystem object
  * @return array	Array of stdcommand, stdhtml, stdout, and stderr responses
  */
 function run($options, $parameters, &$occle_fs)
 {
     if (array_key_exists('h', $options) || array_key_exists('help', $options)) {
         return array('', do_command_help('grep', array('h'), array(true, true)), '', '');
     } else {
         if (!array_key_exists(0, $parameters)) {
             return array('', '', '', do_lang('MISSING_PARAM', '1', 'grep'));
         }
         if (!array_key_exists(1, $parameters)) {
             return array('', '', '', do_lang('MISSING_PARAM', '2', 'grep'));
         } else {
             $parameters[1] = $occle_fs->_pwd_to_array($parameters[1]);
         }
         if (!$occle_fs->_is_file($parameters[1])) {
             return array('', '', '', do_lang('NOT_A_FILE', '2'));
         }
         $_lines = unixify_line_format($occle_fs->read_file($parameters[1]));
         $lines = explode("\n", $_lines);
         if ($parameters[0] == '' || $parameters[0][0] != '#' && $parameters[0][0] != '/') {
             $parameters[0] = '#' . $parameters[0] . '#';
         }
         $matches = preg_grep($parameters[0], $lines);
         $output = '';
         foreach ($matches as $value) {
             $output .= $value . "\n";
         }
         return array('', '', $output, '');
     }
 }
Example #13
0
 /**
  * Unset the X-Pingback HTTP header.
  *
  * @hook
  *
  * @priority 20
  */
 public function template_redirect()
 {
     $headers = headers_list();
     if (preg_grep('/X-Pingback:/', $headers)) {
         header_remove('X-Pingback');
     }
 }
 public function send(SendGrid\Email $email)
 {
     $fields = $email->toWebFormat();
     $headers = array();
     if ("credentials" == $this->method) {
         $fields['api_user'] = $this->username;
         $fields['api_key'] = $this->password;
     } else {
         $headers = array('Authorization' => 'Bearer ' . $this->apikey);
     }
     $files = preg_grep('/files/', array_keys($fields));
     foreach ($files as $k => $file) {
         $fields[$file] = file_get_contents(substr($fields[$file], 1));
     }
     $data = array('body' => $fields);
     if (count($headers)) {
         $data['headers'] = $headers;
     }
     $response = wp_remote_post(self::URL, $data);
     if (!is_array($response) or !isset($response['body'])) {
         return false;
     }
     if ("success" == json_decode($response['body'])->message) {
         return true;
     }
     return false;
 }
 /**
  * Метод возвращает название банка и его идентификатор,
  * фильтруя по первым набранных символам
  *
  * @param Request $request
  * @return \Illuminate\Http\JsonResponse
  */
 public function getBanksAutoCompleteArray(Request $request)
 {
     $validator = Validator::make($request->all(), ['item' => 'required|string|max:255']);
     if ($validator->fails()) {
         $error = $validator->errors()->all();
         return response()->json(['error' => true, $error]);
     }
     $term = $request->get('item');
     $query = \DB::table('banks')->select('title', 'id')->where('publish', '=', 1)->get();
     /**
      * дальше идут манипуляции с объектом ответа
      * для того, чтобы представить его
      * в нужном формате, возможно
      * можно сделать оптимальнее
      */
     foreach ($query as $q) {
         $tempArray[] = $q->title;
     }
     // Шаблон рег. выражения
     $pattern = '/' . preg_quote($term) . '/iu';
     // ф-я возвращает массив совпадений
     $resultArrayBanks = preg_grep($pattern, $tempArray);
     $id = \DB::table('banks')->select('url')->where('publish', '=', 1)->whereIn('title', $resultArrayBanks)->get();
     $i = 0;
     foreach ($resultArrayBanks as $resultArrayBank) {
         $id[$i]->title = $resultArrayBank;
         $i++;
     }
     return \Response::json($id);
 }
Example #16
0
function grep_editlog($filename, $upload = false, $editlog = 'data/editlog')
{
    $keyname = $filename;
    if (substr($filename, -2) == ',v') {
        $keyname = substr($filename, 0, -2);
    }
    $expr = '^' . $keyname . "\t";
    $fp = fopen($editlog, 'r');
    if (!is_resource($fp)) {
        return false;
    }
    // chunk size
    $sz = 8192 * 10;
    $logs = array();
    while (!feof($fp)) {
        $chunk = fread($fp, $sz);
        if (isset($chunk[$sz - 1]) && $chunk[$sz - 1] != "\n") {
            while (($tmp = fgets($fp, 8192)) !== false && substr($tmp, -1) != "\n") {
            }
        }
        if (strstr("\n" . $chunk, "\n" . $keyname . "\t")) {
            $lines = explode("\n", $chunk);
            $matches = preg_grep('%' . $expr . '%', $lines);
            if ($upload) {
                $matches = preg_grep('%UPLOAD$%', $matches);
            } else {
                $matches = preg_grep('%UPLOAD$%', $matches, PREG_GREP_INVERT);
            }
            array_splice($logs, sizeof($logs), 0, $matches);
        }
    }
    fclose($fp);
    return $logs;
}
Example #17
0
 public function testIlNYAPasDeTablesRestantesApresUnDropDB()
 {
     global $config, $db;
     dropDB();
     $this->assertEquals(array(), preg_grep('/^' . str_replace('/', '\\/', $config['db']['prefix']) . '/', $db->fetchAll("show tables;", PDO::FETCH_COLUMN)));
     reinitDB();
 }
Example #18
0
 /**
  * Get the primary namespace for a plugin package.
  *
  * @param \Composer\Package\PackageInterface $package composer object
  * @return string The package's primary namespace.
  * @throws \RuntimeException When the package's primary namespace cannot be determined.
  */
 public function primaryNamespace($package)
 {
     $primaryNs = null;
     $autoLoad = $package->getAutoload();
     foreach ($autoLoad as $type => $pathMap) {
         if ($type !== 'psr-4') {
             continue;
         }
         $count = count($pathMap);
         if ($count === 1) {
             $primaryNs = key($pathMap);
             break;
         }
         $matches = preg_grep('#^(\\./)?src/?$#', $pathMap);
         if ($matches) {
             $primaryNs = key($matches);
             break;
         }
         foreach (['', '.'] as $path) {
             $key = array_search($path, $pathMap, true);
             if ($key !== false) {
                 $primaryNs = $key;
             }
         }
         break;
     }
     if (!$primaryNs) {
         throw new RuntimeException(sprintf("Unable to get primary namespace for package %s." . "\nEnsure you have added proper 'autoload' section to your plugin's config", $package->getName()));
     }
     return trim($primaryNs, '\\');
 }
Example #19
0
 public function execute()
 {
     $cmd = $this->executable;
     if ($this->args !== null) {
         $cmd .= " {$this->args}";
     }
     if ($this->config !== null) {
         $cmd .= " -c '{$this->config}'";
     }
     if ($this->directory !== null) {
         $dirPath = $this->phpci->buildPath . DIRECTORY_SEPARATOR . $this->directory;
         $cmd .= " -d '{$dirPath}'";
     }
     chdir($this->phpci->buildPath);
     $output = '';
     $status = true;
     exec($cmd, $output);
     if (count(preg_grep("/Success \\(/", $output)) == 0) {
         $status = false;
         $this->phpci->log($output);
     }
     if (count($output) == 0) {
         $status = false;
         $this->phpci->log("No test have been performed!");
     }
     return $status;
 }
Example #20
0
 /**
  * Runs the test case.
  * @return void
  */
 public function run($method = NULL)
 {
     $r = new \ReflectionObject($this);
     $methods = array_values(preg_grep(self::METHOD_PATTERN, array_map(function (\ReflectionMethod $rm) {
         return $rm->getName();
     }, $r->getMethods())));
     if (($method === NULL || $method === self::LIST_METHODS) && isset($_SERVER['argv'][1])) {
         if ($_SERVER['argv'][1] === self::LIST_METHODS) {
             Environment::$checkAssertions = FALSE;
             header('Content-Type: application/json');
             echo json_encode($methods);
             return;
         }
         $method = $_SERVER['argv'][1];
     }
     if ($method === NULL) {
         foreach ($methods as $method) {
             $this->runMethod($method);
         }
     } elseif (in_array($method, $methods)) {
         $this->runMethod($method);
     } else {
         throw new TestCaseException("Method '{$method}' does not exist or it is not a testing method.");
     }
 }
 public function __construct()
 {
     $confArray = parse_ini_file(dirname(__FILE__) . '/properties.ini.php', true);
     if (empty($confArray)) {
         throw new Exception("'check_script/properties.ini.php' is missing or the 'mccs.php' script is running under the wrong directory.");
     }
     $this->storeResultsDb = new StoreResultsDb();
     $this->getDataFromJson = new GetDataFromJson();
     $this->parallel = intval($confArray['check_script']['parallel']);
     $this->checkHistory = intval($confArray['check_script']['check_history']);
     $this->verbose = $confArray['check_script']['verbose'];
     $this->fedsDisabled = explode(',', $confArray['disabled_federation']['reg_auth']);
     $regexp = "/^sp_\\d/";
     $confArrayKeys = array_keys($confArray);
     $spsKeys[] = preg_grep($regexp, $confArrayKeys);
     foreach (array_values($spsKeys) as $value) {
         foreach (array_values($value) as $val) {
             $this->spEntityIDs[] = $confArray[$val]['entityID'];
             $this->spACSurls[] = $confArray[$val]['acs_url'];
         }
     }
     if (count($this->spEntityIDs) != count($this->spACSurls)) {
         throw new Exception("Configuration error. Please check properties.ini.");
     }
 }
Example #22
0
 /**
  * @param string $type
  *
  * @return array
  */
 private function getMessageByType($type)
 {
     $messages = [];
     $matches = preg_grep(sprintf('/^### %s/', $type), $this->content);
     if (!empty($matches)) {
         $start = key($matches) + 1;
         $remaining = array_slice($this->content, $start);
         $end = key(preg_grep(sprintf('/^##/', $type), $remaining));
         if ($end) {
             $end += $start;
         } else {
             $end = sizeof($this->content);
         }
         $lines = array_splice($this->content, $start, $end - $start);
         foreach ($lines as $line) {
             if (preg_match('/^[\\-](\\s?)(?<message>.*)/', $line, $matches)) {
                 $messages[] = $matches['message'];
             } else {
                 // Handle multi-line messages
                 end($messages);
                 $previous_message_index = key($messages);
                 if (isset($messages[$previous_message_index]) && $line) {
                     $messages[$previous_message_index] .= "\n" . $line;
                 }
             }
         }
     }
     return $messages;
 }
Example #23
0
 /**
  * Check for added admin menu's
  */
 public function __construct()
 {
     // Get loaded providers
     $providers = array_keys(\App::getLoadedProviders());
     // Get Tdt matches, but not core
     $packages = preg_grep('/^Tdt[\\\\](?!Core)/i', $providers);
     $menu = $this->core_menu;
     // Check for UI controller
     foreach ($packages as $package) {
         // Get package namespace
         $reflector = new \ReflectionClass($package);
         $namespace = $reflector->getNamespaceName();
         // Check for a UI controller
         $controller = $namespace . "\\Ui\\UiController";
         if (class_exists($controller)) {
             // Create controller instance
             $controller = \App::make($controller);
             $package_menu = @$controller->menu();
             // Check for added menu items
             if (!empty($package_menu)) {
                 $menu = array_merge($menu, $package_menu);
             }
             // Push for future use
             array_push($this->package_controllers, $controller);
         }
     }
     // Sort menu's
     usort($menu, function ($a, $b) {
         return $a['priority'] - $b['priority'];
     });
     // Share menu with views
     \View::share('menu', $menu);
 }
Example #24
0
 /**
  * {@inheritDoc}
  *
  * @throws \RuntimeException
  */
 public function getPackageBasePath(PackageInterface $package)
 {
     $extra = $package->getExtra();
     if (!empty($extra['installer-name'])) {
         return 'plugins/' . $extra['installer-name'];
     }
     $primaryNS = null;
     $autoLoad = $package->getAutoload();
     foreach ($autoLoad as $type => $pathMap) {
         if ($type !== 'psr-4') {
             continue;
         }
         $count = count($pathMap);
         if ($count === 1) {
             $primaryNS = key($pathMap);
             break;
         }
         $matches = preg_grep('#^(\\./)?src/?$#', $pathMap);
         if ($matches) {
             $primaryNS = key($matches);
             break;
         }
         foreach (['', '.'] as $path) {
             $key = array_search($path, $pathMap, true);
             if ($key !== false) {
                 $primaryNS = $key;
             }
         }
         break;
     }
     if (!$primaryNS) {
         throw new \RuntimeException('Unable to get CakePHP plugin name.');
     }
     return 'plugins/' . trim(str_replace('\\', '/', $primaryNS), '/');
 }
Example #25
0
 function reachable_squares()
 {
     #Array of square where the piece can move to
     $squares = array();
     $csq = $this->get_current_square();
     $hdist = abs(Board::horz_distance("a1", $csq));
     $vdist = abs(Board::vert_distance("a1", $csq));
     $dist = $hdist > $vdist ? $vdist : $hdist;
     $sq = Board::add_horz_distance($csq, -$dist);
     $sq = Board::add_vert_distance($sq, -$dist);
     $squares = array_merge($squares, Board::squares_in_line($csq, $sq));
     $hdist = abs(Board::horz_distance("h1", $csq));
     $vdist = abs(Board::vert_distance("h1", $csq));
     $dist = $hdist > $vdist ? $vdist : $hdist;
     $sq = Board::add_horz_distance($csq, $dist);
     $sq = Board::add_vert_distance($sq, -$dist);
     $squares = array_merge($squares, Board::squares_in_line($csq, $sq));
     $hdist = abs(Board::horz_distance("a8", $csq));
     $vdist = abs(Board::vert_distance("a8", $csq));
     $dist = $hdist > $vdist ? $vdist : $hdist;
     $sq = Board::add_horz_distance($csq, -$dist);
     $sq = Board::add_vert_distance($sq, $dist);
     $squares = array_merge($squares, Board::squares_in_line($csq, $sq));
     $hdist = abs(Board::horz_distance("h8", $csq));
     $vdist = abs(Board::vert_distance("h8", $csq));
     $dist = $hdist > $vdist ? $vdist : $hdist;
     $sq = Board::add_horz_distance($csq, $dist);
     $sq = Board::add_vert_distance($sq, $dist);
     $squares = array_merge($squares, Board::squares_in_line($csq, $sq));
     #Removes current position square
     $squares = preg_grep("/^{$csq}\$/", $squares, PREG_GREP_INVERT);
     return $squares;
 }
Example #26
0
 /**
  * Return an image path for a new image
  *
  * @param string  $dir    The upload dir.
  * @param integer $width  The image width.
  * @param integer $height The image height.
  * @param string  $type   The image type.
  *
  * @return string
  */
 public function image($dir, $width = null, $height = null, $type = '')
 {
     $originalWidth = $width ?: 'rand';
     $originalHeight = $height ?: 'rand';
     $rootDir = $this->container->get('kernel')->getRootDir() . '/../web';
     $existingImages = glob($rootDir . "/" . $dir . '/*.png');
     // print_r($existingImages);
     if ($matches = preg_grep("/" . $originalWidth . "-" . $originalHeight . ".png/", $existingImages)) {
         if (count($matches) > 30) {
             $image = array_rand($matches);
             return $image;
         }
     }
     $width = $width ?: rand(100, 300);
     $height = $height ?: rand(100, 300);
     $fileName = uniqid();
     $imageName = sprintf($rootDir . '/%s/%s-%s-%s.png', $dir, $fileName, $originalWidth, $originalHeight);
     $image = sprintf('http://%s/%d/%d/%s', 'lorempixel.com', $width, $height, $type);
     if (!is_dir(dirname($imageName))) {
         mkdir(dirname($imageName), 0777, true);
     }
     file_put_contents($imageName, file_get_contents($image));
     $imagePath = $dir . '/' . $fileName . '.png';
     return $imagePath;
 }
Example #27
0
 /**
  * Runs the test case.
  * @return void
  */
 public function run($method = NULL)
 {
     $r = new \ReflectionObject($this);
     $methods = array_values(preg_grep(self::METHOD_PATTERN, array_map(function (\ReflectionMethod $rm) {
         return $rm->getName();
     }, $r->getMethods())));
     if (substr($method, 0, 2) === '--') {
         // back compatibility
         $method = NULL;
     }
     if ($method === NULL && isset($_SERVER['argv']) && ($tmp = preg_filter('#(--method=)?([\\w-]+)$#Ai', '$2', $_SERVER['argv']))) {
         $method = reset($tmp);
         if ($method === self::LIST_METHODS) {
             Environment::$checkAssertions = FALSE;
             header('Content-Type: text/plain');
             echo '[' . implode(',', $methods) . ']';
             return;
         }
     }
     if ($method === NULL) {
         foreach ($methods as $method) {
             $this->runMethod($method);
         }
     } elseif (in_array($method, $methods, TRUE)) {
         $this->runMethod($method);
     } else {
         throw new TestCaseException("Method '{$method}' does not exist or it is not a testing method.");
     }
 }
Example #28
0
 /**
  * List of files in $dir whose filename has the format $format
  *
  * @return array Files
  */
 private static function getFiles($format, $dir, $preprocessed = false)
 {
     $list = preg_grep($format, scandir($dir));
     $files = array();
     // If current script under profiler, get it's output file name for exclusion
     if (function_exists('xdebug_get_profiler_filename') && ($profiler_filename = xdebug_get_profiler_filename()) !== false) {
         $selfFile = realpath($profiler_filename);
     }
     foreach ($list as $file) {
         $absoluteFilename = realpath($dir . '/' . $file);
         // Make sure that script never parses the profile currently being generated. (infinite loop)
         if (!empty($selfFile) && $selfFile === $absoluteFilename) {
             continue;
         }
         if (!$preprocessed) {
             // Exclude preprocessed files
             if (endsWith($absoluteFilename, Webgrind::$config->preprocessedSuffix)) {
                 continue;
             }
             // If set in config, exclude Webgrind files profiles
             $invokeUrl = self::getInvokeUrl($absoluteFilename);
             if (Webgrind::$config->hideWebgrindProfiles && startsWith($invokeUrl, WEBGRIND_ROOT)) {
                 continue;
             }
         }
         $files[$file] = array('absoluteFilename' => $absoluteFilename, 'mtime' => filemtime($absoluteFilename), 'preprocessed' => $preprocessed, 'filesize' => self::bytestostring(filesize($absoluteFilename)));
         if (!$preprocessed) {
             $files[$file]['invokeUrl'] = $invokeUrl;
         }
     }
     return $files;
 }
Example #29
0
 /**
  * init
  *
  * @param xxx $hotpot
  */
 function init($hotpot)
 {
     parent::init($hotpot);
     // replace standard jcloze.js with jgloss.js
     $this->javascripts = preg_grep('/jcloze.js/', $this->javascripts, PREG_GREP_INVERT);
     array_push($this->javascripts, 'mod/hotpot/attempt/hp/6/jcloze/jgloss.js');
 }
Example #30
0
 /**
  * Initialize this Database.
  *
  * @param      AgaviDatabaseManager The database manager of this instance.
  * @param      array                An assoc array of initialization params.
  *
  * @author     David Zülke <*****@*****.**>
  * @since      1.0.5
  */
 public function initialize(AgaviDatabaseManager $databaseManager, array $parameters = array())
 {
     parent::initialize($databaseManager, $parameters);
     if ($matches = preg_grep('/^\\s*SET\\s+NAMES\\b/i', (array) $this->getParameter('init_queries'))) {
         throw new AgaviDatabaseException(sprintf('Depending on your MySQL server configuration, it may not be safe to use "SET NAMES" to configure the connection encoding, as the underlying MySQL client library will not be aware of the changed character set. As a result, string escaping may be applied incorrectly, leading to potential attack vectors in combination with certain multi-byte character sets such as GBK or Big5.' . "\n\n" . 'Please remove the "%s" statement from the "init_queries" configuration parameter in databases.xml and use the configuration parameter "charset" instead.' . "\n\n" . 'The associated PHP bug ticket http://bugs.php.net/47802 contains further information (describes PDO, but the basic issue is the same).', $matches[0]));
     }
 }