YiiRequirementChecker.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. <?php
  2. /**
  3. * @link https://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license https://www.yiiframework.com/license/
  6. */
  7. if (version_compare(PHP_VERSION, '4.3', '<')) {
  8. echo 'At least PHP 4.3 is required to run this script!';
  9. exit(1);
  10. }
  11. /**
  12. * YiiRequirementChecker allows checking, if current system meets the requirements for running the Yii application.
  13. * This class allows rendering of the check report for the web and console application interface.
  14. *
  15. * Example:
  16. *
  17. * ```php
  18. * require_once 'path/to/YiiRequirementChecker.php';
  19. * $requirementsChecker = new YiiRequirementChecker();
  20. * $requirements = array(
  21. * array(
  22. * 'name' => 'PHP Some Extension',
  23. * 'mandatory' => true,
  24. * 'condition' => extension_loaded('some_extension'),
  25. * 'by' => 'Some application feature',
  26. * 'memo' => 'PHP extension "some_extension" required',
  27. * ),
  28. * );
  29. * $requirementsChecker->checkYii()->check($requirements)->render();
  30. * ```
  31. *
  32. * If you wish to render the report with your own representation, use [[getResult()]] instead of [[render()]]
  33. *
  34. * Requirement condition could be in format "eval:PHP expression".
  35. * In this case specified PHP expression will be evaluated in the context of this class instance.
  36. * For example:
  37. *
  38. * ```php
  39. * $requirements = array(
  40. * array(
  41. * 'name' => 'Upload max file size',
  42. * 'condition' => 'eval:$this->checkUploadMaxFileSize("5M")',
  43. * ),
  44. * );
  45. * ```
  46. *
  47. * Note: this class definition does not match ordinary Yii style, because it should match PHP 4.3
  48. * and should not use features from newer PHP versions!
  49. *
  50. * @property array|null $result the check results, this property is for internal usage only.
  51. *
  52. * @author Paul Klimov <klimov.paul@gmail.com>
  53. * @since 2.0
  54. */
  55. class YiiRequirementChecker
  56. {
  57. /**
  58. * @var Check result
  59. */
  60. public $result;
  61. /**
  62. * Check the given requirements, collecting results into internal field.
  63. * This method can be invoked several times checking different requirement sets.
  64. * Use [[getResult()]] or [[render()]] to get the results.
  65. * @param array|string $requirements requirements to be checked.
  66. * If an array, it is treated as the set of requirements;
  67. * If a string, it is treated as the path of the file, which contains the requirements;
  68. * @return $this self instance.
  69. */
  70. function check($requirements)
  71. {
  72. if (is_string($requirements)) {
  73. $requirements = require $requirements;
  74. }
  75. if (!is_array($requirements)) {
  76. $this->usageError('Requirements must be an array, "' . gettype($requirements) . '" has been given!');
  77. }
  78. if (!isset($this->result) || !is_array($this->result)) {
  79. $this->result = array(
  80. 'summary' => array(
  81. 'total' => 0,
  82. 'errors' => 0,
  83. 'warnings' => 0,
  84. ),
  85. 'requirements' => array(),
  86. );
  87. }
  88. foreach ($requirements as $key => $rawRequirement) {
  89. $requirement = $this->normalizeRequirement($rawRequirement, $key);
  90. $this->result['summary']['total']++;
  91. if (!$requirement['condition']) {
  92. if ($requirement['mandatory']) {
  93. $requirement['error'] = true;
  94. $requirement['warning'] = true;
  95. $this->result['summary']['errors']++;
  96. } else {
  97. $requirement['error'] = false;
  98. $requirement['warning'] = true;
  99. $this->result['summary']['warnings']++;
  100. }
  101. } else {
  102. $requirement['error'] = false;
  103. $requirement['warning'] = false;
  104. }
  105. $this->result['requirements'][] = $requirement;
  106. }
  107. return $this;
  108. }
  109. /**
  110. * Performs the check for the Yii core requirements.
  111. * @return YiiRequirementChecker self instance.
  112. */
  113. function checkYii()
  114. {
  115. return $this->check(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'requirements.php');
  116. }
  117. /**
  118. * Return the check results.
  119. * @return array|null check results in format:
  120. *
  121. * ```php
  122. * array(
  123. * 'summary' => array(
  124. * 'total' => total number of checks,
  125. * 'errors' => number of errors,
  126. * 'warnings' => number of warnings,
  127. * ),
  128. * 'requirements' => array(
  129. * array(
  130. * ...
  131. * 'error' => is there an error,
  132. * 'warning' => is there a warning,
  133. * ),
  134. * ...
  135. * ),
  136. * )
  137. * ```
  138. */
  139. function getResult()
  140. {
  141. if (isset($this->result)) {
  142. return $this->result;
  143. } else {
  144. return null;
  145. }
  146. }
  147. /**
  148. * Renders the requirements check result.
  149. * The output will vary depending is a script running from web or from console.
  150. */
  151. function render()
  152. {
  153. if (!isset($this->result)) {
  154. $this->usageError('Nothing to render!');
  155. }
  156. $baseViewFilePath = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views';
  157. if (!empty($_SERVER['argv'])) {
  158. $viewFileName = $baseViewFilePath . DIRECTORY_SEPARATOR . 'console' . DIRECTORY_SEPARATOR . 'index.php';
  159. } else {
  160. $viewFileName = $baseViewFilePath . DIRECTORY_SEPARATOR . 'web' . DIRECTORY_SEPARATOR . 'index.php';
  161. }
  162. $this->renderViewFile($viewFileName, $this->result);
  163. }
  164. /**
  165. * Checks if the given PHP extension is available and its version matches the given one.
  166. * @param string $extensionName PHP extension name.
  167. * @param string $version required PHP extension version.
  168. * @param string $compare comparison operator, by default '>='
  169. * @return bool if PHP extension version matches.
  170. */
  171. function checkPhpExtensionVersion($extensionName, $version, $compare = '>=')
  172. {
  173. if (!extension_loaded($extensionName)) {
  174. return false;
  175. }
  176. $extensionVersion = phpversion($extensionName);
  177. if (empty($extensionVersion)) {
  178. return false;
  179. }
  180. if (strncasecmp($extensionVersion, 'PECL-', 5) === 0) {
  181. $extensionVersion = substr($extensionVersion, 5);
  182. }
  183. return version_compare($extensionVersion, $version, $compare);
  184. }
  185. /**
  186. * Checks if PHP configuration option (from php.ini) is on.
  187. * @param string $name configuration option name.
  188. * @return bool option is on.
  189. */
  190. function checkPhpIniOn($name)
  191. {
  192. $value = ini_get($name);
  193. if (empty($value)) {
  194. return false;
  195. }
  196. return ((int) $value === 1 || strtolower($value) === 'on');
  197. }
  198. /**
  199. * Checks if PHP configuration option (from php.ini) is off.
  200. * @param string $name configuration option name.
  201. * @return bool option is off.
  202. */
  203. function checkPhpIniOff($name)
  204. {
  205. $value = ini_get($name);
  206. if (empty($value)) {
  207. return true;
  208. }
  209. return (strtolower($value) === 'off');
  210. }
  211. /**
  212. * Compare byte sizes of values given in the verbose representation,
  213. * like '5M', '15K' etc.
  214. * @param string $a first value.
  215. * @param string $b second value.
  216. * @param string $compare comparison operator, by default '>='.
  217. * @return bool comparison result.
  218. */
  219. function compareByteSize($a, $b, $compare = '>=')
  220. {
  221. $compareExpression = '(' . $this->getByteSize($a) . $compare . $this->getByteSize($b) . ')';
  222. return $this->evaluateExpression($compareExpression);
  223. }
  224. /**
  225. * Gets the size in bytes from verbose size representation.
  226. * For example: '5K' => 5*1024
  227. * @param string $verboseSize verbose size representation.
  228. * @return int actual size in bytes.
  229. */
  230. function getByteSize($verboseSize)
  231. {
  232. if (empty($verboseSize)) {
  233. return 0;
  234. }
  235. if (is_numeric($verboseSize)) {
  236. return (int) $verboseSize;
  237. }
  238. $sizeUnit = trim($verboseSize, '0123456789');
  239. $size = trim(str_replace($sizeUnit, '', $verboseSize));
  240. if (!is_numeric($size)) {
  241. return 0;
  242. }
  243. switch (strtolower($sizeUnit)) {
  244. case 'kb':
  245. case 'k':
  246. return $size * 1024;
  247. case 'mb':
  248. case 'm':
  249. return $size * 1024 * 1024;
  250. case 'gb':
  251. case 'g':
  252. return $size * 1024 * 1024 * 1024;
  253. default:
  254. return 0;
  255. }
  256. }
  257. /**
  258. * Checks if upload max file size matches the given range.
  259. * @param string|null $min verbose file size minimum required value, pass null to skip minimum check.
  260. * @param string|null $max verbose file size maximum required value, pass null to skip maximum check.
  261. * @return bool success.
  262. */
  263. function checkUploadMaxFileSize($min = null, $max = null)
  264. {
  265. $postMaxSize = ini_get('post_max_size');
  266. $uploadMaxFileSize = ini_get('upload_max_filesize');
  267. if ($min !== null) {
  268. $minCheckResult = $this->compareByteSize($postMaxSize, $min, '>=') && $this->compareByteSize($uploadMaxFileSize, $min, '>=');
  269. } else {
  270. $minCheckResult = true;
  271. }
  272. if ($max !== null) {
  273. $maxCheckResult = $this->compareByteSize($postMaxSize, $max, '<=') && $this->compareByteSize($uploadMaxFileSize, $max, '<=');
  274. } else {
  275. $maxCheckResult = true;
  276. }
  277. return ($minCheckResult && $maxCheckResult);
  278. }
  279. /**
  280. * Renders a view file.
  281. * This method includes the view file as a PHP script
  282. * and captures the display result if required.
  283. * @param string $_viewFile_ view file
  284. * @param array|null $_data_ data to be extracted and made available to the view file
  285. * @param bool $_return_ whether the rendering result should be returned as a string
  286. * @return string|null the rendering result. Null if the rendering result is not required.
  287. */
  288. function renderViewFile($_viewFile_, $_data_ = null, $_return_ = false)
  289. {
  290. // we use special variable names here to avoid conflict when extracting data
  291. if (is_array($_data_)) {
  292. extract($_data_, EXTR_PREFIX_SAME, 'data');
  293. } else {
  294. $data = $_data_;
  295. }
  296. if ($_return_) {
  297. ob_start();
  298. ob_implicit_flush(false);
  299. require $_viewFile_;
  300. return ob_get_clean();
  301. } else {
  302. require $_viewFile_;
  303. }
  304. }
  305. /**
  306. * Normalizes requirement ensuring it has correct format.
  307. * @param array $requirement raw requirement.
  308. * @param int $requirementKey requirement key in the list.
  309. * @return array normalized requirement.
  310. */
  311. function normalizeRequirement($requirement, $requirementKey = 0)
  312. {
  313. if (!is_array($requirement)) {
  314. $this->usageError('Requirement must be an array!');
  315. }
  316. if (!array_key_exists('condition', $requirement)) {
  317. $this->usageError("Requirement '{$requirementKey}' has no condition!");
  318. } else {
  319. $evalPrefix = 'eval:';
  320. if (is_string($requirement['condition']) && strpos($requirement['condition'], $evalPrefix) === 0) {
  321. $expression = substr($requirement['condition'], strlen($evalPrefix));
  322. $requirement['condition'] = $this->evaluateExpression($expression);
  323. }
  324. }
  325. if (!array_key_exists('name', $requirement)) {
  326. $requirement['name'] = is_numeric($requirementKey) ? 'Requirement #' . $requirementKey : $requirementKey;
  327. }
  328. if (!array_key_exists('mandatory', $requirement)) {
  329. if (array_key_exists('required', $requirement)) {
  330. $requirement['mandatory'] = $requirement['required'];
  331. } else {
  332. $requirement['mandatory'] = false;
  333. }
  334. }
  335. if (!array_key_exists('by', $requirement)) {
  336. $requirement['by'] = 'Unknown';
  337. }
  338. if (!array_key_exists('memo', $requirement)) {
  339. $requirement['memo'] = '';
  340. }
  341. return $requirement;
  342. }
  343. /**
  344. * Displays a usage error.
  345. * This method will then terminate the execution of the current application.
  346. * @param string $message the error message
  347. */
  348. function usageError($message)
  349. {
  350. echo "Error: $message\n\n";
  351. exit(1);
  352. }
  353. /**
  354. * Evaluates a PHP expression under the context of this class.
  355. * @param string $expression a PHP expression to be evaluated.
  356. * @return mixed the expression result.
  357. */
  358. function evaluateExpression($expression)
  359. {
  360. return eval('return ' . $expression . ';');
  361. }
  362. /**
  363. * Returns the server information.
  364. * @return string server information.
  365. */
  366. function getServerInfo()
  367. {
  368. return isset($_SERVER['SERVER_SOFTWARE']) ? $_SERVER['SERVER_SOFTWARE'] : '';
  369. }
  370. /**
  371. * Returns the now date if possible in string representation.
  372. * @return string now date.
  373. */
  374. function getNowDate()
  375. {
  376. return @strftime('%Y-%m-%d %H:%M', time());
  377. }
  378. }