getThemeAnalyzers() публичный статический Метод

public static getThemeAnalyzers ( $theme = null )
Пример #1
0
 public function generate($folder, $name = null)
 {
     $list = Analyzer::getThemeAnalyzers($this->themesToShow);
     $list = '"' . join('", "', $list) . '"';
     $sqlite = new \Sqlite3($folder . '/dump.sqlite');
     $sqlQuery = 'SELECT * FROM results WHERE analyzer in (' . $list . ')';
     $res = $sqlite->query($sqlQuery);
     $results = array();
     $titleCache = array();
     $severityCache = array();
     while ($row = $res->fetchArray(SQLITE3_ASSOC)) {
         if (!isset($results[$row['file']])) {
             $file = array('errors' => 0, 'warnings' => 0, 'fixable' => 0, 'filename' => $row['file'], 'messages' => array());
             $results[$row['file']] = $file;
         }
         if (!isset($titleCache[$row['analyzer']])) {
             $analyzer = Analyzer::getInstance($row['analyzer']);
             $titleCache[$row['analyzer']] = $analyzer->getDescription()->getName();
             $severityCache[$row['analyzer']] = $analyzer->getSeverity();
         }
         $message = array('type' => 'warning', 'source' => $row['analyzer'], 'severity' => $severityCache[$row['analyzer']], 'fixable' => 'fixable', 'message' => $titleCache[$row['analyzer']]);
         if (!isset($results[$row['file']]['messages'][$row['line']])) {
             $results[$row['file']]['messages'][$row['line']] = array(0 => array());
         }
         $results[$row['file']]['messages'][$row['line']][0][] = $message;
         ++$results[$row['file']]['warnings'];
         $this->count();
     }
     if ($name === null) {
         return json_encode($results);
     } else {
         file_put_contents($folder . '/' . $name . '.' . self::FILE_EXTENSION, json_encode($results));
         return true;
     }
 }
Пример #2
0
 public function __construct()
 {
     $this->config = Config::factory();
     $analyzers = Analyzer::getThemeAnalyzers($this->config->thema);
     $this->themesList = '("' . implode('", "', $analyzers) . '")';
     $this->sqlite = new \Sqlite3($this->config->projects_root . '/projects/' . $this->config->project . '/dump.sqlite', \SQLITE3_OPEN_READONLY);
     $this->datastore = new Datastore($this->config);
 }
Пример #3
0
 public function run()
 {
     $result = new \Stdclass();
     $analyzers = Analyzer::getThemeAnalyzers('OneFile');
     foreach ($analyzers as $analyzer) {
         $a = Analyzer::getInstance($analyzer);
         $results = $a->getArray();
         if (!empty($results)) {
             $result->{$a->getDescription()->getName()} = $results;
         }
     }
     file_put_contents($this->config->projects_root . '/projects/' . $project . '/onepage.json', json_encode($result));
 }
Пример #4
0
 public function generate($folder, $name = 'txt')
 {
     $config = Config::factory();
     $themes = $config->thema;
     $analyzers = array();
     foreach ($themes as $theme) {
         $analyzers[] = Analyzer::getThemeAnalyzers($theme);
     }
     $analyzers = call_user_func_array('array_merge', $analyzers);
     display(count($analyzers) . " analyzers\n");
     $res = $this->sqlite->query('SELECT distinct analyzer FROM results WHERE analyzer IN ("' . implode('","', $analyzers) . '") ORDER BY analyzer');
     $skeleton = array();
     while ($row = $res->fetchArray(SQLITE3_ASSOC)) {
         $skeleton[$row['analyzer']] = 0;
     }
     display(count($skeleton) . " distinct analyzers\n");
     $titles = array();
     foreach ($skeleton as $analyzer => $foo) {
         if ($analyzer == 'total') {
             continue;
         }
         $ini = parse_ini_file($this->config->dir_root . '/human/en/' . $analyzer . '.ini');
         $titles[$analyzer] = '"' . $ini['name'] . '"';
     }
     $all = array();
     $res = $this->sqlite->query('SELECT * FROM results WHERE analyzer IN ("' . implode('","', $analyzers) . '") ORDER BY file');
     $total = 0;
     while ($row = $res->fetchArray(SQLITE3_ASSOC)) {
         if (!isset($all[$row['file']])) {
             $all[$row['file']] = $skeleton;
         }
         ++$all[$row['file']][$row['analyzer']];
         ++$total;
     }
     display($total . " issues read\n");
     $txt = " \t" . implode("\t", array_values($titles)) . "\n";
     foreach ($all as $file => $values) {
         $txt .= "{$file}\t" . implode("\t", array_values($values)) . "\n";
     }
     file_put_contents($folder . '/' . $name . '.' . self::FILE_EXTENSION, $txt);
     display(count($all) . " issues reported\n");
     print "Upload " . $name . '.' . self::FILE_EXTENSION . " on http://amp.pharm.mssm.edu/clustergrammer/\n";
 }
Пример #5
0
    private function generateAppinfo()
    {
        $extensions = array('PHP' => array('Short tags' => 'Structures/ShortTags', 'Echo tags <?=' => 'Php/EchoTagUsage', 'Incompilable' => 'Php/Incompilable', '@ operator' => 'Structures/Noscream', 'Alternative syntax' => 'Php/AlternativeSyntax', 'Magic constants' => 'Constants/MagicConstantUsage', 'halt compiler' => 'Php/Haltcompiler', 'Assertions' => 'Php/AssertionUsage', 'Casting' => 'Php/CastingUsage', 'Resources' => 'Structures/ResourcesUsage', 'Nested Loops' => 'Structures/NestedLoops', 'Autoload' => 'Php/AutoloadUsage', 'inclusion' => 'Structures/IncludeUsage', 'include_once' => 'Structures/OnceUsage', 'Output control' => 'Extensions/Extob', 'Goto' => 'Php/Gotonames', 'Labels' => 'Php/Labelnames', 'Coalesce' => 'Php/Coalesce', 'Null Coalesce' => 'Php/NullCoalesce', 'File upload' => 'Structures/FileUploadUsage', 'Environnement Variables' => 'Php/UsesEnv'), 'Composer' => array('composer.json' => 'Composer/UseComposer', 'composer.lock' => 'Composer/UseComposerLock', 'composer autoload' => 'Composer/Autoload'), 'Web' => array('$_GET, _POST...' => 'Php/UseWeb', 'Apache' => 'Extensions/Extapache', 'Fast CGI' => 'Extensions/Extfpm', 'IIS' => 'Extensions/Extiis', 'NSAPI' => 'Extensions/Extnsapi'), 'CLI' => array('$argv, $argc' => 'Php/UseCli', 'CLI script' => 'Files/IsCliScript', 'Ncurses' => 'Extensions/Extncurses', 'Newt' => 'Extensions/Extnewt', 'Readline' => 'Extensions/Extreadline'), 'Composer Packages' => array(), 'Namespaces' => array('Namespaces' => 'Namespaces/Namespacesnames', 'Alias' => 'Namespaces/Alias'), 'Variables' => array('References' => 'Variables/References', 'Array' => 'Arrays/Arrayindex', 'Multidimensional arrays' => 'Arrays/Multidimensional', 'Array short syntax' => 'Arrays/ArrayNSUsage', 'List short syntax' => 'Structures/ListShortSyntax', 'Variable variables' => 'Variables/VariableVariables', 'PHP arrays' => 'Arrays/Phparrayindex', 'Globals' => 'Structures/GlobalUsage', 'PHP SuperGlobals' => 'Php/SuperGlobalUsage'), 'Functions' => array('Functions' => 'Functions/Functionnames', 'Redeclared PHP Functions' => 'Functions/RedeclaredPhpFunction', 'Closures' => 'Functions/Closures', 'Typehint' => 'Functions/Typehints', 'Scalar Typehint' => 'Php/ScalarTypehintUsage', 'Return Typehint' => 'Php/ReturnTypehintUsage', 'Nullable Typehint' => 'Php/UseNullableType', 'Static variables' => 'Variables/StaticVariables', 'Function dereferencing' => 'Structures/FunctionSubscripting', 'Constant scalar expression' => 'Structures/ConstantScalarExpression', '... usage' => 'Php/EllipsisUsage', 'func_get_args' => 'Functions/VariableArguments', 'Dynamic functioncall' => 'Functions/Dynamiccall', 'Recursive Functions' => 'Functions/Recursive', 'Generator Functions' => 'Functions/IsGenerator', 'Conditioned Function' => 'Functions/ConditionedFunctions'), 'Classes' => array('Classes' => 'Classes/Classnames', 'Anonymous Classes' => 'Classes/Anonymous', 'Class aliases' => 'Classes/ClassAliasUsage', 'Abstract classes' => 'Classes/Abstractclass', 'Interfaces' => 'Interfaces/Interfacenames', 'Traits' => 'Traits/Traitnames', 'Static properties' => 'Classes/StaticProperties', 'Static methods' => 'Classes/StaticMethods', 'Abstract methods' => 'Classes/Abstractmethods', 'Final methods' => 'Classes/Finalmethod', 'Class constants' => 'Classes/ConstantDefinition', 'Overwritten constants' => 'Classes/OverwrittenConst', 'Magic methods' => 'Classes/MagicMethod', 'Cloning' => 'Classes/CloningUsage', 'Dynamic class call' => 'Classes/VariableClasses', 'PHP 4 constructor' => 'Classes/OldStyleConstructor', 'Multiple class in one file' => 'Classes/MultipleClassesInFile'), 'Constants' => array('Constants' => 'Constants/ConstantUsage', 'Boolean' => 'Type/BooleanValue', 'Null' => 'Type/NullValue', 'Variable Constant' => 'Constants/VariableConstant', 'PHP constants' => 'Constants/PhpConstantUsage', 'PHP Magic constants' => 'Constants/MagicConstantUsage', 'Conditioned constant' => 'Constants/ConditionedConstants'), 'Numbers' => array('Integers' => 'Type/Integer', 'Hexadecimal' => 'Type/Hexadecimal', 'Octal' => 'Type/Octal', 'Binary' => 'Type/Binary', 'Real' => 'Type/Real'), 'Strings' => array('Heredoc' => 'Type/Heredoc', 'Nowdoc' => 'Type/Nowdoc'), 'Errors' => array('Throw exceptions' => 'Php/ThrowUsage', 'Try...Catch' => 'Php/TryCatchUsage', 'Multiple catch' => 'Structures/MultipleCatch', 'Multiple Exceptions' => 'Exceptions/MultipleCatch', 'Finally' => 'Structures/TryFinally', 'Trigger error' => 'Php/TriggerErrorUsage', 'Error messages' => 'Structures/ErrorMessages'), 'External systems' => array('System' => 'Structures/ShellUsage', 'Files' => 'Structures/FileUsage', 'LDAP' => 'Extensions/Extldap', 'mail' => 'Structures/MailUsage'), 'Extensions' => array('ext/amqp' => 'Extensions/Extamqp', 'ext/apache' => 'Extensions/Extapache', 'ext/apc' => 'Extensions/Extapc', 'ext/apcu' => 'Extensions/Extapcu', 'ext/array' => 'Extensions/Extarray', 'ext/ast' => 'Extensions/Extast', 'ext/bcmath' => 'Extensions/Extbcmath', 'ext/bzip2' => 'Extensions/Extbzip2', 'ext/cairo' => 'Extensions/Extcairo', 'ext/calendar' => 'Extensions/Extcalendar', 'ext/com' => 'Extensions/Extcom', 'ext/crypto' => 'Extensions/Extcrypto', 'ext/ctype' => 'Extensions/Extctype', 'ext/curl' => 'Extensions/Extcurl', 'ext/cyrus' => 'Extensions/Extcyrus', 'ext/date' => 'Extensions/Extdate', 'ext/dba' => 'Extensions/Extdba', 'ext/dio' => 'Extensions/Extdio', 'ext/dom' => 'Extensions/Extdom', 'ext/eaccelerator' => 'Extensions/Exteaccelerator', 'ext/enchant' => 'Extensions/Extenchant', 'ext/ereg' => 'Extensions/Extereg', 'ext/event' => 'Extensions/Extevent', 'ext/ev' => 'Extensions/Extev', 'ext/exif' => 'Extensions/Extexif', 'ext/expect' => 'Extensions/Extexpect', 'ext/fann' => 'Extensions/Extfann', 'ext/fdf' => 'Extensions/Extfdf', 'ext/ffmpeg' => 'Extensions/Extffmpeg', 'ext/file' => 'Extensions/Extfile', 'ext/fileinfo' => 'Extensions/Extfileinfo', 'ext/filter' => 'Extensions/Extfilter', 'ext/fpm' => 'Extensions/Extfpm', 'ext/ftp' => 'Extensions/Extftp', 'ext/gd' => 'Extensions/Extgd', 'ext/gearman' => 'Extensions/Extgearman', 'ext/geoip' => 'Extensions/Extgeoip', 'ext/gettext' => 'Extensions/Extgettext', 'ext/gmagick' => 'Extensions/Extgmagick', 'ext/gmp' => 'Extensions/Extgmp', 'ext/gnupg' => 'Extensions/Extgnupg', 'ext/hash' => 'Extensions/Exthash', 'ext/php_http' => 'Extensions/Exthttp', 'ext/ibase' => 'Extensions/Extibase', 'ext/iconv' => 'Extensions/Exticonv', 'ext/iis' => 'Extensions/Extiis', 'ext/imagick' => 'Extensions/Extimagick', 'ext/imap' => 'Extensions/Extimap', 'ext/info' => 'Extensions/Extinfo', 'ext/inotify' => 'Extensions/Extinotify', 'ext/intl' => 'Extensions/Extintl', 'ext/json' => 'Extensions/Extjson', 'ext/kdm5' => 'Extensions/Extkdm5', 'ext/ldap' => 'Extensions/Extldap', 'ext/libevent' => 'Extensions/Extlibevent', 'ext/libxml' => 'Extensions/Extlibxml', 'ext/mail' => 'Extensions/Extmail', 'ext/mailparse' => 'Extensions/Extmailparse', 'ext/math' => 'Extensions/Extmath', 'ext/mbstring' => 'Extensions/Extmbstring', 'ext/mcrypt' => 'Extensions/Extmcrypt', 'ext/memcache' => 'Extensions/Extmemcache', 'ext/memcached' => 'Extensions/Extmemcached', 'ext/ming' => 'Extensions/Extming', 'ext/mongo' => 'Extensions/Extmongo', 'ext/mssql' => 'Extensions/Extmssql', 'ext/mysql' => 'Extensions/Extmysql', 'ext/mysqli' => 'Extensions/Extmysqli', 'ext/ob' => 'Extensions/Extob', 'ext/oci8' => 'Extensions/Extoci8', 'ext/odbc' => 'Extensions/Extodbc', 'ext/opcache' => 'Extensions/Extopcache', 'ext/openssl' => 'Extensions/Extopenssl', 'ext/parsekit' => 'Extensions/Extparsekit', 'ext/pcntl' => 'Extensions/Extpcntl', 'ext/pcre' => 'Extensions/Extpcre', 'ext/pdo' => 'Extensions/Extpdo', 'ext/pgsql' => 'Extensions/Extpgsql', 'ext/phalcon' => 'Extensions/Extphalcon', 'ext/phar' => 'Extensions/Extphar', 'ext/posix' => 'Extensions/Extposix', 'ext/proctitle' => 'Extensions/Extproctitle', 'ext/pspell' => 'Extensions/Extpspell', 'ext/readline' => 'Extensions/Extreadline', 'ext/recode' => 'Extensions/Extrecode', 'ext/redis' => 'Extensions/Extredis', 'ext/reflexion' => 'Extensions/Extreflection', 'ext/runkit' => 'Extensions/Extrunkit', 'ext/sem' => 'Extensions/Extsem', 'ext/session' => 'Extensions/Extsession', 'ext/shmop' => 'Extensions/Extshmop', 'ext/simplexml' => 'Extensions/Extsimplexml', 'ext/snmp' => 'Extensions/Extsnmp', 'ext/soap' => 'Extensions/Extsoap', 'ext/sockets' => 'Extensions/Extsockets', 'ext/spl' => 'Extensions/Extspl', 'ext/sqlite' => 'Extensions/Extsqlite', 'ext/sqlite3' => 'Extensions/Extsqlite3', 'ext/sqlsrv' => 'Extensions/Extsqlsrv', 'ext/ssh2' => 'Extensions/Extssh2', 'ext/standard' => 'Extensions/Extstandard', 'ext/tidy' => 'Extensions/Exttidy', 'ext/tokenizer' => 'Extensions/Exttokenizer', 'ext/trader' => 'Extensions/Exttrader', 'ext/wddx' => 'Extensions/Extwddx', 'ext/wikidiff2' => 'Extensions/Extwikidiff2', 'ext/wincache' => 'Extensions/Extwincache', 'ext/xcache' => 'Extensions/Extxcache', 'ext/xdebug' => 'Extensions/Extxdebug', 'ext/xdiff' => 'Extensions/Extxdiff', 'ext/xhprof' => 'Extensions/Extxhprof', 'ext/xml' => 'Extensions/Extxml', 'ext/xmlreader' => 'Extensions/Extxmlreader', 'ext/xmlrpc' => 'Extensions/Extxmlrpc', 'ext/xmlwriter' => 'Extensions/Extxmlwriter', 'ext/xsl' => 'Extensions/Extxsl', 'ext/yaml' => 'Extensions/Extyaml', 'ext/yis' => 'Extensions/Extyis', 'ext/zip' => 'Extensions/Extzip', 'ext/zlib' => 'Extensions/Extzlib', 'ext/zmq' => 'Extensions/Extzmq'));
        // collecting information for Extensions
        $themed = Analyzer::getThemeAnalyzers('Appinfo');
        $res = $this->sqlite->query('SELECT analyzer, count FROM resultsCounts WHERE analyzer IN ("' . implode('", "', $themed) . '")');
        $sources = array();
        while ($row = $res->fetchArray(\SQLITE3_ASSOC)) {
            $sources[$row['analyzer']] = $row['count'];
        }
        $data = array();
        foreach ($extensions as $section => $hash) {
            $data[$section] = array();
            foreach ($hash as $name => $ext) {
                if (!isset($sources[$ext])) {
                    $data[$section][$name] = self::NOT_RUN;
                    continue;
                }
                if (!in_array($ext, $themed)) {
                    $data[$section][$name] = self::NOT_RUN;
                    continue;
                }
                // incompatible
                if ($sources[$ext] == Analyzer::CONFIGURATION_INCOMPATIBLE) {
                    $data[$section][$name] = self::INCOMPATIBLE;
                    continue;
                }
                if ($sources[$ext] == Analyzer::VERSION_INCOMPATIBLE) {
                    $data[$section][$name] = self::INCOMPATIBLE;
                    continue;
                }
                $data[$section][$name] = $sources[$ext] > 0 ? self::YES : self::NO;
            }
            if ($section == 'Extensions') {
                $list = $data[$section];
                uksort($data[$section], function ($ka, $kb) use($list) {
                    if ($list[$ka] == $list[$kb]) {
                        if ($ka > $kb) {
                            return 1;
                        }
                        if ($ka == $kb) {
                            return 0;
                        }
                        if ($ka > $kb) {
                            return -1;
                        }
                    } else {
                        return $list[$ka] == self::YES ? -1 : 1;
                    }
                });
            }
        }
        // collecting information for Composer
        if (isset($sources['Composer/PackagesNames'])) {
            $data['Composer Packages'] = array();
            $res = $this->dump->query('SELECT fullcode FROM results WHERE analyzer = "Composer/PackagesNames"');
            while ($row = $res->fetchArray(\SQLITE3_ASSOC)) {
                $data['Composer Packages'][] = $row['fullcode'];
            }
        } else {
            unset($data['Composer Packages']);
        }
        $list = array();
        foreach ($data as $section => $points) {
            $listPoint = array();
            foreach ($points as $point => $status) {
                $listPoint[] = '<li>' . $this->makeIcon($status) . '&nbsp;' . $point . '</li>';
            }
            $listPoint = implode("\n", $listPoint);
            $list[] = <<<HTML
        <ul class="sidebar-menu">
          <li class="treeview">
            <a href="#"><i class="fa fa-certificate"></i> <span>{$section}</span><i class="fa fa-angle-left pull-right"></i></a>
            <ul class="treeview-menu">
                {$listPoint}
            </ul>
          </li>
        </ul>
HTML;
        }
        $list = implode("\n", $list);
        $list = <<<HTML
        <div class="sidebar">
{$list}
        </div>
HTML;
        $html = $this->getBasedPage('appinfo');
        $html = $this->injectBloc($html, 'APPINFO', $list);
        $this->putBasedPage('appinfo', $html);
    }
Пример #6
0
    public function generate($folder, $name = null)
    {
        $themed = Analyzer::getThemeAnalyzers('Appinfo');
        $res = $this->sqlite->query('SELECT analyzer, count FROM resultsCounts WHERE analyzer IN ("' . implode('", "', $themed) . '")');
        $sources = array();
        while ($row = $res->fetchArray(\SQLITE3_ASSOC)) {
            $sources[$row['analyzer']] = $row['count'];
        }
        $configureDirectives = json_decode(file_get_contents($this->config->dir_root . '/data/configure.json'));
        // preparing the list of PHP extensions to compile PHP with
        $return = array(<<<TEXT
;;;;;;;;;;;;;;;;;;;;;;;;
; PHP configure list   ;
;;;;;;;;;;;;;;;;;;;;;;;;

TEXT
, './configure');
        $pecl = array();
        foreach ($configureDirectives as $ext => $configure) {
            if (isset($sources[$configure->analysis])) {
                if (!empty($configure->activate) && $sources[$configure->analysis] != 0) {
                    $return[] = ' ' . $configure->activate;
                    if (!empty($configure->others)) {
                        $return[] = "   " . join("\n    ", $configure->others);
                    }
                    if (!empty($configure->pecl)) {
                        $pecl[] = '#pecl install ' . basename($configure->pecl) . ' (' . $configure->pecl . ')';
                    }
                } elseif (!empty($configure->deactivate) && $sources[$configure->analysis] == 0) {
                    $return[] = ' ' . $configure->deactivate;
                }
            } else {
                display("Missing {$configure->analysis} in sqlite\n");
            }
        }
        $return = array_merge($return, array('', '; For debug purposes', ';--enable-dtrace', ';--disable-phpdbg', '', ';--enable-zend-signals', ';--disable-opcache'));
        $final = '';
        if (!empty($pecl)) {
            $c = count($pecl);
            $final .= "# install " . ($c === 1 ? 'one' : $c) . " extra extension" . ($c === 1 ? '' : 's') . "\n";
            $final .= implode("\n", $pecl) . "\n\n";
        }
        $final .= implode("\n", $return);
        $shouldDisableFunctions = json_decode(file_get_contents($this->config->dir_root . '/data/shouldDisableFunction.json'));
        $functionsList = array();
        $classesList = array();
        foreach ((array) $shouldDisableFunctions as $ext => $toDisable) {
            if ($sources[$ext] == 0) {
                if (isset($toDisable->functions)) {
                    $functionsList[] = $toDisable->functions;
                }
                if (isset($toDisable->classes)) {
                    $classesList[] = $toDisable->classes;
                }
            }
        }
        if (empty($functionsList)) {
            $functionsList = '';
        } else {
            $functionsList = call_user_func_array('array_merge', $functionsList);
            $functionsList = join(',', $functionsList);
        }
        if (empty($classesList)) {
            $classesList = '';
        } else {
            $classesList = call_user_func_array('array_merge', $classesList);
            $classesList = join(',', $classesList);
        }
        // preparing the list of PHP directives to review before using this application
        $directives = array('standard', 'bcmath', 'date', 'file', 'fileupload', 'mail', 'ob', 'env', 'apc', 'amqp', 'apache', 'assertion', 'curl', 'dba', 'filter', 'image', 'intl', 'ldap', 'mbstring', 'opcache', 'openssl', 'pcre', 'pdo', 'pgsql', 'session', 'sqlite', 'sqlite3', 'com', 'eaccelerator', 'geoip', 'ibase', 'imagick', 'mailparse', 'mongo', 'trader', 'wincache', 'xcache');
        $data = array();
        $res = $this->sqlite->query(<<<SQL
SELECT analyzer FROM resultsCounts 
    WHERE ( analyzer LIKE "Extensions/Ext%" OR 
            analyzer IN ("Structures/FileUploadUsage", "Php/UsesEnv"))
        AND count > 0
SQL
);
        while ($row = $res->fetchArray(\SQLITE3_ASSOC)) {
            if ($row['analyzer'] == 'Structures/FileUploadUsage') {
                $data['File Upload'] = (array) json_decode(file_get_contents($this->config->dir_root . '/data/directives/fileupload.json'));
            } elseif ($row['analyzer'] == 'Php/UsesEnv') {
                $data['Environnement'] = (array) json_decode(file_get_contents($this->config->dir_root . '/data/directives/env.json'));
            } else {
                $ext = substr($row['analyzer'], 14);
                if (in_array($ext, $directives)) {
                    $data[$ext] = (array) json_decode(file_get_contents($this->config->dir_root . '/data/directives/' . $ext . '.json'));
                }
            }
        }
        $directives = <<<TEXT

;;;;;;;;;;;;;;;;;;;;;;;;;;
; Suggestion for php.ini ;
;;;;;;;;;;;;;;;;;;;;;;;;;;

; The directives below are selected based on the code provided. 
; They only cover the related directives that may have an impact on the code
;
; The list may not be exhaustive
; The suggested values are not recommendations, and should be reviewed and adapted
;



TEXT;
        foreach ($data as $section => $details) {
            $directives .= "[{$section}]\n";
            foreach ((array) $details as $detail) {
                if ($detail->name == 'Extra configurations') {
                    preg_match('#(http://[^"]+?)"#is', $detail->documentation, $url);
                    $directives .= "; More information about {$section} : \n;{$url['1']}\n\n";
                } else {
                    $documentation = wordwrap(' ' . $detail->documentation, 80, "\n; ");
                    $directives .= ";{$documentation}\n{$detail->name} = {$detail->suggested}\n\n";
                }
            }
            if ($section === 'standard') {
                $directives .= ";{$documentation}\ndisable_functions = {$functionsList}\ndisable_classes = {$classesList}\n\n";
            }
            $directives .= "\n\n";
        }
        $final .= "\n\n" . $directives;
        if ($name === null) {
            return $final;
        } else {
            file_put_contents($folder . '/' . $name . '.' . self::FILE_EXTENSION, $final);
            return true;
        }
    }
Пример #7
0
    public function run()
    {
        $project = $this->config->project;
        if ($project == 'default') {
            throw new ProjectNeeded($project);
        }
        if (!file_exists($this->config->projects_root . '/projects/' . $project)) {
            throw new NoSuchProject($project);
        }
        $this->checkTokenLimit();
        $begin = microtime(true);
        Analyzer::$gremlinStatic = $this->gremlin;
        // Take this before we clean it up
        $rows = $this->datastore->getRow('analyzed');
        $analyzed = array();
        foreach ($rows as $row) {
            $analyzed[$row['analyzer']] = $row['counts'];
        }
        if ($this->config->program !== null) {
            $analyzer = $this->config->program;
            if (Analyzer::getClass($analyzer)) {
                $analyzers_class = array($analyzer);
            } else {
                $r = Analyzer::getSuggestionClass($analyzer);
                if (count($r) > 0) {
                    echo 'did you mean : ', implode(', ', str_replace('_', '/', $r)), "\n";
                }
                throw new NoSuchAnalyzer($analyzer);
            }
        } elseif (is_string($this->config->thema)) {
            $thema = $this->config->thema;
            if (!($analyzers_class = Analyzer::getThemeAnalyzers($thema))) {
                throw new NoSuchAnalyzer($thema);
            }
            $this->datastore->addRow('hash', array($this->config->thema => count($analyzers_class)));
        } else {
            die("Usage :php exakat analyze -T <\"Thema\"> -p <project>\n\nphp exakat analyze -P <One/rule> -p <project>\n");
        }
        $this->log->log("Analyzing project {$project}");
        $this->log->log("Runnable analyzers\t" . count($analyzers_class));
        if ($this->config->noDependencies) {
            $dependencies2 = $analyzers_class;
        } else {
            $dependencies = array();
            $dependencies2 = array();
            foreach ($analyzers_class as $a) {
                $d = Analyzer::getInstance($a);
                $this->configName = str_replace('/', '_', $a);
                $d = $d->dependsOn();
                if (!is_array($d)) {
                    throw new DependsOnMustReturnArray(get_class($this));
                }
                if (empty($d)) {
                    $dependencies2[] = $a;
                } else {
                    $diff = array_diff($d, $dependencies2);
                    if (empty($diff)) {
                        $dependencies2[] = $a;
                    } else {
                        $dependencies[$a] = $diff;
                    }
                }
            }
            $c = count($dependencies) + 1;
            while (!empty($dependencies) && $c > count($dependencies)) {
                $c = count($dependencies);
                foreach ($dependencies as $a => &$d) {
                    $diff = array_diff($d, $dependencies2);
                    foreach ($diff as $k => $v) {
                        if (!isset($dependencies[$v])) {
                            $x = Analyzer::getInstance($v);
                            if ($x === null) {
                                display("No such dependency as '{$v}'. Ignoring\n");
                                continue;
                            }
                            $dep = $x->dependsOn();
                            if (count($dep) == 0) {
                                $dependencies2[] = $v;
                                ++$c;
                            } else {
                                $dependencies[$v] = $dep;
                                $c += count($dep) + 1;
                            }
                        } elseif (count($dependencies[$v]) == 0) {
                            $dependencies2[] = $v;
                            unset($diff[$k]);
                        }
                    }
                    if (empty($diff)) {
                        $dependencies2[] = $a;
                        unset($dependencies[$a]);
                    } else {
                        $d = $diff;
                    }
                }
                unset($d);
            }
            if (!empty($dependencies)) {
                die("Dependencies depending on each other : can't finalize. Aborting\n" . print_r($dependencies, true));
            }
        }
        $total_results = 0;
        $Php = new Phpexec($this->config->version);
        $progressBar = new Progressbar(0, count($dependencies2) + 1, exec('tput cols'));
        foreach ($dependencies2 as $analyzer_class) {
            if (!$this->config->verbose && !$this->config->quiet) {
                echo $progressBar->advance();
            }
            $begin = microtime(true);
            $analyzer = Analyzer::getInstance($analyzer_class);
            $this->configName = str_replace(array('/', '\\', 'Exakat\\Analyzer\\'), array('_', '_', ''), $analyzer_class);
            if ($this->config->noRefresh === true && isset($analyzed[$analyzer_class])) {
                display("{$analyzer_class} is already processed\n");
                continue 1;
            }
            $analyzer->init();
            if (!$analyzer->checkPhpVersion($this->config->phpversion)) {
                $analyzerQuoted = str_replace('\\', '\\\\', get_class($analyzer));
                $analyzer = str_replace('\\', '\\\\', $analyzer_class);
                $query = <<<GREMLIN
result = g.addV('Noresult').property('code',                        'Not Compatible With PhpVersion')
                           .property('fullcode',                    'Not Compatible With PhpVersion')
                           .property('virtual',                      true)
                           .property('notCompatibleWithPhpVersion', '{$this->config->phpversion}')
                           .property('token',                       'T_INCOMPATIBLE');

g.addV('Analysis').property('analyzer', '{$analyzerQuoted}').addE('ANALYZED').to(result);

GREMLIN;
                $this->gremlin->query($query);
                $this->datastore->addRow('analyzed', array($analyzer_class => -2));
                display("{$analyzer} is not compatible with PHP version {$this->config->phpversion}. Ignoring\n");
            } elseif (!$analyzer->checkPhpConfiguration($Php)) {
                $analyzerQuoted = str_replace('\\', '\\\\', get_class($analyzer));
                $analyzer = str_replace('\\', '\\\\', $analyzer_class);
                $query = <<<GREMLIN
result = g.addV('Noresult').property('code',                              'Not Compatible With Configuration')
                           .property('fullcode',                          'Not Compatible With Configuration')
                           .property('virtual',                            true)
                           .property('notCompatibleWithPhpConfiguration', '{$this->config->phpversion}')
                           .property('token',                             'T_INCOMPATIBLE');

index = g.addV('Analysis').property('analyzer', '{$analyzerQuoted}').addE('ANALYZED').to(result);
GREMLIN;
                $this->gremlin->query($query);
                $this->datastore->addRow('analyzed', array($analyzer_class => -1));
                display("{$analyzer} is not compatible with PHP configuration of this version. Ignoring\n");
            } else {
                display("{$analyzer_class} running\n");
                $analyzer->run();
                $count = $analyzer->getRowCount();
                $processed = $analyzer->getProcessedCount();
                $queries = $analyzer->getQueryCount();
                $rawQueries = $analyzer->getRawQueryCount();
                $total_results += $count;
                display("{$analyzer_class} run ({$count} / {$processed})\n");
                $end = microtime(true);
                $this->log->log("{$analyzer_class}\t" . ($end - $begin) . "\t{$count}\t{$processed}\t{$queries}\t{$rawQueries}");
                // storing the number of row found in Hash table (datastore)
                $this->datastore->addRow('analyzed', array($analyzer_class => $count));
            }
        }
        if (!$this->config->verbose && !$this->config->quiet) {
            echo $progressBar->advance();
        }
        display("Done\n");
    }
Пример #8
0
    public function run()
    {
        if (!file_exists($this->config->projects_root . '/projects/' . $this->config->project)) {
            throw new NoSuchProject($this->config->project);
        }
        $res = $this->gremlin->query('g.V().hasLabel("Project").values("fullcode")');
        if ($res->results[0] !== $this->config->project) {
            throw new NotProjectInGraph($this->config->project, $res->results[0]);
        }
        // move this to .dump.sqlite then rename at the end, or any imtermediate time
        // Mention that some are not yet arrived in the snitch
        $this->sqliteFile = $this->config->projects_root . '/projects/' . $this->config->project . '/.dump.sqlite';
        $this->sqliteFileFinal = $this->config->projects_root . '/projects/' . $this->config->project . '/dump.sqlite';
        if (file_exists($this->sqliteFile)) {
            unlink($this->sqliteFile);
            display('Removing old .dump.sqlite');
        }
        $this->addSnitch();
        Analyzer::initDocs();
        Analyzer::$gremlinStatic = $this->gremlin;
        if ($this->config->update === true) {
            copy($this->sqliteFileFinal, $this->sqliteFile);
            $sqlite = new \Sqlite3($this->sqliteFile);
        } else {
            $sqlite = new \Sqlite3($this->sqliteFile);
            $this->getAtomCounts($sqlite);
            $this->collectStructures($sqlite);
            $sqlite->query('CREATE TABLE themas (  id INTEGER PRIMARY KEY AUTOINCREMENT,
                                                   thema STRING
                                                  )');
            $sqlite->query('CREATE TABLE results (  id INTEGER PRIMARY KEY AUTOINCREMENT,
                                                    fullcode STRING,
                                                    file STRING,
                                                    line INTEGER,
                                                    namespace STRING,
                                                    class STRING,
                                                    function STRING,
                                                    analyzer STRING,
                                                    severity STRING
                                                  )');
            $sqlite->query('CREATE TABLE resultsCounts (   id INTEGER PRIMARY KEY AUTOINCREMENT,
                                                           analyzer STRING,
                                                           count INTEGER DEFAULT -6)');
            display('Inited tables');
        }
        $sqlQuery = <<<SQL
DELETE FROM results WHERE analyzer = :analyzer
SQL;
        $this->cleanResults = $sqlite->prepare($sqlQuery);
        $sqlQuery = <<<SQL
REPLACE INTO results ("id", "fullcode", "file", "line", "namespace", "class", "function", "analyzer", "severity") 
             VALUES ( NULL, :fullcode, :file,  :line,  :namespace,  :class,  :function,  :analyzer,  :severity )
SQL;
        $this->stmtResults = $sqlite->prepare($sqlQuery);
        $sqlQuery = <<<SQL
REPLACE INTO resultsCounts ("id", "analyzer", "count") VALUES (NULL, :class, :count )
SQL;
        $this->stmtResultsCounts = $sqlite->prepare($sqlQuery);
        $themes = array();
        if ($this->config->thema !== null) {
            $thema = $this->config->thema;
            $themes = Analyzer::getThemeAnalyzers($thema);
            if (empty($themes)) {
                $r = Analyzer::getSuggestionThema($thema);
                if (count($r) > 0) {
                    echo 'did you mean : ', implode(', ', str_replace('_', '/', $r)), "\n";
                }
                throw new NoSuchThema($thema);
            }
            display('Processing thema : ' . $thema);
        } elseif ($this->config->program !== null) {
            $analyzer = $this->config->program;
            if (!Analyzer::getClass($analyzer)) {
                $r = Analyzer::getSuggestionClass($analyzer);
                if (count($r) > 0) {
                    echo 'did you mean : ', implode(', ', str_replace('_', '/', $r)), "\n";
                }
                throw new NoSuchAnalyzer($analyzer);
            }
            $themes = array($analyzer);
            display('Processing one analyzer : ' . $analyzer);
        } else {
            display('No analysis dump requested (-T <thema> | -P <Analyzer>)');
            $this->finish();
            return;
        }
        /*
        $res = $sqlite->query('SELECT COUNT(*) FROM themas WHERE thema="'.$thema.'"');
        $count = $res->fetchArray(\SQLITE3_NUM);
        if ($count === 1) {
            display("$thema was already run\n");
        } else {
            display("$thema was not already run\n");
        }
        die();
        print_r($themes);
        */
        $sqlitePath = $this->config->projects_root . '/projects/' . $this->config->project . '/datastore.sqlite';
        $counts = array();
        $datastore = new \Sqlite3($sqlitePath, \SQLITE3_OPEN_READONLY);
        $datastore->busyTimeout(5000);
        $res = $datastore->query('SELECT * FROM analyzed');
        while ($row = $res->fetchArray(\SQLITE3_ASSOC)) {
            $counts[$row['analyzer']] = $row['counts'];
        }
        $this->log->log('count analyzed : ' . count($counts) . "\n");
        $this->log->log('counts ' . implode(', ', $counts) . "\n");
        $datastore->close();
        unset($datastore);
        foreach ($themes as $id => $thema) {
            if (isset($counts[$thema])) {
                display($thema . ' : ' . ($counts[$thema] >= 0 ? 'Yes' : 'N/A') . "\n");
                $this->processResults($thema, $counts[$thema]);
                unset($themes[$id]);
            } else {
                display($thema . " : No\n");
            }
        }
        $this->log->log('Still ' . count($themes) . " to be processed\n");
        display('Still ' . count($themes) . " to be processed\n");
        if (count($themes) === 0) {
            if ($this->config->thema !== null) {
                $sqlite->query('INSERT INTO themas ("id", "thema") VALUES ( NULL, "' . $this->config->thema . '")');
            }
        }
        $this->finish();
    }
Пример #9
0
 public function __construct()
 {
     parent::__construct();
     $this->themes = Analyzer::getThemeAnalyzers('ZendFramework');
     $this->themesList = '("' . implode('", "', $this->themes) . '")';
 }
Пример #10
0
 protected function Dashboard($title)
 {
     $css = new \Stdclass();
     $css->displayTitles = true;
     $css->titles = array('Library', 'Folder', 'Home page');
     $css->readOrder = $css->titles;
     $titles = array('Code Smells' => 'Analyze', 'Dead Code' => 'Dead code', 'Security' => 'Security', 'Performances' => 'Performances');
     $list = Analyzer::getThemeAnalyzers($titles[$title]);
     $where = 'WHERE analyzer in ("' . implode('", "', $list) . '")';
     $res = $this->dump->query('SELECT severity, count(*) AS nb FROM results ' . $where . ' GROUP BY severity ORDER BY severity');
     $severities = array();
     while ($row = $res->fetchArray(\SQLITE3_ASSOC)) {
         $severities[$row['severity']] = array('severity' => $row['severity'], 'count' => $row['nb']);
     }
     $res = $this->dump->query('SELECT analyzer, count(*) AS nb, severity AS severity FROM results ' . $where . ' GROUP BY analyzer');
     $listBySeverity = array();
     $config = Config::factory();
     while ($row = $res->fetchArray(\SQLITE3_ASSOC)) {
         $ini = parse_ini_file($config->dir_root . '/human/en/' . $row['analyzer'] . '.ini');
         $listBySeverity[] = array('name' => $ini['name'], 'severity' => $row['severity'], 'count' => $row['nb']);
     }
     uasort($listBySeverity, function ($a, $b) {
         $s = array('Critical' => 6, 'Major' => 5, 'Middle' => 4, 'Minor' => 3, 'None' => 0);
         if ($s[$a['severity']] > $s[$b['severity']]) {
             return -1;
         } elseif ($s[$a['severity']] < $s[$b['severity']]) {
             return 1;
         } else {
             return 0;
         }
     });
     $listBySeverity = array_slice($listBySeverity, 0, 5);
     $res = $this->dump->query('SELECT file, count(*) AS nb FROM results ' . $where . ' GROUP BY file ORDER BY count(*) DESC LIMIT 5');
     $listByFile = array();
     while ($row = $res->fetchArray(\SQLITE3_ASSOC)) {
         $listByFile[] = array('name' => $row['file'], 'severity' => '', 'count' => $row['nb']);
     }
     $info = array('upLeft' => $severities, 'upRight' => '&nbsp;', 'downLeft' => $listBySeverity, 'downRight' => $listByFile);
     return $this->formatDashboard($info, $css);
 }