PageRenderTime 58ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/engine/lib/elgglib.php

https://github.com/fragilbert/Elgg
PHP | 2087 lines | 1048 code | 228 blank | 811 comment | 153 complexity | 9e1c9ee81b60ae5ef2485134eaaa5056 MD5 | raw file
Possible License(s): MIT, BSD-3-Clause, LGPL-2.1, GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * Bootstrapping and helper procedural code available for use in Elgg core and plugins.
  4. *
  5. * @package Elgg.Core
  6. * @todo These functions can't be subpackaged because they cover a wide mix of
  7. * purposes and subsystems. Many of them should be moved to more relevant files.
  8. */
  9. /**
  10. * Register a php library.
  11. *
  12. * @param string $name The name of the library
  13. * @param string $location The location of the file
  14. *
  15. * @return void
  16. * @since 1.8.0
  17. */
  18. function elgg_register_library($name, $location) {
  19. global $CONFIG;
  20. if (!isset($CONFIG->libraries)) {
  21. $CONFIG->libraries = array();
  22. }
  23. $CONFIG->libraries[$name] = $location;
  24. }
  25. /**
  26. * Load a php library.
  27. *
  28. * @param string $name The name of the library
  29. *
  30. * @return void
  31. * @throws InvalidParameterException
  32. * @since 1.8.0
  33. */
  34. function elgg_load_library($name) {
  35. global $CONFIG;
  36. if (!isset($CONFIG->libraries)) {
  37. $CONFIG->libraries = array();
  38. }
  39. if (!isset($CONFIG->libraries[$name])) {
  40. $error = elgg_echo('InvalidParameterException:LibraryNotRegistered', array($name));
  41. throw new InvalidParameterException($error);
  42. }
  43. if (!include_once($CONFIG->libraries[$name])) {
  44. $error = elgg_echo('InvalidParameterException:LibraryNotFound', array(
  45. $name,
  46. $CONFIG->libraries[$name])
  47. );
  48. throw new InvalidParameterException($error);
  49. }
  50. }
  51. /**
  52. * Forward to $location.
  53. *
  54. * Sends a 'Location: $location' header and exists. If headers have
  55. * already been sent, returns FALSE.
  56. *
  57. * @param string $location URL to forward to browser to. Can be path relative to the network's URL.
  58. * @param string $reason Short explanation for why we're forwarding
  59. *
  60. * @return false False if headers have been sent. Terminates execution if forwarding.
  61. * @throws SecurityException
  62. */
  63. function forward($location = "", $reason = 'system') {
  64. if (!headers_sent($file, $line)) {
  65. if ($location === REFERER) {
  66. $location = $_SERVER['HTTP_REFERER'];
  67. }
  68. $location = elgg_normalize_url($location);
  69. // return new forward location or false to stop the forward or empty string to exit
  70. $current_page = current_page_url();
  71. $params = array('current_url' => $current_page, 'forward_url' => $location);
  72. $location = elgg_trigger_plugin_hook('forward', $reason, $params, $location);
  73. if ($location) {
  74. header("Location: {$location}");
  75. exit;
  76. } else if ($location === '') {
  77. exit;
  78. }
  79. } else {
  80. throw new SecurityException(elgg_echo('SecurityException:ForwardFailedToRedirect', array($file, $line)));
  81. }
  82. }
  83. /**
  84. * Register a JavaScript file for inclusion
  85. *
  86. * This function handles adding JavaScript to a web page. If multiple
  87. * calls are made to register the same JavaScript file based on the $id
  88. * variable, only the last file is included. This allows a plugin to add
  89. * JavaScript from a view that may be called more than once. It also handles
  90. * more than one plugin adding the same JavaScript.
  91. *
  92. * jQuery plugins often have filenames such as jquery.rating.js. A best practice
  93. * is to base $name on the filename: "jquery.rating". It is recommended to not
  94. * use version numbers in the name.
  95. *
  96. * The JavaScript files can be local to the server or remote (such as
  97. * Google's CDN).
  98. *
  99. * @param string $name An identifier for the JavaScript library
  100. * @param string $url URL of the JavaScript file
  101. * @param string $location Page location: head or footer. (default: head)
  102. * @param int $priority Priority of the JS file (lower numbers load earlier)
  103. *
  104. * @return bool
  105. * @since 1.8.0
  106. */
  107. function elgg_register_js($name, $url, $location = 'head', $priority = null) {
  108. if (is_array($url)) {
  109. $config = $url;
  110. $url = elgg_extract('src', $config);
  111. $location = elgg_extract('location', $config, 'footer');
  112. $priority = elgg_extract('priority', $config);
  113. _elgg_services()->amdConfig->setShim($name, $config);
  114. _elgg_services()->amdConfig->setPath($name, elgg_normalize_url($url));
  115. }
  116. return elgg_register_external_file('js', $name, $url, $location, $priority);
  117. }
  118. /**
  119. * Unregister a JavaScript file
  120. *
  121. * @param string $name The identifier for the JavaScript library
  122. *
  123. * @return bool
  124. * @since 1.8.0
  125. */
  126. function elgg_unregister_js($name) {
  127. return elgg_unregister_external_file('js', $name);
  128. }
  129. /**
  130. * Load a JavaScript resource on this page
  131. *
  132. * This must be called before elgg_view_page(). It can be called before the
  133. * script is registered. If you do not want a script loaded, unregister it.
  134. *
  135. * @param string $name Identifier of the JavaScript resource
  136. *
  137. * @return void
  138. * @since 1.8.0
  139. */
  140. function elgg_load_js($name) {
  141. elgg_load_external_file('js', $name);
  142. }
  143. /**
  144. * Request that Elgg load an AMD module onto the page.
  145. *
  146. * @param string $name The AMD module name.
  147. * @since 1.9.0
  148. */
  149. function elgg_require_js($name) {
  150. _elgg_services()->amdConfig->addDependency($name);
  151. }
  152. /**
  153. * Get the JavaScript URLs that are loaded
  154. *
  155. * @param string $location 'head' or 'footer'
  156. *
  157. * @return array
  158. * @since 1.8.0
  159. */
  160. function elgg_get_loaded_js($location = 'head') {
  161. return elgg_get_loaded_external_files('js', $location);
  162. }
  163. /**
  164. * Register a CSS file for inclusion in the HTML head
  165. *
  166. * @param string $name An identifier for the CSS file
  167. * @param string $url URL of the CSS file
  168. * @param int $priority Priority of the CSS file (lower numbers load earlier)
  169. *
  170. * @return bool
  171. * @since 1.8.0
  172. */
  173. function elgg_register_css($name, $url, $priority = null) {
  174. return elgg_register_external_file('css', $name, $url, 'head', $priority);
  175. }
  176. /**
  177. * Unregister a CSS file
  178. *
  179. * @param string $name The identifier for the CSS file
  180. *
  181. * @return bool
  182. * @since 1.8.0
  183. */
  184. function elgg_unregister_css($name) {
  185. return elgg_unregister_external_file('css', $name);
  186. }
  187. /**
  188. * Load a CSS file for this page
  189. *
  190. * This must be called before elgg_view_page(). It can be called before the
  191. * CSS file is registered. If you do not want a CSS file loaded, unregister it.
  192. *
  193. * @param string $name Identifier of the CSS file
  194. *
  195. * @return void
  196. * @since 1.8.0
  197. */
  198. function elgg_load_css($name) {
  199. elgg_load_external_file('css', $name);
  200. }
  201. /**
  202. * Get the loaded CSS URLs
  203. *
  204. * @return array
  205. * @since 1.8.0
  206. */
  207. function elgg_get_loaded_css() {
  208. return elgg_get_loaded_external_files('css', 'head');
  209. }
  210. /**
  211. * Core registration function for external files
  212. *
  213. * @param string $type Type of external resource (js or css)
  214. * @param string $name Identifier used as key
  215. * @param string $url URL
  216. * @param string $location Location in the page to include the file
  217. * @param int $priority Loading priority of the file
  218. *
  219. * @return bool
  220. * @since 1.8.0
  221. */
  222. function elgg_register_external_file($type, $name, $url, $location, $priority = 500) {
  223. global $CONFIG;
  224. if (empty($name) || empty($url)) {
  225. return false;
  226. }
  227. $url = elgg_format_url($url);
  228. $url = elgg_normalize_url($url);
  229. elgg_bootstrap_externals_data_structure($type);
  230. $name = trim(strtolower($name));
  231. // normalize bogus priorities, but allow empty, null, and false to be defaults.
  232. if (!is_numeric($priority)) {
  233. $priority = 500;
  234. }
  235. // no negative priorities right now.
  236. $priority = max((int)$priority, 0);
  237. $item = elgg_extract($name, $CONFIG->externals_map[$type]);
  238. if ($item) {
  239. // updating a registered item
  240. // don't update loaded because it could already be set
  241. $item->url = $url;
  242. $item->location = $location;
  243. // if loaded before registered, that means it hasn't been added to the list yet
  244. if ($CONFIG->externals[$type]->contains($item)) {
  245. $priority = $CONFIG->externals[$type]->move($item, $priority);
  246. } else {
  247. $priority = $CONFIG->externals[$type]->add($item, $priority);
  248. }
  249. } else {
  250. $item = new stdClass();
  251. $item->loaded = false;
  252. $item->url = $url;
  253. $item->location = $location;
  254. $priority = $CONFIG->externals[$type]->add($item, $priority);
  255. }
  256. $CONFIG->externals_map[$type][$name] = $item;
  257. return $priority !== false;
  258. }
  259. /**
  260. * Unregister an external file
  261. *
  262. * @param string $type Type of file: js or css
  263. * @param string $name The identifier of the file
  264. *
  265. * @return bool
  266. * @since 1.8.0
  267. */
  268. function elgg_unregister_external_file($type, $name) {
  269. global $CONFIG;
  270. elgg_bootstrap_externals_data_structure($type);
  271. $name = trim(strtolower($name));
  272. $item = elgg_extract($name, $CONFIG->externals_map[$type]);
  273. if ($item) {
  274. unset($CONFIG->externals_map[$type][$name]);
  275. return $CONFIG->externals[$type]->remove($item);
  276. }
  277. return false;
  278. }
  279. /**
  280. * Load an external resource for use on this page
  281. *
  282. * @param string $type Type of file: js or css
  283. * @param string $name The identifier for the file
  284. *
  285. * @return void
  286. * @since 1.8.0
  287. */
  288. function elgg_load_external_file($type, $name) {
  289. global $CONFIG;
  290. elgg_bootstrap_externals_data_structure($type);
  291. $name = trim(strtolower($name));
  292. $item = elgg_extract($name, $CONFIG->externals_map[$type]);
  293. if ($item) {
  294. // update a registered item
  295. $item->loaded = true;
  296. } else {
  297. $item = new stdClass();
  298. $item->loaded = true;
  299. $item->url = '';
  300. $item->location = '';
  301. $CONFIG->externals[$type]->add($item);
  302. $CONFIG->externals_map[$type][$name] = $item;
  303. }
  304. }
  305. /**
  306. * Get external resource descriptors
  307. *
  308. * @param string $type Type of file: js or css
  309. * @param string $location Page location
  310. *
  311. * @return array
  312. * @since 1.8.0
  313. */
  314. function elgg_get_loaded_external_files($type, $location) {
  315. global $CONFIG;
  316. if (isset($CONFIG->externals) && $CONFIG->externals[$type] instanceof ElggPriorityList) {
  317. $items = $CONFIG->externals[$type]->getElements();
  318. $callback = "return \$v->loaded == true && \$v->location == '$location';";
  319. $items = array_filter($items, create_function('$v', $callback));
  320. if ($items) {
  321. array_walk($items, create_function('&$v,$k', '$v = $v->url;'));
  322. }
  323. return $items;
  324. }
  325. return array();
  326. }
  327. /**
  328. * Bootstraps the externals data structure in $CONFIG.
  329. *
  330. * @param string $type The type of external, js or css.
  331. * @access private
  332. */
  333. function elgg_bootstrap_externals_data_structure($type) {
  334. global $CONFIG;
  335. if (!isset($CONFIG->externals)) {
  336. $CONFIG->externals = array();
  337. }
  338. if (!isset($CONFIG->externals[$type]) || !$CONFIG->externals[$type] instanceof ElggPriorityList) {
  339. $CONFIG->externals[$type] = new ElggPriorityList();
  340. }
  341. if (!isset($CONFIG->externals_map)) {
  342. $CONFIG->externals_map = array();
  343. }
  344. if (!isset($CONFIG->externals_map[$type])) {
  345. $CONFIG->externals_map[$type] = array();
  346. }
  347. }
  348. /**
  349. * Returns a list of files in $directory.
  350. *
  351. * Only returns files. Does not recurse into subdirs.
  352. *
  353. * @param string $directory Directory to look in
  354. * @param array $exceptions Array of filenames to ignore
  355. * @param array $list Array of files to append to
  356. * @param mixed $extensions Array of extensions to allow, NULL for all. Use a dot: array('.php').
  357. *
  358. * @return array Filenames in $directory, in the form $directory/filename.
  359. */
  360. function elgg_get_file_list($directory, $exceptions = array(), $list = array(),
  361. $extensions = NULL) {
  362. $directory = sanitise_filepath($directory);
  363. if ($handle = opendir($directory)) {
  364. while (($file = readdir($handle)) !== FALSE) {
  365. if (!is_file($directory . $file) || in_array($file, $exceptions)) {
  366. continue;
  367. }
  368. if (is_array($extensions)) {
  369. if (in_array(strrchr($file, '.'), $extensions)) {
  370. $list[] = $directory . $file;
  371. }
  372. } else {
  373. $list[] = $directory . $file;
  374. }
  375. }
  376. closedir($handle);
  377. }
  378. return $list;
  379. }
  380. /**
  381. * Sanitise file paths ensuring that they begin and end with slashes etc.
  382. *
  383. * @param string $path The path
  384. * @param bool $append_slash Add tailing slash
  385. *
  386. * @return string
  387. */
  388. function sanitise_filepath($path, $append_slash = TRUE) {
  389. // Convert to correct UNIX paths
  390. $path = str_replace('\\', '/', $path);
  391. $path = str_replace('../', '/', $path);
  392. // replace // with / except when preceeded by :
  393. $path = preg_replace("/([^:])\/\//", "$1/", $path);
  394. // Sort trailing slash
  395. $path = trim($path);
  396. // rtrim defaults plus /
  397. $path = rtrim($path, " \n\t\0\x0B/");
  398. if ($append_slash) {
  399. $path = $path . '/';
  400. }
  401. return $path;
  402. }
  403. /**
  404. * Queues a message to be displayed.
  405. *
  406. * Messages will not be displayed immediately, but are stored in
  407. * for later display, usually upon next page load.
  408. *
  409. * The method of displaying these messages differs depending upon plugins and
  410. * viewtypes. The core default viewtype retrieves messages in
  411. * {@link views/default/page/shells/default.php} and displays messages as
  412. * javascript popups.
  413. *
  414. * @internal Messages are stored as strings in the Elgg session as ['msg'][$register] array.
  415. *
  416. * @warning This function is used to both add to and clear the message
  417. * stack. If $messages is null, $register will be returned and cleared.
  418. * If $messages is null and $register is empty, all messages will be
  419. * returned and removed.
  420. *
  421. * @important This function handles the standard {@link system_message()} ($register =
  422. * 'messages') as well as {@link register_error()} messages ($register = 'errors').
  423. *
  424. * @param mixed $message Optionally, a single message or array of messages to add, (default: null)
  425. * @param string $register Types of message: "error", "success" (default: success)
  426. * @param bool $count Count the number of messages (default: false)
  427. *
  428. * @return bool|array Either the array of messages, or a response regarding
  429. * whether the message addition was successful.
  430. * @todo Clean up. Separate registering messages and retrieving them.
  431. */
  432. function system_messages($message = null, $register = "success", $count = false) {
  433. $session = _elgg_services()->session;
  434. $messages = $session->get('msg', array());
  435. if (!isset($messages[$register]) && !empty($register)) {
  436. $messages[$register] = array();
  437. }
  438. if (!$count) {
  439. if (!empty($message) && is_array($message)) {
  440. $messages[$register] = array_merge($messages[$register], $message);
  441. return true;
  442. } else if (!empty($message) && is_string($message)) {
  443. $messages[$register][] = $message;
  444. $session->set('msg', $messages);
  445. return true;
  446. } else if (is_null($message)) {
  447. if ($register != "") {
  448. $returnarray = array();
  449. $returnarray[$register] = $messages[$register];
  450. $messages[$register] = array();
  451. } else {
  452. $returnarray = $messages;
  453. $messages = array();
  454. }
  455. $session->set('msg', $messages);
  456. return $returnarray;
  457. }
  458. } else {
  459. if (!empty($register)) {
  460. return sizeof($messages[$register]);
  461. } else {
  462. $count = 0;
  463. foreach ($messages as $submessages) {
  464. $count += sizeof($submessages);
  465. }
  466. return $count;
  467. }
  468. }
  469. return false;
  470. }
  471. /**
  472. * Counts the number of messages, either globally or in a particular register
  473. *
  474. * @param string $register Optionally, the register
  475. *
  476. * @return integer The number of messages
  477. */
  478. function count_messages($register = "") {
  479. return system_messages(null, $register, true);
  480. }
  481. /**
  482. * Display a system message on next page load.
  483. *
  484. * @see system_messages()
  485. *
  486. * @param string|array $message Message or messages to add
  487. *
  488. * @return bool
  489. */
  490. function system_message($message) {
  491. return system_messages($message, "success");
  492. }
  493. /**
  494. * Display an error on next page load.
  495. *
  496. * @see system_messages()
  497. *
  498. * @param string|array $error Error or errors to add
  499. *
  500. * @return bool
  501. */
  502. function register_error($error) {
  503. return system_messages($error, "error");
  504. }
  505. /**
  506. * Register a callback as an Elgg event handler.
  507. *
  508. * Events are emitted by Elgg when certain actions occur. Plugins
  509. * can respond to these events or halt them completely by registering a handler
  510. * as a callback to an event. Multiple handlers can be registered for
  511. * the same event and will be executed in order of $priority. Any handler
  512. * returning false will halt the execution chain.
  513. *
  514. * This function is called with the event name, event type, and handler callback name.
  515. * Setting the optional $priority allows plugin authors to specify when the
  516. * callback should be run. Priorities for plugins should be 1-1000.
  517. *
  518. * The callback is passed 3 arguments when called: $event, $type, and optional $params.
  519. *
  520. * $event is the name of event being emitted.
  521. * $type is the type of event or object concerned.
  522. * $params is an optional parameter passed that can include a related object. See
  523. * specific event documentation for details on which events pass what parameteres.
  524. *
  525. * @tip If a priority isn't specified it is determined by the order the handler was
  526. * registered relative to the event and type. For plugins, this generally means
  527. * the earlier the plugin is in the load order, the earlier the priorities are for
  528. * any event handlers.
  529. *
  530. * @tip $event and $object_type can use the special keyword 'all'. Handler callbacks registered
  531. * with $event = all will be called for all events of type $object_type. Similarly,
  532. * callbacks registered with $object_type = all will be called for all events of type
  533. * $event, regardless of $object_type. If $event and $object_type both are 'all', the
  534. * handler callback will be called for all events.
  535. *
  536. * @tip Event handler callbacks are considered in the follow order:
  537. * - Specific registration where 'all' isn't used.
  538. * - Registration where 'all' is used for $event only.
  539. * - Registration where 'all' is used for $type only.
  540. * - Registration where 'all' is used for both.
  541. *
  542. * @warning If you use the 'all' keyword, you must have logic in the handler callback to
  543. * test the passed parameters before taking an action.
  544. *
  545. * @tip When referring to events, the preferred syntax is "event, type".
  546. *
  547. * @internal Events are stored in $CONFIG->events as:
  548. * <code>
  549. * $CONFIG->events[$event][$type][$priority] = $callback;
  550. * </code>
  551. *
  552. * @param string $event The event type
  553. * @param string $object_type The object type
  554. * @param string $callback The handler callback
  555. * @param int $priority The priority - 0 is default, negative before, positive after
  556. *
  557. * @return bool
  558. * @link http://docs.elgg.org/Tutorials/Plugins/Events
  559. * @example events/basic.php Basic example of registering an event handler callback.
  560. * @example events/advanced.php Advanced example of registering an event handler
  561. * callback and halting execution.
  562. * @example events/all.php Example of how to use the 'all' keyword.
  563. */
  564. function elgg_register_event_handler($event, $object_type, $callback, $priority = 500) {
  565. return _elgg_services()->events->registerHandler($event, $object_type, $callback, $priority);
  566. }
  567. /**
  568. * Unregisters a callback for an event.
  569. *
  570. * @param string $event The event type
  571. * @param string $object_type The object type
  572. * @param string $callback The callback
  573. *
  574. * @return void
  575. * @since 1.7
  576. */
  577. function elgg_unregister_event_handler($event, $object_type, $callback) {
  578. return _elgg_services()->events->unregisterHandler($event, $object_type, $callback);
  579. }
  580. /**
  581. * Trigger an Elgg Event and run all handler callbacks registered to that event, type.
  582. *
  583. * This function runs all handlers registered to $event, $object_type or
  584. * the special keyword 'all' for either or both.
  585. *
  586. * $event is usually a verb: create, update, delete, annotation.
  587. *
  588. * $object_type is usually a noun: object, group, user, annotation, relationship, metadata.
  589. *
  590. * $object is usually an Elgg* object assciated with the event.
  591. *
  592. * @warning Elgg events should only be triggered by core. Plugin authors should use
  593. * {@link trigger_elgg_plugin_hook()} instead.
  594. *
  595. * @tip When referring to events, the preferred syntax is "event, type".
  596. *
  597. * @internal Only rarely should events be changed, added, or removed in core.
  598. * When making changes to events, be sure to first create a ticket in trac.
  599. *
  600. * @internal @tip Think of $object_type as the primary namespace element, and
  601. * $event as the secondary namespace.
  602. *
  603. * @param string $event The event type
  604. * @param string $object_type The object type
  605. * @param string $object The object involved in the event
  606. *
  607. * @return bool The result of running all handler callbacks.
  608. * @link http://docs.elgg.org/Tutorials/Core/Events
  609. * @internal @example events/emit.php Basic emitting of an Elgg event.
  610. */
  611. function elgg_trigger_event($event, $object_type, $object = null) {
  612. return _elgg_services()->events->trigger($event, $object_type, $object);
  613. }
  614. /**
  615. * Register a callback as a plugin hook handler.
  616. *
  617. * Plugin hooks allow developers to losely couple plugins and features by
  618. * repsonding to and emitting {@link elgg_trigger_plugin_hook()} customizable hooks.
  619. * Handler callbacks can respond to the hook, change the details of the hook, or
  620. * ignore it.
  621. *
  622. * Multiple handlers can be registered for a plugin hook, and each callback
  623. * is called in order of priority. If the return value of a handler is not
  624. * null, that value is passed to the next callback in the call stack. When all
  625. * callbacks have been run, the final value is passed back to the caller
  626. * via {@link elgg_trigger_plugin_hook()}.
  627. *
  628. * Similar to Elgg Events, plugin hook handler callbacks are registered by passing
  629. * a hook, a type, and a priority.
  630. *
  631. * The callback is passed 4 arguments when called: $hook, $type, $value, and $params.
  632. *
  633. * - str $hook The name of the hook.
  634. * - str $type The type of hook.
  635. * - mixed $value The return value of the last handler or the default
  636. * value if no other handlers have been called.
  637. * - mixed $params An optional array of parameters. Used to provide additional
  638. * information to plugins.
  639. *
  640. * @internal Plugin hooks are stored in $CONFIG->hooks as:
  641. * <code>
  642. * $CONFIG->hooks[$hook][$type][$priority] = $callback;
  643. * </code>
  644. *
  645. * @tip Plugin hooks are similar to Elgg Events in that Elgg emits
  646. * a plugin hook when certain actions occur, but a plugin hook allows you to alter the
  647. * parameters, as well as halt execution.
  648. *
  649. * @tip If a priority isn't specified it is determined by the order the handler was
  650. * registered relative to the event and type. For plugins, this generally means
  651. * the earlier the plugin is in the load order, the earlier the priorities are for
  652. * any event handlers.
  653. *
  654. * @tip Like Elgg Events, $hook and $type can use the special keyword 'all'.
  655. * Handler callbacks registered with $hook = all will be called for all hooks
  656. * of type $type. Similarly, handlers registered with $type = all will be
  657. * called for all hooks of type $event, regardless of $object_type. If $hook
  658. * and $type both are 'all', the handler will be called for all hooks.
  659. *
  660. * @tip Plugin hooks are sometimes used to gather lists from plugins. This is
  661. * usually done by pushing elements into an array passed in $params. Be sure
  662. * to append to and then return $value so you don't overwrite other plugin's
  663. * values.
  664. *
  665. * @warning Unlike Elgg Events, a handler that returns false will NOT halt the
  666. * execution chain.
  667. *
  668. * @param string $hook The name of the hook
  669. * @param string $type The type of the hook
  670. * @param callable $callback The name of a valid function or an array with object and method
  671. * @param int $priority The priority - 500 is default, lower numbers called first
  672. *
  673. * @return bool
  674. *
  675. * @example hooks/register/basic.php Registering for a plugin hook and examining the variables.
  676. * @example hooks/register/advanced.php Registering for a plugin hook and changing the params.
  677. * @link http://docs.elgg.org/Tutorials/Plugins/Hooks
  678. * @since 1.8.0
  679. */
  680. function elgg_register_plugin_hook_handler($hook, $type, $callback, $priority = 500) {
  681. return _elgg_services()->hooks->registerHandler($hook, $type, $callback, $priority);
  682. }
  683. /**
  684. * Unregister a callback as a plugin hook.
  685. *
  686. * @param string $hook The name of the hook
  687. * @param string $entity_type The name of the type of entity (eg "user", "object" etc)
  688. * @param callable $callback The PHP callback to be removed
  689. *
  690. * @return void
  691. * @since 1.8.0
  692. */
  693. function elgg_unregister_plugin_hook_handler($hook, $entity_type, $callback) {
  694. _elgg_services()->hooks->unregisterHandler($hook, $entity_type, $callback);
  695. }
  696. /**
  697. * Trigger a Plugin Hook and run all handler callbacks registered to that hook:type.
  698. *
  699. * This function runs all handlers regsitered to $hook, $type or
  700. * the special keyword 'all' for either or both.
  701. *
  702. * Use $params to send additional information to the handler callbacks.
  703. *
  704. * $returnvalue Is the initial value to pass to the handlers, which can
  705. * then change it. It is useful to use $returnvalue to set defaults.
  706. * If no handlers are registered, $returnvalue is immediately returned.
  707. *
  708. * $hook is usually a verb: import, get_views, output.
  709. *
  710. * $type is usually a noun: user, ecml, page.
  711. *
  712. * @tip Like Elgg Events, $hook and $type can use the special keyword 'all'.
  713. * Handler callbacks registered with $hook = all will be called for all hooks
  714. * of type $type. Similarly, handlers registered with $type = all will be
  715. * called for all hooks of type $event, regardless of $object_type. If $hook
  716. * and $type both are 'all', the handler will be called for all hooks.
  717. *
  718. * @internal The checks for $hook and/or $type not being equal to 'all' is to
  719. * prevent a plugin hook being registered with an 'all' being called more than
  720. * once if the trigger occurs with an 'all'. An example in core of this is in
  721. * actions.php:
  722. * elgg_trigger_plugin_hook('action_gatekeeper:permissions:check', 'all', ...)
  723. *
  724. * @see elgg_register_plugin_hook_handler()
  725. *
  726. * @param string $hook The name of the hook to trigger ("all" will
  727. * trigger for all $types regardless of $hook value)
  728. * @param string $type The type of the hook to trigger ("all" will
  729. * trigger for all $hooks regardless of $type value)
  730. * @param mixed $params Additional parameters to pass to the handlers
  731. * @param mixed $returnvalue An initial return value
  732. *
  733. * @return mixed|null The return value of the last handler callback called
  734. *
  735. * @example hooks/trigger/basic.php Trigger a hook that determins if execution
  736. * should continue.
  737. * @example hooks/trigger/advanced.php Trigger a hook with a default value and use
  738. * the results to populate a menu.
  739. * @example hooks/basic.php Trigger and respond to a basic plugin hook.
  740. * @link http://docs.elgg.org/Tutorials/Plugins/Hooks
  741. *
  742. * @since 1.8.0
  743. */
  744. function elgg_trigger_plugin_hook($hook, $type, $params = null, $returnvalue = null) {
  745. return _elgg_services()->hooks->trigger($hook, $type, $params, $returnvalue);
  746. }
  747. /**
  748. * Intercepts, logs, and displays uncaught exceptions.
  749. *
  750. * To use a viewtype other than failsafe, create the views:
  751. * <viewtype>/messages/exceptions/admin_exception
  752. * <viewtype>/messages/exceptions/exception
  753. * See the json viewtype for an example.
  754. *
  755. * @warning This function should never be called directly.
  756. *
  757. * @see http://www.php.net/set-exception-handler
  758. *
  759. * @param Exception $exception The exception being handled
  760. *
  761. * @return void
  762. * @access private
  763. */
  764. function _elgg_php_exception_handler($exception) {
  765. $timestamp = time();
  766. error_log("Exception #$timestamp: $exception");
  767. // Wipe any existing output buffer
  768. ob_end_clean();
  769. // make sure the error isn't cached
  770. header("Cache-Control: no-cache, must-revalidate", true);
  771. header('Expires: Fri, 05 Feb 1982 00:00:00 -0500', true);
  772. // @note Do not send a 500 header because it is not a server error
  773. // we don't want the 'pagesetup', 'system' event to fire
  774. global $CONFIG;
  775. $CONFIG->pagesetupdone = true;
  776. try {
  777. if (elgg_is_admin_logged_in()) {
  778. if (!elgg_view_exists("messages/exceptions/admin_exception")) {
  779. elgg_set_viewtype('failsafe');
  780. }
  781. $body = elgg_view("messages/exceptions/admin_exception", array(
  782. 'object' => $exception,
  783. 'ts' => $timestamp
  784. ));
  785. } else {
  786. if (!elgg_view_exists("messages/exceptions/exception")) {
  787. elgg_set_viewtype('failsafe');
  788. }
  789. $body = elgg_view("messages/exceptions/exception", array(
  790. 'object' => $exception,
  791. 'ts' => $timestamp
  792. ));
  793. }
  794. echo elgg_view_page(elgg_echo('exception:title'), $body);
  795. } catch (Exception $e) {
  796. $timestamp = time();
  797. $message = $e->getMessage();
  798. echo "Fatal error in exception handler. Check log for Exception #$timestamp";
  799. error_log("Exception #$timestamp : fatal error in exception handler : $message");
  800. }
  801. }
  802. /**
  803. * Intercepts catchable PHP errors.
  804. *
  805. * @warning This function should never be called directly.
  806. *
  807. * @internal
  808. * For catchable fatal errors, throws an Exception with the error.
  809. *
  810. * For non-fatal errors, depending upon the debug settings, either
  811. * log the error or ignore it.
  812. *
  813. * @see http://www.php.net/set-error-handler
  814. *
  815. * @param int $errno The level of the error raised
  816. * @param string $errmsg The error message
  817. * @param string $filename The filename the error was raised in
  818. * @param int $linenum The line number the error was raised at
  819. * @param array $vars An array that points to the active symbol table where error occurred
  820. *
  821. * @return true
  822. * @throws Exception
  823. * @access private
  824. * @todo Replace error_log calls with elgg_log calls.
  825. */
  826. function _elgg_php_error_handler($errno, $errmsg, $filename, $linenum, $vars) {
  827. $error = date("Y-m-d H:i:s (T)") . ": \"$errmsg\" in file $filename (line $linenum)";
  828. switch ($errno) {
  829. case E_USER_ERROR:
  830. error_log("PHP ERROR: $error");
  831. register_error("ERROR: $error");
  832. // Since this is a fatal error, we want to stop any further execution but do so gracefully.
  833. throw new Exception($error);
  834. break;
  835. case E_WARNING :
  836. case E_USER_WARNING :
  837. case E_RECOVERABLE_ERROR: // (e.g. type hint violation)
  838. // check if the error wasn't suppressed by the error control operator (@)
  839. if (error_reporting()) {
  840. error_log("PHP WARNING: $error");
  841. }
  842. break;
  843. default:
  844. global $CONFIG;
  845. if (isset($CONFIG->debug) && $CONFIG->debug === 'NOTICE') {
  846. error_log("PHP NOTICE: $error");
  847. }
  848. }
  849. return true;
  850. }
  851. /**
  852. * Display or log a message.
  853. *
  854. * If $level is >= to the debug setting in {@link $CONFIG->debug}, the
  855. * message will be sent to {@link elgg_dump()}. Messages with lower
  856. * priority than {@link $CONFIG->debug} are ignored.
  857. *
  858. * {@link elgg_dump()} outputs all levels but NOTICE to screen by default.
  859. *
  860. * @note No messages will be displayed unless debugging has been enabled.
  861. *
  862. * @param string $message User message
  863. * @param string $level NOTICE | WARNING | ERROR | DEBUG
  864. *
  865. * @return bool
  866. * @since 1.7.0
  867. * @todo This is complicated and confusing. Using int constants for debug levels will
  868. * make things easier.
  869. */
  870. function elgg_log($message, $level = 'NOTICE') {
  871. return _elgg_services()->logger->log($message, $level);
  872. }
  873. /**
  874. * Logs or displays $value.
  875. *
  876. * If $to_screen is true, $value is displayed to screen. Else,
  877. * it is handled by PHP's {@link error_log()} function.
  878. *
  879. * A {@elgg_plugin_hook debug log} is called. If a handler returns
  880. * false, it will stop the default logging method.
  881. *
  882. * @param mixed $value The value
  883. * @param bool $to_screen Display to screen?
  884. * @param string $level The debug level
  885. *
  886. * @since 1.7.0
  887. */
  888. function elgg_dump($value, $to_screen = TRUE, $level = 'NOTICE') {
  889. _elgg_services()->logger->dump($value, $to_screen, $level);
  890. }
  891. /**
  892. * Sends a notice about deprecated use of a function, view, etc.
  893. *
  894. * This function either displays or logs the deprecation message,
  895. * depending upon the deprecation policies in {@link CODING.txt}.
  896. * Logged messages are sent with the level of 'WARNING'. Only admins
  897. * get visual deprecation notices. When non-admins are logged in, the
  898. * notices are sent to PHP's log through elgg_dump().
  899. *
  900. * A user-visual message will be displayed if $dep_version is greater
  901. * than 1 minor releases lower than the current Elgg version, or at all
  902. * lower than the current Elgg major version.
  903. *
  904. * @note This will always at least log a warning. Don't use to pre-deprecate things.
  905. * This assumes we are releasing in order and deprecating according to policy.
  906. *
  907. * @see CODING.txt
  908. *
  909. * @param string $msg Message to log / display.
  910. * @param string $dep_version Human-readable *release* version: 1.7, 1.8, ...
  911. * @param int $backtrace_level How many levels back to display the backtrace.
  912. * Useful if calling from functions that are called
  913. * from other places (like elgg_view()). Set to -1
  914. * for a full backtrace.
  915. *
  916. * @return bool
  917. * @since 1.7.0
  918. */
  919. function elgg_deprecated_notice($msg, $dep_version, $backtrace_level = 1) {
  920. // if it's a major release behind, visual and logged
  921. // if it's a 1 minor release behind, visual and logged
  922. // if it's for current minor release, logged.
  923. // bugfixes don't matter because we are not deprecating between them
  924. if (!$dep_version) {
  925. return false;
  926. }
  927. $elgg_version = get_version(true);
  928. $elgg_version_arr = explode('.', $elgg_version);
  929. $elgg_major_version = (int)$elgg_version_arr[0];
  930. $elgg_minor_version = (int)$elgg_version_arr[1];
  931. $dep_major_version = (int)$dep_version;
  932. $dep_minor_version = 10 * ($dep_version - $dep_major_version);
  933. $visual = false;
  934. if (($dep_major_version < $elgg_major_version) ||
  935. ($dep_minor_version < $elgg_minor_version)) {
  936. $visual = true;
  937. }
  938. $msg = "Deprecated in $dep_major_version.$dep_minor_version: $msg";
  939. if ($visual && elgg_is_admin_logged_in()) {
  940. register_error($msg);
  941. }
  942. // Get a file and line number for the log. Never show this in the UI.
  943. // Skip over the function that sent this notice and see who called the deprecated
  944. // function itself.
  945. $msg .= " Called from ";
  946. $stack = array();
  947. $backtrace = debug_backtrace();
  948. // never show this call.
  949. array_shift($backtrace);
  950. $i = count($backtrace);
  951. foreach ($backtrace as $trace) {
  952. $stack[] = "[#$i] {$trace['file']}:{$trace['line']}";
  953. $i--;
  954. if ($backtrace_level > 0) {
  955. if ($backtrace_level <= 1) {
  956. break;
  957. }
  958. $backtrace_level--;
  959. }
  960. }
  961. $msg .= implode("<br /> -> ", $stack);
  962. elgg_log($msg, 'WARNING');
  963. return true;
  964. }
  965. /**
  966. * Returns the current page's complete URL.
  967. *
  968. * The current URL is assembled using the network's wwwroot and the request URI
  969. * in $_SERVER as populated by the web server. This function will include
  970. * any schemes, usernames and passwords, and ports.
  971. *
  972. * @return string The current page URL.
  973. */
  974. function current_page_url() {
  975. $url = parse_url(elgg_get_site_url());
  976. $page = $url['scheme'] . "://";
  977. // user/pass
  978. if ((isset($url['user'])) && ($url['user'])) {
  979. $page .= $url['user'];
  980. }
  981. if ((isset($url['pass'])) && ($url['pass'])) {
  982. $page .= ":" . $url['pass'];
  983. }
  984. if ((isset($url['user']) && $url['user']) ||
  985. (isset($url['pass']) && $url['pass'])) {
  986. $page .= "@";
  987. }
  988. $page .= $url['host'];
  989. if ((isset($url['port'])) && ($url['port'])) {
  990. $page .= ":" . $url['port'];
  991. }
  992. $page = trim($page, "/");
  993. $page .= $_SERVER['REQUEST_URI'];
  994. return $page;
  995. }
  996. /**
  997. * Return the full URL of the current page.
  998. *
  999. * @return string The URL
  1000. * @todo Combine / replace with current_page_url()
  1001. */
  1002. function full_url() {
  1003. $s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
  1004. $protocol = substr(strtolower($_SERVER["SERVER_PROTOCOL"]), 0,
  1005. strpos(strtolower($_SERVER["SERVER_PROTOCOL"]), "/")) . $s;
  1006. $port = ($_SERVER["SERVER_PORT"] == "80" || $_SERVER["SERVER_PORT"] == "443") ?
  1007. "" : (":" . $_SERVER["SERVER_PORT"]);
  1008. // This is here to prevent XSS in poorly written browsers used by 80% of the population.
  1009. // {@trac [5813]}
  1010. $quotes = array('\'', '"');
  1011. $encoded = array('%27', '%22');
  1012. return $protocol . "://" . $_SERVER['SERVER_NAME'] . $port .
  1013. str_replace($quotes, $encoded, $_SERVER['REQUEST_URI']);
  1014. }
  1015. /**
  1016. * Builds a URL from the a parts array like one returned by {@link parse_url()}.
  1017. *
  1018. * @note If only partial information is passed, a partial URL will be returned.
  1019. *
  1020. * @param array $parts Associative array of URL components like parse_url() returns
  1021. * @param bool $html_encode HTML Encode the url?
  1022. *
  1023. * @return string Full URL
  1024. * @since 1.7.0
  1025. */
  1026. function elgg_http_build_url(array $parts, $html_encode = TRUE) {
  1027. // build only what's given to us.
  1028. $scheme = isset($parts['scheme']) ? "{$parts['scheme']}://" : '';
  1029. $host = isset($parts['host']) ? "{$parts['host']}" : '';
  1030. $port = isset($parts['port']) ? ":{$parts['port']}" : '';
  1031. $path = isset($parts['path']) ? "{$parts['path']}" : '';
  1032. $query = isset($parts['query']) ? "?{$parts['query']}" : '';
  1033. $string = $scheme . $host . $port . $path . $query;
  1034. if ($html_encode) {
  1035. return elgg_format_url($string);
  1036. } else {
  1037. return $string;
  1038. }
  1039. }
  1040. /**
  1041. * Adds action tokens to URL
  1042. *
  1043. * As of 1.7.0 action tokens are required on all actions.
  1044. * Use this function to append action tokens to a URL's GET parameters.
  1045. * This will preserve any existing GET parameters.
  1046. *
  1047. * @note If you are using {@elgg_view input/form} you don't need to
  1048. * add tokens to the action. The form view automatically handles
  1049. * tokens.
  1050. *
  1051. * @param string $url Full action URL
  1052. * @param bool $html_encode HTML encode the url? (default: false)
  1053. *
  1054. * @return string URL with action tokens
  1055. * @since 1.7.0
  1056. * @link http://docs.elgg.org/Tutorials/Actions
  1057. */
  1058. function elgg_add_action_tokens_to_url($url, $html_encode = FALSE) {
  1059. $components = parse_url(elgg_normalize_url($url));
  1060. if (isset($components['query'])) {
  1061. $query = elgg_parse_str($components['query']);
  1062. } else {
  1063. $query = array();
  1064. }
  1065. if (isset($query['__elgg_ts']) && isset($query['__elgg_token'])) {
  1066. return $url;
  1067. }
  1068. // append action tokens to the existing query
  1069. $query['__elgg_ts'] = time();
  1070. $query['__elgg_token'] = generate_action_token($query['__elgg_ts']);
  1071. $components['query'] = http_build_query($query);
  1072. // rebuild the full url
  1073. return elgg_http_build_url($components, $html_encode);
  1074. }
  1075. /**
  1076. * Removes an element from a URL's query string.
  1077. *
  1078. * @note You can send a partial URL string.
  1079. *
  1080. * @param string $url Full URL
  1081. * @param string $element The element to remove
  1082. *
  1083. * @return string The new URL with the query element removed.
  1084. * @since 1.7.0
  1085. */
  1086. function elgg_http_remove_url_query_element($url, $element) {
  1087. $url_array = parse_url($url);
  1088. if (isset($url_array['query'])) {
  1089. $query = elgg_parse_str($url_array['query']);
  1090. } else {
  1091. // nothing to remove. Return original URL.
  1092. return $url;
  1093. }
  1094. if (array_key_exists($element, $query)) {
  1095. unset($query[$element]);
  1096. }
  1097. $url_array['query'] = http_build_query($query);
  1098. $string = elgg_http_build_url($url_array, false);
  1099. return $string;
  1100. }
  1101. /**
  1102. * Adds an element or elements to a URL's query string.
  1103. *
  1104. * @param string $url The URL
  1105. * @param array $elements Key/value pairs to add to the URL
  1106. *
  1107. * @return string The new URL with the query strings added
  1108. * @since 1.7.0
  1109. */
  1110. function elgg_http_add_url_query_elements($url, array $elements) {
  1111. $url_array = parse_url($url);
  1112. if (isset($url_array['query'])) {
  1113. $query = elgg_parse_str($url_array['query']);
  1114. } else {
  1115. $query = array();
  1116. }
  1117. foreach ($elements as $k => $v) {
  1118. $query[$k] = $v;
  1119. }
  1120. $url_array['query'] = http_build_query($query);
  1121. $string = elgg_http_build_url($url_array, false);
  1122. return $string;
  1123. }
  1124. /**
  1125. * Test if two URLs are functionally identical.
  1126. *
  1127. * @tip If $ignore_params is used, neither the name nor its value will be considered when comparing.
  1128. *
  1129. * @tip The order of GET params doesn't matter.
  1130. *
  1131. * @param string $url1 First URL
  1132. * @param string $url2 Second URL
  1133. * @param array $ignore_params GET params to ignore in the comparison
  1134. *
  1135. * @return bool
  1136. * @since 1.8.0
  1137. */
  1138. function elgg_http_url_is_identical($url1, $url2, $ignore_params = array('offset', 'limit')) {
  1139. // if the server portion is missing but it starts with / then add the url in.
  1140. // @todo use elgg_normalize_url()
  1141. if (elgg_substr($url1, 0, 1) == '/') {
  1142. $url1 = elgg_get_site_url() . ltrim($url1, '/');
  1143. }
  1144. if (elgg_substr($url1, 0, 1) == '/') {
  1145. $url2 = elgg_get_site_url() . ltrim($url2, '/');
  1146. }
  1147. // @todo - should probably do something with relative URLs
  1148. if ($url1 == $url2) {
  1149. return TRUE;
  1150. }
  1151. $url1_info = parse_url($url1);
  1152. $url2_info = parse_url($url2);
  1153. if (isset($url1_info['path'])) {
  1154. $url1_info['path'] = trim($url1_info['path'], '/');
  1155. }
  1156. if (isset($url2_info['path'])) {
  1157. $url2_info['path'] = trim($url2_info['path'], '/');
  1158. }
  1159. // compare basic bits
  1160. $parts = array('scheme', 'host', 'path');
  1161. foreach ($parts as $part) {
  1162. if ((isset($url1_info[$part]) && isset($url2_info[$part]))
  1163. && $url1_info[$part] != $url2_info[$part]) {
  1164. return FALSE;
  1165. } elseif (isset($url1_info[$part]) && !isset($url2_info[$part])) {
  1166. return FALSE;
  1167. } elseif (!isset($url1_info[$part]) && isset($url2_info[$part])) {
  1168. return FALSE;
  1169. }
  1170. }
  1171. // quick compare of get params
  1172. if (isset($url1_info['query']) && isset($url2_info['query'])
  1173. && $url1_info['query'] == $url2_info['query']) {
  1174. return TRUE;
  1175. }
  1176. // compare get params that might be out of order
  1177. $url1_params = array();
  1178. $url2_params = array();
  1179. if (isset($url1_info['query'])) {
  1180. if ($url1_info['query'] = html_entity_decode($url1_info['query'])) {
  1181. $url1_params = elgg_parse_str($url1_info['query']);
  1182. }
  1183. }
  1184. if (isset($url2_info['query'])) {
  1185. if ($url2_info['query'] = html_entity_decode($url2_info['query'])) {
  1186. $url2_params = elgg_parse_str($url2_info['query']);
  1187. }
  1188. }
  1189. // drop ignored params
  1190. foreach ($ignore_params as $param) {
  1191. if (isset($url1_params[$param])) {
  1192. unset($url1_params[$param]);
  1193. }
  1194. if (isset($url2_params[$param])) {
  1195. unset($url2_params[$param]);
  1196. }
  1197. }
  1198. // array_diff_assoc only returns the items in arr1 that aren't in arrN
  1199. // but not the items that ARE in arrN but NOT in arr1
  1200. // if arr1 is an empty array, this function will return 0 no matter what.
  1201. // since we only care if they're different and not how different,
  1202. // add the results together to get a non-zero (ie, different) result
  1203. $diff_count = count(array_diff_assoc($url1_params, $url2_params));
  1204. $diff_count += count(array_diff_assoc($url2_params, $url1_params));
  1205. if ($diff_count > 0) {
  1206. return FALSE;
  1207. }
  1208. return TRUE;
  1209. }
  1210. /**
  1211. * Checks for $array[$key] and returns its value if it exists, else
  1212. * returns $default.
  1213. *
  1214. * Shorthand for $value = (isset($array['key'])) ? $array['key'] : 'default';
  1215. *
  1216. * @param string $key The key to check.
  1217. * @param array $array The array to check against.
  1218. * @param mixed $default Default value to return if nothing is found.
  1219. * @param bool $strict Return array key if it's set, even if empty. If false,
  1220. * return $default if the array key is unset or empty.
  1221. *
  1222. * @return mixed
  1223. * @since 1.8.0
  1224. */
  1225. function elgg_extract($key, array $array, $default = null, $strict = true) {
  1226. if (!is_array($array)) {
  1227. return $default;
  1228. }
  1229. if ($strict) {
  1230. return (isset($array[$key])) ? $array[$key] : $default;
  1231. } else {
  1232. return (isset($array[$key]) && !empty($array[$key])) ? $array[$key] : $default;
  1233. }
  1234. }
  1235. /**
  1236. * Sorts a 3d array by specific element.
  1237. *
  1238. * @warning Will re-index numeric indexes.
  1239. *
  1240. * @note This operates the same as the built-in sort functions.
  1241. * It sorts the array and returns a bool for success.
  1242. *
  1243. * Do this: elgg_sort_3d_array_by_value($my_array);
  1244. * Not this: $my_array = elgg_sort_3d_array_by_value($my_array);
  1245. *
  1246. * @param array &$array Array to sort
  1247. * @param string $element Element to sort by
  1248. * @param int $sort_order PHP sort order
  1249. * {@see http://us2.php.net/array_multisort}
  1250. * @param int $sort_type PHP sort type
  1251. * {@see http://us2.php.net/sort}
  1252. *
  1253. * @return bool
  1254. */
  1255. function elgg_sort_3d_array_by_value(&$array, $element, $sort_order = SORT_ASC,
  1256. $sort_type = SORT_LOCALE_STRING) {
  1257. $sort = array();
  1258. foreach ($array as $v) {
  1259. if (isset($v[$element])) {
  1260. $sort[] = strtolower($v[$element]);
  1261. } else {
  1262. $sort[] = NULL;
  1263. }
  1264. };
  1265. return array_multisort($sort, $sort_order, $sort_type, $array);
  1266. }
  1267. /**
  1268. * Return the state of a php.ini setting as a bool
  1269. *
  1270. * @warning Using this on ini settings that are not boolean
  1271. * will be inaccurate!
  1272. *
  1273. * @param string $ini_get_arg The INI setting
  1274. *
  1275. * @return bool Depending on whether it's on or off
  1276. */
  1277. function ini_get_bool($ini_get_arg) {
  1278. $temp = strtolower(ini_get($ini_get_arg));
  1279. if ($temp == '1' || $temp == 'on' || $temp == 'true') {
  1280. return true;
  1281. }
  1282. return false;
  1283. }
  1284. /**
  1285. * Returns a PHP INI setting in bytes.
  1286. *
  1287. * @tip Use this for arithmetic when determining if a file can be uploaded.
  1288. *
  1289. * @param string $setting The php.ini setting
  1290. *
  1291. * @return int
  1292. * @since 1.7.0
  1293. * @link http://www.php.net/manual/en/function.ini-get.php
  1294. */
  1295. function elgg_get_ini_setting_in_bytes($setting) {
  1296. // retrieve INI setting
  1297. $val = ini_get($setting);
  1298. // convert INI setting when shorthand notation is used
  1299. $last = strtolower($val[strlen($val) - 1]);
  1300. switch($last) {
  1301. case 'g':
  1302. $val *= 1024;
  1303. // fallthrough intentional
  1304. case 'm':
  1305. $val *= 1024;
  1306. // fallthrough intentional
  1307. case 'k':
  1308. $val *= 1024;
  1309. }
  1310. // return byte value
  1311. return $val;
  1312. }
  1313. /**
  1314. * Returns true is string is not empty, false, or null.
  1315. *
  1316. * Function to be used in array_filter which returns true if $string is not null.
  1317. *
  1318. * @param string $string The string to test
  1319. *
  1320. * @return bool
  1321. * @todo This is used once in metadata.php. Use a lambda function instead.
  1322. */
  1323. function is_not_null($string) {
  1324. if (($string === '') || ($string === false) || ($string === null)) {
  1325. return false;
  1326. }
  1327. return true;
  1328. }
  1329. /**
  1330. * Normalise the singular keys in an options array to plural keys.
  1331. *
  1332. * Used in elgg_get_entities*() functions to support shortcutting plural
  1333. * names by singular names.
  1334. *
  1335. * @param array $options The options array. $options['keys'] = 'values';
  1336. * @param array $singulars A list of singular words to pluralize by adding 's'.
  1337. *
  1338. * @return array
  1339. * @since 1.7.0
  1340. * @access private
  1341. */
  1342. function elgg_normalise_plural_options_array($options, $singulars) {
  1343. foreach ($singulars as $singular) {
  1344. $plural = $singular . 's';
  1345. if (array_key_exists($singular, $options)) {
  1346. if ($options[$singular] === ELGG_ENTITIES_ANY_VALUE) {
  1347. $options[$plural] = $options[$singular];
  1348. } else {
  1349. // Test for array refs #2641
  1350. if (!is_array($options[$singular])) {
  1351. $options[$plural] = array($options[$singular]);
  1352. } else {
  1353. $options[$plural] = $options[$singular];
  1354. }
  1355. }
  1356. }
  1357. unset($options[$singular]);
  1358. }
  1359. return $options;
  1360. }
  1361. /**
  1362. * Emits a shutdown:system event upon PHP shutdown, but before database connections are dropped.
  1363. *
  1364. * @tip Register for the shutdown:system event to perform functions at the end of page loads.
  1365. *
  1366. * @warning Using this event to perform long-running functions is not very
  1367. * useful. Servers will hold pages until processing is done before sending
  1368. * them out to the browser.
  1369. *
  1370. * @see http://www.php.net/register-shutdown-function
  1371. *
  1372. * @return void
  1373. * @see register_shutdown_hook()
  1374. * @access private
  1375. */
  1376. function _elgg_shutdown_hook() {
  1377. global $START_MICROTIME;
  1378. try {
  1379. elgg_trigger_event('shutdown', 'system');
  1380. $time = (float)(microtime(TRUE) - $START_MICROTIME);
  1381. // demoted to NOTICE from DEBUG so javascript is not corrupted
  1382. elgg_log("Page {$_SERVER['REQUEST_URI']} generated in $time seconds", 'NOTICE');
  1383. } catch (Exception $e) {
  1384. $message = 'Error: ' . get_class($e) . ' thrown within the shutdown handler. ';
  1385. $message .= "Message: '{$e->getMessage()}' in file {$e->getFile()} (line {$e->getLine()})";
  1386. error_log($message);
  1387. error_log("Exception trace stack: {$e->getTraceAsString()}");
  1388. }
  1389. }
  1390. /**
  1391. * Serve javascript pages.
  1392. *
  1393. * Searches for views under js/ and outputs them with special
  1394. * headers for caching control.
  1395. *
  1396. * @param array $page The page array
  1397. *
  1398. * @return bool
  1399. * @elgg_pagehandler js
  1400. * @access private
  1401. */
  1402. function elgg_js_page_handler($page) {
  1403. return elgg_cacheable_view_page_handler($page, 'js');
  1404. }
  1405. /**
  1406. * Serve individual views for Ajax.
  1407. *
  1408. * /ajax/view/<name of view>?<key/value params>
  1409. *
  1410. * @param array $page The page array
  1411. *
  1412. * @return bool
  1413. * @elgg_pagehandler ajax
  1414. * @access private
  1415. */
  1416. function elgg_ajax_page_handler($page) {
  1417. if (is_array($page) && sizeof($page)) {
  1418. // throw away 'view' and form the view name
  1419. unset($page[0]);
  1420. $view = implode('/', $page);
  1421. $allowed_views = elgg_get_config('allowed_ajax_views');
  1422. if (!array_key_exists($view, $allowed_views)) {
  1423. header('HTTP/1.1 403 Forbidden');
  1424. exit;
  1425. }
  1426. // pull out GET parameters through filter
  1427. $vars = array();
  1428. foreach ($_GET as $name => $value) {
  1429. $vars[$name] = get_input($name);
  1430. }
  1431. if (isset($vars['guid'])) {
  1432. $vars['entity'] = get_entity($vars['guid']);
  1433. }
  1434. // Try to guess the mime-type
  1435. switch ($page[1]) {
  1436. case "js":
  1437. header("Content-Type: text/javascript");
  1438. break;
  1439. case "css":
  1440. header("Content-Type: text/css");
  1441. break;
  1442. }
  1443. echo elgg_view($view, $vars);
  1444. return true;
  1445. }
  1446. return false;
  1447. }
  1448. /**
  1449. * Serve CSS
  1450. *
  1451. * Serves CSS from the css views directory with headers for caching control
  1452. *
  1453. * @param array $page The page array
  1454. *
  1455. * @return bool
  1456. * @elgg_pagehandler css
  1457. * @access private
  1458. */
  1459. function elgg_css_page_handler($page) {
  1460. if (!isset($page[0])) {
  1461. // default css
  1462. $page[0] = 'elgg';
  1463. }
  1464. return elgg_cacheable_view_page_handler($page, 'css');
  1465. }
  1466. /**
  1467. * Serves a JS or CSS view with headers for caching.
  1468. *
  1469. * /<css||js>/name/of/view.<last_cache>.<css||js>
  1470. *
  1471. * @param array $page The page array
  1472. * @param string $type The type: js or css
  1473. *
  1474. * @return bool
  1475. * @access private
  1476. */
  1477. function elgg_cacheable_view_page_handler($page, $type) {
  1478. switch ($type) {
  1479. case 'js':
  1480. $content_type = 'text/javascript';
  1481. break;
  1482. case 'css':
  1483. $content_type = 'text/css';
  1484. break;
  1485. default:
  1486. return false;
  1487. break;
  1488. }
  1489. if ($page) {
  1490. // the view file names can have multiple dots
  1491. // eg: views/default/js/calendars/jquery.fullcalendar.min.php
  1492. // translates to the url /js/<ts>/calendars/jquery.fullcalendar.min.js
  1493. // and the view js/calendars/jquery.fullcalendar.min
  1494. // we ignore the last two dots for the ts and the ext.
  1495. // Additionally, the times…

Large files files are truncated, but you can click here to view the full file