|
| 1 | +<?php |
| 2 | +if (PHP_SAPI !== 'cli') exit; |
| 3 | +if ($_SERVER['argc'] !== 2) exit; |
| 4 | + |
| 5 | +$name = $_SERVER['argv'][1]; |
| 6 | +// Sanity checks. |
| 7 | +if (basename($name) !== $name) { |
| 8 | + fwrite(STDERR, 'Refusing to load plugin file "'.$name.'" for security reasons.'."\n"); |
| 9 | + exit(1); |
| 10 | +} |
| 11 | +if (!is_readable('plugins/'.$name.'.php')) { |
| 12 | + fwrite(STDERR, 'Unable to find plugin file "'.$name.'".'."\n"); |
| 13 | + exit(1); |
| 14 | +} |
| 15 | + |
| 16 | +// Try to find class. |
| 17 | +$file = 'plugins/'.$name.'.php'; |
| 18 | +$code = file_get_contents('plugins/'.$name.'.php'); |
| 19 | +$tokens = token_get_all($code); |
| 20 | + |
| 21 | +$classFound = false; |
| 22 | +$classes = []; |
| 23 | +for ($i = 0, $max = count($tokens); $i < $max; $i++) { |
| 24 | + if ($tokens[$i][0] === T_CLASS) $classFound = true; |
| 25 | + if ($classFound && $tokens[$i][0] === T_STRING) { |
| 26 | + $classes[] = $tokens[$i][1]; |
| 27 | + $classFound = false; |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +// Sanity checks. |
| 32 | +if (count($classes) == 0) { |
| 33 | + fwrite(STDERR, 'Unable to load plugin file "'.$name.'", because it does not define any classes.'."\n"); |
| 34 | + exit(1); |
| 35 | +} |
| 36 | + |
| 37 | +if (count($classes) > 1) { |
| 38 | + fwrite(STDERR, 'Unable to load plugin file "'.$name.'", because it defines multiple classes.'."\n"); |
| 39 | + exit(1); |
| 40 | +} |
| 41 | + |
| 42 | +// Check constructor. |
| 43 | +$class = $classes[0]; |
| 44 | +require($file); |
| 45 | + |
| 46 | +$constructor = (new \ReflectionClass($class))->getConstructor(); |
| 47 | + |
| 48 | +if ($constructor && $constructor->getNumberOfRequiredParameters() > 0) { |
| 49 | + $requiredParameters = array_slice($constructor->getParameters(), 0, $constructor->getNumberOfRequiredParameters()); |
| 50 | + |
| 51 | + fwrite(STDERR, 'Unable to load plugin file "'.$name.'", because it has required parameters: '.implode(', ', array_map(function ($item) { |
| 52 | + return $item->getName(); |
| 53 | + }, $requiredParameters))."\n". |
| 54 | +'Create a file "'.getcwd().'/plugins-enabled/'.$name.'.php" with the following contents to load the plugin:'."\n\n". |
| 55 | +'<?php |
| 56 | +require_once('.var_export($file, true).'); |
| 57 | +
|
| 58 | +'.$constructor->getDocComment().' |
| 59 | +return new '.$class.'( |
| 60 | + '.implode(",\n\t", array_map(function ($item) { |
| 61 | + return '$'.$item->getName()." = ".($item->isOptional() ? var_export($item->getDefaultValue(), true) : '???'); |
| 62 | + }, $constructor->getParameters())).' |
| 63 | +); |
| 64 | +'); |
| 65 | + exit(1); |
| 66 | +} |
| 67 | + |
| 68 | +echo '<?php |
| 69 | +require_once('.var_export($file, true).'); |
| 70 | +
|
| 71 | +return new '.$class.'(); |
| 72 | +'; |
| 73 | +exit(0); |
0 commit comments