diff options
Diffstat (limited to 'engine/lib/elgglib.php')
| -rw-r--r-- | engine/lib/elgglib.php | 3659 |
1 files changed, 1593 insertions, 2066 deletions
diff --git a/engine/lib/elgglib.php b/engine/lib/elgglib.php index 9b5b34d86..34111c69d 100644 --- a/engine/lib/elgglib.php +++ b/engine/lib/elgglib.php @@ -1,1501 +1,546 @@ <?php /** - * Elgg library - * Contains important functionality core to Elgg + * Bootstrapping and helper procedural code available for use in Elgg core and plugins. * - * @package Elgg - * @subpackage Core - * @author Curverider Ltd - * @link http://elgg.org/ + * @package Elgg.Core + * @todo These functions can't be subpackaged because they cover a wide mix of + * purposes and subsystems. Many of them should be moved to more relevant files. */ -/** - * Getting directories and moving the browser - */ +// prep core classes to be autoloadable +spl_autoload_register('_elgg_autoload'); +elgg_register_classes(dirname(dirname(__FILE__)) . '/classes'); /** - * Adds messages to the session so they'll be carried over, and forwards the browser. - * Returns false if headers have already been sent and the browser cannot be moved. + * Autoload classes * - * @param string $location URL to forward to browser to - * @return nothing|false - */ -function forward($location = "") { - global $CONFIG; - - if (!headers_sent()) { - $current_page = current_page_url(); - // What is this meant to do? - //if (strpos($current_page, $CONFIG->wwwroot . "action") ===false) - - $_SESSION['msg'] = array_merge($_SESSION['msg'], system_messages()); - if ((substr_count($location, 'http://') == 0) && (substr_count($location, 'https://') == 0)) { - $location = $CONFIG->url . $location; - } - - header("Location: {$location}"); - exit; - } - - return false; -} - -/** - * Return the current page URL. + * @param string $class The name of the class + * + * @return void + * @throws Exception + * @access private */ -function current_page_url() { +function _elgg_autoload($class) { global $CONFIG; - $url = parse_url($CONFIG->wwwroot); - - $page = $url['scheme'] . "://"; - - // 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 .="@"; - } - - $page .= $url['host']; - - if ((isset($url['port'])) && ($url['port'])) { - $page .= ":" . $url['port']; + if (!isset($CONFIG->classes[$class]) || !include($CONFIG->classes[$class])) { + return false; } - - //$page.="/"; - $page = trim($page, "/"); - - $page .= $_SERVER['REQUEST_URI']; - - return $page; } /** - * Templating and visual functionality - */ - -$CURRENT_SYSTEM_VIEWTYPE = ""; - -/** - * Override the view mode detection for the elgg view system. + * Register all files found in $dir as classes + * Need to be named MyClass.php * - * This function will force any further views to be rendered using $viewtype. Remember to call elgg_set_viewtype() with - * no parameters to reset. + * @param string $dir The dir to look in * - * @param string $viewtype The view type, e.g. 'rss', or 'default'. - * @return bool + * @return void + * @since 1.8.0 */ -function elgg_set_viewtype($viewtype = "") { - global $CURRENT_SYSTEM_VIEWTYPE; +function elgg_register_classes($dir) { + $classes = elgg_get_file_list($dir, array(), array(), array('.php')); - $CURRENT_SYSTEM_VIEWTYPE = $viewtype; - - return true; + foreach ($classes as $class) { + elgg_register_class(basename($class, '.php'), $class); + } } /** - * Return the current view type used by the elgg view system. + * Register a classname to a file. * - * By default, this function will return a value based on the default for your system or from the command line - * view parameter. However, you may force a given view type by calling elgg_set_viewtype() + * @param string $class The name of the class + * @param string $location The location of the file * - * @return string The view. + * @return true + * @since 1.8.0 */ -function elgg_get_viewtype() { - global $CURRENT_SYSTEM_VIEWTYPE, $CONFIG; - - $viewtype = NULL; - - if ($CURRENT_SYSTEM_VIEWTYPE != "") { - return $CURRENT_SYSTEM_VIEWTYPE; - } - - if ((empty($_SESSION['view'])) || ( (trim($CONFIG->view!="")) && ($_SESSION['view']!=$CONFIG->view) )) { - $_SESSION['view'] = "default"; - // If we have a config default view for this site then use that instead of 'default' - if (/*(is_installed()) && */(!empty($CONFIG->view)) && (trim($CONFIG->view)!="")) { - $_SESSION['view'] = $CONFIG->view; - } - } +function elgg_register_class($class, $location) { + global $CONFIG; - if (empty($viewtype) && is_callable('get_input')) { - $viewtype = get_input('view'); + if (!isset($CONFIG->classes)) { + $CONFIG->classes = array(); } - if (empty($viewtype)) { - $viewtype = $_SESSION['view']; - } + $CONFIG->classes[$class] = $location; - return $viewtype; + return true; } /** - * Return the location of a given view. + * Register a php library. * - * @param string $view The view. - * @param string $viewtype The viewtype + * @param string $name The name of the library + * @param string $location The location of the file + * + * @return void + * @since 1.8.0 */ -function elgg_get_view_location($view, $viewtype = '') { +function elgg_register_library($name, $location) { global $CONFIG; - if (empty($viewtype)) { - $viewtype = elgg_get_viewtype(); - } - - if (!isset($CONFIG->views->locations[$viewtype][$view])) { - if (!isset($CONFIG->viewpath)) { - return dirname(dirname(dirname(__FILE__))) . "/views/"; - } else { - return $CONFIG->viewpath; - } - } else { - return $CONFIG->views->locations[$viewtype][$view]; + if (!isset($CONFIG->libraries)) { + $CONFIG->libraries = array(); } - return false; + $CONFIG->libraries[$name] = $location; } /** - * Handles templating views + * Load a php library. * - * @see set_template_handler + * @param string $name The name of the library * - * @param string $view The name and location of the view to use - * @param array $vars Any variables that the view requires, passed as an array - * @param boolean $bypass If set to true, elgg_view will bypass any specified alternative template handler; by default, it will hand off to this if requested (see set_template_handler) - * @param boolean $debug If set to true, the viewer will complain if it can't find a view - * @param string $viewtype If set, forces the viewtype for the elgg_view call to be this value (default: standard detection) - * @return string The HTML content + * @return void + * @throws InvalidParameterException + * @since 1.8.0 + * @todo return boolean in 1.9 to indicate whether the library has been loaded */ -function elgg_view($view, $vars = array(), $bypass = false, $debug = false, $viewtype = '') { +function elgg_load_library($name) { global $CONFIG; - static $usercache; - - $view = (string)$view; - - // basic checking for bad paths - if (strpos($view, '..') !== false) { - return false; - } - - $view_orig = $view; - - // Trigger the pagesetup event - if (!isset($CONFIG->pagesetupdone)) { - trigger_elgg_event('pagesetup','system'); - $CONFIG->pagesetupdone = true; - } - - if (!is_array($usercache)) { - $usercache = array(); - } - if (!is_array($vars)) { - elgg_log('Vars in views must be an array!', 'ERROR'); - $vars = array(); - } + static $loaded_libraries = array(); - if (empty($vars)) { - $vars = array(); - } - - // Load session and configuration variables into $vars - // $_SESSION will always be an array if it is set - if (isset($_SESSION) /*&& is_array($_SESSION)*/ ) { - //= array_merge($vars, $_SESSION); - $vars += $_SESSION; - } - - $vars['config'] = array(); - - if (!empty($CONFIG)) { - $vars['config'] = $CONFIG; - } - - $vars['url'] = $CONFIG->url; - - // Load page owner variables into $vars - if (is_callable('page_owner')) { - $vars['page_owner'] = page_owner(); - } else { - $vars['page_owner'] = -1; - } - - if (($vars['page_owner'] != -1) && (is_installed())) { - if (!isset($usercache[$vars['page_owner']])) { - $vars['page_owner_user'] = get_entity($vars['page_owner']); - $usercache[$vars['page_owner']] = $vars['page_owner_user']; - } else { - $vars['page_owner_user'] = $usercache[$vars['page_owner']]; - } + if (in_array($name, $loaded_libraries)) { + return; } - if (!isset($vars['js'])) { - $vars['js'] = ""; + if (!isset($CONFIG->libraries)) { + $CONFIG->libraries = array(); } - // If it's been requested, pass off to a template handler instead - if ($bypass == false && isset($CONFIG->template_handler) && !empty($CONFIG->template_handler)) { - $template_handler = $CONFIG->template_handler; - if (is_callable($template_handler)) { - return $template_handler($view, $vars); - } + if (!isset($CONFIG->libraries[$name])) { + $error = elgg_echo('InvalidParameterException:LibraryNotRegistered', array($name)); + throw new InvalidParameterException($error); } - // Get the current viewtype - if (empty($viewtype)) { - $viewtype = elgg_get_viewtype(); + if (!include_once($CONFIG->libraries[$name])) { + $error = elgg_echo('InvalidParameterException:LibraryNotFound', array( + $name, + $CONFIG->libraries[$name]) + ); + throw new InvalidParameterException($error); } - // Set up any extensions to the requested view - if (isset($CONFIG->views->extensions[$view])) { - $viewlist = $CONFIG->views->extensions[$view]; - } else { - $viewlist = array(500 => $view); - } - // Start the output buffer, find the requested view file, and execute it - ob_start(); - - foreach($viewlist as $priority => $view) { - $view_location = elgg_get_view_location($view, $viewtype); - $view_file = "$view_location$viewtype/$view.php"; - $default_view_file = "{$view_location}default/$view.php"; - - // try to include view - if (!file_exists($view_file) || !include($view_file)) { - // requested view does not exist - $error = "$viewtype/$view view does not exist."; - - // attempt to load default view - if ($viewtype != 'default') { - if (file_exists($default_view_file) && include($default_view_file)) { - // default view found - $error .= " Using default/$view instead."; - } else { - // no view found at all - $error = "Neither $viewtype/$view nor default/$view view exists."; - } - } - - // log warning - elgg_log($error, 'WARNING'); - } - } - - // Save the output buffer into the $content variable - $content = ob_get_clean(); - - // Plugin hook - $content = trigger_plugin_hook('display', 'view', - array('view' => $view_orig, 'vars' => $vars), $content); - - // Return $content - return $content; + $loaded_libraries[] = $name; } /** - * Returns whether the specified view exists + * Forward to $location. * - * @param string $view The view name - * @param string $viewtype If set, forces the viewtype - * @param bool $recurse If false, do not recursively check extensions - * @return true|false Depending on success + * Sends a 'Location: $location' header and exists. If headers have + * already been sent, returns FALSE. + * + * @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_view_exists($view, $viewtype = '', $recurse = true) { - global $CONFIG; - - // Detect view type - if (empty($viewtype)) { - $viewtype = elgg_get_viewtype(); - } - - if (!isset($CONFIG->views->locations[$viewtype][$view])) { - if (!isset($CONFIG->viewpath)) { - $location = dirname(dirname(dirname(__FILE__))) . "/views/"; - } else { - $location = $CONFIG->viewpath; +function forward($location = "", $reason = 'system') { + if (!headers_sent($file, $line)) { + if ($location === REFERER) { + $location = $_SERVER['HTTP_REFERER']; } - } else { - $location = $CONFIG->views->locations[$viewtype][$view]; - } - if (file_exists($location . "{$viewtype}/{$view}.php")) { - return true; - } + $location = elgg_normalize_url($location); - // If we got here then check whether this exists as an extension - // We optionally recursively check whether the extended view exists also for the viewtype - if ($recurse && isset($CONFIG->views->extensions[$view])) { - foreach( $CONFIG->views->extensions[$view] as $view_extension ) { - // do not recursively check to stay away from infinite loops - if (elgg_view_exists($view_extension, $viewtype, false)) { - return true; - } + // 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); + + if ($location) { + header("Location: {$location}"); + exit; + } else if ($location === '') { + exit; } + } else { + throw new SecurityException(elgg_echo('SecurityException:ForwardFailedToRedirect', array($file, $line))); } - - return false; } /** - * Registers a view to be simply cached + * Register a JavaScript file for inclusion * - * Views cached in this manner must take no parameters and be login agnostic - - * that is to say, they look the same no matter who is logged in (or logged out). + * 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. * - * CSS and the basic jS views are automatically cached like this. + * 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. * - * @param string $viewname View name - */ -function elgg_view_register_simplecache($viewname) { - global $CONFIG; - - if (!isset($CONFIG->views)) { - $CONFIG->views = new stdClass; - } - - if (!isset($CONFIG->views->simplecache)) { - $CONFIG->views->simplecache = array(); - } - - //if (elgg_view_exists($viewname)) - $CONFIG->views->simplecache[] = $viewname; -} - -/** - * Regenerates the simple cache. + * The JavaScript files can be local to the server or remote (such as + * Google's CDN). * - * @see elgg_view_register_simplecache + * @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_view_regenerate_simplecache() { - global $CONFIG; - - // @todo elgg_view() checks if the page set is done (isset($CONFIG->pagesetupdone)) and - // triggers an event if it's not. Calling elgg_view() here breaks submenus - // (at least) because the page setup hook is called before any - // contexts can be correctly set (since this is called before page_handler()). - // To avoid this, lie about $CONFIG->pagehandlerdone to force - // the trigger correctly when the first view is actually being output. - $CONFIG->pagesetupdone = TRUE; - - if (isset($CONFIG->views->simplecache)) { - if (!file_exists($CONFIG->dataroot . 'views_simplecache')) { - @mkdir($CONFIG->dataroot . 'views_simplecache'); - } - - if (!empty($CONFIG->views->simplecache) && is_array($CONFIG->views->simplecache)) { - foreach($CONFIG->views->simplecache as $view) { - $viewcontents = elgg_view($view); - $viewname = md5(elgg_get_viewtype() . $view); - if ($handle = fopen($CONFIG->dataroot . 'views_simplecache/' . $viewname, 'w')) { - fwrite($handle, $viewcontents); - fclose($handle); - } - } - } - - datalist_set('simplecache_lastupdate', 0); - } - - unset($CONFIG->pagesetupdone); +function elgg_register_js($name, $url, $location = 'head', $priority = null) { + return elgg_register_external_file('js', $name, $url, $location, $priority); } /** - * Enables the simple cache. + * Unregister a JavaScript file * - * @see elgg_view_register_simplecache + * @param string $name The identifier for the JavaScript library * + * @return bool + * @since 1.8.0 */ - -function elgg_view_enable_simplecache() { - global $CONFIG; - if(!$CONFIG->simplecache_enabled) { - datalist_set('simplecache_enabled',1); - $CONFIG->simplecache_enabled = 1; - elgg_view_regenerate_simplecache(); - } +function elgg_unregister_js($name) { + return elgg_unregister_external_file('js', $name); } /** - * Disables the simple cache. + * Load a JavaScript resource on this page * - * @see elgg_view_register_simplecache + * 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. * - */ -function elgg_view_disable_simplecache() { - global $CONFIG; - if ($CONFIG->simplecache_enabled) { - datalist_set('simplecache_enabled',0); - $CONFIG->simplecache_enabled = 0; - - // purge simple cache - if ($handle = opendir($CONFIG->dataroot.'views_simplecache')) { - while (false !== ($file = readdir($handle))) { - if ($file != "." && $file != "..") { - unlink($CONFIG->dataroot.'views_simplecache/'.$file); - } - } - closedir($handle); - } - } -} - -/** - * This is a factory function which produces an ElggCache object suitable for caching file load paths. + * @param string $name Identifier of the JavaScript resource * - * TODO: Can this be done in a cleaner way? - * TODO: Swap to memcache etc? + * @return void + * @since 1.8.0 */ -function elgg_get_filepath_cache() { - global $CONFIG; - static $FILE_PATH_CACHE; - if (!$FILE_PATH_CACHE) $FILE_PATH_CACHE = new ElggFileCache($CONFIG->dataroot); - - return $FILE_PATH_CACHE; +function elgg_load_js($name) { + elgg_load_external_file('js', $name); } /** - * Function which resets the file path cache. + * Get the JavaScript URLs that are loaded * - */ -function elgg_filepath_cache_reset() { - $cache = elgg_get_filepath_cache(); - return $cache->delete('view_paths'); -} - -/** - * Saves a filepath cache. + * @param string $location 'head' or 'footer' * - * @param mixed $data + * @return array + * @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_get_loaded_js($location = 'head') { + return elgg_get_loaded_external_files('js', $location); } /** - * Retrieve the contents of the filepath cache. + * Register a CSS file for inclusion in the HTML head * - */ -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; -} - -/** - * Enable the filepath 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 bool + * @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_register_css($name, $url, $priority = null) { + return elgg_register_external_file('css', $name, $url, 'head', $priority); } /** - * Disable filepath cache. + * Unregister a CSS file * - */ -function elgg_disable_filepath_cache() { - global $CONFIG; - - datalist_set('viewpath_cache_enabled',0); - $CONFIG->viewpath_cache_enabled = 0; - elgg_filepath_cache_reset(); -} - -/** - * Internal function for retrieving views used by elgg_view_tree + * @param string $name The identifier for the CSS file * - * @param unknown_type $dir - * @param unknown_type $base - * @return unknown + * @return bool + * @since 1.8.0 */ -function elgg_get_views($dir, $base) { - $return = array(); - if (file_exists($dir) && is_dir($dir)) { - if ($handle = opendir($dir)) { - while ($view = readdir($handle)) { - if (!in_array($view, array('.','..','.svn','CVS'))) { - if (is_dir($dir . '/' . $view)) { - if ($val = elgg_get_views($dir . '/' . $view, $base . '/' . $view)) { - $return = array_merge($return, $val); - } - } else { - $view = str_replace('.php','',$view); - $return[] = $base . '/' . $view; - } - } - } - } - } - return $return; +function elgg_unregister_css($name) { + return elgg_unregister_external_file('css', $name); } /** - * @deprecated 1.7. Use elgg_extend_view(). - * @param $dir - * @param $base + * 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 get_views($dir, $base) { - elgg_deprecated_notice('get_views() was deprecated by elgg_get_views()!', 1.7); - elgg_get_views($dir, $base); +function elgg_load_css($name) { + elgg_load_external_file('css', $name); } /** - * When given a partial view root (eg 'js' or 'page_elements'), returns an array of views underneath it + * Get the loaded CSS URLs * - * @param string $view_root The root view - * @param string $viewtype Optionally specify a view type other than the current one. - * @return array A list of view names underneath that root view + * @return array + * @since 1.8.0 */ -function elgg_view_tree($view_root, $viewtype = "") { - global $CONFIG; - static $treecache; - - // Get viewtype - if (!$viewtype) { - $viewtype = elgg_get_viewtype(); - } - - // Has the treecache been initialised? - if (!isset($treecache)) { - $treecache = array(); - } - // A little light internal caching - if (!empty($treecache[$view_root])) { - return $treecache[$view_root]; - } - - // Examine $CONFIG->views->locations - if (isset($CONFIG->views->locations[$viewtype])) { - foreach($CONFIG->views->locations[$viewtype] as $view => $path) { - $pos = strpos($view,$view_root); - if ($pos === 0) { - $treecache[$view_root][] = $view; - } - } - } - - // Now examine core - $location = $CONFIG->viewpath; - $viewtype = elgg_get_viewtype(); - $root = $location . $viewtype . '/' . $view_root; - - if (file_exists($root) && is_dir($root)) { - $val = elgg_get_views($root, $view_root); - if (!is_array($treecache[$view_root])) { - $treecache[$view_root] = array(); - } - $treecache[$view_root] = array_merge($treecache[$view_root], $val); - } - - return $treecache[$view_root]; +function elgg_get_loaded_css() { + return elgg_get_loaded_external_files('css', 'head'); } /** - * When given an entity, views it intelligently. + * Core registration function for external files * - * Expects a view to exist called entity-type/subtype, or for the entity to have a parameter - * 'view' which lists a different view to display. In both cases, elgg_view will be called with - * array('entity' => $entity, 'full' => $full) as its parameters, and therefore this is what - * the view should expect to receive. + * @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 ElggEntity $entity The entity to display - * @param boolean $full Determines whether or not to display the full version of an object, or a smaller version for use in aggregators etc - * @param boolean $bypass If set to true, elgg_view will bypass any specified alternative template handler; by default, it will hand off to this if requested (see set_template_handler) - * @param boolean $debug If set to true, the viewer will complain if it can't find a view - * @return string HTML to display or false + * @return bool + * @since 1.8.0 */ -function elgg_view_entity(ElggEntity $entity, $full = false, $bypass = true, $debug = false) { - global $autofeed; - $autofeed = true; - - // No point continuing if entity is null - if (!$entity) { - return ''; - } +function elgg_register_external_file($type, $name, $url, $location, $priority = 500) { + global $CONFIG; - if (!($entity instanceof ElggEntity)) { + if (empty($name) || empty($url)) { return false; } - // if this entity has a view defined, use it - $view = $entity->view; - if (is_string($view)) { - return elgg_view($view, - array('entity' => $entity, 'full' => $full), - $bypass, - $debug); - } + $url = elgg_format_url($url); + $url = elgg_normalize_url($url); + + elgg_bootstrap_externals_data_structure($type); - $entity_type = $entity->getType(); + $name = trim(strtolower($name)); - $subtype = $entity->getSubtype(); - if (empty($subtype)) { - $subtype = $entity_type; + // normalize bogus priorities, but allow empty, null, and false to be defaults. + if (!is_numeric($priority)) { + $priority = 500; } - $contents = ''; - if (elgg_view_exists("{$entity_type}/{$subtype}")) { - $contents = elgg_view("{$entity_type}/{$subtype}", array( - 'entity' => $entity, - 'full' => $full - ), $bypass, $debug); - } - if (empty($contents)) { - $contents = elgg_view("{$entity_type}/default",array( - 'entity' => $entity, - 'full' => $full - ), $bypass, $debug); - } - // Marcus Povey 20090616 : Speculative and low impact approach for fixing #964 - if ($full) { - $annotations = elgg_view_entity_annotations($entity, $full); + // no negative priorities right now. + $priority = max((int)$priority, 0); - if ($annotations) { - $contents .= $annotations; - } - } - return $contents; -} + $item = elgg_extract($name, $CONFIG->externals_map[$type]); -/** - * When given an annotation, views it intelligently. - * - * This function expects annotation views to be of the form annotation/name, where name - * is the type of annotation. - * - * @param ElggAnnotation $annotation The annotation to display - * @param boolean $full Determines whether or not to display the full version of an object, or a smaller version for use in aggregators etc - * @param boolean $bypass If set to true, elgg_view will bypass any specified alternative template handler; by default, it will hand off to this if requested (see set_template_handler) - * @param boolean $debug If set to true, the viewer will complain if it can't find a view - * @return string HTML (etc) to display - */ -function elgg_view_annotation(ElggAnnotation $annotation, $bypass = true, $debug = false) { - global $autofeed; - $autofeed = true; - - $view = $annotation->view; - if (is_string($view)) { - return elgg_view($view,array('annotation' => $annotation), $bypass, $debug); - } + if ($item) { + // updating a registered item + // don't update loaded because it could already be set + $item->url = $url; + $item->location = $location; - $name = $annotation->name; - $intname = (int) $name; - if ("{$intname}" == "{$name}") { - $name = get_metastring($intname); - } - if (empty($name)) { - return ""; - } - - if (elgg_view_exists("annotation/{$name}")) { - return elgg_view("annotation/{$name}",array('annotation' => $annotation), $bypass, $debug); + // 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 { - return elgg_view("annotation/default",array('annotation' => $annotation), $bypass, $debug); - } -} - - -/** - * Returns a view of a list of entities, plus navigation. It is intended that this function - * be called from other wrapper functions. - * - * @see list_entities - * @see list_user_objects - * @see list_user_friends_objects - * @see list_entities_from_metadata - * @see list_entities_from_metadata_multi - * @see list_entities_from_relationships - * @see list_site_members - * - * @param array $entities List of entities - * @param int $count The total number of entities across all pages - * @param int $offset The current indexing offset - * @param int $limit The number of entities to display per page - * @param true|false $fullview Whether or not to display the full view (default: true) - * @param true|false $viewtypetoggle Whether or not to allow users to toggle to gallery view - * @param bool $pagination Whether pagination is offered. - * @return string The list of entities - */ -function elgg_view_entity_list($entities, $count, $offset, $limit, $fullview = true, $viewtypetoggle = true, $pagination = true) { - $count = (int) $count; - $offset = (int) $offset; - $limit = (int) $limit; - - $context = get_context(); - - $html = elgg_view('entities/entity_list',array( - 'entities' => $entities, - 'count' => $count, - 'offset' => $offset, - 'limit' => $limit, - 'baseurl' => $_SERVER['REQUEST_URI'], - 'fullview' => $fullview, - 'context' => $context, - 'viewtypetoggle' => $viewtypetoggle, - 'viewtype' => get_input('search_viewtype','list'), - 'pagination' => $pagination - )); - - return $html; -} + $item = new stdClass(); + $item->loaded = false; + $item->url = $url; + $item->location = $location; -/** - * Returns a view of a list of annotations, plus navigation. It is intended that this function - * be called from other wrapper functions. - * - * @param array $annotations List of annotations - * @param int $count The total number of annotations across all pages - * @param int $offset The current indexing offset - * @param int $limit The number of annotations to display per page - * @return string The list of annotations - */ -function elgg_view_annotation_list($annotations, $count, $offset, $limit) { - $count = (int) $count; - $offset = (int) $offset; - $limit = (int) $limit; - - $html = ""; - - $nav = elgg_view('navigation/pagination',array( - 'baseurl' => $_SERVER['REQUEST_URI'], - 'offset' => $offset, - 'count' => $count, - 'limit' => $limit, - 'word' => 'annoff', - 'nonefound' => false, - )); - - $html .= $nav; - - if (is_array($annotations) && sizeof($annotations) > 0) { - foreach($annotations as $annotation) { - $html .= elgg_view_annotation($annotation, "", false); - } + $priority = $CONFIG->externals[$type]->add($item, $priority); } - if ($count) { - $html .= $nav; - } + $CONFIG->externals_map[$type][$name] = $item; - return $html; + return $priority !== false; } /** - * Display a selective rendered list of annotations for a given entity. - * - * The list is produced as the result of the entity:annotate plugin hook - * and is designed to provide a more generic framework to allow plugins - * to extend the generic display of entities with their own annotation - * renderings. + * Unregister an external file * - * This is called automatically by the framework from elgg_view_entity() + * @param string $type Type of file: js or css + * @param string $name The identifier of the file * - * @param ElggEntity $entity - * @param bool $full - * @return string or false on failure + * @return bool + * @since 1.8.0 */ -function elgg_view_entity_annotations(ElggEntity $entity, $full = true) { - - // No point continuing if entity is null - if (!$entity) { - return false; - } - - if (!($entity instanceof ElggEntity)) { - return false; - } +function elgg_unregister_external_file($type, $name) { + global $CONFIG; - $entity_type = $entity->getType(); + elgg_bootstrap_externals_data_structure($type); - $annotations = trigger_plugin_hook('entity:annotate', $entity_type, - array( - 'entity' => $entity, - 'full' => $full, - ) - ); - - return $annotations; -} + $name = trim(strtolower($name)); + $item = elgg_extract($name, $CONFIG->externals_map[$type]); -/** - * Displays an internal layout for the use of a plugin canvas. - * Takes a variable number of parameters, which are made available - * in the views as $vars['area1'] .. $vars['areaN']. - * - * @param string $layout The name of the views in canvas/layouts/. - * @return string The layout - */ -function elgg_view_layout($layout) { - $arg = 1; - $param_array = array(); - while ($arg < func_num_args()) { - $param_array['area' . $arg] = func_get_arg($arg); - $arg++; + if ($item) { + unset($CONFIG->externals_map[$type][$name]); + return $CONFIG->externals[$type]->remove($item); } - if (elgg_view_exists("canvas/layouts/{$layout}")) { - return elgg_view("canvas/layouts/{$layout}",$param_array); - } else { - return elgg_view("canvas/default",$param_array); - } -} - -/** - * Returns a view for the page title - * - * @param string $title The page title - * @param string $submenu Should a submenu be displayed? (default false, use not recommended) - * @return string The HTML (etc) - */ -function elgg_view_title($title, $submenu = false) { - $title = elgg_view('page_elements/title', array('title' => $title, 'submenu' => $submenu)); - - return $title; + return false; } /** - * Adds an item to the submenu + * Load an external resource for use on this page * - * @param string $label The human-readable label - * @param string $link The URL of the submenu item - * @param boolean $onclick Used to provide a JS popup to confirm delete - * @param mixed $selected BOOL to force on/off, NULL to allow auto selection - */ -function add_submenu_item($label, $link, $group = 'a', $onclick = false, $selected = NULL) { - global $CONFIG; - - if (!isset($CONFIG->submenu)) { - $CONFIG->submenu = array(); - } - if (!isset($CONFIG->submenu[$group])) { - $CONFIG->submenu[$group] = array(); - } - - $item = new stdClass; - $item->value = $link; - $item->name = $label; - $item->onclick = $onclick; - $item->selected = $selected; - $CONFIG->submenu[$group][] = $item; -} - -/** - * Gets a formatted list of submenu items + * @param string $type Type of file: js or css + * @param string $name The identifier for the file * - * @params bool preselected Selected menu item - * @params bool preselectedgroup Selected menu item group - * @return string List of items + * @return void + * @since 1.8.0 */ -function get_submenu() { - $submenu_total = ""; +function elgg_load_external_file($type, $name) { global $CONFIG; - if (isset($CONFIG->submenu) && $submenu_register = $CONFIG->submenu) { - ksort($submenu_register); - $selected_key = NULL; - $selected_group = NULL; - - foreach($submenu_register as $groupname => $submenu_register_group) { - $submenu = ""; - - foreach($submenu_register_group as $key => $item) { - $selected = false; - // figure out the selected item if required - // if null, try to figure out what should be selected. - // warning: Fuzzy logic. - if (!$selected_key && !$selected_group) { - if ($item->selected === NULL) { - $uri_info = parse_url($_SERVER['REQUEST_URI']); - $item_info = parse_url($item->value); - - // don't want to mangle already encoded queries but want to - // make sure we're comparing encoded to encoded. - // for the record, queries *should* be encoded - $uri_params = array(); - $item_params = array(); - if (isset($uri_info['query'])) { - $uri_info['query'] = html_entity_decode($uri_info['query']); - $uri_params = elgg_parse_str($uri_info['query']); - } - if (isset($item_info['query'])) { - $item_info['query'] = html_entity_decode($item_info['query']); - $item_params = elgg_parse_str($item_info['query']); - } - - $uri_info['path'] = trim($uri_info['path'], '/'); - $item_info['path'] = trim($item_info['path'], '/'); - - // only if we're on the same path - // can't check server because sometimes it's not set in REQUEST_URI - if ($uri_info['path'] == $item_info['path']) { - - // if no query terms, we have a match - if (!isset($uri_info['query']) && !isset($item_info['query'])) { - $selected_key = $key; - $selected_group = $groupname; - $selected = TRUE; - } else { - if ($uri_info['query'] == $item_info['query']) { - //var_dump("Good on 1"); - $selected_key = $key; - $selected_group = $groupname; - $selected = TRUE; - } elseif (!count(array_diff($uri_params, $item_params))) { - $selected_key = $key; - $selected_group = $groupname; - $selected = TRUE; - } - } - } - // if TRUE or FALSE, set selected to this item. - // Group doesn't seem to have anything to do with selected? - } else { - $selected = $item->selected; - $selected_key = $key; - $selected_group = $groupname; - } - } + elgg_bootstrap_externals_data_structure($type); - $submenu .= elgg_view('canvas_header/submenu_template', array( - 'href' => $item->value, - 'label' => $item->name, - 'onclick' => $item->onclick, - 'selected' => $selected, - )); - - } + $name = trim(strtolower($name)); - $submenu_total .= elgg_view('canvas_header/submenu_group', array( - 'submenu' => $submenu, - 'group_name' => $groupname - )); + $item = elgg_extract($name, $CONFIG->externals_map[$type]); - } - } - - return $submenu_total; -} - - -/** - * Automatically views comments and a comment form relating to the given entity - * - * @param ElggEntity $entity The entity to comment on - * @return string|false The HTML (etc) for the comments, or false on failure - */ -function elgg_view_comments($entity){ - - if (!($entity instanceof ElggEntity)) { - return false; - } - - if ($comments = trigger_plugin_hook('comments',$entity->getType(),array('entity' => $entity),false)) { - return $comments; + if ($item) { + // update a registered item + $item->loaded = true; } else { - $comments = list_annotations($entity->getGUID(),'generic_comment'); + $item = new stdClass(); + $item->loaded = true; + $item->url = ''; + $item->location = ''; - //display the comment form - $comments .= elgg_view('comments/forms/edit',array('entity' => $entity)); - - return $comments; + $CONFIG->externals[$type]->add($item); + $CONFIG->externals_map[$type][$name] = $item; } } /** - * Count the number of comments attached to an entity + * Get external resource descriptors * - * @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"); - } -} - -/** - * Wrapper function to display search listings. + * @param string $type Type of file: js or css + * @param string $location Page location * - * @param string $icon The icon for the listing - * @param string $info Any information that needs to be displayed. - * @return string The HTML (etc) representing the listing - */ -function elgg_view_listing($icon, $info) { - return elgg_view('entities/entity_listing',array('icon' => $icon, 'info' => $info)); -} - -/** - * Sets an alternative function to handle templates, which will be passed to by elgg_view. - * This function must take the $view and $vars parameters from elgg_view: - * - * function my_template_function(string $view, array $vars = array()) - * - * @see elgg_view - * - * @param string $function_name The name of the function to pass to. - * @return true|false - */ -function set_template_handler($function_name) { - global $CONFIG; - if (!empty($function_name) && is_callable($function_name)) { - $CONFIG->template_handler = $function_name; - return true; - } - return false; -} - -/** - * Extends a view by adding other views to be displayed at the same time. - * - * @param string $view The view to add to. - * @param string $view_name The name of the view to extend - * @param int $priority The priority, from 0 to 1000, to add at (lowest numbers will be displayed first) - * @param string $viewtype Not used + * @return array + * @since 1.8.0 */ -function elgg_extend_view($view, $view_name, $priority = 501, $viewtype = '') { +function elgg_get_loaded_external_files($type, $location) { global $CONFIG; - if (!isset($CONFIG->views)) { - $CONFIG->views = new stdClass; - } - - if (!isset($CONFIG->views->extensions)) { - $CONFIG->views->extensions = array(); - } + if (isset($CONFIG->externals) && $CONFIG->externals[$type] instanceof ElggPriorityList) { + $items = $CONFIG->externals[$type]->getElements(); - if (!isset($CONFIG->views->extensions[$view])) { - $CONFIG->views->extensions[$view][500] = "{$view}"; - } - - while(isset($CONFIG->views->extensions[$view][$priority])) { - $priority++; + $callback = "return \$v->loaded == true && \$v->location == '$location';"; + $items = array_filter($items, create_function('$v', $callback)); + if ($items) { + array_walk($items, create_function('&$v,$k', '$v = $v->url;')); + } + return $items; } - - $CONFIG->views->extensions[$view][$priority] = "{$view_name}"; - ksort($CONFIG->views->extensions[$view]); + return array(); } /** - * @deprecated 1.7. Use elgg_extend_view(). - * @param $view - * @param $view_name - * @param $priority - * @param $viewtype - */ -function extend_view($view, $view_name, $priority = 501, $viewtype = '') { - elgg_deprecated_notice('extend_view() was deprecated by elgg_extend_view()!', 1.7); - elgg_extend_view($view, $view_name, $priority, $viewtype); -} - -/** - * Set an alternative base location for a view (as opposed to the default of $CONFIG->viewpath) + * Bootstraps the externals data structure in $CONFIG. * - * @param string $view The name of the view - * @param string $location The base location path + * @param string $type The type of external, js or css. + * @access private */ -function set_view_location($view, $location, $viewtype = '') { +function elgg_bootstrap_externals_data_structure($type) { global $CONFIG; - if (empty($viewtype)) { - $viewtype = 'default'; - } - - if (!isset($CONFIG->views)) { - $CONFIG->views = new stdClass; + if (!isset($CONFIG->externals)) { + $CONFIG->externals = array(); } - if (!isset($CONFIG->views->locations)) { - $CONFIG->views->locations = array($viewtype => array($view => $location)); - - } else if (!isset($CONFIG->views->locations[$viewtype])) { - $CONFIG->views->locations[$viewtype] = array($view => $location); - - } else { - $CONFIG->views->locations[$viewtype][$view] = $location; + if (!isset($CONFIG->externals[$type]) || !$CONFIG->externals[$type] instanceof ElggPriorityList) { + $CONFIG->externals[$type] = new ElggPriorityList(); } -} -/** - * Auto-registers views from a particular starting location - * - * @param string $view_base The base of the view name - * @param string $folder The folder to begin looking in - * @param string $base_location_path The base views directory to use with set_view_location - * @param string $viewtype The type of view we're looking at (default, rss, etc) - */ -function autoregister_views($view_base, $folder, $base_location_path, $viewtype) { - if (!isset($i)) { - $i = 0; + if (!isset($CONFIG->externals_map)) { + $CONFIG->externals_map = array(); } - if ($handle = opendir($folder)) { - while ($view = readdir($handle)) { - if (!in_array($view,array('.','..','.svn','CVS')) && !is_dir($folder . "/" . $view)) { - if ((substr_count($view,".php") > 0) || (substr_count($view,".png") > 0)) { - if (!empty($view_base)) { - $view_base_new = $view_base . "/"; - } else { - $view_base_new = ""; - } - - set_view_location($view_base_new . str_replace(".php","",$view), $base_location_path, $viewtype); - } - } else if (!in_array($view,array('.','..','.svn','CVS')) && is_dir($folder . "/" . $view)) { - if (!empty($view_base)) { - $view_base_new = $view_base . "/"; - } else { - $view_base_new = ""; - } - autoregister_views($view_base_new . $view, $folder . "/" . $view, $base_location_path, $viewtype); - } - } + if (!isset($CONFIG->externals_map[$type])) { + $CONFIG->externals_map[$type] = array(); } } /** - * Returns a representation of a full 'page' (which might be an HTML page, RSS file, etc, depending on the current view) + * Returns a list of files in $directory. * - * @param unknown_type $title - * @param unknown_type $body - * @return unknown - */ -function page_draw($title, $body, $sidebar = "") { - - // get messages - try for errors first - $sysmessages = system_messages(null, "errors"); - if (count($sysmessages["errors"]) == 0) { - // no errors so grab rest of messages - $sysmessages = system_messages(null, ""); - } else { - // we have errors - clear out remaining messages - system_messages(null, ""); - } - - // Draw the page - $output = elgg_view('pageshells/pageshell', array( - 'title' => $title, - 'body' => $body, - 'sidebar' => $sidebar, - 'sysmessages' => $sysmessages, - ) - ); - $split_output = str_split($output, 1024); - - foreach($split_output as $chunk) { - echo $chunk; - } -} - -/** - * Displays a UNIX timestamp in a friendly way (eg "less than a minute ago") + * Only returns files. Does not recurse into subdirs. * - * @param int $time A UNIX epoch timestamp - * @return string The friendly time - */ -function friendly_time($time) { - $diff = time() - ((int) $time); - - $minute = 60; - $hour = $minute * 60; - $day = $hour * 24; - - if ($diff < $minute) { - $friendly_time = elgg_echo("friendlytime:justnow"); - } else if ($diff < $hour) { - $diff = round($diff / $minute); - if ($diff == 0) { - $diff = 1; - } - - if ($diff > 1) { - $friendly_time = sprintf(elgg_echo("friendlytime:minutes"), $diff); - } else { - $friendly_time = sprintf(elgg_echo("friendlytime:minutes:singular"), $diff); - } - } else if ($diff < $day) { - $diff = round($diff / $hour); - if ($diff == 0) { - $diff = 1; - } - - if ($diff > 1) { - $friendly_time = sprintf(elgg_echo("friendlytime:hours"), $diff); - } else { - $friendly_time = sprintf(elgg_echo("friendlytime:hours:singular"), $diff); - } - } else { - $diff = round($diff / $day); - if ($diff == 0) { - $diff = 1; - } - - if ($diff > 1) { - $friendly_time = sprintf(elgg_echo("friendlytime:days"), $diff); - } else { - $friendly_time = sprintf(elgg_echo("friendlytime:days:singular"), $diff); - } - } - - $timestamp = htmlentities(date(elgg_echo('friendlytime:date_format'), $time)); - return "<acronym title=\"$timestamp\">$friendly_time</acronym>"; -} - -/** - * When given a title, returns a version suitable for inclusion in a URL + * @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'). * - * @param string $title The title - * @return string The optimised title + * @return array Filenames in $directory, in the form $directory/filename. */ -function friendly_title($title) { - $title = trim($title); - $title = strtolower($title); - $title = preg_replace("/[^\w ]/","",$title); - $title = str_replace(" ","-",$title); - $title = str_replace("--","-",$title); - return $title; -} +function elgg_get_file_list($directory, $exceptions = array(), $list = array(), +$extensions = NULL) { -/** - * Library loading and handling - */ - -/** - * @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')); -} - -/** - * Returns a list of files in $directory - * - * @param str $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. (With a dot: array('.php')) - * @return array - */ -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) { - if (!is_file($file) || in_array($file, $exceptions)) { + if (!is_file($directory . $file) || in_array($file, $exceptions)) { continue; } if (is_array($extensions)) { if (in_array(strrchr($file, '.'), $extensions)) { - $list[] = $directory . "/" . $file; + $list[] = $directory . $file; } } else { - $list[] = $directory . "/" . $file; + $list[] = $directory . $file; } } + closedir($handle); } return $list; } /** - * Ensures that the installation has all the correct files, that PHP is configured correctly, and so on. - * Leaves appropriate messages in the error register if not. + * Sanitise file paths ensuring that they begin and end with slashes etc. * - * @return true|false True if everything is ok (or Elgg is fit enough to run); false if not. - */ -function sanitised() { - $sanitised = true; - - if (!file_exists(dirname(dirname(__FILE__)) . "/settings.php")) { - // See if we are being asked to save the file - $save_vars = get_input('db_install_vars'); - $result = ""; - if ($save_vars) { - $result = create_settings($save_vars, dirname(dirname(__FILE__)) . "/settings.example.php"); - - if (file_put_contents(dirname(dirname(__FILE__)) . "/settings.php", $result)) { - // blank result to stop it being displayed in textarea - $result = ""; - } - } - - // Recheck to see if the file is still missing - if (!file_exists(dirname(dirname(__FILE__)) . "/settings.php")) { - register_error(elgg_view("messages/sanitisation/settings", array('settings.php' => $result))); - $sanitised = false; - } - } - - if (!file_exists(dirname(dirname(dirname(__FILE__))) . "/.htaccess")) { - if (!@copy(dirname(dirname(dirname(__FILE__))) . "/htaccess_dist", dirname(dirname(dirname(__FILE__))) . "/.htaccess")) { - register_error(elgg_view("messages/sanitisation/htaccess", array('.htaccess' => file_get_contents(dirname(dirname(dirname(__FILE__))) . "/htaccess_dist")))); - $sanitised = false; - } - } - - return $sanitised; -} - -/** - * Registers - */ - -/** - * Adds an array with a name to a given generic array register. - * For example, these are used for menus. + * @param string $path The path + * @param bool $append_slash Add tailing slash * - * @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 + * @return string */ -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(); - } +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); - $subregister = new stdClass; - $subregister->name = $subregister_name; - $subregister->value = $subregister_value; + // Sort trailing slash + $path = trim($path); + // rtrim defaults plus / + $path = rtrim($path, " \n\t\0\x0B/"); - if (is_array($children_array)) { - $subregister->children = $children_array; + if ($append_slash) { + $path = $path . '/'; } - $CONFIG->registers[$register_name][$subregister_name] = $subregister; - return true; + return $path; } /** - * Returns a register object + * Queues a message to be displayed. * - * @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 - */ -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 + * Messages will not be displayed immediately, but are stored in + * for later display, usually upon next page load. * - * @param string $register_name The name of the register - * @return array|false Depending on success - */ -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 menu register - * This is used in the core to create the tools dropdown menu - * You can obtain the menu array by calling get_register('menu') + * 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. * - * @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 (not used and will likely be deprecated) - * @return true|false Depending on success - */ -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(); - } - - $CONFIG->menucontexts[] = $context; - return add_to_register('menu', $menu_name, $menu_url, $menu_children); -} - -/** - * Returns a menu item for use in the children section of add_menu() - * This is not currently used in the Elgg core + * @internal Messages are stored as strings in the $_SESSION['msg'][$register] array. * - * @param string $menu_name The name of the menu item - * @param string $menu_url Its URL - * @return stdClass|false Depending on success - */ -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); -} - - -/** - * Message register handling - * If a null $message parameter is given, the function returns the array of messages so far and empties it - * based on the $register parameters. Otherwise, any message or array of messages is added. + * @warning This function is used to both add to and clear the message + * stack. If $messages is null, $register will be returned and cleared. + * If $messages is null and $register is empty, all messages will be + * returned and removed. * - * @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 + * @important This function handles the standard {@link system_message()} ($register = + * 'messages') as well as {@link register_error()} messages ($register = 'errors'). + * + * @param mixed $message Optionally, a single message or array of messages to add, (default: null) + * @param string $register Types of message: "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(); } @@ -1525,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; @@ -1538,299 +583,414 @@ 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 = "") { - return system_messages(null,$register,true); + return system_messages(null, $register, true); } /** - * An alias for system_messages($message) to handle standard user information messages + * Display a system message on next page load. + * + * @see system_messages() * * @param string|array $message Message or messages to add - * @return true|false Success response + * + * @return bool */ function system_message($message) { - return system_messages($message, "messages"); + return system_messages($message, "success"); } /** - * An alias for system_messages($message) to handle error messages + * Display an error on next page load. + * + * @see system_messages() * - * @param string|array $message Error or errors to add - * @return true|false Success response + * @param string|array $error Error or errors to add + * + * @return bool */ function register_error($error) { - return system_messages($error, "errors"); + return system_messages($error, "error"); } /** - * Event register - * Adds functions to the register for a particular event, but also calls all functions registered to an event when required + * 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 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. * - * Event handler functions must be of the form: + * 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 + * callback should be run. Priorities for plugins should be 1-1000. * - * event_handler_function($event, $object_type, $object); + * The callback is passed 3 arguments when called: $event, $type, and optional $params. * - * And must return true or false depending on success. A false will halt the event in its tracks and no more functions will be called. + * $event is the name of event being emitted. + * $type is the type of event or object concerned. + * $params is an optional parameter passed that can include a related object. See + * specific event documentation for details on which events pass what parameteres. * - * You can then simply register them using the following function. Optionally, this can be called with a priority nominally from 0 to 1000, where functions with lower priority values are called first (note that priorities CANNOT be negative): + * @tip If a priority isn't specified it is determined by the order the handler was + * registered relative to the event and type. For plugins, this generally means + * the earlier the plugin is in the load order, the earlier the priorities are for + * any event handlers. * - * register_elgg_event_handler($event, $object_type, $function_name [, $priority = 500]); + * @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, + * 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 callback will be called for all events. * - * Note that you can also use 'all' in place of both the event and object type. + * @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. * - * To trigger an event properly, you should always use: + * @warning If you use the 'all' keyword, you must have logic in the handler callback to + * test the passed parameters before taking an action. * - * trigger_elgg_event($event, $object_type [, $object]); + * @tip When referring to events, the preferred syntax is "event, type". * - * Where $object is optional, and represents the $object_type the event concerns. This will return true if successful, or false if it fails. + * @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 $callback The handler callback + * @param int $priority The priority - 0 is default, negative before, positive after * - * @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 + * @return bool + * @link http://docs.elgg.org/Tutorials/Plugins/Events + * @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 events($event = "", $object_type = "", $function = "", $priority = 500, $call = false, $object = null) { +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(); - } else if (!isset($CONFIG->events[$event]) && !empty($event)) { + } + if (!isset($CONFIG->events[$event])) { $CONFIG->events[$event] = array(); - } else if (!isset($CONFIG->events[$event][$object_type]) && !empty($event) && !empty($object_type)) { + } + if (!isset($CONFIG->events[$event][$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; - } - } - } + if (!is_callable($callback, true)) { + return false; + } - return $return; + $priority = max((int) $priority, 0); + while (isset($CONFIG->events[$event][$object_type][$priority])) { + $priority++; } - - return false; + $CONFIG->events[$event][$object_type][$priority] = $callback; + ksort($CONFIG->events[$event][$object_type]); + return true; } /** - * Alias function for events, that registers a function to a particular kind of 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 - * @return true|false Depending on success - */ -function register_elgg_event_handler($event, $object_type, $function, $priority = 500) { - return events($event, $object_type, $function, $priority); -} - -/** - * Unregisters a function to a particular kind of event + * @param string $callback The callback * - * @param string $event The event type - * @param string $object_type The object type - * @param string $function The function name + * @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]); + } } } } /** - * Alias function for events, that triggers a particular kind of event + * Trigger an Elgg Event and run all handler callbacks registered to that event, type. * - * @param string $event The event type + * 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. + * + * $object_type is usually a noun: object, group, user, annotation, relationship, metadata. + * + * $object is usually an Elgg* object assciated with the event. + * + * @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 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 $object_type The object type - * @param string $function The function name - * @return true|false Depending on success + * @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 function to a plugin hook for a particular entity type, with a given priority. + * Register a callback as a plugin hook handler. + * + * Plugin hooks allow developers to losely couple plugins and features by + * 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 + * 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()}. * - * eg if you want the function "export_user" to be called when the hook "export" for "user" entities - * is run, use: + * Similar to Elgg Events, plugin hook handler callbacks are registered by passing + * a hook, a type, and a priority. * - * register_plugin_hook("export", "user", "export_user"); + * The callback is passed 4 arguments when called: $hook, $type, $value, and $params. * - * "all" is a valid value for both $hook and $entity_type. "none" is a valid value for $entity_type. + * - 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. * - * The export_user function would then be defined as: + * @internal Plugin hooks are stored in $CONFIG->hooks as: + * <code> + * $CONFIG->hooks[$hook][$type][$priority] = $callback; + * </code> * - * function export_user($hook, $entity_type, $returnvalue, $params); + * @tip Plugin hooks are similar to Elgg Events in that Elgg emits + * a plugin hook when certain actions occur, but a plugin hook allows you to alter the + * parameters, as well as halt execution. * - * Where $returnvalue is the return value returned by the last function returned by the hook, and - * $params is an array containing a set of parameters (or nothing). + * @tip If a priority isn't specified it is determined by the order the handler was + * registered relative to the event and type. For plugins, this generally means + * the earlier the plugin is in the load order, the earlier the priorities are for + * any event handlers. * - * @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 - * @param string $priority The priority - 0 is first, 1000 last, default is 500 - * @return true|false Depending on success + * @tip Like Elgg Events, $hook and $type can use the special keyword 'all'. + * 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. + * + * @tip Plugin hooks are sometimes used to gather lists from plugins. This is + * usually done by pushing elements into an array passed in $params. Be sure + * to append to and then return $value so you don't overwrite other plugin's + * values. + * + * @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 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, $entity_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][$entity_type]) && !empty($entity_type)) { - $CONFIG->hooks[$hook][$entity_type] = array(); + } + if (!isset($CONFIG->hooks[$hook][$type])) { + $CONFIG->hooks[$hook][$type] = array(); } - if (!empty($hook) && !empty($entity_type) && is_callable($function)) { - $priority = (int) $priority; - if ($priority < 0) { - $priority = 0; - } - while (isset($CONFIG->hooks[$hook][$entity_type][$priority])) { - $priority++; - } - $CONFIG->hooks[$hook][$entity_type][$priority] = $function; - ksort($CONFIG->hooks[$hook][$entity_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 function to a plugin hook for a particular entity type + * 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 + * @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]); + } } } } /** - * Triggers a plugin hook, with various parameters as an array. For example, to provide - * a 'foo' hook that concerns an entity of type 'bar', with a parameter called 'param1' - * with value 'value1', that by default returns true, you'd call: + * 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 callbacks. * - * trigger_plugin_hook('foo', 'bar', array('param1' => 'value1'), true); + * $returnvalue Is the initial value to pass to the handlers, which can + * then change it. It is useful to use $returnvalue to set defaults. + * If no handlers are registered, $returnvalue is immediately returned. * - * @see register_plugin_hook - * @param string $hook The name of the hook to trigger - * @param string $entity_type The name of the entity type to trigger it for (or "all", or "none") - * @param array $params Any parameters. It's good practice to name the keys, i.e. by using array('name' => 'value', 'name2' => 'value2') - * @param mixed $returnvalue An initial return value - * @return mixed|null The cumulative return value for the plugin hook functions + * $hook is usually a verb: import, get_views, output. + * + * $type is usually a noun: user, ecml, page. + * + * @tip Like Elgg Events, $hook and $type can use the special keyword 'all'. + * 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. + * + * @internal The checks for $hook and/or $type not being equal to 'all' is to + * prevent a plugin hook being registered with an 'all' being called more than + * once if the trigger occurs with an 'all'. An example in core of this is in + * actions.php: + * elgg_trigger_plugin_hook('action_gatekeeper:permissions:check', 'all', ...) + * + * @see elgg_register_plugin_hook_handler() + * + * @param string $hook The name of the hook to trigger ("all" will + * 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, $entity_type, $params = null, $returnvalue = null) { +function elgg_trigger_plugin_hook($hook, $type, $params = null, $returnvalue = null) { global $CONFIG; - //if (!isset($CONFIG->hooks) || !isset($CONFIG->hooks[$hook]) || !isset($CONFIG->hooks[$hook][$entity_type])) - // return $returnvalue; - - if (!empty($CONFIG->hooks[$hook][$entity_type]) && is_array($CONFIG->hooks[$hook][$entity_type])) { - foreach($CONFIG->hooks[$hook][$entity_type] as $hookfunction) { - $temp_return_value = $hookfunction($hook, $entity_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]; } } - //else - //if (!isset($CONFIG->hooks['all'][$entity_type])) - // return $returnvalue; - - if (!empty($CONFIG->hooks['all'][$entity_type]) && is_array($CONFIG->hooks['all'][$entity_type])) { - foreach($CONFIG->hooks['all'][$entity_type] as $hookfunction) { - $temp_return_value = $hookfunction($hook, $entity_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]; } } - //else - //if (!isset($CONFIG->hooks[$hook]['all'])) - // return $returnvalue; - - if (!empty($CONFIG->hooks[$hook]['all']) && is_array($CONFIG->hooks[$hook]['all'])) { - foreach($CONFIG->hooks[$hook]['all'] as $hookfunction) { - $temp_return_value = $hookfunction($hook, $entity_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']; } } - //else - //if (!isset($CONFIG->hooks['all']['all'])) - // return $returnvalue; + 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, $entity_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; + } + } } } } @@ -1839,26 +999,85 @@ function trigger_plugin_hook($hook, $entity_type, $params = null, $returnvalue = } /** - * Error handling + * 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"); + } +} /** - * PHP Error handler function. - * This function acts as a wrapper to catch and report PHP error messages. + * Intercepts catchable PHP errors. + * + * @warning This function should never be called directly. + * + * @internal + * For catchable fatal errors, throws an Exception with the error. + * + * For non-fatal errors, depending upon the debug settings, either + * 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) { case E_USER_ERROR: - error_log("ERROR: $error"); + error_log("PHP ERROR: $error"); register_error("ERROR: $error"); // Since this is a fatal error, we want to stop any further execution but do so gracefully. @@ -1867,13 +1086,18 @@ function __elgg_php_error_handler($errno, $errmsg, $filename, $linenum, $vars) { case E_WARNING : case E_USER_WARNING : - error_log("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: global $CONFIG; if (isset($CONFIG->debug) && $CONFIG->debug === 'NOTICE') { - error_log("NOTICE: $error"); + error_log("PHP NOTICE: $error"); } } @@ -1881,19 +1105,25 @@ function __elgg_php_error_handler($errno, $errmsg, $filename, $linenum, $vars) { } /** - * Throws a message to the Elgg logger + * Display or log a message. + * + * If $level is >= to the debug setting in {@link $CONFIG->debug}, the + * message will be sent to {@link elgg_dump()}. Messages with lower + * priority than {@link $CONFIG->debug} are ignored. * - * The Elgg log is currently implemented such that any messages sent at a level - * greater than or equal to the debug setting will be sent to elgg_dump. - * The default location for elgg_dump is the screen except for notices. + * {@link elgg_dump()} outputs all levels but NOTICE to screen by default. * - * Note: No messages will be displayed unless debugging has been enabled. + * @note No messages will be displayed unless debugging has been enabled. + * + * @param string $message User message + * @param string $level NOTICE | WARNING | ERROR | DEBUG * - * @param str $message User message - * @param str $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. */ -function elgg_log($message, $level='NOTICE') { +function elgg_log($message, $level = 'NOTICE') { global $CONFIG; // only log when debugging is enabled @@ -1929,27 +1159,46 @@ function elgg_log($message, $level='NOTICE') { } /** - * Extremely generic var_dump-esque wrapper + * Logs or displays $value. + * + * If $to_screen is true, $value is displayed to screen. Else, + * it is handled by PHP's {@link error_log()} function. * - * Immediately dumps the given $value as a human-readable string. - * The $value can instead be written to the screen or server log depending on - * the value of the $to_screen flag. + * A {@elgg_plugin_hook debug log} is called. If a handler returns + * false, it will stop the default logging method. + * + * @param mixed $value The value + * @param bool $to_screen Display to screen? + * @param string $level The debug level * - * @param mixed $value - * @param bool $to_screen - * @param string $level * @return void + * @since 1.7.0 */ 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; } + // Do not want to write to screen before page creation has started. + // This is not fool-proof but probably fixes 95% of the cases when logging + // results in data sent to the browser before the page is begun. + if (!isset($CONFIG->pagesetupdone)) { + $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); @@ -1960,406 +1209,544 @@ function elgg_dump($value, $to_screen = TRUE, $level = 'NOTICE') { } /** - * Custom exception handler. - * This function catches any thrown exceptions and handles them appropriately. + * Sends a notice about deprecated use of a function, view, etc. * - * @see http://www.php.net/set-exception-handler - * @param Exception $exception The exception being handled + * 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'. 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 + * lower than the current Elgg major version. + * + * @note This will always at least log a warning. Don't use to pre-deprecate things. + * This assumes we are releasing in order and deprecating according to policy. + * + * @see CODING.txt + * + * @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_php_exception_handler($exception) { - error_log("*** FATAL EXCEPTION *** : " . $exception); - - ob_end_clean(); // Wipe any existing output buffer - - // 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); - //header("Internal Server Error", true, 500); +function elgg_deprecated_notice($msg, $dep_version, $backtrace_level = 1) { + // if it's a major release behind, visual and logged + // if it's a 1 minor release behind, visual and logged + // if it's for current minor release, logged. + // bugfixes don't matter because we are not deprecating between them - $body = elgg_view("messages/exceptions/exception",array('object' => $exception)); - page_draw(elgg_echo('exception:title'), $body); -} + if (!$dep_version) { + return false; + } -/** - * Data lists - */ + $elgg_version = get_version(true); + $elgg_version_arr = explode('.', $elgg_version); + $elgg_major_version = (int)$elgg_version_arr[0]; + $elgg_minor_version = (int)$elgg_version_arr[1]; -$DATALIST_CACHE = array(); + $dep_major_version = (int)$dep_version; + $dep_minor_version = 10 * ($dep_version - $dep_major_version); -/** - * Get the value of a particular piece of data in the datalist - * - * @param string $name The name of the datalist - * @return string|false Depending on success - */ -function datalist_get($name) { - global $CONFIG, $DATALIST_CACHE; + $visual = false; - // We need this, because sometimes datalists are received before the database is created - if (!is_db_installed()) { - return false; + if (($dep_major_version < $elgg_major_version) || + ($dep_minor_version < $elgg_minor_version)) { + $visual = true; } - $name = sanitise_string($name); - if (isset($DATALIST_CACHE[$name])) { - return $DATALIST_CACHE[$name]; - } + $msg = "Deprecated in $dep_major_version.$dep_minor_version: $msg"; - // 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; + if ($visual && elgg_is_admin_logged_in()) { + register_error($msg); } - // [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; + // 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(); + // never show this call. + array_shift($backtrace); + $i = count($backtrace); - // Cache it if memcache is available - if ($datalist_memcache) { - $datalist_memcache->save($row->name, $row->value); - } - } + foreach ($backtrace as $trace) { + $stack[] = "[#$i] {$trace['file']}:{$trace['line']}"; + $i--; - if (isset($DATALIST_CACHE[$name])) { - return $DATALIST_CACHE[$name]; + if ($backtrace_level > 0) { + if ($backtrace_level <= 1) { + break; + } + $backtrace_level--; } } + $msg .= implode("<br /> -> ", $stack); - /*if ($row = get_data_row("SELECT value from {$CONFIG->dbprefix}datalists where name = '{$name}' limit 1")) { - $DATALIST_CACHE[$name] = $row->value; - - // Cache it if memcache is available - if ($datalist_memcache) $datalist_memcache->save($name, $row->value); - - return $row->value; - }*/ + elgg_log($msg, 'WARNING'); - return false; + return true; } /** - * Sets the value for a system-wide piece of data (overwriting a previous value if it exists) + * Returns the current page's complete URL. * - * @param string $name The name of the datalist - * @param string $value The new value - * @return true + * 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. + * + * @return string The current page URL. */ -function datalist_set($name, $value) { - - global $CONFIG, $DATALIST_CACHE; +function current_page_url() { + $url = parse_url(elgg_get_site_url()); - $name = sanitise_string($name); - $value = sanitise_string($value); + $page = $url['scheme'] . "://"; - // If memcache is available then invalidate the cached copy - static $datalist_memcache; - if ((!$datalist_memcache) && (is_memcache_available())) { - $datalist_memcache = new ElggMemcache('datalist_memcache'); + // 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 ($datalist_memcache) { - $datalist_memcache->delete($name); + $page .= $url['host']; + + if ((isset($url['port'])) && ($url['port'])) { + $page .= ":" . $url['port']; } - //delete_data("delete from {$CONFIG->dbprefix}datalists where name = '{$name}'"); - insert_data("INSERT into {$CONFIG->dbprefix}datalists set name = '{$name}', value = '{$value}' ON DUPLICATE KEY UPDATE value='{$value}'"); + $page = trim($page, "/"); - $DATALIST_CACHE[$name] = $value; + $page .= $_SERVER['REQUEST_URI']; - return true; + return $page; +} + +/** + * Return the full URL of the current page. + * + * @return string The URL + * @todo Combine / replace with current_page_url() + */ +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"]); + + // This is here to prevent XSS in poorly written browsers used by 80% of the population. + // 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']); } /** - * Runs a function once - not per page load, but per installation. - * If you like, you can also set the threshold for the function execution - i.e., - * if the function was executed before or on $timelastupdatedcheck, this - * function will run it again. + * Builds a URL from the a parts array like one returned by {@link parse_url()}. + * + * @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 $html_encode HTML Encode the url? * - * @param string $functionname The name of the function you want to run. - * @param int $timelastupdatedcheck Optionally, the UNIX epoch timestamp of the execution threshold - * @return true|false Depending on success. + * @return string Full URL + * @since 1.7.0 */ -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; +function elgg_http_build_url(array $parts, $html_encode = TRUE) { + // build only what's given to us. + $scheme = isset($parts['scheme']) ? "{$parts['scheme']}://" : ''; + $host = isset($parts['host']) ? "{$parts['host']}" : ''; + $port = isset($parts['port']) ? ":{$parts['port']}" : ''; + $path = isset($parts['path']) ? "{$parts['path']}" : ''; + $query = isset($parts['query']) ? "?{$parts['query']}" : ''; + + $string = $scheme . $host . $port . $path . $query; + + if ($html_encode) { + return elgg_format_url($string); } else { - return false; + return $string; } } /** - * Sends a notice about deprecated use of a function, view, etc. - * Note: This will ALWAYS at least log a warning. Don't use to pre-deprecate things. - * This assumes we are releasing in order and deprecating according to policy. + * Adds action tokens to URL * - * @param str $msg Message to log / display. - * @param str $version human-readable *release* version the function was deprecated. No bloody A, B, (R)C, or D. + * As of 1.7.0 action tokens are required on all actions. + * Use this function to append action tokens to a URL's GET parameters. + * This will preserve any existing GET parameters. * - * @return bool + * @note If you are using {@elgg_view input/form} you don't need to + * add tokens to the action. The form view automatically handles + * 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_deprecated_notice($msg, $dep_version) { - // 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? +function elgg_add_action_tokens_to_url($url, $html_encode = FALSE) { + $components = parse_url(elgg_normalize_url($url)); - if (!$dep_version) { - return FALSE; + if (isset($components['query'])) { + $query = elgg_parse_str($components['query']); + } else { + $query = array(); } - $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]; + if (isset($query['__elgg_ts']) && isset($query['__elgg_token'])) { + return $url; + } - $dep_version_arr = explode('.', $dep_version); - $dep_major_version = $dep_version_arr[0]; - $dep_minor_version = $dep_version_arr[1]; + // append action tokens to the existing query + $query['__elgg_ts'] = time(); + $query['__elgg_token'] = generate_action_token($query['__elgg_ts']); + $components['query'] = http_build_query($query); - $last_working_version = $dep_minor_version - 1; + // rebuild the full url + return elgg_http_build_url($components, $html_encode); +} - $visual = FALSE; +/** + * Removes an element from a URL's query string. + * + * @note You can send a partial URL string. + * + * @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 + */ +function elgg_http_remove_url_query_element($url, $element) { + $url_array = parse_url($url); - // 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 (isset($url_array['query'])) { + $query = elgg_parse_str($url_array['query']); + } else { + // nothing to remove. Return original URL. + return $url; } - $msg = "Deprecated in $dep_version: $msg"; - - if ($visual) { - register_error($msg); + if (array_key_exists($element, $query)) { + unset($query[$element]); } - // 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. - $backtrace = debug_backtrace(); - $caller = $backtrace[1]; - $msg .= " (Called from {$caller['file']}:{$caller['line']})"; - - elgg_log($msg, 'WARNING'); - - return TRUE; + $url_array['query'] = http_build_query($query); + $string = elgg_http_build_url($url_array, false); + return $string; } - /** - * Privilege elevation and gatekeeper code + * Adds an element or elements to a URL's query string. + * + * @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) { + $url_array = parse_url($url); + if (isset($url_array['query'])) { + $query = elgg_parse_str($url_array['query']); + } else { + $query = array(); + } + + foreach ($elements as $k => $v) { + $query[$k] = $v; + } + + $url_array['query'] = http_build_query($query); + $string = elgg_http_build_url($url_array, false); + + return $string; +} /** - * Gatekeeper function which ensures that a we are being executed from - * a specified location. - * - * 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; + * Test if two URLs are functionally identical. * - * ... do secure stuff ... - * } + * @tip If $ignore_params is used, neither the name nor its value will be considered when comparing. * - * function my_call_function() - * { - * // will work - * my_secure_function(); - * } + * @tip The order of GET params doesn't matter. * - * function bad_function() - * { - * // Will not work - * my_secure_function(); - * } + * @param string $url1 First URL + * @param string $url2 Second URL + * @param array $ignore_params GET params to ignore in the comparison * - * @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. + * @return bool + * @since 1.8.0 */ -function call_gatekeeper($function, $file = "") { - // Sanity check - if (!$function) { - return false; +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, '/'); } - // Check against call stack to see if this is being called from the correct location - $callstack = debug_backtrace(); - $stack_element = false; + if (elgg_substr($url1, 0, 1) == '/') { + $url2 = elgg_get_site_url() . ltrim($url2, '/'); + } - 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; - } + // @todo - should probably do something with relative URLs + + if ($url1 == $url2) { + return TRUE; + } + + $url1_info = parse_url($url1); + $url2_info = parse_url($url2); + + if (isset($url1_info['path'])) { + $url1_info['path'] = trim($url1_info['path'], '/'); + } + if (isset($url2_info['path'])) { + $url2_info['path'] = trim($url2_info['path'], '/'); + } + + // compare basic bits + $parts = array('scheme', 'host', 'path'); + + 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; } } - if (!$stack_element) { - return false; + // quick compare of get params + if (isset($url1_info['query']) && isset($url2_info['query']) + && $url1_info['query'] == $url2_info['query']) { + return TRUE; } + // compare get params that might be out of order + $url1_params = array(); + $url2_params = array(); - // If file then check that this it is being called from this function - if ($file) { - $mirror = null; + if (isset($url1_info['query'])) { + if ($url1_info['query'] = html_entity_decode($url1_info['query'])) { + $url1_params = elgg_parse_str($url1_info['query']); + } + } - if (is_array($function)) { - $mirror = new ReflectionMethod($function[0], $function[1]); - } else { - $mirror = new ReflectionFunction($function); + if (isset($url2_info['query'])) { + if ($url2_info['query'] = html_entity_decode($url2_info['query'])) { + $url2_params = elgg_parse_str($url2_info['query']); } + } - if ((!$mirror) || (strcmp($file,$mirror->getFileName())!=0)) { - return false; + // 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]); } } - return true; + // 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; } /** - * This function checks to see if it is being called at somepoint by a function defined somewhere - * on a given path (optionally including subdirectories). + * Checks for $array[$key] and returns its value if it exists, else + * returns $default. * - * 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. + * Shorthand for $value = (isset($array['key'])) ? $array['key'] : 'default'; * - * @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. + * @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. + * + * @return mixed + * @since 1.8.0 */ -function callpath_gatekeeper($path, $include_subdirs = true, $strict_mode = false) { - global $CONFIG; - - $path = sanitise_string($path); - - if ($path) { - $callstack = debug_backtrace(); +function elgg_extract($key, array $array, $default = null, $strict = true) { + if (!is_array($array)) { + return $default; + } - foreach ($callstack as $call) { - $call['file'] = str_replace("\\","/",$call['file']); + if ($strict) { + return (isset($array[$key])) ? $array[$key] : $default; + } else { + return (isset($array[$key]) && !empty($array[$key])) ? $array[$key] : $default; + } +} - if ($include_subdirs) { - if (strpos($call['file'], $path) === 0) { +/** + * 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. + * + * 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_sort_3d_array_by_value(&$array, $element, $sort_order = SORT_ASC, +$sort_type = SORT_LOCALE_STRING) { - 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; - } - } - } + $sort = array(); + foreach ($array as $v) { + if (isset($v[$element])) { + $sort[] = strtolower($v[$element]); + } else { + $sort[] = NULL; } - return false; - } - - 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)); - } + }; - return false; + return array_multisort($sort, $sort_order, $sort_type, $array); } /** - * Returns true or false depending on whether a PHP .ini setting is on or off + * Return the state of a php.ini setting as a bool + * + * @warning Using this on ini settings that are not boolean + * will be inaccurate! * * @param string $ini_get_arg The INI setting - * @return true|false Depending on whether it's on or off + * + * @return bool Depending on whether it's on or off */ function ini_get_bool($ini_get_arg) { - $temp = ini_get($ini_get_arg); + $temp = strtolower(ini_get($ini_get_arg)); - if ($temp == '1' or strtolower($temp) == 'on') { + if ($temp == '1' || $temp == 'on' || $temp == 'true') { return true; } return false; } /** + * Returns a PHP INI setting in bytes. + * + * @tip Use this for arithmetic when determining if a file can be uploaded. + * + * @param string $setting The php.ini setting + * + * @return int + * @since 1.7.0 + * @link http://www.php.net/manual/en/function.ini-get.php + */ +function elgg_get_ini_setting_in_bytes($setting) { + // retrieve INI setting + $val = ini_get($setting); + + // convert INI setting when shorthand notation is used + $last = strtolower($val[strlen($val) - 1]); + switch($last) { + case 'g': + $val *= 1024; + // fallthrough intentional + case 'm': + $val *= 1024; + // fallthrough intentional + case 'k': + $val *= 1024; + } + + // return byte value + return $val; +} + +/** + * 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 + * @param string $string The string to test + * * @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)) { + if (($string === '') || ($string === false) || ($string === null)) { return false; } return true; } - /** - * Normalise the singular keys in an options array - * to the plural keys. + * 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'. * - * @param $options - * @param $singulars * @return array + * @since 1.7.0 + * @access private */ function elgg_normalise_plural_options_array($options, $singulars) { foreach ($singulars as $singular) { $plural = $singular . 's'; - // normalize the singular to plural - // isset() returns FALSE for array values of NULL, so they are ignored. - // everything else falsy is included. - //if (isset($options[$singular]) && $options[$singular] !== NULL && $options[$singular] !== FALSE) { - if (isset($options[$singular])) { - if (isset($options[$plural])) { - if (is_array($options[$plural])) { - $options[$plural][] = $options[$singlar]; + 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] = array($options[$plural], $options[$singular]); + $options[$plural] = $options[$singular]; } - } else { - $options[$plural] = array($options[$singular]); } } + unset($options[$singular]); } @@ -2367,411 +1754,551 @@ function elgg_normalise_plural_options_array($options, $singulars) { } /** - * Get the full URL of the current page. + * Emits a shutdown:system event upon PHP shutdown, but before database connections are dropped. * - * @return string The URL + * @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. + * + * @see http://www.php.net/register-shutdown-function + * + * @return void + * @see register_shutdown_hook() + * @access private */ -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"]); - return $protocol . "://" . $_SERVER['SERVER_NAME'] . $port . $_SERVER['REQUEST_URI']; -} - -/** - * Useful function found in the comments on the PHP man page for ip2long. - * Returns 1 if an IP matches a given range. - * - * TODO: Check licence... assuming this is PD since it was found several places on the interwebs.. - * please check or rewrite. - * - * Matches: - * xxx.xxx.xxx.xxx (exact) - * xxx.xxx.xxx.[yyy-zzz] (range) - * xxx.xxx.xxx.xxx/nn (nn = # bits, cisco style -- i.e. /24 = class C) - * Does not match: - * xxx.xxx.xxx.xx[yyy-zzz] (range, partial octets not supported) - */ -function test_ip($range, $ip) { - $result = 1; - - # IP Pattern Matcher - # J.Adams <jna@retina.net> - # - # Matches: - # - # xxx.xxx.xxx.xxx (exact) - # xxx.xxx.xxx.[yyy-zzz] (range) - # xxx.xxx.xxx.xxx/nn (nn = # bits, cisco style -- i.e. /24 = class C) - # - # Does not match: - # xxx.xxx.xxx.xx[yyy-zzz] (range, partial octets not supported) - - if (ereg("([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)/([0-9]+)",$range,$regs)) { - # perform a mask match - $ipl = ip2long($ip); - $rangel = ip2long($regs[1] . "." . $regs[2] . "." . $regs[3] . "." . $regs[4]); - - $maskl = 0; - - for ($i = 0; $i< 31; $i++) { - if ($i < $regs[5]-1) { - $maskl = $maskl + pow(2,(30-$i)); - } - } +function _elgg_shutdown_hook() { + global $START_MICROTIME; - if (($maskl & $rangel) == ($maskl & $ipl)) { - return 1; - } else { - return 0; - } - } else { - # range based - $maskocts = split("\.",$range); - $ipocts = split("\.",$ip); - - # perform a range match - for ($i=0; $i<4; $i++) { - if (ereg("\[([0-9]+)\-([0-9]+)\]",$maskocts[$i],$regs)) { - if ( ($ipocts[$i] > $regs[2]) || ($ipocts[$i] < $regs[1])) { - $result = 0; - } - } else { - if ($maskocts[$i] <> $ipocts[$i]) { - $result = 0; - } - } - } + 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'); + } 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()}"); } +} - return $result; +/** + * Serve javascript pages. + * + * Searches for views under js/ and outputs them with special + * headers for caching control. + * + * @param array $page The page array + * + * @return bool + * @elgg_pagehandler js + * @access private + */ +function elgg_js_page_handler($page) { + return elgg_cacheable_view_page_handler($page, 'js'); } /** - * Match an IP address against a number of ip addresses or ranges, returning true if found. + * Serve individual views for Ajax. + * + * /ajax/view/<name of view>?<key/value params> + * + * @param array $page The page array * - * @param array $networks - * @param string $ip * @return bool + * @elgg_pagehandler ajax + * @access private */ -function is_ip_in_array(array $networks, $ip) { - global $SYSTEM_LOG; +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); + + $allowed_views = elgg_get_config('allowed_ajax_views'); + if (!array_key_exists($view, $allowed_views)) { + header('HTTP/1.1 403 Forbidden'); + exit; + } - foreach ($networks as $network) { - if (test_ip(trim($network), $ip)) { - return true; + // pull out GET parameters through filter + $vars = array(); + foreach ($_GET as $name => $value) { + $vars[$name] = get_input($name); } - } + if (isset($vars['guid'])) { + $vars['entity'] = get_entity($vars['guid']); + } + + echo elgg_view($view, $vars); + return true; + } return false; } /** - * An interface for objects that behave as elements within a social network that have a profile. - * - */ -interface Friendable { - /** - * Adds a user as a friend - * - * @param int $friend_guid The GUID of the user to add - */ - public function addFriend($friend_guid); - - /** - * Removes a user as a friend - * - * @param int $friend_guid The GUID of the user to remove - */ - public function removeFriend($friend_guid); - - /** - * Determines whether or not the current user is a friend of this entity - * - */ - public function isFriend(); - - /** - * Determines whether or not this entity is friends with a particular entity - * - * @param int $user_guid The GUID of the entity this entity may or may not be friends with - */ - public function isFriendsWith($user_guid); - - /** - * Determines whether or not a foreign entity has made this one a friend - * - * @param int $user_guid The GUID of the foreign entity - */ - public function isFriendOf($user_guid); - - /** - * Returns this entity's friends - * - * @param string $subtype The subtype of entity to return - * @param int $limit The number of entities to return - * @param int $offset Indexing offset - */ - public function getFriends($subtype = "", $limit = 10, $offset = 0); - - /** - * Returns entities that have made this entity a friend - * - * @param string $subtype The subtype of entity to return - * @param int $limit The number of entities to return - * @param int $offset Indexing offset - */ - public function getFriendsOf($subtype = "", $limit = 10, $offset = 0); - - /** - * Returns objects in this entity's container - * - * @param string $subtype The subtype of entity to return - * @param int $limit The number of entities to return - * @param int $offset Indexing offset - */ - public function getObjects($subtype="", $limit = 10, $offset = 0); - - /** - * Returns objects in the containers of this entity's friends - * - * @param string $subtype The subtype of entity to return - * @param int $limit The number of entities to return - * @param int $offset Indexing offset - */ - public function getFriendsObjects($subtype = "", $limit = 10, $offset = 0); - - /** - * Returns the number of object entities in this entity's container - * - * @param string $subtype The subtype of entity to count - */ - public function countObjects($subtype = ""); -} - -/** - * Rebuilds a parsed (partial) URL - * - * @param array $parts Associative array of URL components like parse_url() returns - * @return str Full URL - * @since 1.7 + * Serve CSS + * + * 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_http_build_url(array $parts) { - // build only what's given to us. - $scheme = isset($parts['scheme']) ? "{$parts['scheme']}://" : ''; - $host = isset($parts['host']) ? "{$parts['host']}" : ''; - $port = isset($parts['port']) ? ":{$parts['port']}" : ''; - $path = isset($parts['path']) ? "{$parts['path']}" : ''; - $query = isset($parts['query']) ? "?{$parts['query']}" : ''; - - $string = $scheme . $host . $port . $path . $query; - - return $string; +function elgg_css_page_handler($page) { + if (!isset($page[0])) { + // default css + $page[0] = 'elgg'; + } + + return elgg_cacheable_view_page_handler($page, 'css'); } - /** - * Adds action tokens to URL + * Serves a JS or CSS view with headers for caching. * - * @param str $link Full action URL - * @return str URL with action tokens - * @since 1.7 + * /<css||js>/name/of/view.<last_cache>.<css||js> + * + * @param array $page The page array + * @param string $type The type: js or css + * + * @return bool + * @access private */ -function elgg_add_action_tokens_to_url($url) { - $components = parse_url($url); +function elgg_cacheable_view_page_handler($page, $type) { - if (isset($components['query'])) { - $query = elgg_parse_str($components['query']); - } else { - $query = array(); - } + switch ($type) { + case 'js': + $content_type = 'text/javascript'; + break; - if (isset($query['__elgg_ts']) && isset($query['__elgg_token'])) { - return $url; + case 'css': + $content_type = 'text/css'; + break; + + default: + return false; + break; } - // append action tokens to the existing query - $query['__elgg_ts'] = time(); - $query['__elgg_token'] = generate_action_token($query['__elgg_ts']); - $components['query'] = http_build_query($query); + 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"); - // rebuild the full url - return elgg_http_build_url($components); -} + header("Content-type: $content_type"); -/** - * @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'); + // @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)); - return elgg_add_action_tokens_to_url($url); + echo $return; + return true; + } + return false; } /** - * Removes a single elementry from a (partial) url query. + * 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. * - * @param string $url - * @param string $element + * This is used mostly for elgg_get_entities() and other similar functions. + * + * @param string $order_by An order by clause + * @access private * @return string + * @access private */ -function elgg_http_remove_url_query_element($url, $element) { - $url_array = parse_url($url); +function elgg_sql_reverse_order_by_clause($order_by) { + $order_by = strtolower($order_by); - if (isset($url_array['query'])) { - $query = elgg_parse_str($url_array['query']); + 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 { - // nothing to remove. Return original URL. - return $url; + // no order specified, so default to desc since mysql defaults to asc + $return = $order_by . ' desc'; } - if (array_key_exists($element, $query)) { - unset($query[$element]); - } + return $return; +} - $url_array['query'] = http_build_query($query); - $string = elgg_http_build_url($url_array); - return $string; +/** + * Enable objects with an enable() method. + * + * Used as a callback for ElggBatch. + * + * @todo why aren't these static methods on ElggBatch? + * + * @param object $object The object to enable + * @return bool + * @access private + */ +function elgg_batch_enable_callback($object) { + // our db functions return the number of rows affected... + return $object->enable() ? true : false; } +/** + * 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; +} /** - * Adds get params to $url + * Delete objects with a delete() method. + * + * Used as a callback for ElggBatch. * - * @param str $url - * @param array $elements k/v pairs. - * @return str + * @param object $object The object to disable + * @return bool + * @access private */ -function elgg_http_add_url_query_elements($url, array $elements) { - $url_array = parse_url($url); +function elgg_batch_delete_callback($object) { + // our db functions return the number of rows affected... + return $object->delete() ? true : false; +} - if (isset($url_array['query'])) { - $query = elgg_parse_str($url_array['query']); - } else { - $query = array(); +/** + * 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; } - foreach ($elements as $k => $v) { - $query[$k] = $v; + // at least one of these is required. + $required = array( + // generic restraints + 'guid', 'guids' + ); + + switch ($type) { + case 'metadata': + $metadata_required = array( + 'metadata_owner_guid', 'metadata_owner_guids', + 'metadata_name', 'metadata_names', + 'metadata_value', 'metadata_values' + ); + + $required = array_merge($required, $metadata_required); + break; + + case 'annotations': + case 'annotation': + $annotations_required = array( + 'annotation_owner_guid', 'annotation_owner_guids', + 'annotation_name', 'annotation_names', + 'annotation_value', 'annotation_values' + ); + + $required = array_merge($required, $annotations_required); + break; + + default: + return false; } - $url_array['query'] = http_build_query($query); - $string = elgg_http_build_url($url_array); + foreach ($required as $key) { + // check that it exists and is something. + if (isset($options[$key]) && $options[$key]) { + return true; + } + } - return $string; + return false; } /** - * Returns the PHP INI setting in bytes + * Intercepts the index page when Walled Garden mode is enabled. * - * @param str $setting - * @return int - * @since 1.7 - * @link http://www.php.net/manual/en/function.ini-get.php + * @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_get_ini_setting_in_bytes($setting) { - // retrieve INI setting - $val = ini_get($setting); - - // convert INI setting when shorthand notation is used - $last = strtolower($val[strlen($val)-1]); - switch($last) { - case 'g': - $val *= 1024; - case 'm': - $val *= 1024; - case 'k': - $val *= 1024; +function elgg_walled_garden_index($hook, $type, $value, $params) { + if ($value) { + // do not create a second index page so return + return; } - // return byte value - return $val; + elgg_load_css('elgg.walled_garden'); + elgg_load_js('elgg.walled_garden'); + + $content = elgg_view('core/walled_garden/login'); + + $params = array( + 'content' => $content, + 'class' => 'elgg-walledgarden-double', + 'id' => 'elgg-walledgarden-login', + ); + $body = elgg_view_layout('walled_garden', $params); + echo elgg_view_page('', $body, 'walled_garden'); + + // return true to prevent other plugins from adding a front page + 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; } /** - * Server javascript pages. + * Checks the status of the Walled Garden and forwards to a login page + * if required. * - * @param $page - * @return unknown_type + * If the site is in Walled Garden mode, all page except those registered as + * plugin pages by {@elgg_hook public_pages walled_garden} will redirect to + * a login page. + * + * @since 1.8.0 + * @elgg_event_handler init system + * @link http://docs.elgg.org/Tutorials/WalledGarden + * @return void + * @access private */ -function js_page_handler($page) { - if (is_array($page) && sizeof($page)) { - $js = str_replace('.js','',$page[0]); - $return = elgg_view('js/' . $js); +function elgg_walled_garden() { + global $CONFIG; - header('Content-type: text/javascript'); - header('Expires: ' . date('r',time() + 864000)); - header("Pragma: public"); - header("Cache-Control: public"); - header("Content-Length: " . strlen($return)); + elgg_register_css('elgg.walled_garden', '/css/walled_garden.css'); + elgg_register_js('elgg.walled_garden', '/js/walled_garden.js'); - echo $return; - exit; + elgg_register_page_handler('walled_garden', '_elgg_walled_garden_ajax_handler'); + + // check for external page view + if (isset($CONFIG->site) && $CONFIG->site instanceof ElggSite) { + $CONFIG->site->checkWalledGarden(); } } /** - * This function is a shutdown hook registered on startup which does nothing more than trigger a - * shutdown event when the script is shutting down, but before database connections have been dropped etc. + * Remove public access for walled gardens * + * @param string $hook + * @param string $type + * @param array $accesses + * @return array + * @access private */ -function __elgg_shutdown_hook() { - global $START_MICROTIME; - - trigger_elgg_event('shutdown', 'system'); - - $time = (float)(microtime(TRUE) - $START_MICROTIME); - elgg_log("Page {$_SERVER['REQUEST_URI']} generated in $time seconds", 'DEBUG'); +function _elgg_walled_garden_remove_public_access($hook, $type, $accesses) { + if (isset($accesses[ACCESS_PUBLIC])) { + unset($accesses[ACCESS_PUBLIC]); + } + return $accesses; } /** - * Register functions for Elgg core + * Boots the engine * - * @return unknown_type + * 1. sets error handlers + * 2. connects to database + * 3. verifies the installation suceeded + * 4. loads application configuration + * 5. loads i18n data + * 6. loads site configuration + * + * @access private */ -function elgg_init() { - // Page handler for JS - register_page_handler('js','js_page_handler'); +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(); - // Register an event triggered at system shutdown - register_shutdown_function('__elgg_shutdown_hook'); + _elgg_session_boot(); + + _elgg_load_cache(); + + _elgg_load_translations(); } /** - * Boot Elgg - * @return unknown_type + * Elgg's main init. + * + * Handles core actions for comments, the JS pagehandler, and the shutdown function. + * + * @elgg_event_handler init system + * @return void + * @access private */ -function elgg_boot() { - // Actions - register_action('comments/add'); - register_action('comments/delete'); +function elgg_init() { + global $CONFIG; - elgg_view_register_simplecache('css'); - elgg_view_register_simplecache('js/friendsPickerv1'); - elgg_view_register_simplecache('js/initialise_elgg'); + elgg_register_action('comments/add'); + elgg_register_action('comments/delete'); + + 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); + } + } } /** - * Runs unit tests for the API. + * 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; } -/** - * Some useful constant definitions +/**#@+ + * 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 */ define('ACCESS_DEFAULT', -1); define('ACCESS_PRIVATE', 0); define('ACCESS_LOGGED_IN', 1); define('ACCESS_PUBLIC', 2); define('ACCESS_FRIENDS', -2); +/**#@-*/ +/** + * Constant to request the value of a parameter be ignored in elgg_get_*() functions + * + * @see elgg_get_entities() + * @var NULL + * @since 1.7 + */ define('ELGG_ENTITIES_ANY_VALUE', NULL); + +/** + * Constant to request the value of a parameter be nothing in elgg_get_*() functions. + * + * @see elgg_get_entities() + * @var int 0 + * @since 1.7 + */ define('ELGG_ENTITIES_NO_VALUE', 0); -register_elgg_event_handler('init', 'system', 'elgg_init'); -register_elgg_event_handler('boot', 'system', 'elgg_boot', 1000); -register_plugin_hook('unit_test', 'system', 'elgg_api_test');
\ No newline at end of file +/** + * Used in calls to forward() to specify the browser should be redirected to the + * referring page. + * + * @see forward + * @var int -1 + */ +define('REFERRER', -1); + +/** + * Alternate spelling for REFERRER. Included because of some bad documentation + * in the original HTTP spec. + * + * @see forward() + * @link http://en.wikipedia.org/wiki/HTTP_referrer#Origin_of_the_term_referer + * @var int -1 + */ +define('REFERER', -1); + +elgg_register_event_handler('init', 'system', 'elgg_init'); +elgg_register_event_handler('boot', 'system', '_elgg_engine_boot', 1); +elgg_register_plugin_hook_handler('unit_test', 'system', 'elgg_api_test'); + +elgg_register_event_handler('init', 'system', 'add_custom_menu_items', 1000); +elgg_register_event_handler('init', 'system', 'elgg_walled_garden', 1000); |
