diff options
Diffstat (limited to 'engine/lib/elgglib.php')
| -rw-r--r-- | engine/lib/elgglib.php | 852 |
1 files changed, 624 insertions, 228 deletions
diff --git a/engine/lib/elgglib.php b/engine/lib/elgglib.php index 3511be0ca..34111c69d 100644 --- a/engine/lib/elgglib.php +++ b/engine/lib/elgglib.php @@ -18,6 +18,7 @@ elgg_register_classes(dirname(dirname(__FILE__)) . '/classes'); * * @return void * @throws Exception + * @access private */ function _elgg_autoload($class) { global $CONFIG; @@ -33,21 +34,15 @@ function _elgg_autoload($class) { * * @param string $dir The dir to look in * - * @return true + * @return void * @since 1.8.0 */ function elgg_register_classes($dir) { $classes = elgg_get_file_list($dir, array(), array(), array('.php')); - if (!$classes) { - return false; - } - foreach ($classes as $class) { elgg_register_class(basename($class, '.php'), $class); } - - return true; } /** @@ -98,10 +93,17 @@ function elgg_register_library($name, $location) { * @return void * @throws InvalidParameterException * @since 1.8.0 + * @todo return boolean in 1.9 to indicate whether the library has been loaded */ function elgg_load_library($name) { global $CONFIG; + static $loaded_libraries = array(); + + if (in_array($name, $loaded_libraries)) { + return; + } + if (!isset($CONFIG->libraries)) { $CONFIG->libraries = array(); } @@ -112,9 +114,14 @@ function elgg_load_library($name) { } if (!include_once($CONFIG->libraries[$name])) { - $error = elgg_echo('InvalidParameterException:LibraryNotRegistered', array($name)); + $error = elgg_echo('InvalidParameterException:LibraryNotFound', array( + $name, + $CONFIG->libraries[$name]) + ); throw new InvalidParameterException($error); } + + $loaded_libraries[] = $name; } /** @@ -126,12 +133,11 @@ function elgg_load_library($name) { * @param string $location URL to forward to browser to. Can be path relative to the network's URL. * @param string $reason Short explanation for why we're forwarding * - * @return False False if headers have been sent. Terminates execution if forwarding. + * @return false False if headers have been sent. Terminates execution if forwarding. + * @throws SecurityException */ function forward($location = "", $reason = 'system') { - global $CONFIG; - - if (!headers_sent()) { + if (!headers_sent($file, $line)) { if ($location === REFERER) { $location = $_SERVER['HTTP_REFERER']; } @@ -149,9 +155,9 @@ function forward($location = "", $reason = 'system') { } else if ($location === '') { exit; } + } else { + throw new SecurityException(elgg_echo('SecurityException:ForwardFailedToRedirect', array($file, $line))); } - - return false; } /** @@ -163,174 +169,283 @@ function forward($location = "", $reason = 'system') { * JavaScript from a view that may be called more than once. It also handles * more than one plugin adding the same JavaScript. * - * Plugin authors are encouraged to use the $id variable. jQuery plugins - * often have filenames such as jquery.rating.js. In that case, the id - * would be "jquery.rating". It is recommended to not use version numbers - * in the id. + * jQuery plugins often have filenames such as jquery.rating.js. A best practice + * is to base $name on the filename: "jquery.rating". It is recommended to not + * use version numbers in the name. * * The JavaScript files can be local to the server or remote (such as * Google's CDN). * + * @param string $name An identifier for the JavaScript library * @param string $url URL of the JavaScript file - * @param string $id An identifier of the JavaScript library * @param string $location Page location: head or footer. (default: head) + * @param int $priority Priority of the JS file (lower numbers load earlier) + * * @return bool + * @since 1.8.0 */ -function elgg_register_js($url, $id = '', $location = 'head') { - return elgg_register_external_file('javascript', $url, $id, $location); +function elgg_register_js($name, $url, $location = 'head', $priority = null) { + return elgg_register_external_file('js', $name, $url, $location, $priority); +} + +/** + * Unregister a JavaScript file + * + * @param string $name The identifier for the JavaScript library + * + * @return bool + * @since 1.8.0 + */ +function elgg_unregister_js($name) { + return elgg_unregister_external_file('js', $name); +} + +/** + * Load a JavaScript resource on this page + * + * This must be called before elgg_view_page(). It can be called before the + * script is registered. If you do not want a script loaded, unregister it. + * + * @param string $name Identifier of the JavaScript resource + * + * @return void + * @since 1.8.0 + */ +function elgg_load_js($name) { + elgg_load_external_file('js', $name); +} + +/** + * Get the JavaScript URLs that are loaded + * + * @param string $location 'head' or 'footer' + * + * @return array + * @since 1.8.0 + */ +function elgg_get_loaded_js($location = 'head') { + return elgg_get_loaded_external_files('js', $location); } /** * Register a CSS file for inclusion in the HTML head * - * @param string $url URL of the CSS file - * @param string $id An identifier for the CSS file + * @param string $name An identifier for the CSS file + * @param string $url URL of the CSS file + * @param int $priority Priority of the CSS file (lower numbers load earlier) + * + * @return bool + * @since 1.8.0 + */ +function elgg_register_css($name, $url, $priority = null) { + return elgg_register_external_file('css', $name, $url, 'head', $priority); +} + +/** + * Unregister a CSS file + * + * @param string $name The identifier for the CSS file + * * @return bool + * @since 1.8.0 + */ +function elgg_unregister_css($name) { + return elgg_unregister_external_file('css', $name); +} + +/** + * Load a CSS file for this page + * + * This must be called before elgg_view_page(). It can be called before the + * CSS file is registered. If you do not want a CSS file loaded, unregister it. + * + * @param string $name Identifier of the CSS file + * + * @return void + * @since 1.8.0 + */ +function elgg_load_css($name) { + elgg_load_external_file('css', $name); +} + +/** + * Get the loaded CSS URLs + * + * @return array + * @since 1.8.0 */ -function elgg_register_css($url, $id = '') { - return elgg_register_external_file('css', $url, $id, 'head'); +function elgg_get_loaded_css() { + return elgg_get_loaded_external_files('css', 'head'); } /** * Core registration function for external files * - * @param string $type Type of external resource + * @param string $type Type of external resource (js or css) + * @param string $name Identifier used as key * @param string $url URL - * @param string $id Identifier used as key * @param string $location Location in the page to include the file + * @param int $priority Loading priority of the file + * * @return bool + * @since 1.8.0 */ -function elgg_register_external_file($type, $url, $id, $location) { +function elgg_register_external_file($type, $name, $url, $location, $priority = 500) { global $CONFIG; - if (empty($url)) { + if (empty($name) || empty($url)) { return false; } $url = elgg_format_url($url); + $url = elgg_normalize_url($url); + + elgg_bootstrap_externals_data_structure($type); - if (!isset($CONFIG->externals)) { - $CONFIG->externals = array(); - } + $name = trim(strtolower($name)); - if (!isset($CONFIG->externals[$type])) { - $CONFIG->externals[$type] = array(); + // normalize bogus priorities, but allow empty, null, and false to be defaults. + if (!is_numeric($priority)) { + $priority = 500; } - if (!isset($CONFIG->externals[$type][$location])) { - $CONFIG->externals[$type][$location] = array(); - } + // no negative priorities right now. + $priority = max((int)$priority, 0); - if (!$id) { - $id = count($CONFIG->externals[$type][$location]); + $item = elgg_extract($name, $CONFIG->externals_map[$type]); + + if ($item) { + // updating a registered item + // don't update loaded because it could already be set + $item->url = $url; + $item->location = $location; + + // if loaded before registered, that means it hasn't been added to the list yet + if ($CONFIG->externals[$type]->contains($item)) { + $priority = $CONFIG->externals[$type]->move($item, $priority); + } else { + $priority = $CONFIG->externals[$type]->add($item, $priority); + } } else { - $id = trim(strtolower($id)); - } + $item = new stdClass(); + $item->loaded = false; + $item->url = $url; + $item->location = $location; - $CONFIG->externals[$type][$location][$id] = elgg_normalize_url($url); + $priority = $CONFIG->externals[$type]->add($item, $priority); + } - return true; -} + $CONFIG->externals_map[$type][$name] = $item; -/** - * Unregister a JavaScript file - * - * @param string $id The identifier for the JavaScript library - * @param string $url Optional URL to search for if id is not specified - * @param string $location Location in the page - * @return bool - */ -function elgg_unregister_js($id = '', $url = '', $location = 'head') { - return elgg_unregister_external_file('javascript', $id, $url, $location); + return $priority !== false; } /** * Unregister an external file * - * @param string $id The identifier of the CSS file - * @param string $url Optional URL to search for if id is not specified - * @return bool - */ -function elgg_unregister_css($id = '', $url = '') { - return elgg_unregister_external_file('css', $id, $url, 'head'); -} - -/** - * Unregister an external file + * @param string $type Type of file: js or css + * @param string $name The identifier of the file * - * @param string $type Type of file: javascript or css - * @param string $id The identifier of the file - * @param string $url Optional URL to search for if the id is not specified - * @param string $location Location in the page * @return bool + * @since 1.8.0 */ -function elgg_unregister_external_file($type, $id = '', $url = '', $location = 'head') { +function elgg_unregister_external_file($type, $name) { global $CONFIG; - if (!isset($CONFIG->externals)) { - return false; - } - - if (!isset($CONFIG->externals[$type])) { - return false; - } + elgg_bootstrap_externals_data_structure($type); - if (!isset($CONFIG->externals[$type][$location])) { - return false; - } - - if (array_key_exists($id, $CONFIG->externals[$type][$location])) { - unset($CONFIG->externals[$type][$location][$id]); - return true; - } + $name = trim(strtolower($name)); + $item = elgg_extract($name, $CONFIG->externals_map[$type]); - // was not registered with an id so do a search for the url - $key = array_search($url, $CONFIG->externals[$type][$location]); - if ($key) { - unset($CONFIG->externals[$type][$location][$key]); - return true; + if ($item) { + unset($CONFIG->externals_map[$type][$name]); + return $CONFIG->externals[$type]->remove($item); } return false; } /** - * Get the JavaScript URLs + * Load an external resource for use on this page * - * @param string $location 'head' or 'footer' + * @param string $type Type of file: js or css + * @param string $name The identifier for the file * - * @return array + * @return void + * @since 1.8.0 */ -function elgg_get_js($location = 'head') { - return elgg_get_external_file('javascript', $location); +function elgg_load_external_file($type, $name) { + global $CONFIG; + + elgg_bootstrap_externals_data_structure($type); + + $name = trim(strtolower($name)); + + $item = elgg_extract($name, $CONFIG->externals_map[$type]); + + if ($item) { + // update a registered item + $item->loaded = true; + } else { + $item = new stdClass(); + $item->loaded = true; + $item->url = ''; + $item->location = ''; + + $CONFIG->externals[$type]->add($item); + $CONFIG->externals_map[$type][$name] = $item; + } } /** - * Get the CSS URLs + * Get external resource descriptors + * + * @param string $type Type of file: js or css + * @param string $location Page location * * @return array + * @since 1.8.0 */ -function elgg_get_css() { - return elgg_get_external_file('css', 'head'); +function elgg_get_loaded_external_files($type, $location) { + global $CONFIG; + + if (isset($CONFIG->externals) && $CONFIG->externals[$type] instanceof ElggPriorityList) { + $items = $CONFIG->externals[$type]->getElements(); + + $callback = "return \$v->loaded == true && \$v->location == '$location';"; + $items = array_filter($items, create_function('$v', $callback)); + if ($items) { + array_walk($items, create_function('&$v,$k', '$v = $v->url;')); + } + return $items; + } + return array(); } /** - * Get external resource descriptors + * Bootstraps the externals data structure in $CONFIG. * - * @param string $type Type of resource - * @param string $location Page location - * @return array + * @param string $type The type of external, js or css. + * @access private */ -function elgg_get_external_file($type, $location) { +function elgg_bootstrap_externals_data_structure($type) { global $CONFIG; - if (isset($CONFIG->externals) && - isset($CONFIG->externals[$type]) && - isset($CONFIG->externals[$type][$location])) { + if (!isset($CONFIG->externals)) { + $CONFIG->externals = array(); + } + + if (!isset($CONFIG->externals[$type]) || !$CONFIG->externals[$type] instanceof ElggPriorityList) { + $CONFIG->externals[$type] = new ElggPriorityList(); + } - return array_values($CONFIG->externals[$type][$location]); + if (!isset($CONFIG->externals_map)) { + $CONFIG->externals_map = array(); + } + + if (!isset($CONFIG->externals_map[$type])) { + $CONFIG->externals_map[$type] = array(); } - return array(); } /** @@ -418,10 +533,10 @@ function sanitise_filepath($path, $append_slash = TRUE) { * 'messages') as well as {@link register_error()} messages ($register = 'errors'). * * @param mixed $message Optionally, a single message or array of messages to add, (default: null) - * @param string $register Types of message: "errors", "messages" (default: messages) + * @param string $register Types of message: "error", "success" (default: success) * @param bool $count Count the number of messages (default: false) * - * @return true|false|array Either the array of messages, or a response regarding + * @return bool|array Either the array of messages, or a response regarding * whether the message addition was successful. * @todo Clean up. Separate registering messages and retrieving them. */ @@ -455,7 +570,7 @@ function system_messages($message = null, $register = "success", $count = false) return sizeof($_SESSION['msg'][$register]); } else { $count = 0; - foreach ($_SESSION['msg'] as $register => $submessages) { + foreach ($_SESSION['msg'] as $submessages) { $count += sizeof($submessages); } return $count; @@ -564,7 +679,7 @@ function elgg_register_event_handler($event, $object_type, $callback, $priority global $CONFIG; if (empty($event) || empty($object_type)) { - return FALSE; + return false; } if (!isset($CONFIG->events)) { @@ -577,8 +692,8 @@ function elgg_register_event_handler($event, $object_type, $callback, $priority $CONFIG->events[$event][$object_type] = array(); } - if (!is_callable($callback)) { - return FALSE; + if (!is_callable($callback, true)) { + return false; } $priority = max((int) $priority, 0); @@ -588,7 +703,7 @@ function elgg_register_event_handler($event, $object_type, $callback, $priority } $CONFIG->events[$event][$object_type][$priority] = $callback; ksort($CONFIG->events[$event][$object_type]); - return TRUE; + return true; } /** @@ -603,9 +718,12 @@ function elgg_register_event_handler($event, $object_type, $callback, $priority */ function elgg_unregister_event_handler($event, $object_type, $callback) { global $CONFIG; - foreach ($CONFIG->events[$event][$object_type] as $key => $event_callback) { - if ($event_callback == $callback) { - unset($CONFIG->events[$event][$object_type][$key]); + + if (isset($CONFIG->events[$event]) && isset($CONFIG->events[$event][$object_type])) { + foreach ($CONFIG->events[$event][$object_type] as $key => $event_callback) { + if ($event_callback == $callback) { + unset($CONFIG->events[$event][$object_type][$key]); + } } } } @@ -628,7 +746,7 @@ function elgg_unregister_event_handler($event, $object_type, $callback) { * @tip When referring to events, the preferred syntax is "event, type". * * @internal Only rarely should events be changed, added, or removed in core. - * When making changes to events, be sure to first create a ticket in trac. + * When making changes to events, be sure to first create a ticket on Github. * * @internal @tip Think of $object_type as the primary namespace element, and * $event as the secondary namespace. @@ -663,14 +781,14 @@ function elgg_trigger_event($event, $object_type, $object = null) { foreach ($events as $callback_list) { if (is_array($callback_list)) { foreach ($callback_list as $callback) { - if (call_user_func_array($callback, $args) === FALSE) { - return FALSE; + if (is_callable($callback) && (call_user_func_array($callback, $args) === false)) { + return false; } } } } - return TRUE; + return true; } /** @@ -729,7 +847,7 @@ function elgg_trigger_event($event, $object_type, $object = null) { * * @param string $hook The name of the hook * @param string $type The type of the hook - * @param callback $callback The name of a valid function or an array with object and method + * @param callable $callback The name of a valid function or an array with object and method * @param int $priority The priority - 500 is default, lower numbers called first * * @return bool @@ -743,7 +861,7 @@ function elgg_register_plugin_hook_handler($hook, $type, $callback, $priority = global $CONFIG; if (empty($hook) || empty($type)) { - return FALSE; + return false; } if (!isset($CONFIG->hooks)) { @@ -756,8 +874,8 @@ function elgg_register_plugin_hook_handler($hook, $type, $callback, $priority = $CONFIG->hooks[$hook][$type] = array(); } - if (!is_callable($callback)) { - return FALSE; + if (!is_callable($callback, true)) { + return false; } $priority = max((int) $priority, 0); @@ -767,7 +885,7 @@ function elgg_register_plugin_hook_handler($hook, $type, $callback, $priority = } $CONFIG->hooks[$hook][$type][$priority] = $callback; ksort($CONFIG->hooks[$hook][$type]); - return TRUE; + return true; } /** @@ -775,16 +893,19 @@ function elgg_register_plugin_hook_handler($hook, $type, $callback, $priority = * * @param string $hook The name of the hook * @param string $entity_type The name of the type of entity (eg "user", "object" etc) - * @param callback $callback The PHP callback to be removed + * @param callable $callback The PHP callback to be removed * * @return void * @since 1.8.0 */ function elgg_unregister_plugin_hook_handler($hook, $entity_type, $callback) { global $CONFIG; - foreach ($CONFIG->hooks[$hook][$entity_type] as $key => $hook_callback) { - if ($hook_callback == $callback) { - unset($CONFIG->hooks[$hook][$entity_type][$key]); + + if (isset($CONFIG->hooks[$hook]) && isset($CONFIG->hooks[$hook][$entity_type])) { + foreach ($CONFIG->hooks[$hook][$entity_type] as $key => $hook_callback) { + if ($hook_callback == $callback) { + unset($CONFIG->hooks[$hook][$entity_type][$key]); + } } } } @@ -811,6 +932,12 @@ function elgg_unregister_plugin_hook_handler($hook, $entity_type, $callback) { * called for all hooks of type $event, regardless of $object_type. If $hook * and $type both are 'all', the handler will be called for all hooks. * + * @internal The checks for $hook and/or $type not being equal to 'all' is to + * prevent a plugin hook being registered with an 'all' being called more than + * once if the trigger occurs with an 'all'. An example in core of this is in + * actions.php: + * elgg_trigger_plugin_hook('action_gatekeeper:permissions:check', 'all', ...) + * * @see elgg_register_plugin_hook_handler() * * @param string $hook The name of the hook to trigger ("all" will @@ -836,13 +963,19 @@ function elgg_trigger_plugin_hook($hook, $type, $params = null, $returnvalue = n $hooks = array(); if (isset($CONFIG->hooks[$hook][$type])) { - $hooks[] = $CONFIG->hooks[$hook][$type]; + if ($hook != 'all' && $type != 'all') { + $hooks[] = $CONFIG->hooks[$hook][$type]; + } } if (isset($CONFIG->hooks['all'][$type])) { - $hooks[] = $CONFIG->hooks['all'][$type]; + if ($type != 'all') { + $hooks[] = $CONFIG->hooks['all'][$type]; + } } if (isset($CONFIG->hooks[$hook]['all'])) { - $hooks[] = $CONFIG->hooks[$hook]['all']; + if ($hook != 'all') { + $hooks[] = $CONFIG->hooks[$hook]['all']; + } } if (isset($CONFIG->hooks['all']['all'])) { $hooks[] = $CONFIG->hooks['all']['all']; @@ -851,10 +984,12 @@ function elgg_trigger_plugin_hook($hook, $type, $params = null, $returnvalue = n foreach ($hooks as $callback_list) { if (is_array($callback_list)) { foreach ($callback_list as $hookcallback) { - $args = array($hook, $type, $returnvalue, $params); - $temp_return_value = call_user_func_array($hookcallback, $args); - if (!is_null($temp_return_value)) { - $returnvalue = $temp_return_value; + if (is_callable($hookcallback)) { + $args = array($hook, $type, $returnvalue, $params); + $temp_return_value = call_user_func_array($hookcallback, $args); + if (!is_null($temp_return_value)) { + $returnvalue = $temp_return_value; + } } } } @@ -864,7 +999,7 @@ function elgg_trigger_plugin_hook($hook, $type, $params = null, $returnvalue = n } /** - * Intercepts, logs, and display uncaught exceptions. + * Intercepts, logs, and displays uncaught exceptions. * * @warning This function should never be called directly. * @@ -873,9 +1008,11 @@ function elgg_trigger_plugin_hook($hook, $type, $params = null, $returnvalue = n * @param Exception $exception The exception being handled * * @return void + * @access private */ function _elgg_php_exception_handler($exception) { - error_log("*** FATAL EXCEPTION *** : " . $exception); + $timestamp = time(); + error_log("Exception #$timestamp: $exception"); // Wipe any existing output buffer ob_end_clean(); @@ -884,11 +1021,31 @@ function _elgg_php_exception_handler($exception) { header("Cache-Control: no-cache, must-revalidate", true); header('Expires: Fri, 05 Feb 1982 00:00:00 -0500', true); // @note Do not send a 500 header because it is not a server error - //header("Internal Server Error", true, 500); - elgg_set_viewtype('failsafe'); - $body = elgg_view("messages/exceptions/exception", array('object' => $exception)); - echo elgg_view_page(elgg_echo('exception:title'), $body); + try { + // we don't want the 'pagesetup', 'system' event to fire + global $CONFIG; + $CONFIG->pagesetupdone = true; + + elgg_set_viewtype('failsafe'); + if (elgg_is_admin_logged_in()) { + $body = elgg_view("messages/exceptions/admin_exception", array( + 'object' => $exception, + 'ts' => $timestamp + )); + } else { + $body = elgg_view("messages/exceptions/exception", array( + 'object' => $exception, + 'ts' => $timestamp + )); + } + echo elgg_view_page(elgg_echo('exception:title'), $body); + } catch (Exception $e) { + $timestamp = time(); + $message = $e->getMessage(); + echo "Fatal error in exception handler. Check log for Exception #$timestamp"; + error_log("Exception #$timestamp : fatal error in exception handler : $message"); + } } /** @@ -911,6 +1068,9 @@ function _elgg_php_exception_handler($exception) { * @param array $vars An array that points to the active symbol table where error occurred * * @return true + * @throws Exception + * @access private + * @todo Replace error_log calls with elgg_log calls. */ function _elgg_php_error_handler($errno, $errmsg, $filename, $linenum, $vars) { $error = date("Y-m-d H:i:s (T)") . ": \"$errmsg\" in file $filename (line $linenum)"; @@ -926,7 +1086,12 @@ function _elgg_php_error_handler($errno, $errmsg, $filename, $linenum, $vars) { case E_WARNING : case E_USER_WARNING : - error_log("PHP WARNING: $error"); + case E_RECOVERABLE_ERROR: // (e.g. type hint violation) + + // check if the error wasn't suppressed by the error control operator (@) + if (error_reporting()) { + error_log("PHP WARNING: $error"); + } break; default: @@ -950,8 +1115,8 @@ function _elgg_php_error_handler($errno, $errmsg, $filename, $linenum, $vars) { * * @note No messages will be displayed unless debugging has been enabled. * - * @param str $message User message - * @param str $level NOTICE | WARNING | ERROR | DEBUG + * @param string $message User message + * @param string $level NOTICE | WARNING | ERROR | DEBUG * * @return bool * @since 1.7.0 @@ -1013,9 +1178,11 @@ function elgg_dump($value, $to_screen = TRUE, $level = 'NOTICE') { global $CONFIG; // plugin can return false to stop the default logging method - $params = array('level' => $level, - 'msg' => $value, - 'to_screen' => $to_screen); + $params = array( + 'level' => $level, + 'msg' => $value, + 'to_screen' => $to_screen, + ); if (!elgg_trigger_plugin_hook('debug', 'log', $params, true)) { return; } @@ -1027,6 +1194,11 @@ function elgg_dump($value, $to_screen = TRUE, $level = 'NOTICE') { $to_screen = FALSE; } + // Do not want to write to JS or CSS pages + if (elgg_in_context('js') || elgg_in_context('css')) { + $to_screen = FALSE; + } + if ($to_screen == TRUE) { echo '<pre>'; print_r($value); @@ -1041,7 +1213,9 @@ function elgg_dump($value, $to_screen = TRUE, $level = 'NOTICE') { * * This function either displays or logs the deprecation message, * depending upon the deprecation policies in {@link CODING.txt}. - * Logged messages are sent with the level of 'WARNING'. + * Logged messages are sent with the level of 'WARNING'. Only admins + * get visual deprecation notices. When non-admins are logged in, the + * notices are sent to PHP's log through elgg_dump(). * * A user-visual message will be displayed if $dep_version is greater * than 1 minor releases lower than the current Elgg version, or at all @@ -1052,23 +1226,27 @@ function elgg_dump($value, $to_screen = TRUE, $level = 'NOTICE') { * * @see CODING.txt * - * @param str $msg Message to log / display. - * @param str $dep_version Human-readable *release* version: 1.7, 1.7.3 + * @param string $msg Message to log / display. + * @param string $dep_version Human-readable *release* version: 1.7, 1.8, ... + * @param int $backtrace_level How many levels back to display the backtrace. + * Useful if calling from functions that are called + * from other places (like elgg_view()). Set to -1 + * for a full backtrace. * * @return bool * @since 1.7.0 */ -function elgg_deprecated_notice($msg, $dep_version) { +function elgg_deprecated_notice($msg, $dep_version, $backtrace_level = 1) { // if it's a major release behind, visual and logged // if it's a 1 minor release behind, visual and logged // if it's for current minor release, logged. - // bugfixes don't matter because you're not deprecating between them, RIGHT? + // bugfixes don't matter because we are not deprecating between them if (!$dep_version) { - return FALSE; + return false; } - $elgg_version = get_version(TRUE); + $elgg_version = get_version(true); $elgg_version_arr = explode('.', $elgg_version); $elgg_major_version = (int)$elgg_version_arr[0]; $elgg_minor_version = (int)$elgg_version_arr[1]; @@ -1076,29 +1254,46 @@ function elgg_deprecated_notice($msg, $dep_version) { $dep_major_version = (int)$dep_version; $dep_minor_version = 10 * ($dep_version - $dep_major_version); - $visual = FALSE; + $visual = false; if (($dep_major_version < $elgg_major_version) || ($dep_minor_version < $elgg_minor_version)) { - $visual = TRUE; + $visual = true; } $msg = "Deprecated in $dep_major_version.$dep_minor_version: $msg"; - if ($visual) { + if ($visual && elgg_is_admin_logged_in()) { register_error($msg); } // Get a file and line number for the log. Never show this in the UI. // Skip over the function that sent this notice and see who called the deprecated // function itself. + $msg .= " Called from "; + $stack = array(); $backtrace = debug_backtrace(); - $caller = $backtrace[1]; - $msg .= " (Called from {$caller['file']}:{$caller['line']})"; + // never show this call. + array_shift($backtrace); + $i = count($backtrace); + + foreach ($backtrace as $trace) { + $stack[] = "[#$i] {$trace['file']}:{$trace['line']}"; + $i--; + + if ($backtrace_level > 0) { + if ($backtrace_level <= 1) { + break; + } + $backtrace_level--; + } + } + + $msg .= implode("<br /> -> ", $stack); elgg_log($msg, 'WARNING'); - return TRUE; + return true; } /** @@ -1111,8 +1306,6 @@ function elgg_deprecated_notice($msg, $dep_version) { * @return string The current page URL. */ function current_page_url() { - global $CONFIG; - $url = parse_url(elgg_get_site_url()); $page = $url['scheme'] . "://"; @@ -1157,7 +1350,7 @@ function full_url() { "" : (":" . $_SERVER["SERVER_PORT"]); // This is here to prevent XSS in poorly written browsers used by 80% of the population. - // {@trac [5813]} + // https://github.com/Elgg/Elgg/commit/0c947e80f512cb0a482b1864fd0a6965c8a0cd4a $quotes = array('\'', '"'); $encoded = array('%27', '%22'); @@ -1173,7 +1366,7 @@ function full_url() { * @param array $parts Associative array of URL components like parse_url() returns * @param bool $html_encode HTML Encode the url? * - * @return str Full URL + * @return string Full URL * @since 1.7.0 */ function elgg_http_build_url(array $parts, $html_encode = TRUE) { @@ -1204,10 +1397,10 @@ function elgg_http_build_url(array $parts, $html_encode = TRUE) { * add tokens to the action. The form view automatically handles * tokens. * - * @param str $url Full action URL - * @param bool $html_encode HTML encode the url? (default: false) + * @param string $url Full action URL + * @param bool $html_encode HTML encode the url? (default: false) * - * @return str URL with action tokens + * @return string URL with action tokens * @since 1.7.0 * @link http://docs.elgg.org/Tutorials/Actions */ @@ -1259,17 +1452,17 @@ function elgg_http_remove_url_query_element($url, $element) { } $url_array['query'] = http_build_query($query); - $string = elgg_http_build_url($url_array); + $string = elgg_http_build_url($url_array, false); return $string; } /** * Adds an element or elements to a URL's query string. * - * @param str $url The URL - * @param array $elements Key/value pairs to add to the URL + * @param string $url The URL + * @param array $elements Key/value pairs to add to the URL * - * @return str The new URL with the query strings added + * @return string The new URL with the query strings added * @since 1.7.0 */ function elgg_http_add_url_query_elements($url, array $elements) { @@ -1306,8 +1499,6 @@ function elgg_http_add_url_query_elements($url, array $elements) { * @since 1.8.0 */ function elgg_http_url_is_identical($url1, $url2, $ignore_params = array('offset', 'limit')) { - global $CONFIG; - // if the server portion is missing but it starts with / then add the url in. // @todo use elgg_normalize_url() if (elgg_substr($url1, 0, 1) == '/') { @@ -1327,8 +1518,12 @@ function elgg_http_url_is_identical($url1, $url2, $ignore_params = array('offset $url1_info = parse_url($url1); $url2_info = parse_url($url2); - $url1_info['path'] = trim($url1_info['path'], '/'); - $url2_info['path'] = trim($url2_info['path'], '/'); + if (isset($url1_info['path'])) { + $url1_info['path'] = trim($url1_info['path'], '/'); + } + if (isset($url2_info['path'])) { + $url2_info['path'] = trim($url2_info['path'], '/'); + } // compare basic bits $parts = array('scheme', 'host', 'path'); @@ -1402,10 +1597,14 @@ function elgg_http_url_is_identical($url1, $url2, $ignore_params = array('offset * @param bool $strict Return array key if it's set, even if empty. If false, * return $default if the array key is unset or empty. * - * @return void + * @return mixed * @since 1.8.0 */ -function elgg_extract($key, array $array, $default = NULL, $strict = true) { +function elgg_extract($key, array $array, $default = null, $strict = true) { + if (!is_array($array)) { + return $default; + } + if ($strict) { return (isset($array[$key])) ? $array[$key] : $default; } else { @@ -1438,7 +1637,7 @@ $sort_type = SORT_LOCALE_STRING) { $sort = array(); - foreach ($array as $k => $v) { + foreach ($array as $v) { if (isset($v[$element])) { $sort[] = strtolower($v[$element]); } else { @@ -1457,7 +1656,7 @@ $sort_type = SORT_LOCALE_STRING) { * * @param string $ini_get_arg The INI setting * - * @return true|false Depending on whether it's on or off + * @return bool Depending on whether it's on or off */ function ini_get_bool($ini_get_arg) { $temp = strtolower(ini_get($ini_get_arg)); @@ -1473,7 +1672,7 @@ function ini_get_bool($ini_get_arg) { * * @tip Use this for arithmetic when determining if a file can be uploaded. * - * @param str $setting The php.ini setting + * @param string $setting The php.ini setting * * @return int * @since 1.7.0 @@ -1488,8 +1687,10 @@ function elgg_get_ini_setting_in_bytes($setting) { switch($last) { case 'g': $val *= 1024; + // fallthrough intentional case 'm': $val *= 1024; + // fallthrough intentional case 'k': $val *= 1024; } @@ -1523,10 +1724,11 @@ function is_not_null($string) { * names by singular names. * * @param array $options The options array. $options['keys'] = 'values'; - * @param array $singulars A list of sinular words to pluralize by adding 's'. + * @param array $singulars A list of singular words to pluralize by adding 's'. * * @return array * @since 1.7.0 + * @access private */ function elgg_normalise_plural_options_array($options, $singulars) { foreach ($singulars as $singular) { @@ -1560,17 +1762,27 @@ function elgg_normalise_plural_options_array($options, $singulars) { * useful. Servers will hold pages until processing is done before sending * them out to the browser. * + * @see http://www.php.net/register-shutdown-function + * * @return void * @see register_shutdown_hook() + * @access private */ function _elgg_shutdown_hook() { global $START_MICROTIME; - elgg_trigger_event('shutdown', 'system'); + try { + elgg_trigger_event('shutdown', 'system'); - $time = (float)(microtime(TRUE) - $START_MICROTIME); - // demoted to NOTICE from DEBUG so javascript is not corrupted - elgg_log("Page {$_SERVER['REQUEST_URI']} generated in $time seconds", 'NOTICE'); + $time = (float)(microtime(TRUE) - $START_MICROTIME); + // demoted to NOTICE from DEBUG so javascript is not corrupted + elgg_log("Page {$_SERVER['REQUEST_URI']} generated in $time seconds", 'NOTICE'); + } catch (Exception $e) { + $message = 'Error: ' . get_class($e) . ' thrown within the shutdown handler. '; + $message .= "Message: '{$e->getMessage()}' in file {$e->getFile()} (line {$e->getLine()})"; + error_log($message); + error_log("Exception trace stack: {$e->getTraceAsString()}"); + } } /** @@ -1581,25 +1793,51 @@ function _elgg_shutdown_hook() { * * @param array $page The page array * - * @return void + * @return bool * @elgg_pagehandler js + * @access private + */ +function elgg_js_page_handler($page) { + return elgg_cacheable_view_page_handler($page, 'js'); +} + +/** + * Serve individual views for Ajax. + * + * /ajax/view/<name of view>?<key/value params> + * + * @param array $page The page array + * + * @return bool + * @elgg_pagehandler ajax + * @access private */ -function js_page_handler($page) { +function elgg_ajax_page_handler($page) { if (is_array($page) && sizeof($page)) { - $js = implode('/', $page); - $js = substr($js, 0, strpos($js, '.')); - $return = elgg_view('js/' . $js); + // throw away 'view' and form the view name + unset($page[0]); + $view = implode('/', $page); - header('Content-type: text/javascript'); + $allowed_views = elgg_get_config('allowed_ajax_views'); + if (!array_key_exists($view, $allowed_views)) { + header('HTTP/1.1 403 Forbidden'); + exit; + } - // @todo should js be cached when simple cache turned off - //header('Expires: ' . date('r', time() + 864000)); - //header("Pragma: public"); - //header("Cache-Control: public"); - //header("Content-Length: " . strlen($return)); + // pull out GET parameters through filter + $vars = array(); + foreach ($_GET as $name => $value) { + $vars[$name] = get_input($name); + } - echo $return; + if (isset($vars['guid'])) { + $vars['entity'] = get_entity($vars['guid']); + } + + echo elgg_view($view, $vars); + return true; } + return false; } /** @@ -1609,26 +1847,71 @@ function js_page_handler($page) { * * @param array $page The page array * - * @return void + * @return bool * @elgg_pagehandler css + * @access private */ -function css_page_handler($page) { +function elgg_css_page_handler($page) { if (!isset($page[0])) { // default css $page[0] = 'elgg'; } + + return elgg_cacheable_view_page_handler($page, 'css'); +} - $css = substr($page[0], 0, strpos($page[0], '.')); - $return = elgg_view("css/$css"); +/** + * Serves a JS or CSS view with headers for caching. + * + * /<css||js>/name/of/view.<last_cache>.<css||js> + * + * @param array $page The page array + * @param string $type The type: js or css + * + * @return bool + * @access private + */ +function elgg_cacheable_view_page_handler($page, $type) { - header("Content-type: text/css", true); + switch ($type) { + case 'js': + $content_type = 'text/javascript'; + break; + + case 'css': + $content_type = 'text/css'; + break; + + default: + return false; + break; + } + + if ($page) { + // the view file names can have multiple dots + // eg: views/default/js/calendars/jquery.fullcalendar.min.php + // translates to the url /js/calendars/jquery.fullcalendar.min.<ts>.js + // and the view js/calendars/jquery.fullcalendar.min + // we ignore the last two dots for the ts and the ext. + // Additionally, the timestamp is optional. + $page = implode('/', $page); + $regex = '|(.+?)\.([\d]+\.)?\w+$|'; + preg_match($regex, $page, $matches); + $view = $matches[1]; + $return = elgg_view("$type/$view"); - // @todo should css be cached when simple cache is turned off - //header('Expires: ' . date('r', time() + 86400000), true); - //header("Pragma: public", true); - //header("Cache-Control: public", true); + header("Content-type: $content_type"); - echo $return; + // @todo should js be cached when simple cache turned off + //header('Expires: ' . gmdate('D, d M Y H:i:s \G\M\T', strtotime("+10 days")), true); + //header("Pragma: public"); + //header("Cache-Control: public"); + //header("Content-Length: " . strlen($return)); + + echo $return; + return true; + } + return false; } /** @@ -1640,6 +1923,7 @@ function css_page_handler($page) { * @param string $order_by An order by clause * @access private * @return string + * @access private */ function elgg_sql_reverse_order_by_clause($order_by) { $order_by = strtolower($order_by); @@ -1661,9 +1945,11 @@ function elgg_sql_reverse_order_by_clause($order_by) { * * Used as a callback for ElggBatch. * + * @todo why aren't these static methods on ElggBatch? + * * @param object $object The object to enable - * @access private * @return bool + * @access private */ function elgg_batch_enable_callback($object) { // our db functions return the number of rows affected... @@ -1676,8 +1962,8 @@ function elgg_batch_enable_callback($object) { * Used as a callback for ElggBatch. * * @param object $object The object to disable - * @access private * @return bool + * @access private */ function elgg_batch_disable_callback($object) { // our db functions return the number of rows affected... @@ -1690,8 +1976,8 @@ function elgg_batch_disable_callback($object) { * Used as a callback for ElggBatch. * * @param object $object The object to disable - * @access private * @return bool + * @access private */ function elgg_batch_delete_callback($object) { // our db functions return the number of rows affected... @@ -1705,6 +1991,7 @@ function elgg_batch_delete_callback($object) { * @param array $options Options array * @param string $type Options type: metadata or annotations * @return bool + * @access private */ function elgg_is_valid_options_for_batch_operation($options, $type) { if (!$options || !is_array($options)) { @@ -1714,7 +2001,7 @@ function elgg_is_valid_options_for_batch_operation($options, $type) { // at least one of these is required. $required = array( // generic restraints - 'guid', 'guids', 'limit' + 'guid', 'guids' ); switch ($type) { @@ -1758,15 +2045,53 @@ function elgg_is_valid_options_for_batch_operation($options, $type) { * * @link http://docs.elgg.org/Tutorials/WalledGarden * @elgg_plugin_hook index system - * @return void + * + * @param string $hook The name of the hook + * @param string $type The type of hook + * @param bool $value Has a plugin already rendered an index page? + * @param array $params Array of parameters (should be empty) + * @return bool + * @access private */ -function elgg_walled_garden_index() { - $login = elgg_view('core/account/login_walled_garden'); +function elgg_walled_garden_index($hook, $type, $value, $params) { + if ($value) { + // do not create a second index page so return + return; + } + + elgg_load_css('elgg.walled_garden'); + elgg_load_js('elgg.walled_garden'); + + $content = elgg_view('core/walled_garden/login'); + + $params = array( + 'content' => $content, + 'class' => 'elgg-walledgarden-double', + 'id' => 'elgg-walledgarden-login', + ); + $body = elgg_view_layout('walled_garden', $params); + echo elgg_view_page('', $body, 'walled_garden'); - echo elgg_view_page('', $login, 'walled_garden'); + // return true to prevent other plugins from adding a front page + return true; +} - // @hack Index must exit to keep plugins from continuing to extend - exit; +/** + * Serve walled garden sections + * + * @param array $page Array of URL segments + * @return string + * @access private + */ +function _elgg_walled_garden_ajax_handler($page) { + $view = $page[0]; + $params = array( + 'content' => elgg_view("core/walled_garden/$view"), + 'class' => 'elgg-walledgarden-single hidden', + 'id' => str_replace('_', '-', "elgg-walledgarden-$view"), + ); + echo elgg_view_layout('walled_garden', $params); + return true; } /** @@ -1781,10 +2106,16 @@ function elgg_walled_garden_index() { * @elgg_event_handler init system * @link http://docs.elgg.org/Tutorials/WalledGarden * @return void + * @access private */ function elgg_walled_garden() { global $CONFIG; + elgg_register_css('elgg.walled_garden', '/css/walled_garden.css'); + elgg_register_js('elgg.walled_garden', '/js/walled_garden.js'); + + elgg_register_page_handler('walled_garden', '_elgg_walled_garden_ajax_handler'); + // check for external page view if (isset($CONFIG->site) && $CONFIG->site instanceof ElggSite) { $CONFIG->site->checkWalledGarden(); @@ -1792,24 +2123,83 @@ function elgg_walled_garden() { } /** + * Remove public access for walled gardens + * + * @param string $hook + * @param string $type + * @param array $accesses + * @return array + * @access private + */ +function _elgg_walled_garden_remove_public_access($hook, $type, $accesses) { + if (isset($accesses[ACCESS_PUBLIC])) { + unset($accesses[ACCESS_PUBLIC]); + } + return $accesses; +} + +/** + * Boots the engine + * + * 1. sets error handlers + * 2. connects to database + * 3. verifies the installation suceeded + * 4. loads application configuration + * 5. loads i18n data + * 6. loads site configuration + * + * @access private + */ +function _elgg_engine_boot() { + // Register the error handlers + set_error_handler('_elgg_php_error_handler'); + set_exception_handler('_elgg_php_exception_handler'); + + setup_db_connections(); + + verify_installation(); + + _elgg_load_application_config(); + + _elgg_load_site_config(); + + _elgg_session_boot(); + + _elgg_load_cache(); + + _elgg_load_translations(); +} + +/** * Elgg's main init. * - * Handles core actions for comments and likes, the JS pagehandler, and the shutdown function. + * Handles core actions for comments, the JS pagehandler, and the shutdown function. * * @elgg_event_handler init system * @return void + * @access private */ function elgg_init() { global $CONFIG; elgg_register_action('comments/add'); elgg_register_action('comments/delete'); - elgg_register_action('likes/add'); - elgg_register_action('likes/delete'); - elgg_register_page_handler('js', 'js_page_handler'); - elgg_register_page_handler('css', 'css_page_handler'); + elgg_register_page_handler('js', 'elgg_js_page_handler'); + elgg_register_page_handler('css', 'elgg_css_page_handler'); + elgg_register_page_handler('ajax', 'elgg_ajax_page_handler'); + elgg_register_js('elgg.autocomplete', 'js/lib/ui.autocomplete.js'); + elgg_register_js('jquery.ui.autocomplete.html', 'vendors/jquery/jquery.ui.autocomplete.html.js'); + elgg_register_js('elgg.userpicker', 'js/lib/ui.userpicker.js'); + elgg_register_js('elgg.friendspicker', 'js/lib/ui.friends_picker.js'); + elgg_register_js('jquery.easing', 'vendors/jquery/jquery.easing.1.3.packed.js'); + elgg_register_js('elgg.avatar_cropper', 'js/lib/ui.avatar_cropper.js'); + elgg_register_js('jquery.imgareaselect', 'vendors/jquery/jquery.imgareaselect-0.9.8/scripts/jquery.imgareaselect.min.js'); + elgg_register_js('elgg.ui.river', 'js/lib/ui.river.js'); + + elgg_register_css('jquery.imgareaselect', 'vendors/jquery/jquery.imgareaselect-0.9.8/css/imgareaselect-deprecated.css'); + // Trigger the shutdown:system event upon PHP shutdown. register_shutdown_function('_elgg_shutdown_hook'); @@ -1817,8 +2207,9 @@ function elgg_init() { elgg_register_menu_item('topbar', array( 'name' => 'elgg_logo', 'href' => 'http://www.elgg.org/', - 'text' => "<img src=\"$logo_url\" alt=\"Elgg logo\" />", + 'text' => "<img src=\"$logo_url\" alt=\"Elgg logo\" width=\"38\" height=\"20\" />", 'priority' => 1, + 'link_class' => 'elgg-topbar-logo', )); // Sets a blacklist of words in the current language. @@ -1842,7 +2233,8 @@ function elgg_init() { * @param array $params empty * * @elgg_plugin_hook unit_tests system - * @return void + * @return array + * @access private */ function elgg_api_test($hook, $type, $value, $params) { global $CONFIG; @@ -1853,7 +2245,10 @@ function elgg_api_test($hook, $type, $value, $params) { } /**#@+ - * Controlls access levels on ElggEntity entities, metadata, and annotations. + * Controls access levels on ElggEntity entities, metadata, and annotations. + * + * @warning ACCESS_DEFAULT is a place holder for the input/access view. Do not + * use it when saving an entity. * * @var int */ @@ -1887,7 +2282,7 @@ define('ELGG_ENTITIES_NO_VALUE', 0); * referring page. * * @see forward - * @var unknown_type + * @var int -1 */ define('REFERRER', -1); @@ -1902,6 +2297,7 @@ define('REFERRER', -1); define('REFERER', -1); elgg_register_event_handler('init', 'system', 'elgg_init'); +elgg_register_event_handler('boot', 'system', '_elgg_engine_boot', 1); elgg_register_plugin_hook_handler('unit_test', 'system', 'elgg_api_test'); elgg_register_event_handler('init', 'system', 'add_custom_menu_items', 1000); |
