diff options
Diffstat (limited to 'engine/lib/elgglib.php')
| -rw-r--r-- | engine/lib/elgglib.php | 2889 |
1 files changed, 1287 insertions, 1602 deletions
diff --git a/engine/lib/elgglib.php b/engine/lib/elgglib.php index 8ff0a24a5..34111c69d 100644 --- a/engine/lib/elgglib.php +++ b/engine/lib/elgglib.php @@ -2,24 +2,41 @@ /** * Bootstrapping and helper procedural code available for use in Elgg core and plugins. * - * * @package Elgg.Core * @todo These functions can't be subpackaged because they cover a wide mix of - * puposes and subsystems. Many of them should be moved to more relevant files. + * purposes and subsystems. Many of them should be moved to more relevant files. */ // prep core classes to be autoloadable -spl_autoload_register('__elgg_autoload'); +spl_autoload_register('_elgg_autoload'); elgg_register_classes(dirname(dirname(__FILE__)) . '/classes'); -function __elgg_autoload($class) { +/** + * Autoload classes + * + * @param string $class The name of the class + * + * @return void + * @throws Exception + * @access private + */ +function _elgg_autoload($class) { global $CONFIG; - if (!include($CONFIG->classes[$class])) { - throw new Exception("Failed to autoload $class"); + if (!isset($CONFIG->classes[$class]) || !include($CONFIG->classes[$class])) { + return false; } } +/** + * Register all files found in $dir as classes + * Need to be named MyClass.php + * + * @param string $dir The dir to look in + * + * @return void + * @since 1.8.0 + */ function elgg_register_classes($dir) { $classes = elgg_get_file_list($dir, array(), array(), array('.php')); @@ -28,6 +45,15 @@ function elgg_register_classes($dir) { } } +/** + * Register a classname to a file. + * + * @param string $class The name of the class + * @param string $location The location of the file + * + * @return true + * @since 1.8.0 + */ function elgg_register_class($class, $location) { global $CONFIG; @@ -36,548 +62,390 @@ function elgg_register_class($class, $location) { } $CONFIG->classes[$class] = $location; + + return true; } /** - * Forward to $location. + * Register a php library. * - * Sends a 'Location: $location' header and exists. If headers have already been sent, returns FALSE. + * @param string $name The name of the library + * @param string $location The location of the file * - * @param string $location URL to forward to browser to. Can be path relative to the network's URL. - * @return False False if headers have been sent. Terminates execution if forwarding. + * @return void + * @since 1.8.0 */ -function forward($location = "") { +function elgg_register_library($name, $location) { global $CONFIG; - if (!headers_sent()) { - if ($location === REFERER) { - $location = $_SERVER['HTTP_REFERER']; - } - - if ((substr_count($location, 'http://') == 0) && (substr_count($location, 'https://') == 0)) { - $location = $CONFIG->url . $location; - } - - // return new forward location or false to stop the forward or empty string to exit - $current_page = current_page_url(); - $params = array('current_url' => $current_page, 'forward_url' => $location); - $location = trigger_plugin_hook('forward', 'system', $params, $location); - - if ($location) { - header("Location: {$location}"); - exit; - } else if ($location === '') { - exit; - } + if (!isset($CONFIG->libraries)) { + $CONFIG->libraries = array(); } - return false; + $CONFIG->libraries[$name] = $location; } /** - * Returns the current page's complete URL. + * Load a php library. * - * The current URL is assembled using the network's wwwroot and the request URI - * in $_SERVER as populated by the web server. This function will include - * any schemes, usernames and passwords, and ports. + * @param string $name The name of the library * - * @return string The current page URL. + * @return void + * @throws InvalidParameterException + * @since 1.8.0 + * @todo return boolean in 1.9 to indicate whether the library has been loaded */ -function current_page_url() { +function elgg_load_library($name) { global $CONFIG; - $url = parse_url($CONFIG->wwwroot); - - $page = $url['scheme'] . "://"; + static $loaded_libraries = array(); - // user/pass - if ((isset($url['user'])) && ($url['user'])) { - $page .= $url['user']; - } - if ((isset($url['pass'])) && ($url['pass'])) { - $page .= ":".$url['pass']; - } - if ((isset($url['user']) && $url['user']) || - (isset($url['pass']) && $url['pass'])) { - $page .="@"; + if (in_array($name, $loaded_libraries)) { + return; } - $page .= $url['host']; - - if ((isset($url['port'])) && ($url['port'])) { - $page .= ":" . $url['port']; + if (!isset($CONFIG->libraries)) { + $CONFIG->libraries = array(); } - $page = trim($page, "/"); + if (!isset($CONFIG->libraries[$name])) { + $error = elgg_echo('InvalidParameterException:LibraryNotRegistered', array($name)); + throw new InvalidParameterException($error); + } - $page .= $_SERVER['REQUEST_URI']; + if (!include_once($CONFIG->libraries[$name])) { + $error = elgg_echo('InvalidParameterException:LibraryNotFound', array( + $name, + $CONFIG->libraries[$name]) + ); + throw new InvalidParameterException($error); + } - return $page; + $loaded_libraries[] = $name; } /** - * Returns an ElggCache object suitable for caching view - * file load paths to disk under $CONFIG->dataroot. + * Forward to $location. * - * @todo Can this be done in a cleaner way? - * @todo Swap to memcache etc? + * Sends a 'Location: $location' header and exists. If headers have + * already been sent, returns FALSE. * - * @return ElggFileCache A cache object suitable for caching file load paths. + * @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. + * @throws SecurityException */ -function elgg_get_filepath_cache() { - global $CONFIG; +function forward($location = "", $reason = 'system') { + if (!headers_sent($file, $line)) { + if ($location === REFERER) { + $location = $_SERVER['HTTP_REFERER']; + } - /** - * A default filestore cache using the dataroot. - */ - static $FILE_PATH_CACHE; + $location = elgg_normalize_url($location); - if (!$FILE_PATH_CACHE) { - $FILE_PATH_CACHE = new ElggFileCache($CONFIG->dataroot); - } + // return new forward location or false to stop the forward or empty string to exit + $current_page = current_page_url(); + $params = array('current_url' => $current_page, 'forward_url' => $location); + $location = elgg_trigger_plugin_hook('forward', $reason, $params, $location); - return $FILE_PATH_CACHE; + if ($location) { + header("Location: {$location}"); + exit; + } else if ($location === '') { + exit; + } + } else { + throw new SecurityException(elgg_echo('SecurityException:ForwardFailedToRedirect', array($file, $line))); + } } /** - * Deletes the view file paths cache from disk. + * Register a JavaScript file for inclusion + * + * This function handles adding JavaScript to a web page. If multiple + * calls are made to register the same JavaScript file based on the $id + * variable, only the last file is included. This allows a plugin to add + * JavaScript from a view that may be called more than once. It also handles + * more than one plugin adding the same JavaScript. * - * @return bool On success + * 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 $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_filepath_cache_reset() { - $cache = elgg_get_filepath_cache(); - return $cache->delete('view_paths'); +function elgg_register_js($name, $url, $location = 'head', $priority = null) { + return elgg_register_external_file('js', $name, $url, $location, $priority); } /** - * Saves $data to the views file paths disk cache as - * 'view_paths'. + * Unregister a JavaScript file * - * @param mixed $data The data - * @return bool On success + * @param string $name The identifier for the JavaScript library + * + * @return bool + * @since 1.8.0 */ -function elgg_filepath_cache_save($data) { - global $CONFIG; - - if ($CONFIG->viewpath_cache_enabled) { - $cache = elgg_get_filepath_cache(); - return $cache->save('view_paths', $data); - } - - return false; +function elgg_unregister_js($name) { + return elgg_unregister_external_file('js', $name); } /** - * Returns the contents of the views file paths cache from disk. + * 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 mixed Null if simplecache isn't enabled, the contents of the views file paths cache if it is. + * @return void + * @since 1.8.0 */ -function elgg_filepath_cache_load() { - global $CONFIG; - - if ($CONFIG->viewpath_cache_enabled) { - $cache = elgg_get_filepath_cache(); - $cached_view_paths = $cache->load('view_paths'); - - if ($cached_view_paths) { - return $cached_view_paths; - } - } - - return NULL; +function elgg_load_js($name) { + elgg_load_external_file('js', $name); } /** - * Enables the views file paths disk cache. + * Get the JavaScript URLs that are loaded * - * Uses the 'viewpath_cache_enabled' datalist with a boolean value. - * Resets the views paths cache. + * @param string $location 'head' or 'footer' * - * @return null + * @return array + * @since 1.8.0 */ -function elgg_enable_filepath_cache() { - global $CONFIG; - - datalist_set('viewpath_cache_enabled', 1); - $CONFIG->viewpath_cache_enabled = 1; - elgg_filepath_cache_reset(); +function elgg_get_loaded_js($location = 'head') { + return elgg_get_loaded_external_files('js', $location); } /** - * Disables the views file paths disk cache. + * Register a CSS file for inclusion in the HTML head * - * Uses the 'viewpath_cache_enabled' datalist with a boolean value. - * Resets the views paths cache. + * @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 null + * @return bool + * @since 1.8.0 */ -function elgg_disable_filepath_cache() { - global $CONFIG; - - datalist_set('viewpath_cache_enabled', 0); - $CONFIG->viewpath_cache_enabled = 0; - elgg_filepath_cache_reset(); +function elgg_register_css($name, $url, $priority = null) { + return elgg_register_external_file('css', $name, $url, 'head', $priority); } /** - * Deprecated by elgg_add_submenu_item() + * Unregister a CSS file + * + * @param string $name The identifier for the CSS file * - * @see elgg_add_submenu_item() - * @deprecated 1.8 + * @return bool + * @since 1.8.0 */ -function add_submenu_item($label, $link, $group = 'default', $onclick = false, $selected = NULL) { - elgg_deprecated_notice('add_submenu_item was deprecated by elgg_add_submenu_item', 1.8); - - $item = array( - 'text' => $label, - 'href' => $link, - 'selected' => $selected - ); - - if (!$group) { - $group = 'default'; - } +function elgg_unregister_css($name) { + return elgg_unregister_external_file('css', $name); +} - if ($onclick) { - $js = "onclick=\"javascript:return confirm('". elgg_echo('deleteconfirm') . "')\""; - $item['vars'] = array('js' => $js); - } - // submenu items were added in the page setup hook usually by checking - // the context. We'll pass in the current context here, which will - // emulate that effect. - // if context == 'main' (default) it probably means they always wanted - // the menu item to show up everywhere. - $context = get_context(); +/** + * 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); +} - if ($context == 'main') { - $context = 'all'; - } - return elgg_add_submenu_item($item, $context, $group); +/** + * Get the loaded CSS URLs + * + * @return array + * @since 1.8.0 + */ +function elgg_get_loaded_css() { + return elgg_get_loaded_external_files('css', 'head'); } /** - * Add an entry to the submenu. + * Core registration function for external files * - * @param array $item The item as: - * <code> - * array( - * 'title' => 'Text to display', - * 'url' => 'URL of the link', - * 'id' => 'entry_unique_id' //used by children items to identify parents - * 'parent_id' => 'id_of_parent', - * 'selected' => BOOL // Is this item selected? (If NULL or unset will attempt to guess) - * 'vars' => array() // Array of vars to pass to the navigation/submenu_item view - * ) - * </code> + * @param string $type Type of external resource (js or css) + * @param string $name Identifier used as key + * @param string $url URL + * @param string $location Location in the page to include the file + * @param int $priority Loading priority of the file * - * @param string $context Context in which to display this menu item. 'all' will make it show up all the time. Use sparingly. - * @param string $group Group for the item. Each submenu group has its own <ul> - * @return BOOL - * @since 1.8 - * @see elgg_prepare_submenu + * @return bool + * @since 1.8.0 */ -function elgg_add_submenu_item(array $item, $context = 'all', $group = 'default') { +function elgg_register_external_file($type, $name, $url, $location, $priority = 500) { global $CONFIG; - if (!isset($CONFIG->submenu_items)) { - $CONFIG->submenu_items = array(); + if (empty($name) || empty($url)) { + return false; } - if (!isset($CONFIG->submenu_items[$context])) { - $CONFIG->submenu_items[$context] = array(); - } + $url = elgg_format_url($url); + $url = elgg_normalize_url($url); + + elgg_bootstrap_externals_data_structure($type); - if (!isset($CONFIG->submenu_items[$context][$group])) { - $CONFIG->submenu_items[$context][$group] = array(); - } + $name = trim(strtolower($name)); - if (!isset($item['text'])) { - return FALSE; + // normalize bogus priorities, but allow empty, null, and false to be defaults. + if (!is_numeric($priority)) { + $priority = 500; } - // we use persistent object properties in the submenu - // setup function, so normalize the array to an object. - // we pass it in as an array because this would be the only - // place in elgg that we ask for an object like this. - // consistency ftw. - $item_obj = new StdClass(); + // no negative priorities right now. + $priority = max((int)$priority, 0); - foreach ($item as $k => $v) { - switch ($k) { - case 'parent_id': - case 'id': - // make sure '' and false make sense - $v = (empty($v)) ? NULL : $v; + $item = elgg_extract($name, $CONFIG->externals_map[$type]); - default: - $item_obj->$k = $v; - break; + 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 { + $item = new stdClass(); + $item->loaded = false; + $item->url = $url; + $item->location = $location; + + $priority = $CONFIG->externals[$type]->add($item, $priority); } - $CONFIG->submenu_items[$context][$group][] = $item_obj; + $CONFIG->externals_map[$type][$name] = $item; - return TRUE; + return $priority !== false; } /** - * Properly nest all submenu entries for contexts $context and 'all' + * Unregister an external file * - * @param string $context - * @param bool $sort Sort the menu items alphabetically - * @since 1.8 - * @see elgg_add_submenu_item + * @param string $type Type of file: js or css + * @param string $name The identifier of the file + * + * @return bool + * @since 1.8.0 */ -function elgg_prepare_submenu($context = 'main', $sort = FALSE) { +function elgg_unregister_external_file($type, $name) { global $CONFIG; - if (!isset($CONFIG->submenu_items) || !($CONFIG->submenu_items)) { - return FALSE; - } - - $groups = array(); - - if (isset($CONFIG->submenu_items['all'])) { - $groups = $CONFIG->submenu_items['all']; - } + elgg_bootstrap_externals_data_structure($type); - if (isset($CONFIG->submenu_items[$context])) { - $groups = array_merge_recursive($groups, $CONFIG->submenu_items[$context]); - } + $name = trim(strtolower($name)); + $item = elgg_extract($name, $CONFIG->externals_map[$type]); - if (!$groups) { - return FALSE; + if ($item) { + unset($CONFIG->externals_map[$type][$name]); + return $CONFIG->externals[$type]->remove($item); } - foreach ($groups as $group => $items) { - if ($sort) { - usort($items, 'elgg_submenu_item_cmp'); - } + return false; +} - $parsed_menu = array(); - // determin which children need to go in this item. - foreach ($items as $i => $item) { - // can only support children if there's an id - if (isset($item->id)) { - foreach ($items as $child_i => $child_item) { - // don't check ourselves or used children. - if ($child_i == $i || $child_item->used == TRUE) { - continue; - } +/** + * Load an external resource for use on this page + * + * @param string $type Type of file: js or css + * @param string $name The identifier for the file + * + * @return void + * @since 1.8.0 + */ +function elgg_load_external_file($type, $name) { + global $CONFIG; - if (isset($child_item->parent_id) && $child_item->parent_id == $item->id) { - if (!isset($item->children)) { - $item->children = array(); - } - $item->children[] = $child_item; - $child_item->parent = $item; - // don't unset because we still need to check this item for children - $child_item->used = TRUE; - } - } + elgg_bootstrap_externals_data_structure($type); - // if the parent doesn't have a url, make it the first child item. - if (isset($item->children) && $item->children && !$item->href) { - $child = $item->children[0]; - while ($child && !isset($child->href)) { - if (isset($child->children) && isset($child->children[0])) { - $child = $child->children[0]; - } else { - $child = NULL; - } - } + $name = trim(strtolower($name)); - if ($child && isset($child->href)) { - $item->href = $child->href; - } else { - // @todo There are no URLs anywhere in this tree. - $item->href = $CONFIG->url; - } - } - } + $item = elgg_extract($name, $CONFIG->externals_map[$type]); - // only add top-level elements to the menu. - // the rest are children. - if (!isset($item->parent_id)) { - $parsed_menu[] = $item; - } - } + if ($item) { + // update a registered item + $item->loaded = true; + } else { + $item = new stdClass(); + $item->loaded = true; + $item->url = ''; + $item->location = ''; - $CONFIG->submenu[$context][$group] = $parsed_menu; + $CONFIG->externals[$type]->add($item); + $CONFIG->externals_map[$type][$name] = $item; } - - return TRUE; -} - -/** - * Helper function used to sort submenu items by their display text. - * - * @param object $a - * @param object $b - * @since 1.8 - * @see elgg_prepare_submenu - */ -function elgg_submenu_item_cmp($a, $b) { - $a = $a->text; - $b = $b->text; - - return strnatcmp($a, $b); } /** - * Use elgg_get_submenu(). + * Get external resource descriptors * - * @see elgg_get_submenu() - * @deprecated 1.8 - */ -function get_submenu() { - elgg_deprecated_notice("get_submenu() has been deprecated by elgg_get_submenu()", 1.8); - return elgg_get_submenu(); -} - -/** - * Return the HTML for a sidemenu. + * @param string $type Type of file: js or css + * @param string $location Page location * - * @param string $context The context of the submenu (defaults to main) - * @param BOOL $sort Sort by display name? - * @return string Formatted HTML. - * @since 1.8 - * @todo Rename to a view function. See {@trac #2320}. + * @return array + * @since 1.8.0 */ -function elgg_get_submenu($context = NULL, $sort = FALSE) { +function elgg_get_loaded_external_files($type, $location) { global $CONFIG; - if (!$context) { - $context = get_context(); - } - - if (!elgg_prepare_submenu($context, $sort)) { - return ''; - } - - $groups = $CONFIG->submenu[$context]; - $submenu_html = ''; - - foreach ($groups as $group => $items) { - // how far down we are in children arrays - $depth = 0; - // push and pop parent items - $temp_items = array(); - - while ($item = current($items)) { - // ignore parents created by a child but parent never defined properly - if (!isset($item->text) || !($item->text)) { - next($items); - continue; - } - - // try to guess if this should be selected if they don't specify - if ((!isset($item->selected) || $item->selected === NULL) && isset($item->href)) { - $item->selected = elgg_http_url_is_identical(full_url(), $item->href); - } - - // traverse up the parent tree if matached to mark all parents as selected/expanded. - if ($item->selected && isset($item->parent)) { - $parent = $item->parent; - while ($parent) { - $parent->selected = TRUE; - if (isset($parent->parent)) { - $parent = $parent->parent; - } else { - $parent = NULL; - } - } - } + if (isset($CONFIG->externals) && $CONFIG->externals[$type] instanceof ElggPriorityList) { + $items = $CONFIG->externals[$type]->getElements(); - // get the next item - if (isset($item->children) && $item->children) { - $depth++; - array_push($temp_items, $items); - $items = $item->children; - } elseif ($depth > 0) { - // check if there are more children elements in the current items - // pop back up to the parent(s) if not - if ($item = next($items)) { - continue; - } else { - while($depth > 0) { - $depth--; - $items = array_pop($temp_items); - if ($item = next($items)) { - break; - } - } - } - } else { - next($items); - } + $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;')); } - - $submenu_html .= elgg_view('navigation/submenu_group', array('group' => $group, 'items' => $items)); + return $items; } - - // include the JS for the expand menus too - return elgg_view('navigation/submenu_js') . $submenu_html; + return array(); } /** - * Returns the HTML for "likes" and "like this" on entities. + * Bootstraps the externals data structure in $CONFIG. * - * @param ElggEntity $entity The entity to like - * @return string|false The HTML for the likes, or false on failure - * @since 1.8 - * @see @elgg_view likes/forms/edit + * @param string $type The type of external, js or css. + * @access private */ -function elgg_view_likes($entity){ - if (!($entity instanceof ElggEntity)) { - return false; - } +function elgg_bootstrap_externals_data_structure($type) { + global $CONFIG; - if ($likes = trigger_plugin_hook('likes', $entity->getType(), array('entity' => $entity), false)) { - return $likes; - } else { - $likes = elgg_view('likes/forms/edit', array('entity' => $entity)); - return $likes; + if (!isset($CONFIG->externals)) { + $CONFIG->externals = array(); } -} -/** - * Count the number of likes attached to an entity - * - * @param ElggEntity $entity - * @return int Number of likes - * @since 1.8 - */ -function elgg_count_likes($entity) { - if ($likeno = trigger_plugin_hook('likes:count', $entity->getType(), - array('entity' => $entity), false)) { - return $likeno; - } else { - return count_annotations($entity->getGUID(), "", "", "likes"); + if (!isset($CONFIG->externals[$type]) || !$CONFIG->externals[$type] instanceof ElggPriorityList) { + $CONFIG->externals[$type] = new ElggPriorityList(); } -} -/** - * Count the number of comments attached to an entity - * - * @param ElggEntity $entity - * @return int Number of comments - */ -function elgg_count_comments($entity) { - if ($commentno = trigger_plugin_hook('comments:count', $entity->getType(), - array('entity' => $entity), false)) { - return $commentno; - } else { - return count_annotations($entity->getGUID(), "", "", "generic_comment"); + if (!isset($CONFIG->externals_map)) { + $CONFIG->externals_map = array(); } -} -/** - * @deprecated 1.7 - */ -function get_library_files($directory, $exceptions = array(), $list = array()) { - elgg_deprecated_notice('get_library_files() deprecated by elgg_get_file_list()', 1.7); - return elgg_get_file_list($directory, $exceptions, $list, array('.php')); + if (!isset($CONFIG->externals_map[$type])) { + $CONFIG->externals_map[$type] = array(); + } } /** @@ -585,13 +453,16 @@ function get_library_files($directory, $exceptions = array(), $list = array()) { * * Only returns files. Does not recurse into subdirs. * - * @param string $directory - * @param array $exceptions Array of filenames to ignore - * @param array $list Array of files to append to - * @param mixed $extensions Array of extensions to allow, NULL for all. Use a dot: array('.php'). + * @param string $directory Directory to look in + * @param array $exceptions Array of filenames to ignore + * @param array $list Array of files to append to + * @param mixed $extensions Array of extensions to allow, NULL for all. Use a dot: array('.php'). + * * @return array Filenames in $directory, in the form $directory/filename. */ -function elgg_get_file_list($directory, $exceptions = array(), $list = array(), $extensions = NULL) { +function elgg_get_file_list($directory, $exceptions = array(), $list = array(), +$extensions = NULL) { + $directory = sanitise_filepath($directory); if ($handle = opendir($directory)) { while (($file = readdir($handle)) !== FALSE) { @@ -616,13 +487,17 @@ function elgg_get_file_list($directory, $exceptions = array(), $list = array(), /** * Sanitise file paths ensuring that they begin and end with slashes etc. * - * @param string $path The path + * @param string $path The path + * @param bool $append_slash Add tailing slash + * * @return string */ function sanitise_filepath($path, $append_slash = TRUE) { // Convert to correct UNIX paths $path = str_replace('\\', '/', $path); $path = str_replace('../', '/', $path); + // replace // with / except when preceeded by : + $path = preg_replace("/([^:])\/\//", "$1/", $path); // Sort trailing slash $path = trim($path); @@ -637,182 +512,15 @@ function sanitise_filepath($path, $append_slash = TRUE) { } /** - * Adds an entry in $CONFIG[$register_name][$subregister_name]. - * - * This is only used for the site-wide menu. See {@link add_menu()}. - * - * @param string $register_name The name of the top-level register - * @param string $subregister_name The name of the subregister - * @param mixed $subregister_value The value of the subregister - * @param array $children_array Optionally, an array of children - * @return true|false Depending on success - * @todo Can be deprecated when the new menu system is introduced. - */ -function add_to_register($register_name, $subregister_name, $subregister_value, $children_array = array()) { - global $CONFIG; - - if (empty($register_name) || empty($subregister_name)) { - return false; - } - - if (!isset($CONFIG->registers)) { - $CONFIG->registers = array(); - } - - if (!isset($CONFIG->registers[$register_name])) { - $CONFIG->registers[$register_name] = array(); - } - - $subregister = new stdClass; - $subregister->name = $subregister_name; - $subregister->value = $subregister_value; - - if (is_array($children_array)) { - $subregister->children = $children_array; - } - - $CONFIG->registers[$register_name][$subregister_name] = $subregister; - return true; -} - -/** - * Removes a register entry from $CONFIG[register_name][subregister_name] - * - * This is used to by {@link remove_menu()} to remove site-wide menu items. - * - * @param string $register_name The name of the top-level register - * @param string $subregister_name The name of the subregister - * @return true|false Depending on success - * @since 1.7.0 - * @todo Can be deprecated when the new menu system is introduced. - */ -function remove_from_register($register_name, $subregister_name) { - global $CONFIG; - - if (empty($register_name) || empty($subregister_name)) { - return false; - } - - if (!isset($CONFIG->registers)) { - return false; - } - - if (!isset($CONFIG->registers[$register_name])) { - return false; - } - - if (isset($CONFIG->registers[$register_name][$subregister_name])) { - unset($CONFIG->registers[$register_name][$subregister_name]); - return true; - } - - return false; -} - -/** - * Constructs and returns a register object. - * - * @param string $register_name The name of the register - * @param mixed $register_value The value of the register - * @param array $children_array Optionally, an array of children - * @return false|stdClass Depending on success - * @todo Can be deprecated when the new menu system is introduced. - */ -function make_register_object($register_name, $register_value, $children_array = array()) { - elgg_deprecated_notice('make_register_object() is deprecated by add_submenu_item()', 1.7); - if (empty($register_name) || empty($register_value)) { - return false; - } - - $register = new stdClass; - $register->name = $register_name; - $register->value = $register_value; - $register->children = $children_array; - - return $register; -} - -/** - * If it exists, returns a particular register as an array - * - * @param string $register_name The name of the register - * @return array|false Depending on success - * @todo Can be deprecated when the new menu system is introduced. - */ -function get_register($register_name) { - global $CONFIG; - - if (isset($CONFIG->registers[$register_name])) { - return $CONFIG->registers[$register_name]; - } - - return false; -} - -/** - * Adds an item to the site-wide menu. - * - * You can obtain the menu array by calling {@link get_register('menu')} - * - * @param string $menu_name The name of the menu item - * @param string $menu_url The URL of the page - * @param array $menu_children Optionally, an array of submenu items (not currently used) - * @param string $context - * @return true|false Depending on success - * @todo Can be deprecated when the new menu system is introduced. - */ -function add_menu($menu_name, $menu_url, $menu_children = array(), $context = "") { - global $CONFIG; - - if (!isset($CONFIG->menucontexts)) { - $CONFIG->menucontexts = array(); - } - - if (empty($context)) { - $context = get_plugin_name(); - } - - $value = new stdClass(); - $value->url = $menu_url; - $value->context = $context; - - $CONFIG->menucontexts[] = $context; - return add_to_register('menu', $menu_name, $value, $menu_children); -} - -/** - * Removes an item from the menu register - * - * @param string $menu_name The name of the menu item - * @return true|false Depending on success - */ -function remove_menu($menu_name) { - return remove_from_register('menu', $menu_name); -} - -/** - * Returns a menu item for use in the children section of add_menu() - * This is not currently used in the Elgg core. - * - * @param string $menu_name The name of the menu item - * @param string $menu_url Its URL - * @return stdClass|false Depending on success - * @todo Can be deprecated when the new menu system is introduced. - */ -function menu_item($menu_name, $menu_url) { - elgg_deprecated_notice('menu_item() is deprecated by add_submenu_item', 1.7); - return make_register_object($menu_name, $menu_url); -} - -/** * Queues a message to be displayed. * * Messages will not be displayed immediately, but are stored in * for later display, usually upon next page load. * * The method of displaying these messages differs depending upon plugins and - * viewtypes. The core default viewtype retrieves messages in {@link views/default/page_shells/default.php} - * and displays messages as javascript popups. + * viewtypes. The core default viewtype retrieves messages in + * {@link views/default/page/shells/default.php} and displays messages as + * javascript popups. * * @internal Messages are stored as strings in the $_SESSION['msg'][$register] array. * @@ -824,13 +532,15 @@ function menu_item($menu_name, $menu_url) { * @important This function handles the standard {@link system_message()} ($register = * 'messages') as well as {@link register_error()} messages ($register = 'errors'). * - * @param string|array $message Optionally, a single message or array of messages to add, (default: null) - * @param string $register This allows for different types of messages: "errors", "messages" (default: messages) - * @param bool $count Count the number of messages (default: false) - * @return true|false|array Either the array of messages, or a response regarding whether the message addition was successful + * @param mixed $message Optionally, a single message or array of messages to add, (default: null) + * @param string $register Types of message: "error", "success" (default: success) + * @param bool $count Count the number of messages (default: false) + * + * @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. */ -function system_messages($message = null, $register = "messages", $count = false) { +function system_messages($message = null, $register = "success", $count = false) { if (!isset($_SESSION['msg'])) { $_SESSION['msg'] = array(); } @@ -860,7 +570,7 @@ function system_messages($message = null, $register = "messages", $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; @@ -873,6 +583,7 @@ function system_messages($message = null, $register = "messages", $count = false * Counts the number of messages, either globally or in a particular register * * @param string $register Optionally, the register + * * @return integer The number of messages */ function count_messages($register = "") { @@ -883,140 +594,42 @@ function count_messages($register = "") { * Display a system message on next page load. * * @see system_messages() + * * @param string|array $message Message or messages to add - * @return Bool + * + * @return bool */ function system_message($message) { - return system_messages($message, "messages"); + return system_messages($message, "success"); } /** * Display an error on next page load. * * @see system_messages() - * @param string|array $message Error or errors to add - * @return true|false Success response - */ -function register_error($error) { - return system_messages($error, "errors"); -} - -/** - * Register a callback function as a handler or trigger registered handlers for an event. - * - * Elgg emits an event when certain core actions occur, like creating an entity. - * Functions registered to these events can respond to the event, prevent the - * event from completing, or ignore the event. * - * Callback functions are registered with {@link register_elgg_event_handler()} + * @param string|array $error Error or errors to add * - * When an event is triggered ({@link trigger_elgg_event()}, each callback function is - * run in order of priority. Any callback that returns false will halt execution - * and control will be passed back to the caller. - * - * @internal Events are stored in $CONFIG->events as: - * <code> - * $CONFIG->events[$event][$type][$priority] = 'callback_function' - * </code> - * - * @note You cannot generally alter the event, only halt it. - * @tip Plugin authors should use {@link register_elgg_event_handler()} to register events. - * - * @param string $event The type of event (eg 'init', 'update', 'delete') - * @param string $object_type The type of object (eg 'system', 'blog', 'user') - * @param string $function The name of the function that will handle the event - * @param int $priority A priority to add new event handlers at. Lower numbers will be called first (default 500) - * @param boolean $call Set to true to call the event rather than add to it (default false) - * @param mixed $object Optionally, the object the event is being performed on (eg a user) - * @return true|false Depending on success - * - * @todo Separate registering and calling events. {@trac #2466} - * @example events/basic.php Register and respond to an Elgg event - * @example events/advanced.php Register for an Elgg event and optionally halt it. - * @internal @example events/emit.php Basic emitting of an Elgg event. - * @link http://docs.elgg.org/Tutorials/Core/Events + * @return bool */ -function events($event = "", $object_type = "", $function = "", $priority = 500, $call = false, $object = null) { - global $CONFIG; - - if (!isset($CONFIG->events)) { - $CONFIG->events = array(); - } else if (!isset($CONFIG->events[$event]) && !empty($event)) { - $CONFIG->events[$event] = array(); - } else if (!isset($CONFIG->events[$event][$object_type]) && !empty($event) && !empty($object_type)) { - $CONFIG->events[$event][$object_type] = array(); - } - - if (!$call) { - if (!empty($event) && !empty($object_type) && is_callable($function)) { - $priority = (int) $priority; - if ($priority < 0) { - $priority = 0; - } - while (isset($CONFIG->events[$event][$object_type][$priority])) { - $priority++; - } - $CONFIG->events[$event][$object_type][$priority] = $function; - ksort($CONFIG->events[$event][$object_type]); - return true; - } else { - return false; - } - } else { - $return = true; - if (!empty($CONFIG->events[$event][$object_type]) && is_array($CONFIG->events[$event][$object_type])) { - foreach($CONFIG->events[$event][$object_type] as $eventfunction) { - if ($eventfunction($event, $object_type, $object) === false) { - return false; - } - } - } - - if (!empty($CONFIG->events['all'][$object_type]) && is_array($CONFIG->events['all'][$object_type])) { - foreach($CONFIG->events['all'][$object_type] as $eventfunction) { - if ($eventfunction($event, $object_type, $object) === false) { - return false; - } - } - } - - if (!empty($CONFIG->events[$event]['all']) && is_array($CONFIG->events[$event]['all'])) { - foreach($CONFIG->events[$event]['all'] as $eventfunction) { - if ($eventfunction($event, $object_type, $object) === false) { - return false; - } - } - } - - if (!empty($CONFIG->events['all']['all']) && is_array($CONFIG->events['all']['all'])) { - foreach($CONFIG->events['all']['all'] as $eventfunction) { - if ($eventfunction($event, $object_type, $object) === false) { - return false; - } - } - } - - return $return; - - } - - return false; +function register_error($error) { + return system_messages($error, "error"); } /** - * Register a callback function as an Elgg event handler. + * Register a callback as an Elgg event handler. * * Events are emitted by Elgg when certain actions occur. Plugins * can respond to these events or halt them completely by registering a handler - * as a callback function to an event. Multiple handlers can be registered for + * as a callback to an event. Multiple handlers can be registered for * the same event and will be executed in order of $priority. Any handler * returning false will halt the execution chain. * - * This function is called with the event name, event type, and handler function name. + * This function is called with the event name, event type, and handler callback name. * Setting the optional $priority allows plugin authors to specify when the - * function should be run. Priorities for plugins should be 1-1000. + * callback should be run. Priorities for plugins should be 1-1000. * - * The callback function is passed 3 arguments when called: $event, $type, and optional $params. + * The callback is passed 3 arguments when called: $event, $type, and optional $params. * * $event is the name of event being emitted. * $type is the type of event or object concerned. @@ -1028,58 +641,97 @@ function events($event = "", $object_type = "", $function = "", $priority = 500, * the earlier the plugin is in the load order, the earlier the priorities are for * any event handlers. * - * @tip $event and $object_type can use the special keyword 'all'. Handler functions registered + * @tip $event and $object_type can use the special keyword 'all'. Handler callbacks registered * with $event = all will be called for all events of type $object_type. Similarly, - * functions registered with $object_type = all will be called for all events of type + * callbacks registered with $object_type = all will be called for all events of type * $event, regardless of $object_type. If $event and $object_type both are 'all', the - * handler function will be called for all events. + * handler callback will be called for all events. * - * @tip Event handler functions are considered in the follow order: + * @tip Event handler callbacks are considered in the follow order: * - Specific registration where 'all' isn't used. * - Registration where 'all' is used for $event only. * - Registration where 'all' is used for $type only. * - Registration where 'all' is used for both. * - * @warning If you use the 'all' keyword, you must have logic in the handler function to + * @warning If you use the 'all' keyword, you must have logic in the handler callback to * test the passed parameters before taking an action. * * @tip When referring to events, the preferred syntax is "event, type". * - * @param string $event The event type + * @internal Events are stored in $CONFIG->events as: + * <code> + * $CONFIG->events[$event][$type][$priority] = $callback; + * </code> + * + * @param string $event The event type * @param string $object_type The object type - * @param string $function The handler callback function name - * @param int $priority The priority of the event + * @param string $callback The handler callback + * @param int $priority The priority - 0 is default, negative before, positive after + * * @return bool * @link http://docs.elgg.org/Tutorials/Plugins/Events - * @example events/basic.php Basic example of registering an event handler callback function. - * @example events/advanced.php Advanced example of registering an event handler callback function and halting execution. - * @example events/all.php Example of how to use the 'all' keyword. + * @example events/basic.php Basic example of registering an event handler callback. + * @example events/advanced.php Advanced example of registering an event handler + * callback and halting execution. + * @example events/all.php Example of how to use the 'all' keyword. */ -function register_elgg_event_handler($event, $object_type, $function, $priority = 500) { - return events($event, $object_type, $function, $priority); +function elgg_register_event_handler($event, $object_type, $callback, $priority = 500) { + global $CONFIG; + + if (empty($event) || empty($object_type)) { + return false; + } + + if (!isset($CONFIG->events)) { + $CONFIG->events = array(); + } + if (!isset($CONFIG->events[$event])) { + $CONFIG->events[$event] = array(); + } + if (!isset($CONFIG->events[$event][$object_type])) { + $CONFIG->events[$event][$object_type] = array(); + } + + if (!is_callable($callback, true)) { + return false; + } + + $priority = max((int) $priority, 0); + + while (isset($CONFIG->events[$event][$object_type][$priority])) { + $priority++; + } + $CONFIG->events[$event][$object_type][$priority] = $callback; + ksort($CONFIG->events[$event][$object_type]); + return true; } /** - * Unregisters a callback function from an event. + * Unregisters a callback for an event. * - * @param string $event The event type + * @param string $event The event type * @param string $object_type The object type - * @param string $function The function name - * @since 1.7.0 + * @param string $callback The callback + * + * @return void + * @since 1.7 */ -function unregister_elgg_event_handler($event, $object_type, $function) { +function elgg_unregister_event_handler($event, $object_type, $callback) { global $CONFIG; - foreach($CONFIG->events[$event][$object_type] as $key => $event_function) { - if ($event_function == $function) { - 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]); + } } } } /** - * Trigger an Elgg Event and run all handler functions registered to that event, type. + * Trigger an Elgg Event and run all handler callbacks registered to that event, type. * - * This function runs all handlers regsitered to $event, $object_type or + * This function runs all handlers registered to $event, $object_type or * the special keyword 'all' for either or both. * * $event is usually a verb: create, update, delete, annotation. @@ -1088,61 +740,86 @@ function unregister_elgg_event_handler($event, $object_type, $function) { * * $object is usually an Elgg* object assciated with the event. * - * @warning Elgg events should only be called by core. Plugin authors should use + * @warning Elgg events should only be triggered by core. Plugin authors should use * {@link trigger_elgg_plugin_hook()} instead. * * @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. * - * @param string $event The event type + * @param string $event The event type * @param string $object_type The object type - * @param string $function The function name - * @return bool The result of running all handler functions. + * @param string $object The object involved in the event + * + * @return bool The result of running all handler callbacks. * @link http://docs.elgg.org/Tutorials/Core/Events + * @internal @example events/emit.php Basic emitting of an Elgg event. */ -function trigger_elgg_event($event, $object_type, $object = null) { - $return = true; - $return1 = events($event, $object_type, "", null, true, $object); - if (!is_null($return1)) { - $return = $return1; +function elgg_trigger_event($event, $object_type, $object = null) { + global $CONFIG; + + $events = array(); + if (isset($CONFIG->events[$event][$object_type])) { + $events[] = $CONFIG->events[$event][$object_type]; } - return $return; + if (isset($CONFIG->events['all'][$object_type])) { + $events[] = $CONFIG->events['all'][$object_type]; + } + if (isset($CONFIG->events[$event]['all'])) { + $events[] = $CONFIG->events[$event]['all']; + } + if (isset($CONFIG->events['all']['all'])) { + $events[] = $CONFIG->events['all']['all']; + } + + $args = array($event, $object_type, $object); + + foreach ($events as $callback_list) { + if (is_array($callback_list)) { + foreach ($callback_list as $callback) { + if (is_callable($callback) && (call_user_func_array($callback, $args) === false)) { + return false; + } + } + } + } + + return true; } /** - * Register a callback function as a plugin hook handler. + * Register a callback as a plugin hook handler. * * Plugin hooks allow developers to losely couple plugins and features by - * repsonding to and emitting {@link trigger_plugin_hook()} customizable hooks. - * Handler functions can respond to the hook, change the details of the hook, or ignore it. + * repsonding to and emitting {@link elgg_trigger_plugin_hook()} customizable hooks. + * Handler callbacks can respond to the hook, change the details of the hook, or + * ignore it. * * Multiple handlers can be registered for a plugin hook, and each callback - * function is called in order of priority. If the return value of a handler - * function is not null, that value is passed to the next function in the - * call stack. When all functions have been run, the final value is passed - * back to the caller via {@link trigger_plugin_hook()}. + * is called in order of priority. If the return value of a handler is not + * null, that value is passed to the next callback in the call stack. When all + * callbacks have been run, the final value is passed back to the caller + * via {@link elgg_trigger_plugin_hook()}. * - * Similar to Elgg Events, plugin hook handler functions are registered by passing + * Similar to Elgg Events, plugin hook handler callbacks are registered by passing * a hook, a type, and a priority. * - * The callback function is passed 4 arguments when called: $hook, $type - * $value, and $params. + * The callback is passed 4 arguments when called: $hook, $type, $value, and $params. * * - str $hook The name of the hook. * - str $type The type of hook. * - mixed $value The return value of the last handler or the default * value if no other handlers have been called. - * - mixed $params An optional array of parameters. Used to provide additional information - * to plugins. + * - mixed $params An optional array of parameters. Used to provide additional + * information to plugins. * * @internal Plugin hooks are stored in $CONFIG->hooks as: * <code> - * $CONFIG->hooks[$hook][$type][$priority] = 'callback_function' + * $CONFIG->hooks[$hook][$type][$priority] = $callback; * </code> * * @tip Plugin hooks are similar to Elgg Events in that Elgg emits @@ -1155,7 +832,7 @@ function trigger_elgg_event($event, $object_type, $object = null) { * any event handlers. * * @tip Like Elgg Events, $hook and $type can use the special keyword 'all'. - * Handler functions registered with $hook = all will be called for all hooks + * Handler callbacks registered with $hook = all will be called for all hooks * of type $type. Similarly, handlers registered with $type = all will be * 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. @@ -1168,67 +845,78 @@ function trigger_elgg_event($event, $object_type, $object = null) { * @warning Unlike Elgg Events, a handler that returns false will NOT halt the * execution chain. * - * @param string $hook The name of the hook - * @param string $type The type of the hook - * @param string $function The name of a valid function to be run - * @param string $priority The priority - 0 is first, 1000 last, default is 500 + * @param string $hook The name of the hook + * @param string $type The type of the hook + * @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 * * @example hooks/register/basic.php Registering for a plugin hook and examining the variables. * @example hooks/register/advanced.php Registering for a plugin hook and changing the params. * @link http://docs.elgg.org/Tutorials/Plugins/Hooks + * @since 1.8.0 */ -function register_plugin_hook($hook, $type, $function, $priority = 500) { +function elgg_register_plugin_hook_handler($hook, $type, $callback, $priority = 500) { global $CONFIG; + if (empty($hook) || empty($type)) { + return false; + } + if (!isset($CONFIG->hooks)) { $CONFIG->hooks = array(); - } else if (!isset($CONFIG->hooks[$hook]) && !empty($hook)) { + } + if (!isset($CONFIG->hooks[$hook])) { $CONFIG->hooks[$hook] = array(); - } else if (!isset($CONFIG->hooks[$hook][$type]) && !empty($type)) { + } + if (!isset($CONFIG->hooks[$hook][$type])) { $CONFIG->hooks[$hook][$type] = array(); } - if (!empty($hook) && !empty($type) && is_callable($function)) { - $priority = (int) $priority; - if ($priority < 0) { - $priority = 0; - } - while (isset($CONFIG->hooks[$hook][$type][$priority])) { - $priority++; - } - $CONFIG->hooks[$hook][$type][$priority] = $function; - ksort($CONFIG->hooks[$hook][$type]); - return true; - } else { + if (!is_callable($callback, true)) { return false; } + + $priority = max((int) $priority, 0); + + while (isset($CONFIG->hooks[$hook][$type][$priority])) { + $priority++; + } + $CONFIG->hooks[$hook][$type][$priority] = $callback; + ksort($CONFIG->hooks[$hook][$type]); + return true; } /** - * Unregister a callback function as a plugin hook. + * Unregister a callback as a plugin hook. * - * @param string $hook The name of the hook - * @param string $entity_type The name of the type of entity (eg "user", "object" etc) - * @param string $function The name of a valid function to be run - * @since 1.7.0 + * @param string $hook The name of the hook + * @param string $entity_type The name of the type of entity (eg "user", "object" etc) + * @param callable $callback The PHP callback to be removed + * + * @return void + * @since 1.8.0 */ -function unregister_plugin_hook($hook, $entity_type, $function) { +function elgg_unregister_plugin_hook_handler($hook, $entity_type, $callback) { global $CONFIG; - foreach($CONFIG->hooks[$hook][$entity_type] as $key => $hook_function) { - if ($hook_function == $function) { - 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]); + } } } } /** - * Trigger a Plugin Hook and run all handler functions registered to that hook:type. + * Trigger a Plugin Hook and run all handler callbacks registered to that hook:type. * * This function runs all handlers regsitered to $hook, $type or * the special keyword 'all' for either or both. * - * Use $params to send additional information to the handler functions. + * Use $params to send additional information to the handler callbacks. * * $returnvalue Is the initial value to pass to the handlers, which can * then change it. It is useful to use $returnvalue to set defaults. @@ -1239,58 +927,70 @@ function unregister_plugin_hook($hook, $entity_type, $function) { * $type is usually a noun: user, ecml, page. * * @tip Like Elgg Events, $hook and $type can use the special keyword 'all'. - * Handler functions registered with $hook = all will be called for all hooks + * Handler callbacks registered with $hook = all will be called for all hooks * of type $type. Similarly, handlers registered with $type = all will be * 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. * - * @see register_plugin_hook() - * @param string $hook The name of the hook to trigger (NB: "all" will trigger for all $types regardless of $hook value) - * @param string $type The type of the hook to trigger (NB: "all" will trigger for all $hooks regardless of $type value) - * @param mixed $params Additional parameters to pass to the handlers - * @param mixed $returnvalue An initial return value - * @return mixed|null The return value of the last handler function called + * @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() * - * @example hooks/trigger/basic.php Trigger a hook that determins if execution should continue. - * @example hooks/trigger/advanced.php Trigger a hook with a default value and use the results to populate a menu. - * @example hooks/basic.php Trigger and respond to a basic plugin hook. + * @param string $hook The name of the hook to trigger ("all" will + * trigger for all $types regardless of $hook value) + * @param string $type The type of the hook to trigger ("all" will + * trigger for all $hooks regardless of $type value) + * @param mixed $params Additional parameters to pass to the handlers + * @param mixed $returnvalue An initial return value + * + * @return mixed|null The return value of the last handler callback called + * + * @example hooks/trigger/basic.php Trigger a hook that determins if execution + * should continue. + * @example hooks/trigger/advanced.php Trigger a hook with a default value and use + * the results to populate a menu. + * @example hooks/basic.php Trigger and respond to a basic plugin hook. * @link http://docs.elgg.org/Tutorials/Plugins/Hooks + * + * @since 1.8.0 */ -function trigger_plugin_hook($hook, $type, $params = null, $returnvalue = null) { +function elgg_trigger_plugin_hook($hook, $type, $params = null, $returnvalue = null) { global $CONFIG; - if (!empty($CONFIG->hooks[$hook][$type]) && is_array($CONFIG->hooks[$hook][$type])) { - foreach($CONFIG->hooks[$hook][$type] as $hookfunction) { - $temp_return_value = $hookfunction($hook, $type, $returnvalue, $params); - if (!is_null($temp_return_value)) { - $returnvalue = $temp_return_value; - } + $hooks = array(); + if (isset($CONFIG->hooks[$hook][$type])) { + if ($hook != 'all' && $type != 'all') { + $hooks[] = $CONFIG->hooks[$hook][$type]; } } - - if (!empty($CONFIG->hooks['all'][$type]) && is_array($CONFIG->hooks['all'][$type])) { - foreach($CONFIG->hooks['all'][$type] as $hookfunction) { - $temp_return_value = $hookfunction($hook, $type, $returnvalue, $params); - if (!is_null($temp_return_value)) { - $returnvalue = $temp_return_value; - } + if (isset($CONFIG->hooks['all'][$type])) { + if ($type != 'all') { + $hooks[] = $CONFIG->hooks['all'][$type]; } } - - if (!empty($CONFIG->hooks[$hook]['all']) && is_array($CONFIG->hooks[$hook]['all'])) { - foreach($CONFIG->hooks[$hook]['all'] as $hookfunction) { - $temp_return_value = $hookfunction($hook, $type, $returnvalue, $params); - if (!is_null($temp_return_value)) { - $returnvalue = $temp_return_value; - } + if (isset($CONFIG->hooks[$hook]['all'])) { + if ($hook != 'all') { + $hooks[] = $CONFIG->hooks[$hook]['all']; } } + if (isset($CONFIG->hooks['all']['all'])) { + $hooks[] = $CONFIG->hooks['all']['all']; + } - if (!empty($CONFIG->hooks['all']['all']) && is_array($CONFIG->hooks['all']['all'])) { - foreach($CONFIG->hooks['all']['all'] as $hookfunction) { - $temp_return_value = $hookfunction($hook, $type, $returnvalue, $params); - if (!is_null($temp_return_value)) { - $returnvalue = $temp_return_value; + foreach ($hooks as $callback_list) { + if (is_array($callback_list)) { + foreach ($callback_list as $hookcallback) { + 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; + } + } } } } @@ -1299,6 +999,56 @@ function trigger_plugin_hook($hook, $type, $params = null, $returnvalue = null) } /** + * Intercepts, logs, and displays uncaught exceptions. + * + * @warning This function should never be called directly. + * + * @see http://www.php.net/set-exception-handler + * + * @param Exception $exception The exception being handled + * + * @return void + * @access private + */ +function _elgg_php_exception_handler($exception) { + $timestamp = time(); + error_log("Exception #$timestamp: $exception"); + + // Wipe any existing output buffer + ob_end_clean(); + + // make sure the error isn't cached + 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 + + 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"); + } +} + +/** * Intercepts catchable PHP errors. * * @warning This function should never be called directly. @@ -1310,13 +1060,19 @@ function trigger_plugin_hook($hook, $type, $params = null, $returnvalue = null) * log the error or ignore it. * * @see http://www.php.net/set-error-handler - * @param int $errno The level of the error raised - * @param string $errmsg The error message + * + * @param int $errno The level of the error raised + * @param string $errmsg The error message * @param string $filename The filename the error was raised in - * @param int $linenum The line number the error was raised at - * @param array $vars An array that points to the active symbol table at the point that the error occurred + * @param int $linenum The line number the error was raised at + * @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) { +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)"; switch ($errno) { @@ -1330,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: @@ -1354,13 +1115,15 @@ 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 - * @todo This is complicated and confusing. Using int constants for debug levels will make things easier. + * @todo This is complicated and confusing. Using int constants for debug levels will + * make things easier. */ -function elgg_log($message, $level='NOTICE') { +function elgg_log($message, $level = 'NOTICE') { global $CONFIG; // only log when debugging is enabled @@ -1404,9 +1167,10 @@ function elgg_log($message, $level='NOTICE') { * A {@elgg_plugin_hook debug log} is called. If a handler returns * false, it will stop the default logging method. * - * @param mixed $value - * @param bool $to_screen - * @param string $level + * @param mixed $value The value + * @param bool $to_screen Display to screen? + * @param string $level The debug level + * * @return void * @since 1.7.0 */ @@ -1414,10 +1178,12 @@ 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); - if (!trigger_plugin_hook('debug', 'log', $params, true)) { + $params = array( + 'level' => $level, + 'msg' => $value, + 'to_screen' => $to_screen, + ); + if (!elgg_trigger_plugin_hook('debug', 'log', $params, true)) { return; } @@ -1428,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); @@ -1438,168 +1209,13 @@ function elgg_dump($value, $to_screen = TRUE, $level = 'NOTICE') { } /** - * Intercepts, logs, and display uncaught exceptions. - * - * @warning This function should never be called directly. - * - * @see http://www.php.net/set-exception-handler - * @param Exception $exception The exception being handled - */ -function __elgg_php_exception_handler($exception) { - error_log("*** FATAL EXCEPTION *** : " . $exception); - - // Wipe any existing output buffer - ob_end_clean(); - - // make sure the error isn't cached - 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)); - page_draw(elgg_echo('exception:title'), $body); -} - -/** - * An array of key value pairs from the datalists table. - * - * Used as a cache in datalist functions. - * - * @global array $DATALIST_CACHE - */ -$DATALIST_CACHE = array(); - -/** - * Get the value of a datalist element. - * - * @internal Datalists are stored in the datalist table. - * - * @tip Use datalists to store information common to a full installation. - * - * @param string $name The name of the datalist element - * @return string|false The datalist value or false if it doesn't exist. - */ -function datalist_get($name) { - global $CONFIG, $DATALIST_CACHE; - - // We need this, because sometimes datalists are attempted - // to be retrieved before the database is created - if (!is_db_installed()) { - return false; - } - - $name = sanitise_string($name); - if (isset($DATALIST_CACHE[$name])) { - return $DATALIST_CACHE[$name]; - } - - // If memcache enabled then cache value in memcache - $value = null; - static $datalist_memcache; - if ((!$datalist_memcache) && (is_memcache_available())) { - $datalist_memcache = new ElggMemcache('datalist_memcache'); - } - if ($datalist_memcache) { - $value = $datalist_memcache->load($name); - } - if ($value) { - return $value; - } - - // [Marcus Povey 20090217 : Now retrieving all datalist values on first load as this saves about 9 queries per page] - $result = get_data("SELECT * from {$CONFIG->dbprefix}datalists"); - if ($result) { - foreach ($result as $row) { - $DATALIST_CACHE[$row->name] = $row->value; - - // Cache it if memcache is available - if ($datalist_memcache) { - $datalist_memcache->save($row->name, $row->value); - } - } - - if (isset($DATALIST_CACHE[$name])) { - return $DATALIST_CACHE[$name]; - } - } - - return false; -} - -/** - * Set the value for a datalist element. - * - * @param string $name The name of the datalist - * @param string $value The new value - * @return true - */ -function datalist_set($name, $value) { - global $CONFIG, $DATALIST_CACHE; - - $name = sanitise_string($name); - $value = sanitise_string($value); - - // If memcache is available then invalidate the cached copy - static $datalist_memcache; - if ((!$datalist_memcache) && (is_memcache_available())) { - $datalist_memcache = new ElggMemcache('datalist_memcache'); - } - - if ($datalist_memcache) { - $datalist_memcache->delete($name); - } - - insert_data("INSERT into {$CONFIG->dbprefix}datalists set name = '{$name}', value = '{$value}' ON DUPLICATE KEY UPDATE value='{$value}'"); - - $DATALIST_CACHE[$name] = $value; - - return true; -} - -/** - * Run a function one time per installation. - * - * If you pass a timestamp as the second argument, it will run the function - * only if (i) it has never been run before or (ii) the timestamp is >= - * the last time it was run. - * - * @warning Functions are determined by their name. If you change the name of a function - * it will be run again. - * - * @tip Use $timelastupdatedcheck in your plugins init function to perform automated - * upgrades. Schedule a function to run once and pass the timestamp of the new release. - * This will cause the run once function to be run on all installations. To perform - * additional upgrades, create new functions for each release. - * - * @internal A datalist entry $functioname is created with the value of time(). - * - * @param string $functionname The name of the function you want to run. - * @param int $timelastupdatedcheck A UNIX timestamp. If time() is > than this, this function will be run again. - * @return bool - */ -function run_function_once($functionname, $timelastupdatedcheck = 0) { - if ($lastupdated = datalist_get($functionname)) { - $lastupdated = (int) $lastupdated; - } else { - $lastupdated = 0; - } - if (is_callable($functionname) && $lastupdated <= $timelastupdatedcheck) { - $functionname(); - datalist_set($functionname, time()); - return true; - } else { - return false; - } -} - -/** * Sends a notice about deprecated use of a function, view, etc. * * 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 @@ -1609,255 +1225,114 @@ function run_function_once($functionname, $timelastupdatedcheck = 0) { * This assumes we are releasing in order and deprecating according to policy. * * @see CODING.txt - * @param str $msg Message to log / display. - * @param str $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 2 minor releases behind, visual and logged - // if it's 1 minor release behind, logged. - // bugfixes don't matter because you're not deprecating between them, RIGHT? + // if it's a 1 minor release behind, visual and logged + // if it's for current minor release, logged. + // 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 = $elgg_version_arr[0]; - $elgg_minor_version = $elgg_version_arr[1]; - - $dep_version_arr = explode('.', $dep_version); - $dep_major_version = $dep_version_arr[0]; - $dep_minor_version = $dep_version_arr[1]; + $elgg_major_version = (int)$elgg_version_arr[0]; + $elgg_minor_version = (int)$elgg_version_arr[1]; - $last_working_version = $dep_minor_version - 1; + $dep_major_version = (int)$dep_version; + $dep_minor_version = 10 * ($dep_version - $dep_major_version); - $visual = FALSE; + $visual = false; - // use version_compare to account for 1.7a < 1.7 - if (($dep_major_version < $elgg_major_version) - || (($elgg_minor_version - $last_working_version) > 1)) { - $visual = TRUE; + if (($dep_major_version < $elgg_major_version) || + ($dep_minor_version < $elgg_minor_version)) { + $visual = true; } - $msg = "Deprecated in $dep_version: $msg"; + $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']})"; - - elgg_log($msg, 'WARNING'); - - return TRUE; -} - - -/** - * Checks if code is being called from a certain function. - * - * To use, call this function with the function name (and optional file location) that it has to be called - * from, it will either return true or false. - * - * e.g. - * - * function my_secure_function() - * { - * if (!call_gatekeeper("my_call_function")) - * return false; - * - * ... do secure stuff ... - * } - * - * function my_call_function() - * { - * // will work - * my_secure_function(); - * } - * - * function bad_function() - * { - * // Will not work - * my_secure_function(); - * } - * - * @param mixed $function The function that this function must have in its call stack, - * to test against a method pass an array containing a class and method name. - * @param string $file Optional file that the function must reside in. - * @todo This is neat but is it necessary? - */ -function call_gatekeeper($function, $file = "") { - // Sanity check - if (!$function) { - return false; - } + // never show this call. + array_shift($backtrace); + $i = count($backtrace); - // Check against call stack to see if this is being called from the correct location - $callstack = debug_backtrace(); - $stack_element = false; + foreach ($backtrace as $trace) { + $stack[] = "[#$i] {$trace['file']}:{$trace['line']}"; + $i--; - foreach ($callstack as $call) { - if (is_array($function)) { - if ( - (strcmp($call['class'], $function[0]) == 0) && - (strcmp($call['function'], $function[1]) == 0) - ) { - $stack_element = $call; - } - } else { - if (strcmp($call['function'], $function) == 0) { - $stack_element = $call; + if ($backtrace_level > 0) { + if ($backtrace_level <= 1) { + break; } + $backtrace_level--; } } - if (!$stack_element) { - return false; - } - - // If file then check that this it is being called from this function - if ($file) { - $mirror = null; - - if (is_array($function)) { - $mirror = new ReflectionMethod($function[0], $function[1]); - } else { - $mirror = new ReflectionFunction($function); - } + $msg .= implode("<br /> -> ", $stack); - if ((!$mirror) || (strcmp($file,$mirror->getFileName())!=0)) { - return false; - } - } + elgg_log($msg, 'WARNING'); return true; } /** - * This function checks to see if it is being called at somepoint by a function defined somewhere - * on a given path (optionally including subdirectories). + * Returns the current page's complete URL. * - * This function is similar to call_gatekeeper() but returns true if it is being called by a method or function which has been defined on a given path or by a specified file. + * The current URL is assembled using the network's wwwroot and the request URI + * in $_SERVER as populated by the web server. This function will include + * any schemes, usernames and passwords, and ports. * - * @param string $path The full path and filename that this function must have in its call stack If a partial path is given and $include_subdirs is true, then the function will return true if called by any function in or below the specified path. - * @param bool $include_subdirs Are subdirectories of the path ok, or must you specify an absolute path and filename. - * @param bool $strict_mode If true then the calling method or function must be directly called by something on $path, if false the whole call stack is searched. - * @todo Again, very neat, but is it necessary? + * @return string The current page URL. */ -function callpath_gatekeeper($path, $include_subdirs = true, $strict_mode = false) { - global $CONFIG; - - $path = sanitise_string($path); - - if ($path) { - $callstack = debug_backtrace(); - - foreach ($callstack as $call) { - $call['file'] = str_replace("\\","/",$call['file']); - - if ($include_subdirs) { - if (strpos($call['file'], $path) === 0) { - - if ($strict_mode) { - $callstack[1]['file'] = str_replace("\\","/",$callstack[1]['file']); - if ($callstack[1] === $call) { return true; } - } else { - return true; - } - } - } else { - if (strcmp($path, $call['file'])==0) { - if ($strict_mode) { - if ($callstack[1] === $call) { - return true; - } - } else { - return true; - } - } - } +function current_page_url() { + $url = parse_url(elgg_get_site_url()); - } - return false; - } + $page = $url['scheme'] . "://"; - if (isset($CONFIG->debug)) { - system_message("Gatekeeper'd function called from {$callstack[1]['file']}:{$callstack[1]['line']}\n\nStack trace:\n\n" . print_r($callstack, true)); + // user/pass + if ((isset($url['user'])) && ($url['user'])) { + $page .= $url['user']; } - - return false; -} - -/** - * Return the state of a php.ini setting. - * - * Normalizes the setting to bool. - * - * @param string $ini_get_arg The INI setting - * @return true|false Depending on whether it's on or off - */ -function ini_get_bool($ini_get_arg) { - $temp = ini_get($ini_get_arg); - - if ($temp == '1' or strtolower($temp) == 'on') { - return true; + if ((isset($url['pass'])) && ($url['pass'])) { + $page .= ":" . $url['pass']; } - return false; -} - -/** - * Returns true is string is not empty, false, or null. - * - * Function to be used in array_filter which returns true if $string is not null. - * - * @param string $string - * @return bool - * @todo This is used once in metadata.php. Use a lambda function instead. - */ -function is_not_null($string) { - if (($string==='') || ($string===false) || ($string===null)) { - return false; + if ((isset($url['user']) && $url['user']) || + (isset($url['pass']) && $url['pass'])) { + $page .= "@"; } - return true; -} - + $page .= $url['host']; -/** - * Normalise the singular keys in an options array to plural keys. - * - * Used in elgg_get_entities*() functions to support shortcutting plural - * 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'. - * @return array - * @since 1.7.0 - */ -function elgg_normalise_plural_options_array($options, $singulars) { - foreach ($singulars as $singular) { - $plural = $singular . 's'; + if ((isset($url['port'])) && ($url['port'])) { + $page .= ":" . $url['port']; + } - if (array_key_exists($singular, $options)) { - if ($options[$singular] === ELGG_ENTITIES_ANY_VALUE) { - $options[$plural] = $options[$singular]; - } else { - $options[$plural] = array($options[$singular]); - } - } + $page = trim($page, "/"); - unset($options[$singular]); - } + $page .= $_SERVER['REQUEST_URI']; - return $options; + return $page; } /** @@ -1868,42 +1343,19 @@ function elgg_normalise_plural_options_array($options, $singulars) { */ function full_url() { $s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : ""; - $protocol = substr(strtolower($_SERVER["SERVER_PROTOCOL"]), 0, strpos(strtolower($_SERVER["SERVER_PROTOCOL"]), "/")) . $s; - $port = ($_SERVER["SERVER_PORT"] == "80" || $_SERVER["SERVER_PORT"] == "443") ? "" : (":".$_SERVER["SERVER_PORT"]); + $protocol = substr(strtolower($_SERVER["SERVER_PROTOCOL"]), 0, + strpos(strtolower($_SERVER["SERVER_PROTOCOL"]), "/")) . $s; + + $port = ($_SERVER["SERVER_PORT"] == "80" || $_SERVER["SERVER_PORT"] == "443") ? + "" : (":" . $_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'); - return $protocol . "://" . $_SERVER['SERVER_NAME'] . $port . str_replace($quotes, $encoded, $_SERVER['REQUEST_URI']); -} - -/** - * Does nothing. - * - * @param $range - * @param $ip - * @deprecated 1.7 - */ -function test_ip($range, $ip) { - elgg_deprecated_notice('test_ip() was removed because of licensing issues.', 1.7); - - return 0; -} - -/** - * Does nothing. - * - * @param array $networks - * @param string $ip - * @return bool - * @deprecated 1.7 - */ -function is_ip_in_array(array $networks, $ip) { - elgg_deprecated_notice('is_ip_in_array() was removed because of licensing issues.', 1.7); - - return false; + return $protocol . "://" . $_SERVER['SERVER_NAME'] . $port . + str_replace($quotes, $encoded, $_SERVER['REQUEST_URI']); } /** @@ -1911,9 +1363,10 @@ function is_ip_in_array(array $networks, $ip) { * * @note If only partial information is passed, a partial URL will be returned. * - * @param array $parts Associative array of URL components like parse_url() returns - * @param bool $htmlencode HTML Encode the url? - * @return str Full URL + * @param array $parts Associative array of URL components like parse_url() returns + * @param bool $html_encode HTML Encode the url? + * + * @return string Full URL * @since 1.7.0 */ function elgg_http_build_url(array $parts, $html_encode = TRUE) { @@ -1944,14 +1397,15 @@ function elgg_http_build_url(array $parts, $html_encode = TRUE) { * add tokens to the action. The form view automatically handles * tokens. * - * @param str $link Full action URL - * @param bool $htmlencode html encode the url? - * @return str URL with action tokens + * @param string $url Full action URL + * @param bool $html_encode HTML encode the url? (default: false) + * + * @return string URL with action tokens * @since 1.7.0 * @link http://docs.elgg.org/Tutorials/Actions */ -function elgg_add_action_tokens_to_url($url, $html_encode = TRUE) { - $components = parse_url($url); +function elgg_add_action_tokens_to_url($url, $html_encode = FALSE) { + $components = parse_url(elgg_normalize_url($url)); if (isset($components['query'])) { $query = elgg_parse_str($components['query']); @@ -1972,26 +1426,14 @@ function elgg_add_action_tokens_to_url($url, $html_encode = TRUE) { return elgg_http_build_url($components, $html_encode); } - -/** - * Add action tokens to URL. - * - * @deprecated 1.7 final - */ -function elgg_validate_action_url($url) { - elgg_deprecated_notice('elgg_validate_action_url had a short life. Use elgg_add_action_tokens_to_url() instead.', '1.7b'); - - return elgg_add_action_tokens_to_url($url); -} - - /** * Removes an element from a URL's query string. * * @note You can send a partial URL string. * - * @param string $url - * @param string $element + * @param string $url Full URL + * @param string $element The element to remove + * * @return string The new URL with the query element removed. * @since 1.7.0 */ @@ -2010,16 +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 - * @return str The new URL with the query strings added + * @param string $url The URL + * @param array $elements Key/value pairs to add to the URL + * + * @return string The new URL with the query strings added * @since 1.7.0 */ function elgg_http_add_url_query_elements($url, array $elements) { @@ -2036,166 +1479,192 @@ function elgg_http_add_url_query_elements($url, array $elements) { } $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 a breadcrumb to the breadcrumbs stack. + * Test if two URLs are functionally identical. + * + * @tip If $ignore_params is used, neither the name nor its value will be considered when comparing. + * + * @tip The order of GET params doesn't matter. * - * @param string $title The title to display - * @param string $link Optional. The link for the title. - * @link http://docs.elgg.org/Tutorials/UI/Breadcrumbs + * @param string $url1 First URL + * @param string $url2 Second URL + * @param array $ignore_params GET params to ignore in the comparison + * + * @return bool + * @since 1.8.0 */ -function elgg_push_breadcrumb($title, $link = NULL) { - global $CONFIG; - if (!is_array($CONFIG->breadcrumbs)) { - $CONFIG->breadcrumbs = array(); +function elgg_http_url_is_identical($url1, $url2, $ignore_params = array('offset', 'limit')) { + // 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) == '/') { + $url1 = elgg_get_site_url() . ltrim($url1, '/'); } - // avoid key collisions. - $CONFIG->breadcrumbs[] = array('title' => $title, 'link' => $link); -} + if (elgg_substr($url1, 0, 1) == '/') { + $url2 = elgg_get_site_url() . ltrim($url2, '/'); + } -/** - * Removes last breadcrumb entry. - * - * @return array popped item. - * @link http://docs.elgg.org/Tutorials/UI/Breadcrumbs - */ -function elgg_pop_breadcrumb() { - global $CONFIG; + // @todo - should probably do something with relative URLs - if (is_array($CONFIG->breadcrumbs)) { - array_pop($CONFIG->breadcrumbs); + if ($url1 == $url2) { + return TRUE; } - return FALSE; -} + $url1_info = parse_url($url1); + $url2_info = parse_url($url2); -/** - * Returns all breadcrumbs as an array of array('title' => 'Readable Title', 'link' => 'URL') - * - * @return array Breadcrumbs - * @link http://docs.elgg.org/Tutorials/UI/Breadcrumbs - */ -function elgg_get_breadcrumbs() { - global $CONFIG; + if (isset($url1_info['path'])) { + $url1_info['path'] = trim($url1_info['path'], '/'); + } + if (isset($url2_info['path'])) { + $url2_info['path'] = trim($url2_info['path'], '/'); + } - return (is_array($CONFIG->breadcrumbs)) ? $CONFIG->breadcrumbs : array(); -} + // compare basic bits + $parts = array('scheme', 'host', 'path'); -/** - * Load all the REQUEST variables into the sticky form cache - * - * Call this from an action when you want all your submitted variables - * available if the submission fails validation and is sent back to the form - * - * @link http://docs.elgg.org/Tutorials/UI/StickyForms - */ -function elgg_make_sticky_form($form_name) { - global $CONFIG; + foreach ($parts as $part) { + if ((isset($url1_info[$part]) && isset($url2_info[$part])) + && $url1_info[$part] != $url2_info[$part]) { + return FALSE; + } elseif (isset($url1_info[$part]) && !isset($url2_info[$part])) { + return FALSE; + } elseif (!isset($url1_info[$part]) && isset($url2_info[$part])) { + return FALSE; + } + } + + // quick compare of get params + if (isset($url1_info['query']) && isset($url2_info['query']) + && $url1_info['query'] == $url2_info['query']) { + return TRUE; + } - $CONFIG->active_sticky_form = $form_name; - elgg_clear_sticky_form($form_name); + // compare get params that might be out of order + $url1_params = array(); + $url2_params = array(); - if (!isset($_SESSION['sticky_forms'])) { - $_SESSION['sticky_forms'] = array(); + if (isset($url1_info['query'])) { + if ($url1_info['query'] = html_entity_decode($url1_info['query'])) { + $url1_params = elgg_parse_str($url1_info['query']); + } } - $_SESSION['sticky_forms'][$form_name] = array(); - foreach($_REQUEST as $key => $var) { - // will go through XSS filtering on the get function - $_SESSION['sticky_forms'][$form_name][$key] = $var; + if (isset($url2_info['query'])) { + if ($url2_info['query'] = html_entity_decode($url2_info['query'])) { + $url2_params = elgg_parse_str($url2_info['query']); + } } -} -/** - * Clear the sticky form cache - * - * Call this if validation is successful in the action handler or - * when they sticky values have been used to repopulate the form - * after a validation error. - * - * @param string $name Form namespace - * @link http://docs.elgg.org/Tutorials/UI/StickyForms - */ -function elgg_clear_sticky_form($form_name) { - unset($_SESSION['sticky_forms'][$form_name]); -} + // drop ignored params + foreach ($ignore_params as $param) { + if (isset($url1_params[$param])) { + unset($url1_params[$param]); + } + if (isset($url2_params[$param])) { + unset($url2_params[$param]); + } + } -/** - * Has this form been made sticky? - * - * @param string $name Form namespace - * @return boolean - * @link http://docs.elgg.org/Tutorials/UI/StickyForms - */ -function elgg_is_sticky_form($form_name) { - return isset($_SESSION['sticky_forms'][$form_name]); + // array_diff_assoc only returns the items in arr1 that aren't in arrN + // but not the items that ARE in arrN but NOT in arr1 + // if arr1 is an empty array, this function will return 0 no matter what. + // since we only care if they're different and not how different, + // add the results together to get a non-zero (ie, different) result + $diff_count = count(array_diff_assoc($url1_params, $url2_params)); + $diff_count += count(array_diff_assoc($url2_params, $url1_params)); + if ($diff_count > 0) { + return FALSE; + } + + return TRUE; } /** - * Get a specific sticky variable + * Checks for $array[$key] and returns its value if it exists, else + * returns $default. * - * @param string $variable The name of the variable - * @param mixed $default Default value if the variable does not exist in sticky cache - * @param boolean $filter_result Filter for bad input if true - * @return mixed + * Shorthand for $value = (isset($array['key'])) ? $array['key'] : 'default'; + * + * @param string $key The key to check. + * @param array $array The array to check against. + * @param mixed $default Default value to return if nothing is found. + * @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. * - * @todo should this filter the default value? - * @link http://docs.elgg.org/Tutorials/UI/StickyForms + * @return mixed + * @since 1.8.0 */ -function elgg_get_sticky_value($form_name, $variable='', $default = NULL, $filter_result = true) { - if (isset($_SESSION['sticky_forms'][$form_name][$variable])) { - $value = $_SESSION['sticky_forms'][$form_name][$variable]; - if ($filter_result) { - // XSS filter result - $value = filter_tags($value); - } - return $value; +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 { + return (isset($array[$key]) && !empty($array[$key])) ? $array[$key] : $default; } - return $default; } /** - * Clear a specific sticky variable + * Sorts a 3d array by specific element. + * + * @warning Will re-index numeric indexes. + * + * @note This operates the same as the built-in sort functions. + * It sorts the array and returns a bool for success. * - * @param string $variable The name of the variable to clear - * @link http://docs.elgg.org/Tutorials/UI/StickyForms + * Do this: elgg_sort_3d_array_by_value($my_array); + * Not this: $my_array = elgg_sort_3d_array_by_value($my_array); + * + * @param array &$array Array to sort + * @param string $element Element to sort by + * @param int $sort_order PHP sort order + * {@see http://us2.php.net/array_multisort} + * @param int $sort_type PHP sort type + * {@see http://us2.php.net/sort} + * + * @return bool */ -function elgg_clear_sticky_value($form_name, $variable) { - unset($_SESSION['sticky_forms'][$form_name][$variable]); -} +function elgg_sort_3d_array_by_value(&$array, $element, $sort_order = SORT_ASC, +$sort_type = SORT_LOCALE_STRING) { -/** - * Returns the current active sticky form. - * @return mixed Str | FALSE - * @link http://docs.elgg.org/Tutorials/UI/StickyForms - */ -function elgg_get_active_sticky_form() { - global $CONFIG; + $sort = array(); - if (isset($CONFIG->active_sticky_form)) { - $form_name = $CONFIG->active_sticky_form; - } else { - return FALSE; - } + foreach ($array as $v) { + if (isset($v[$element])) { + $sort[] = strtolower($v[$element]); + } else { + $sort[] = NULL; + } + }; - return (elgg_is_sticky_form($form_name)) ? $form_name : FALSE; + return array_multisort($sort, $sort_order, $sort_type, $array); } /** - * Sets the active sticky form. + * Return the state of a php.ini setting as a bool * - * @param string $form_name - * @link http://docs.elgg.org/Tutorials/UI/StickyForms + * @warning Using this on ini settings that are not boolean + * will be inaccurate! + * + * @param string $ini_get_arg The INI setting + * + * @return bool Depending on whether it's on or off */ -function elgg_set_active_sticky_form($form_name) { - global $CONFIG; +function ini_get_bool($ini_get_arg) { + $temp = strtolower(ini_get($ini_get_arg)); - $CONFIG->active_sticky_form = $form_name; + if ($temp == '1' || $temp == 'on' || $temp == 'true') { + return true; + } + return false; } /** @@ -2203,7 +1672,8 @@ function elgg_set_active_sticky_form($form_name) { * * @tip Use this for arithmetic when determining if a file can be uploaded. * - * @param str $setting + * @param string $setting The php.ini setting + * * @return int * @since 1.7.0 * @link http://www.php.net/manual/en/function.ini-get.php @@ -2213,12 +1683,14 @@ function elgg_get_ini_setting_in_bytes($setting) { $val = ini_get($setting); // convert INI setting when shorthand notation is used - $last = strtolower($val[strlen($val)-1]); + $last = strtolower($val[strlen($val) - 1]); switch($last) { case 'g': $val *= 1024; + // fallthrough intentional case 'm': $val *= 1024; + // fallthrough intentional case 'k': $val *= 1024; } @@ -2228,29 +1700,57 @@ function elgg_get_ini_setting_in_bytes($setting) { } /** - * Serve javascript pages. + * Returns true is string is not empty, false, or null. * - * Searches for views under js/ and outputs them with special - * headers for caching control. + * Function to be used in array_filter which returns true if $string is not null. * - * @param $page - * @return unknown_type - * @elgg_pagehandler js + * @param string $string The string to test + * + * @return bool + * @todo This is used once in metadata.php. Use a lambda function instead. */ -function js_page_handler($page) { - if (is_array($page) && sizeof($page)) { - $js = str_replace('.js','',$page[0]); - $return = elgg_view('js/' . $js); +function is_not_null($string) { + if (($string === '') || ($string === false) || ($string === null)) { + return false; + } - header('Content-type: text/javascript'); - header('Expires: ' . date('r',time() + 864000)); - header("Pragma: public"); - header("Cache-Control: public"); - header("Content-Length: " . strlen($return)); + return true; +} - echo $return; - exit; +/** + * Normalise the singular keys in an options array to plural keys. + * + * Used in elgg_get_entities*() functions to support shortcutting plural + * names by singular names. + * + * @param array $options The options array. $options['keys'] = 'values'; + * @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) { + $plural = $singular . 's'; + + if (array_key_exists($singular, $options)) { + if ($options[$singular] === ELGG_ENTITIES_ANY_VALUE) { + $options[$plural] = $options[$singular]; + } else { + // Test for array refs #2641 + if (!is_array($options[$singular])) { + $options[$plural] = array($options[$singular]); + } else { + $options[$plural] = $options[$singular]; + } + } + } + + unset($options[$singular]); } + + return $options; } /** @@ -2258,241 +1758,340 @@ function js_page_handler($page) { * * @tip Register for the shutdown:system event to perform functions at the end of page loads. * - * @warning Using this event to perform long-running functions is not very useful. Servers will hold pages until processing is done - * before sending them out to the browser. + * @warning Using this event to perform long-running functions is not very + * 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() { +function _elgg_shutdown_hook() { global $START_MICROTIME; - trigger_elgg_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()}"); + } } /** - * Elgg's main init. + * Serve javascript pages. + * + * Searches for views under js/ and outputs them with special + * headers for caching control. * - * Handles core actions for comments and likes, the JS pagehandler, and the shutdown function. + * @param array $page The page array * - * @elgg_event_handler init system + * @return bool + * @elgg_pagehandler js + * @access private */ -function elgg_init() { - global $CONFIG; - - register_action('comments/add'); - register_action('comments/delete'); - register_action('likes/add'); - register_action('likes/delete'); - - register_page_handler('js', 'js_page_handler'); - - // Trigger the shutdown:system event upon PHP shutdown. - register_shutdown_function('__elgg_shutdown_hook'); - - // Sets a blacklist of words in the current language. - // This is a comma separated list in word:blacklist. - // @todo possibly deprecate - $CONFIG->wordblacklist = array(); - $list = explode(',', elgg_echo('word:blacklist')); - if ($list) { - foreach ($list as $l) { - $CONFIG->wordblacklist[] = trim($l); - } - } +function elgg_js_page_handler($page) { + return elgg_cacheable_view_page_handler($page, 'js'); } /** - * Intercepts the index page when Walled Garden mode is enabled. + * Serve individual views for Ajax. * - * @link http://docs.elgg.org/Tutorials/WalledGarden - * @elgg_plugin_hook index system + * /ajax/view/<name of view>?<key/value params> + * + * @param array $page The page array + * + * @return bool + * @elgg_pagehandler ajax + * @access private */ -function elgg_walled_garden_index() { - $login = elgg_view('account/forms/login_walled_garden'); +function elgg_ajax_page_handler($page) { + if (is_array($page) && sizeof($page)) { + // throw away 'view' and form the view name + unset($page[0]); + $view = implode('/', $page); - page_draw('', $login, 'page_shells/walled_garden'); + $allowed_views = elgg_get_config('allowed_ajax_views'); + if (!array_key_exists($view, $allowed_views)) { + header('HTTP/1.1 403 Forbidden'); + exit; + } + + // pull out GET parameters through filter + $vars = array(); + foreach ($_GET as $name => $value) { + $vars[$name] = get_input($name); + } - // @hack Index must exit to keep plugins from continuing to extend - exit; + if (isset($vars['guid'])) { + $vars['entity'] = get_entity($vars['guid']); + } + + echo elgg_view($view, $vars); + return true; + } + return false; } /** - * Adds unit tests for the general API. + * Serve CSS * - * @elgg_plugin_hook unit_tests system + * Serves CSS from the css views directory with headers for caching control + * + * @param array $page The page array + * + * @return bool + * @elgg_pagehandler css + * @access private */ -function elgg_api_test($hook, $type, $value, $params) { - global $CONFIG; - $value[] = $CONFIG->path . 'engine/tests/api/entity_getter_functions.php'; - $value[] = $CONFIG->path . 'engine/tests/api/helpers.php'; - $value[] = $CONFIG->path . 'engine/tests/regression/trac_bugs.php'; - return $value; +function elgg_css_page_handler($page) { + if (!isset($page[0])) { + // default css + $page[0] = 'elgg'; + } + + return elgg_cacheable_view_page_handler($page, 'css'); } /** - * Returns the main site menu. + * Serves a JS or CSS view with headers for caching. * - * @note The main site menu is split into "featured" links and - * "more" links. + * /<css||js>/name/of/view.<last_cache>.<css||js> * - * @return array ('featured_urls' and 'more') - * @since 1.8 - * @link http://docs.elgg.org/Tutorials/UI/SiteMenu + * @param array $page The page array + * @param string $type The type: js or css + * + * @return bool + * @access private */ -function elgg_get_nav_items() { - $menu_items = get_register('menu'); - $featured_urls_info = get_config('menu_items_featured_urls'); +function elgg_cacheable_view_page_handler($page, $type) { - $more = array(); - $featured_urls = array(); - $featured_urls_sanitised = array(); + switch ($type) { + case 'js': + $content_type = 'text/javascript'; + break; - // easier to compare with in_array() than embedded foreach()es - $valid_urls = array(); - foreach ($menu_items as $info) { - $valid_urls[] = $info->value->url; - } + case 'css': + $content_type = 'text/css'; + break; - // make sure the url is a valid link. - // this prevents disabled plugins leaving behind - // valid links when not using a pagehandler. - if ($featured_urls_info) { - foreach ($featured_urls_info as $info) { - if (in_array($info->value->url, $valid_urls)) { - $featured_urls[] = $info->value->url; - $featured_urls_sanitised[] = $info; - } - } + default: + return false; + break; } - // add toolbar entries if not hiding dupes. - foreach ($menu_items as $name => $info) { - if (!in_array($info->value->url, $featured_urls)) { - $more[] = $info; - } - } + 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"); - return array( - 'featured' => $featured_urls_sanitised, - 'more' => $more - ); + header("Content-type: $content_type"); + + // @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; } /** - * Registers any custom menu items with the main Site Menu. + * Reverses the ordering in an ORDER BY clause. This is achived by replacing + * asc with desc, or appending desc to the end of the clause. * - * @note Custom menu items are added through the admin interface. Plugins - * can add standard menu items by using {@link add_menu()}. + * This is used mostly for elgg_get_entities() and other similar functions. * - * @since 1.8 - * @link http://docs.elgg.org/Tutorials/UI/SiteMenu - * @elgg_event_handler init system + * @param string $order_by An order by clause + * @access private + * @return string + * @access private */ -function add_custom_menu_items() { - if ($custom_items = get_config('menu_items_custom_items')) { - foreach ($custom_items as $url => $name) { - add_menu($name, $url); - } +function elgg_sql_reverse_order_by_clause($order_by) { + $order_by = strtolower($order_by); + + if (strpos($order_by, ' asc') !== false) { + $return = str_replace(' asc', ' desc', $order_by); + } elseif (strpos($order_by, ' desc') !== false) { + $return = str_replace(' desc', ' asc', $order_by); + } else { + // no order specified, so default to desc since mysql defaults to asc + $return = $order_by . ' desc'; } + + return $return; } /** - * Test if two URLs are functionally identical. + * Enable objects with an enable() method. * - * @tip If $ignore_params is used, neither the name nor its value will be considered when comparing. + * Used as a callback for ElggBatch. * - * @tip The order of GET params doesn't matter. + * @todo why aren't these static methods on ElggBatch? * - * @param string $url1 - * @param string $url2 - * @param array $ignore_params - GET params to ignore in the comparison - * @return BOOL - * @since 1.8 + * @param object $object The object to enable + * @return bool + * @access private */ -function elgg_http_url_is_identical($url1, $url2, $ignore_params = array('offset', 'limit')) { - global $CONFIG; +function elgg_batch_enable_callback($object) { + // our db functions return the number of rows affected... + return $object->enable() ? true : false; +} - // if the server portion is missing but it starts with / then add the url in. - if (elgg_substr($url1, 0, 1) == '/') { - $url1 = $CONFIG->url . ltrim($url1, '/'); - } +/** + * Disable objects with a disable() method. + * + * Used as a callback for ElggBatch. + * + * @param object $object The object to disable + * @return bool + * @access private + */ +function elgg_batch_disable_callback($object) { + // our db functions return the number of rows affected... + return $object->disable() ? true : false; +} - if (elgg_substr($url1, 0, 1) == '/') { - $url2 = $CONFIG->url . ltrim($url2, '/'); +/** + * Delete objects with a delete() method. + * + * Used as a callback for ElggBatch. + * + * @param object $object The object to disable + * @return bool + * @access private + */ +function elgg_batch_delete_callback($object) { + // our db functions return the number of rows affected... + return $object->delete() ? true : false; +} + +/** + * Checks if there are some constraints on the options array for + * potentially dangerous operations. + * + * @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)) { + return false; } - // @todo - should probably do something with relative URLs + // at least one of these is required. + $required = array( + // generic restraints + 'guid', 'guids' + ); - if ($url1 == $url2) { - return TRUE; - } + switch ($type) { + case 'metadata': + $metadata_required = array( + 'metadata_owner_guid', 'metadata_owner_guids', + 'metadata_name', 'metadata_names', + 'metadata_value', 'metadata_values' + ); - $url1_info = parse_url($url1); - $url2_info = parse_url($url2); + $required = array_merge($required, $metadata_required); + break; - $url1_info['path'] = trim($url1_info['path'], '/'); - $url2_info['path'] = trim($url2_info['path'], '/'); + case 'annotations': + case 'annotation': + $annotations_required = array( + 'annotation_owner_guid', 'annotation_owner_guids', + 'annotation_name', 'annotation_names', + 'annotation_value', 'annotation_values' + ); - // compare basic bits - $parts = array('scheme', 'host', 'path'); + $required = array_merge($required, $annotations_required); + break; - foreach ($parts as $part) { - if ((isset($url1_info[$part]) && isset($url2_info[$part])) && $url1_info[$part] != $url2_info[$part]) { - return FALSE; - } elseif (isset($url1_info[$part]) && !isset($url2_info[$part])) { - return FALSE; - } elseif (!isset($url1_info[$part]) && isset($url2_info[$part])) { - return FALSE; - } + default: + return false; } - // quick compare of get params - if (isset($url1_info['query']) && isset($url2_info['query']) && $url1_info['query'] == $url2_info['query']) { - return TRUE; + foreach ($required as $key) { + // check that it exists and is something. + if (isset($options[$key]) && $options[$key]) { + return true; + } } - // compare get params that might be out of order - $url1_params = array(); - $url2_params = array(); + return false; +} - if (isset($url1_info['query'])) { - if ($url1_info['query'] = html_entity_decode($url1_info['query'])) { - $url1_params = elgg_parse_str($url1_info['query']); - } +/** + * Intercepts the index page when Walled Garden mode is enabled. + * + * @link http://docs.elgg.org/Tutorials/WalledGarden + * @elgg_plugin_hook index system + * + * @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($hook, $type, $value, $params) { + if ($value) { + // do not create a second index page so return + return; } - if (isset($url2_info['query'])) { - if ($url2_info['query'] = html_entity_decode($url2_info['query'])) { - $url2_params = elgg_parse_str($url2_info['query']); - } - } + elgg_load_css('elgg.walled_garden'); + elgg_load_js('elgg.walled_garden'); + + $content = elgg_view('core/walled_garden/login'); - // drop ignored params - foreach ($ignore_params as $param) { - if (isset($url1_params[$param])) { - unset($url1_params[$param]); - } - if (isset($url2_params[$param])) { - unset($url2_params[$param]); - } - } + $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'); - // array_diff_assoc only returns the items in arr1 that aren't in arrN - // but not the items that ARE in arrN but NOT in arr1 - // if arr1 is an empty array, this function will return 0 no matter what. - // since we only care if they're different and not how different, - // add the results together to get a non-zero (ie, different) result - $diff_count = count(array_diff_assoc($url1_params, $url2_params)); - $diff_count += count(array_diff_assoc($url2_params, $url1_params)); - if ($diff_count > 0) { - return FALSE; - } + // return true to prevent other plugins from adding a front page + return true; +} - return TRUE; +/** + * 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; } /** @@ -2503,68 +2102,153 @@ function elgg_http_url_is_identical($url1, $url2, $ignore_params = array('offset * plugin pages by {@elgg_hook public_pages walled_garden} will redirect to * a login page. * - * @since 1.8 + * @since 1.8.0 * @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->check_walled_garden(); + $CONFIG->site->checkWalledGarden(); } } /** - * Checks for $array[$key] and returns its value if it exists, else - * returns $default. - * - * Shorthand for $value = (isset($array['key'])) ? $array['key'] : 'default'; + * Remove public access for walled gardens * - * @param string $key The key to check. - * @param array $array The array to check against. - * @param mixed $default Default value to return if nothing is found. - * @since 1.8 + * @param string $hook + * @param string $type + * @param array $accesses + * @return array + * @access private */ -function elgg_get_array_value($key, array $array, $default = NULL) { - return (isset($array[$key])) ? $array[$key] : $default; +function _elgg_walled_garden_remove_public_access($hook, $type, $accesses) { + if (isset($accesses[ACCESS_PUBLIC])) { + unset($accesses[ACCESS_PUBLIC]); + } + return $accesses; } /** - * Sorts a 3d array by specific element. + * Boots the engine * - * @warning Will re-index numeric indexes. + * 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 * - * @note This operates the same as the built-in sort functions. - * ie, sorts the array and returns a bool for success. + * @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. * - * Do this: elgg_sort_3d_array_by_value($my_array); - * Not this: $my_array = elgg_sort_3d_array_by_value($my_array); + * Handles core actions for comments, the JS pagehandler, and the shutdown function. * - * @param array $array Array to sort - * @param string $element Element to sort by - * @param $sort_order - * @param $sort_type - * @return bool + * @elgg_event_handler init system + * @return void + * @access private */ -function elgg_sort_3d_array_by_value(&$array, $element, $sort_order = SORT_ASC, $sort_type = SORT_LOCALE_STRING) { - $sort = array(); +function elgg_init() { + global $CONFIG; - foreach ($array as $k => $v) { - if (isset($v[$element])) { - $sort[] = strtolower($v[$element]); - } else { - $sort[] = NULL; - } - }; + elgg_register_action('comments/add'); + elgg_register_action('comments/delete'); - return array_multisort($sort, $sort_order, $sort_type, $array); + 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'); + + $logo_url = elgg_get_site_url() . "_graphics/elgg_toolbar_logo.gif"; + elgg_register_menu_item('topbar', array( + 'name' => 'elgg_logo', + 'href' => 'http://www.elgg.org/', + '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. + // This is a comma separated list in word:blacklist. + // @todo possibly deprecate + $CONFIG->wordblacklist = array(); + $list = explode(',', elgg_echo('word:blacklist')); + if ($list) { + foreach ($list as $l) { + $CONFIG->wordblacklist[] = trim($l); + } + } } +/** + * Adds unit tests for the general API. + * + * @param string $hook unit_test + * @param string $type system + * @param array $value array of test files + * @param array $params empty + * + * @elgg_plugin_hook unit_tests system + * @return array + * @access private + */ +function elgg_api_test($hook, $type, $value, $params) { + global $CONFIG; + $value[] = $CONFIG->path . 'engine/tests/api/entity_getter_functions.php'; + $value[] = $CONFIG->path . 'engine/tests/api/helpers.php'; + $value[] = $CONFIG->path . 'engine/tests/regression/trac_bugs.php'; + return $value; +} /**#@+ - * 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 */ @@ -2598,7 +2282,7 @@ define('ELGG_ENTITIES_NO_VALUE', 0); * referring page. * * @see forward - * @var unknown_type + * @var int -1 */ define('REFERRER', -1); @@ -2612,8 +2296,9 @@ define('REFERRER', -1); */ define('REFERER', -1); -register_elgg_event_handler('init', 'system', 'elgg_init'); -register_plugin_hook('unit_test', 'system', 'elgg_api_test'); +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'); -register_elgg_event_handler('init', 'system', 'add_custom_menu_items', 1000); -register_elgg_event_handler('init', 'system', 'elgg_walled_garden', 1000); +elgg_register_event_handler('init', 'system', 'add_custom_menu_items', 1000); +elgg_register_event_handler('init', 'system', 'elgg_walled_garden', 1000); |
