No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

401 líneas
13KB

  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 boolean 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 boolean 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 boolean 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 boolean 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 integer 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 = str_replace($sizeUnit, '', $verboseSize);
  236. $size = trim($size);
  237. if (!is_numeric($size)) {
  238. return 0;
  239. }
  240. switch (strtolower($sizeUnit)) {
  241. case 'kb':
  242. case 'k':
  243. return $size * 1024;
  244. case 'mb':
  245. case 'm':
  246. return $size * 1024 * 1024;
  247. case 'gb':
  248. case 'g':
  249. return $size * 1024 * 1024 * 1024;
  250. default:
  251. return 0;
  252. }
  253. }
  254. /**
  255. * Checks if upload max file size matches the given range.
  256. * @param string|null $min verbose file size minimum required value, pass null to skip minimum check.
  257. * @param string|null $max verbose file size maximum required value, pass null to skip maximum check.
  258. * @return boolean success.
  259. */
  260. function checkUploadMaxFileSize($min = null, $max = null)
  261. {
  262. $postMaxSize = ini_get('post_max_size');
  263. $uploadMaxFileSize = ini_get('upload_max_filesize');
  264. if ($min !== null) {
  265. $minCheckResult = $this->compareByteSize($postMaxSize, $min, '>=') && $this->compareByteSize($uploadMaxFileSize, $min, '>=');
  266. } else {
  267. $minCheckResult = true;
  268. }
  269. if ($max !== null) {
  270. $maxCheckResult = $this->compareByteSize($postMaxSize, $max, '<=') && $this->compareByteSize($uploadMaxFileSize, $max, '<=');
  271. } else {
  272. $maxCheckResult = true;
  273. }
  274. return ($minCheckResult && $maxCheckResult);
  275. }
  276. /**
  277. * Renders a view file.
  278. * This method includes the view file as a PHP script
  279. * and captures the display result if required.
  280. * @param string $_viewFile_ view file
  281. * @param array $_data_ data to be extracted and made available to the view file
  282. * @param boolean $_return_ whether the rendering result should be returned as a string
  283. * @return string the rendering result. Null if the rendering result is not required.
  284. */
  285. function renderViewFile($_viewFile_, $_data_ = null, $_return_ = false)
  286. {
  287. // we use special variable names here to avoid conflict when extracting data
  288. if (is_array($_data_)) {
  289. extract($_data_, EXTR_PREFIX_SAME, 'data');
  290. } else {
  291. $data = $_data_;
  292. }
  293. if ($_return_) {
  294. ob_start();
  295. ob_implicit_flush(false);
  296. require($_viewFile_);
  297. return ob_get_clean();
  298. } else {
  299. require($_viewFile_);
  300. }
  301. }
  302. /**
  303. * Normalizes requirement ensuring it has correct format.
  304. * @param array $requirement raw requirement.
  305. * @param integer $requirementKey requirement key in the list.
  306. * @return array normalized requirement.
  307. */
  308. function normalizeRequirement($requirement, $requirementKey = 0)
  309. {
  310. if (!is_array($requirement)) {
  311. $this->usageError('Requirement must be an array!');
  312. }
  313. if (!array_key_exists('condition', $requirement)) {
  314. $this->usageError("Requirement '{$requirementKey}' has no condition!");
  315. } else {
  316. $evalPrefix = 'eval:';
  317. if (is_string($requirement['condition']) && strpos($requirement['condition'], $evalPrefix) === 0) {
  318. $expression = substr($requirement['condition'], strlen($evalPrefix));
  319. $requirement['condition'] = $this->evaluateExpression($expression);
  320. }
  321. }
  322. if (!array_key_exists('name', $requirement)) {
  323. $requirement['name'] = is_numeric($requirementKey) ? 'Requirement #' . $requirementKey : $requirementKey;
  324. }
  325. if (!array_key_exists('mandatory', $requirement)) {
  326. if (array_key_exists('required', $requirement)) {
  327. $requirement['mandatory'] = $requirement['required'];
  328. } else {
  329. $requirement['mandatory'] = false;
  330. }
  331. }
  332. if (!array_key_exists('by', $requirement)) {
  333. $requirement['by'] = 'Unknown';
  334. }
  335. if (!array_key_exists('memo', $requirement)) {
  336. $requirement['memo'] = '';
  337. }
  338. return $requirement;
  339. }
  340. /**
  341. * Displays a usage error.
  342. * This method will then terminate the execution of the current application.
  343. * @param string $message the error message
  344. */
  345. function usageError($message)
  346. {
  347. echo "Error: $message\n\n";
  348. exit(1);
  349. }
  350. /**
  351. * Evaluates a PHP expression under the context of this class.
  352. * @param string $expression a PHP expression to be evaluated.
  353. * @return mixed the expression result.
  354. */
  355. function evaluateExpression($expression)
  356. {
  357. return eval('return ' . $expression . ';');
  358. }
  359. /**
  360. * Returns the server information.
  361. * @return string server information.
  362. */
  363. function getServerInfo()
  364. {
  365. return isset($_SERVER['SERVER_SOFTWARE']) ? $_SERVER['SERVER_SOFTWARE'] : '';;
  366. }
  367. /**
  368. * Returns the now date if possible in string representation.
  369. * @return string now date.
  370. */
  371. function getNowDate()
  372. {
  373. return @strftime('%Y-%m-%d %H:%M', time());;
  374. }
  375. }