aboutsummaryrefslogtreecommitdiff
path: root/cli/studip-compat.php
blob: 4abc67c2e6a57abf610dfc01359f76d700126c5f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
#!/usr/bin/env php
<?php
require_once 'studip_cli_env.inc.php';

$opts = getopt('fhnvc', ['filenames', 'help', 'non-recursive', 'verbose', 'no-color']);

if (isset($opts['h']) || isset($opts['help'])) {
    fwrite(STDOUT, 'Stud.IP compatibility scanner - Checks plugins for common issues' . PHP_EOL);
    fwrite(STDOUT, '================================================================' . PHP_EOL);
    fwrite(STDOUT, 'Usage: ' . basename(__FILE__) . ' [OPTION] [VERSION] [FOLDER] ..' . PHP_EOL);
    fwrite(STDOUT, PHP_EOL);
    fwrite(STDOUT, '[VERSION] is optional, if not given all checks are applied.' . PHP_EOL);
    fwrite(STDOUT, '[FOLDER] will default to the plugins_packages folder.' . PHP_EOL);
    fwrite(STDOUT, 'Supply as many folders as you need.' . PHP_EOL);
    fwrite(STDOUT, PHP_EOL);
    fwrite(STDOUT, 'Options:' . PHP_EOL);
    fwrite(STDOUT, ' -h, --help            Display this help' . PHP_EOL);
    fwrite(STDOUT, ' -f, --filenames       Display only filenames' . PHP_EOL);
    fwrite(STDOUT, ' -n, --non-recursive   Do not scan recursively into subfolders' . PHP_EOL);
    fwrite(STDOUT, ' -c, --no-color        Do not use colors for output' . PHP_EOL);
    fwrite(STDOUT, ' -v, --verbose         Print additional information' . PHP_EOL);
    fwrite(STDOUT, PHP_EOL);
    exit(0);
}

// Reduce arguments by options (this is far from perfect)
$args = $_SERVER['argv'];
$arg_stop = array_search('--', $args);
if ($arg_stop !== false) {
    $args = array_slice($args, $arg_stop + 1);
} elseif (count($opts)) {
    $args = array_slice($args, 1 + count($opts));
} else {
    $args = array_slice($args, 1);
}

$verbose        = isset($opts['v']) || isset($opts['verbose']);
$only_filenames = isset($opts['f']) || isset($opts['filenames']);
$recursive      = !(isset($opts['n']) || isset($opts['non-recursive']));
$no_colors      = isset($opts['c']) || isset($opts['no-color']) || !stream_isatty(STDOUT);
$version        = null;
$folders        = array_values($args) ?: [];

if (count($folders) > 0 && preg_match('/^\d+\.\d+$/', $folders[0])) {
    $version = array_shift($folders);
}

// Prepare logging mechanism
$log = function ($message) use ($no_colors) {
    $ansi = [
        'off'        => 0,
        'bold'       => 1,
        'italic'     => 3,
        'underline'  => 4,
        'blink'      => 5,
        'inverse'    => 7,
        'hidden'     => 8,
        'black'      => 30,
        'red'        => 31,
        'green'      => 32,
        'yellow'     => 33,
        'blue'       => 34,
        'magenta'    => 35,
        'cyan'       => 36,
        'white'      => 37,
        'black_bg'   => 40,
        'red_bg'     => 41,
        'green_bg'   => 42,
        'yellow_bg'  => 43,
        'blue_bg'    => 44,
        'magenta_bg' => 45,
        'cyan_bg'    => 46,
        'white_bg'   => 47
    ];

    $message = trim($message);

    if ($message) {
        $args = array_slice(func_get_args(), 1);
        $message = vsprintf($message . "\n", $args);

        $ansi_codes = implode('|', array_keys($ansi));
        if (preg_match_all('/#\{((?:(?:' . $ansi_codes . '),?)+):(.+?)\}/s', $message, $matches, PREG_SET_ORDER)) {
            foreach ($matches as $match) {
                $chunk = '';
                if (!$no_colors) {
                    $codes = explode(',', $match[1]);
                    foreach ($codes as $code) {
                        $chunk .= "\033[{$ansi[$code]}m";
                    }
                }
                $chunk .= $match[2];
                if (!$no_colors) {
                    $chunk .= "\033[{$ansi[off]}m";
                }

                $message = str_replace($match[0], $chunk, $message);
            }
        }

        print $message;
    }
};
$log_if = function ($condition, $message) use ($log) {
    if ($condition) {
        call_user_func_array($log, array_slice(func_get_args(), 1));
    }
};

// Reduces filename by base path and plugin folder
$reduce = function ($folder) {
    $folder = str_replace($GLOBALS['STUDIP_BASE_PATH'] . '/', '', $folder);
    $folder = str_replace('public/plugins_packages/', '', $folder);
    return $folder;
};

// Get rules
if (!$version) {
    $rules = [];
    foreach (glob(__DIR__ . '/compatbility-rules/*.php') as $file) {
        $version_rules = require $file;
        $rules = array_merge($rules, $version_rules);
    }
} elseif (!file_exists(__DIR__ . "/compatibility-rules/studip-{$version}.php")) {
    $log('#{red:No rules defined for Stud.IP version %s}', $version);
    die;
} else {
    $rules = require __DIR__ . "/compatibility-rules/studip-{$version}.php";
}

// Prepare folders
if (count($folders) === 0) {
    $folders = rtrim($GLOBALS['STUDIP_BASE_PATH'], '/') . '/public/plugins_packages';
    $folders = glob($folders . '/*/*');
}
$folders = array_unique($folders);

$checkRule = function ($rule, $contents) {
    if ($rule[0] === '/' && $rule[strlen($rule) - 1] === '/') {
        return (bool) preg_match("{$rule}s", $contents);
    }

    return strpos($contents, strtolower($rule)) > 0;
};

// Main checker
$check = function ($filename) use ($checkRule, $rules) {
    $errors = [];

    $contents = strtolower(file_get_contents($filename));
    foreach ($rules as $needle => $suggestion) {
        if ($checkRule($needle, $contents)) {
            $errors[$needle] = $suggestion;
        }
    }
    return $errors;
};

// Engage
foreach ($folders as $folder) {
    if (!file_exists($folder) || !is_dir($folder)) {
        $log_if($verbose, 'Skipping non-folder arg #{red:%s}', $folder);
        continue;
    }

    $log_if($verbose && !$only_filenames, '#{green:Scanning} %s', $reduce($folder));
    if ($recursive) {
        $iterator = new RecursiveDirectoryIterator($folder, FilesystemIterator::FOLLOW_SYMLINKS | FilesystemIterator::UNIX_PATHS);
        $iterator = new RecursiveIteratorIterator($iterator);
    } else {
        $iterator = new DirectoryIterator($folder);
    }
    $regexp_iterator = new RegexIterator($iterator, '/.*\.(?:php|tpl|inc|js)$/', RecursiveRegexIterator::MATCH);

    $issues = [];

    foreach ($regexp_iterator as $file) {
        $filename = $file->getPathName();
        $log_if($verbose, "Checking #{magenta:%s}", $filename);
        if ($errors = $check($filename)) {
            $issues[$filename] = $errors;
        }
    }

    if (count($issues) > 0) {
        $issue_count = array_sum(array_map('count', $issues));
        $message = count($issues) === 1
                 ? '#{red:%u issue found in} #{red,bold:%s}'
                 : '#{red:%u issues found in} #{red,bold:%s}';
        $log_if(!$only_filenames, $message, $issue_count, $reduce($folder));

        foreach ($issues as $filename => $errors) {
            if ($only_filenames) {
                $log($filename);
            } else {
                $log('> File #{green,bold:%s}', $reduce($filename));
                foreach ($errors as $needle => $suggestion) {
                    $log('- #{cyan:%s} -> %s', $needle, $suggestion ?: '#{red:No suggestion available}');
                }
            }
        }
    }
}