YiiRequirementChecker.php 13 KB

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