functions.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. use Cake\Core\Configure;
  16. if (!defined('DS')) {
  17. /**
  18. * Define DS as short form of DIRECTORY_SEPARATOR.
  19. */
  20. define('DS', DIRECTORY_SEPARATOR);
  21. }
  22. if (!function_exists('h')) {
  23. /**
  24. * Convenience method for htmlspecialchars.
  25. *
  26. * @param mixed $text Text to wrap through htmlspecialchars. Also works with arrays, and objects.
  27. * Arrays will be mapped and have all their elements escaped. Objects will be string cast if they
  28. * implement a `__toString` method. Otherwise the class name will be used.
  29. * Other scalar types will be returned unchanged.
  30. * @param bool $double Encode existing html entities.
  31. * @param string|null $charset Character set to use when escaping. Defaults to config value in `mb_internal_encoding()`
  32. * or 'UTF-8'.
  33. * @return mixed Wrapped text.
  34. * @link https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#h
  35. */
  36. function h($text, $double = true, $charset = null)
  37. {
  38. if (is_string($text)) {
  39. //optimize for strings
  40. } elseif (is_array($text)) {
  41. $texts = [];
  42. foreach ($text as $k => $t) {
  43. $texts[$k] = h($t, $double, $charset);
  44. }
  45. return $texts;
  46. } elseif (is_object($text)) {
  47. if (method_exists($text, '__toString')) {
  48. $text = (string)$text;
  49. } else {
  50. $text = '(object)' . get_class($text);
  51. }
  52. } elseif ($text === null || is_scalar($text)) {
  53. return $text;
  54. }
  55. static $defaultCharset = false;
  56. if ($defaultCharset === false) {
  57. $defaultCharset = mb_internal_encoding();
  58. if ($defaultCharset === null) {
  59. $defaultCharset = 'UTF-8';
  60. }
  61. }
  62. if (is_string($double)) {
  63. deprecationWarning(
  64. 'Passing charset string for 2nd argument is deprecated. ' .
  65. 'Use the 3rd argument instead.'
  66. );
  67. $charset = $double;
  68. }
  69. return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, $charset ?: $defaultCharset, $double);
  70. }
  71. }
  72. if (!function_exists('pluginSplit')) {
  73. /**
  74. * Splits a dot syntax plugin name into its plugin and class name.
  75. * If $name does not have a dot, then index 0 will be null.
  76. *
  77. * Commonly used like
  78. * ```
  79. * list($plugin, $name) = pluginSplit($name);
  80. * ```
  81. *
  82. * @param string $name The name you want to plugin split.
  83. * @param bool $dotAppend Set to true if you want the plugin to have a '.' appended to it.
  84. * @param string|null $plugin Optional default plugin to use if no plugin is found. Defaults to null.
  85. * @return array Array with 2 indexes. 0 => plugin name, 1 => class name.
  86. * @link https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#pluginSplit
  87. */
  88. function pluginSplit($name, $dotAppend = false, $plugin = null)
  89. {
  90. if (strpos($name, '.') !== false) {
  91. $parts = explode('.', $name, 2);
  92. if ($dotAppend) {
  93. $parts[0] .= '.';
  94. }
  95. return $parts;
  96. }
  97. return [$plugin, $name];
  98. }
  99. }
  100. if (!function_exists('namespaceSplit')) {
  101. /**
  102. * Split the namespace from the classname.
  103. *
  104. * Commonly used like `list($namespace, $className) = namespaceSplit($class);`.
  105. *
  106. * @param string $class The full class name, ie `Cake\Core\App`.
  107. * @return array Array with 2 indexes. 0 => namespace, 1 => classname.
  108. */
  109. function namespaceSplit($class)
  110. {
  111. $pos = strrpos($class, '\\');
  112. if ($pos === false) {
  113. return ['', $class];
  114. }
  115. return [substr($class, 0, $pos), substr($class, $pos + 1)];
  116. }
  117. }
  118. if (!function_exists('pr')) {
  119. /**
  120. * print_r() convenience function.
  121. *
  122. * In terminals this will act similar to using print_r() directly, when not run on cli
  123. * print_r() will also wrap <pre> tags around the output of given variable. Similar to debug().
  124. *
  125. * This function returns the same variable that was passed.
  126. *
  127. * @param mixed $var Variable to print out.
  128. * @return mixed the same $var that was passed to this function
  129. * @link https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#pr
  130. * @see debug()
  131. */
  132. function pr($var)
  133. {
  134. if (!Configure::read('debug')) {
  135. return $var;
  136. }
  137. $template = (PHP_SAPI !== 'cli' && PHP_SAPI !== 'phpdbg') ? '<pre class="pr">%s</pre>' : "\n%s\n\n";
  138. printf($template, trim(print_r($var, true)));
  139. return $var;
  140. }
  141. }
  142. if (!function_exists('pj')) {
  143. /**
  144. * json pretty print convenience function.
  145. *
  146. * In terminals this will act similar to using json_encode() with JSON_PRETTY_PRINT directly, when not run on cli
  147. * will also wrap <pre> tags around the output of given variable. Similar to pr().
  148. *
  149. * This function returns the same variable that was passed.
  150. *
  151. * @param mixed $var Variable to print out.
  152. * @return mixed the same $var that was passed to this function
  153. * @see pr()
  154. * @link https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#pj
  155. */
  156. function pj($var)
  157. {
  158. if (!Configure::read('debug')) {
  159. return $var;
  160. }
  161. $template = (PHP_SAPI !== 'cli' && PHP_SAPI !== 'phpdbg') ? '<pre class="pj">%s</pre>' : "\n%s\n\n";
  162. printf($template, trim(json_encode($var, JSON_PRETTY_PRINT)));
  163. return $var;
  164. }
  165. }
  166. if (!function_exists('env')) {
  167. /**
  168. * Gets an environment variable from available sources, and provides emulation
  169. * for unsupported or inconsistent environment variables (i.e. DOCUMENT_ROOT on
  170. * IIS, or SCRIPT_NAME in CGI mode). Also exposes some additional custom
  171. * environment information.
  172. *
  173. * @param string $key Environment variable name.
  174. * @param string|null $default Specify a default value in case the environment variable is not defined.
  175. * @return string|bool|null Environment variable setting.
  176. * @link https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#env
  177. */
  178. function env($key, $default = null)
  179. {
  180. if ($key === 'HTTPS') {
  181. if (isset($_SERVER['HTTPS'])) {
  182. return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off');
  183. }
  184. return (strpos((string)env('SCRIPT_URI'), 'https://') === 0);
  185. }
  186. if ($key === 'SCRIPT_NAME' && env('CGI_MODE') && isset($_ENV['SCRIPT_URL'])) {
  187. $key = 'SCRIPT_URL';
  188. }
  189. $val = null;
  190. if (isset($_SERVER[$key])) {
  191. $val = $_SERVER[$key];
  192. } elseif (isset($_ENV[$key])) {
  193. $val = $_ENV[$key];
  194. } elseif (getenv($key) !== false) {
  195. $val = getenv($key);
  196. }
  197. if ($key === 'REMOTE_ADDR' && $val === env('SERVER_ADDR')) {
  198. $addr = env('HTTP_PC_REMOTE_ADDR');
  199. if ($addr !== null) {
  200. $val = $addr;
  201. }
  202. }
  203. if ($val !== null) {
  204. return $val;
  205. }
  206. switch ($key) {
  207. case 'DOCUMENT_ROOT':
  208. $name = env('SCRIPT_NAME');
  209. $filename = env('SCRIPT_FILENAME');
  210. $offset = 0;
  211. if (!strpos($name, '.php')) {
  212. $offset = 4;
  213. }
  214. return substr($filename, 0, -(strlen($name) + $offset));
  215. case 'PHP_SELF':
  216. return str_replace(env('DOCUMENT_ROOT'), '', env('SCRIPT_FILENAME'));
  217. case 'CGI_MODE':
  218. return (PHP_SAPI === 'cgi');
  219. }
  220. return $default;
  221. }
  222. }
  223. if (!function_exists('triggerWarning')) {
  224. /**
  225. * Triggers an E_USER_WARNING.
  226. *
  227. * @param string $message The warning message.
  228. * @return void
  229. */
  230. function triggerWarning($message)
  231. {
  232. $stackFrame = 1;
  233. $trace = debug_backtrace();
  234. if (isset($trace[$stackFrame])) {
  235. $frame = $trace[$stackFrame];
  236. $frame += ['file' => '[internal]', 'line' => '??'];
  237. $message = sprintf(
  238. '%s - %s, line: %s',
  239. $message,
  240. $frame['file'],
  241. $frame['line']
  242. );
  243. }
  244. trigger_error($message, E_USER_WARNING);
  245. }
  246. }
  247. if (!function_exists('deprecationWarning')) {
  248. /**
  249. * Helper method for outputting deprecation warnings
  250. *
  251. * @param string $message The message to output as a deprecation warning.
  252. * @param int $stackFrame The stack frame to include in the error. Defaults to 1
  253. * as that should point to application/plugin code.
  254. * @return void
  255. */
  256. function deprecationWarning($message, $stackFrame = 1)
  257. {
  258. if (!(error_reporting() & E_USER_DEPRECATED)) {
  259. return;
  260. }
  261. $trace = debug_backtrace();
  262. if (isset($trace[$stackFrame])) {
  263. $frame = $trace[$stackFrame];
  264. $frame += ['file' => '[internal]', 'line' => '??'];
  265. $message = sprintf(
  266. '%s - %s, line: %s' . "\n" .
  267. ' You can disable deprecation warnings by setting `Error.errorLevel` to' .
  268. ' `E_ALL & ~E_USER_DEPRECATED` in your config/app.php.',
  269. $message,
  270. $frame['file'],
  271. $frame['line']
  272. );
  273. }
  274. trigger_error($message, E_USER_DEPRECATED);
  275. }
  276. }
  277. if (!function_exists('getTypeName')) {
  278. /**
  279. * Returns the objects class or var type of it's not an object
  280. *
  281. * @param mixed $var Variable to check
  282. * @return string Returns the class name or variable type
  283. */
  284. function getTypeName($var)
  285. {
  286. return is_object($var) ? get_class($var) : gettype($var);
  287. }
  288. }