From c5cc2821311012a8a4385a304a043c4b41f2afbb Mon Sep 17 00:00:00 2001 From: brettp Date: Mon, 31 Aug 2009 19:05:21 +0000 Subject: All line endings are now Unix-style. git-svn-id: https://code.elgg.org/elgg/trunk@3451 36083f99-b078-4883-b0ff-0f9b5a30f544 --- engine/handlers/action_handler.php | 38 +- engine/handlers/cron_handler.php | 2 +- engine/handlers/pagehandler.php | 48 +- engine/handlers/xml-rpc_handler.php | 2 +- engine/lib/access.php | 1324 ++++----- engine/lib/activity.php | 302 +- engine/lib/admin.php | 348 +-- engine/lib/api.php | 4 +- engine/lib/configuration.php | 266 +- engine/lib/database.php | 750 ++--- engine/lib/elgglib.php | 20 +- engine/lib/entities.php | 5534 +++++++++++++++++------------------ engine/lib/extender.php | 100 +- engine/lib/input.php | 348 +-- engine/lib/install.php | 100 +- engine/lib/languages.php | 312 +- engine/lib/metadata.php | 1820 ++++++------ engine/lib/metastrings.php | 40 +- engine/lib/notification.php | 846 +++--- engine/lib/objects.php | 416 +-- engine/lib/pagehandler.php | 230 +- engine/lib/pageowner.php | 306 +- engine/lib/pam.php | 24 +- engine/lib/plugins.php | 1384 ++++----- engine/lib/query.php | 12 +- engine/lib/relationships.php | 316 +- engine/lib/river2.php | 596 ++-- engine/lib/sessions.php | 384 +-- engine/lib/sites.php | 140 +- engine/lib/social.php | 214 +- engine/lib/statistics.php | 4 +- engine/lib/tags.php | 322 +- engine/lib/upgrades/2008101303.php | 20 +- engine/lib/users.php | 3000 +++++++++---------- engine/lib/version.php | 116 +- engine/lib/widgets.php | 1050 +++---- engine/settings.example.php | 208 +- engine/start.php | 432 +-- 38 files changed, 10689 insertions(+), 10689 deletions(-) (limited to 'engine') diff --git a/engine/handlers/action_handler.php b/engine/handlers/action_handler.php index 1e769eebd..4878084ad 100644 --- a/engine/handlers/action_handler.php +++ b/engine/handlers/action_handler.php @@ -1,21 +1,21 @@ - + * @author Curverider Ltd + + * @link http://elgg.org/ + */ + /** + * Load Elgg framework + */ + define('externalpage',true); + require_once("../start.php"); + $action = get_input("action"); + action($action); + +?> diff --git a/engine/handlers/cron_handler.php b/engine/handlers/cron_handler.php index a379a0e20..71a8cf2a4 100644 --- a/engine/handlers/cron_handler.php +++ b/engine/handlers/cron_handler.php @@ -8,7 +8,7 @@ * @link http://elgg.org/ */ - // Load Elgg engine + // Load Elgg engine define('externalpage',true); require_once("../start.php"); global $CONFIG; diff --git a/engine/handlers/pagehandler.php b/engine/handlers/pagehandler.php index 167d54957..506ae9802 100644 --- a/engine/handlers/pagehandler.php +++ b/engine/handlers/pagehandler.php @@ -1,27 +1,27 @@ - \ No newline at end of file diff --git a/engine/handlers/xml-rpc_handler.php b/engine/handlers/xml-rpc_handler.php index 6be9b4a09..bc87306c7 100644 --- a/engine/handlers/xml-rpc_handler.php +++ b/engine/handlers/xml-rpc_handler.php @@ -8,7 +8,7 @@ * @link http://elgg.org/ */ - // Load Elgg engine + // Load Elgg engine define('externalpage',true); require_once("../start.php"); global $CONFIG; diff --git a/engine/lib/access.php b/engine/lib/access.php index 7f3a8131f..392c89a2f 100644 --- a/engine/lib/access.php +++ b/engine/lib/access.php @@ -1,665 +1,665 @@ -site_id))) $site_id = $CONFIG->site_id; - $user_id = (int) $user_id; - $site_id = (int) $site_id; - - if (isset($access_list[$user_id])) return $access_list[$user_id]; - - $access_list[$user_id] = "(" . implode(",",get_access_array($user_id, $site_id, $flush)) . ")"; - - return $access_list[$user_id]; - - } - - /** - * Gets an array of access restrictions the given user is allowed to see on this site - * - * @param int $user_id User ID; defaults to currently logged in user - * @param int $site_id Site ID; defaults to current site - * @param boolean $flush If set to true, will refresh the access list from the database - * @return array An array of access collections suitable for injection in an SQL call - */ - function get_access_array($user_id = 0, $site_id = 0, $flush = false) { - - global $CONFIG, $init_finished; - static $access_array, $acm, $ac; // Caches. $ac* flag whether we have executed a query previously, and stop it being run again if no data is returned. - - if (!isset($access_array) || (!isset($init_finished)) || (!$init_finished)) - $access_array = array(); - - if ($user_id == 0) $user_id = get_loggedin_userid(); - - if (($site_id == 0) && (isset($CONFIG->site_guid))) $site_id = $CONFIG->site_guid; - $user_id = (int) $user_id; - $site_id = (int) $site_id; - - if (empty($access_array[$user_id]) || $flush == true) { - - $query = "SELECT am.access_collection_id FROM {$CONFIG->dbprefix}access_collection_membership am "; - $query .= " LEFT JOIN {$CONFIG->dbprefix}access_collections ag ON ag.id = am.access_collection_id "; - $query .= " WHERE am.user_guid = {$user_id} AND (ag.site_guid = {$site_id} OR ag.site_guid = 0)"; - - $tmp_access_array = array(ACCESS_PUBLIC); - if (isloggedin()) { - $tmp_access_array[] = ACCESS_LOGGED_IN; - - // The following can only return sensible data if the user is logged in. - - if ($collections = get_data($query)) { - foreach($collections as $collection) - if (!empty($collection->access_collection_id)) $tmp_access_array[] = $collection->access_collection_id; - - } - - $query = "SELECT ag.id FROM {$CONFIG->dbprefix}access_collections ag "; - $query .= " WHERE ag.owner_guid = {$user_id} AND (ag.site_guid = {$site_id} OR ag.site_guid = 0)"; - - if ($collections = get_data($query)) { - foreach($collections as $collection) - if (!empty($collection->id)) $tmp_access_array[] = $collection->id; - } - - - global $is_admin; - - if (isset($is_admin) && $is_admin == true) { - $tmp_access_array[] = ACCESS_PRIVATE; - } - - $access_array[$user_id] = $tmp_access_array; - } - else - $tmp_return = $tmp_access_array; // No user id logged in so we can only access public info - - - } else { - $tmp_access_array = $access_array[$user_id]; - } - - $tmp_return = $access_array[$user_id]; - - return trigger_plugin_hook('access:collections:read','user',array('user_id' => $user_id, 'site_id' => $site_id),$tmp_access_array); - } - - /** - * Gets the default access permission for new content - * - * @return int default access id (see ACCESS defines in elgglib.php) - */ - function get_default_access($user=null) - { - global $CONFIG; - - if (!$CONFIG->allow_user_default_access) { - return $CONFIG->default_access; - } - - if (!$user) { - if (isloggedin()) { - $user = $_SESSION['user']; - } else { - return $CONFIG->default_access; - } - } - - if (false !== ($default_access = $user->getPrivateSetting('elgg_default_access'))) { - return $default_access; - } else { - return $CONFIG->default_access; - } - } - - /** - * Override the default behaviour and allow results to show hidden entities as well. - * THIS IS A HACK. - * - * TODO: Replace this with query object! - */ - $ENTITY_SHOW_HIDDEN_OVERRIDE = false; - - /** - * This will be replaced. Do not use in plugins! - * - * @param bool $show - */ - function access_show_hidden_entities($show_hidden) - { - global $ENTITY_SHOW_HIDDEN_OVERRIDE; - $ENTITY_SHOW_HIDDEN_OVERRIDE = $show_hidden; - } - - /** - * This will be replaced. Do not use in plugins! - */ - function access_get_show_hidden_status() - { - global $ENTITY_SHOW_HIDDEN_OVERRIDE; - return $ENTITY_SHOW_HIDDEN_OVERRIDE; - } - - /** - * Add annotation restriction - * - * Returns an SQL fragment that is true (or optionally false) if the given user has - * added an annotation with the given name to the given entity. - * - * TODO: This is fairly generic so perhaps it could be moved to annotations.php - * - * @param string $annotation_name name of the annotation - * @param string $entity_guid SQL string that evaluates to the GUID of the entity the annotation should be attached to - * @param string $owner_guid SQL string that evaluates to the GUID of the owner of the annotation * - * @param boolean $exists If set to true, will return true if the annotation exists, otherwise returns false - * @return string An SQL fragment suitable for inserting into a WHERE clause - */ - - function get_annotation_sql($annotation_name,$entity_guid,$owner_guid,$exists) { - global $CONFIG; - - if ($exists) { - $not = ''; - } else { - $not = 'NOT'; - } - - $sql = <<dbprefix}annotations a -INNER JOIN {$CONFIG->dbprefix}metastrings ms ON (a.name_id = ms.id) -WHERE ms.string = '$annotation_name' -AND a.entity_guid = $entity_guid -AND a.owner_guid = $owner_guid) -END; - return $sql; - } - - /** - * Add access restriction sql code to a given query. - * - * Note that if this code is executed in privileged mode it will return blank. - * - * TODO: DELETE once Query classes are fully integrated - * - * @param string $table_prefix Optional xxx. prefix for the access code. - */ - function get_access_sql_suffix($table_prefix = "",$owner=null) - { - global $ENTITY_SHOW_HIDDEN_OVERRIDE, $CONFIG; - - $sql = ""; - $friends_bit = ""; - $enemies_bit = ""; - - if ($table_prefix) - $table_prefix = sanitise_string($table_prefix) . "."; - - $access = get_access_list(); - - if (!isset($owner)) { - $owner = get_loggedin_userid(); - } - if (!$owner) $owner = -1; - - global $is_admin; - - if (isset($is_admin) && $is_admin == true) { - $sql = " (1 = 1) "; - } else if ($owner != -1) { - $friends_bit = $table_prefix.'access_id = '.ACCESS_FRIENDS.' AND '; - $friends_bit .= "{$table_prefix}owner_guid IN (SELECT guid_one FROM {$CONFIG->dbprefix}entity_relationships WHERE relationship='friend' AND guid_two=$owner)"; - $friends_bit = '('.$friends_bit.') OR '; - - if ((isset($CONFIG->user_block_and_filter_enabled)) && ($CONFIG->user_block_and_filter_enabled)) { - // check to see if the user is in the entity owner's block list - // or if the entity owner is in the user's filter list - // if so, disallow access - - $enemies_bit = get_annotation_sql('elgg_block_list',"{$table_prefix}owner_guid",$owner,false); - $enemies_bit = '('.$enemies_bit. ' AND '.get_annotation_sql('elgg_filter_list',$owner,"{$table_prefix}owner_guid",false).')'; - } - } - - if (empty($sql)) - $sql = " $friends_bit ({$table_prefix}access_id in {$access} or ({$table_prefix}owner_guid = {$owner}) or ({$table_prefix}access_id = " . ACCESS_PRIVATE . " and {$table_prefix}owner_guid = $owner))"; - - if ($enemies_bit) { - $sql = "$enemies_bit AND ($sql)"; - } - - if (!$ENTITY_SHOW_HIDDEN_OVERRIDE) - $sql .= " and {$table_prefix}enabled='yes'"; - return '('.$sql.')'; - } - - /** - * Determines whether the given user has access to the given entity - * - * @param ElggEntity $entity The entity to check access for. - * @param ElggUser $user Optionally the user to check access for. - * - * @return boolean True if the user can access the entity - */ - - function has_access_to_entity($entity,$user = null) { - global $CONFIG; - - if (!isset($user)) { - $access_bit = get_access_sql_suffix("e"); - } else { - $access_bit = get_access_sql_suffix("e",$user->getGUID()); - } - - $query = "SELECT guid from {$CONFIG->dbprefix}entities e WHERE e.guid = ".$entity->getGUID(); - $query .= " AND ".$access_bit; // Add access controls - if (get_data($query)) { - return true; - } else { - return false; - } - } - - /** - * Returns an array of access permissions that the specified user is allowed to save objects with. - * Permissions are of the form ('id' => 'Description') - * - * @param int $user_id The user's GUID. - * @param int $site_id The current site. - * @param true|false $flush If this is set to true, this will shun any cached version - * @return array List of access permissions= - */ - function get_write_access_array($user_id = 0, $site_id = 0, $flush = false) { - - global $CONFIG; - static $access_array; - - if ($user_id == 0) $user_id = get_loggedin_userid(); - if (($site_id == 0) && (isset($CONFIG->site_id))) $site_id = $CONFIG->site_id; - $user_id = (int) $user_id; - $site_id = (int) $site_id; - - if (empty($access_array[$user_id]) || $flush == true) { - - $query = "SELECT ag.* FROM {$CONFIG->dbprefix}access_collections ag "; - $query .= " WHERE (ag.site_guid = {$site_id} OR ag.site_guid = 0)"; - $query .= " AND (ag.owner_guid = {$user_id})"; - $query .= " AND ag.id >= 3"; - - $tmp_access_array = array(0 => elgg_echo("PRIVATE"), ACCESS_FRIENDS => elgg_echo("access:friends:label"), 1 => elgg_echo("LOGGED_IN"), 2 => elgg_echo("PUBLIC")); - if ($collections = get_data($query)) { - foreach($collections as $collection) - $tmp_access_array[$collection->id] = $collection->name; - } - - $access_array[$user_id] = $tmp_access_array; - - } else { - $tmp_access_array = $access_array[$user_id]; - } - - $tmp_access_array = trigger_plugin_hook('access:collections:write','user',array('user_id' => $user_id, 'site_id' => $site_id),$tmp_access_array); - - return $tmp_access_array; - - } - - /** - * Creates a new access control collection owned by the specified user. - * - * @param string $name The name of the collection. - * @param int $owner_guid The GUID of the owner (default: currently logged in user). - * @param int $site_guid The GUID of the site (default: current site). - * @return int|false Depending on success (the collection ID if successful). - */ - function create_access_collection($name, $owner_guid = 0, $site_guid = 0) { - - global $CONFIG; - - $name = trim($name); - if (empty($name)) return false; - - if ($owner_guid == 0) $owner_guid = get_loggedin_userid(); - if (($site_id == 0) && (isset($CONFIG->site_guid))) $site_id = $CONFIG->site_guid; - $name = sanitise_string($name); - - return insert_data("insert into {$CONFIG->dbprefix}access_collections set name = '{$name}', owner_guid = {$owner_guid}, site_guid = {$site_id}"); - - } - - /** - * Updates the membership in an access collection. - * - * @param int $collection_id The ID of the collection. - * @param array $members Array of member GUIDs - * @return true|false Depending on success - */ - function update_access_collection($collection_id, $members) { - - global $CONFIG; - $collection_id = (int) $collection_id; - - $collections = get_write_access_array(); - - if (array_key_exists($collection_id, $collections)) { - - delete_data("delete from {$CONFIG->dbprefix}access_collection_membership where access_collection_id = {$collection_id}"); - - if (is_array($members) && sizeof($members) > 0) { - foreach($members as $member) { - $member = (int) $member; - if (get_user($member)) - insert_data("insert into {$CONFIG->dbprefix}access_collection_membership set access_collection_id = {$collection_id}, user_guid = {$member}"); - } - return true; - } - - } - - return false; - } - - /** - * Deletes a specified access collection - * - * @param int $collection_id The collection ID - * @return true|false Depending on success - */ - function delete_access_collection($collection_id) { - - $collection_id = (int) $collection_id; - $collections = get_write_access_array(); - if (array_key_exists($collection_id, $collections)) { - global $CONFIG; - delete_data("delete from {$CONFIG->dbprefix}access_collection_membership where access_collection_id = {$collection_id}"); - delete_data("delete from {$CONFIG->dbprefix}access_collections where id = {$collection_id}"); - return true; - } else { - return false; - } - - } - - /** - * Get a specified access collection - * - * @param int $collection_id The collection ID - * @return array|false Depending on success - */ - function get_access_collection($collection_id) { - - $collection_id = (int) $collection_id; - global $CONFIG; - $get_collection = get_data_row("SELECT * FROM {$CONFIG->dbprefix}access_collections WHERE id = {$collection_id}"); - - return $get_collection; - - } - - /** - * Adds a user to the specified user collection - * - * @param int $user_guid The GUID of the user to add - * @param int $collection_id The ID of the collection to add them to - * @return true|false Depending on success - */ - function add_user_to_access_collection($user_guid, $collection_id) { - - $collection_id = (int) $collection_id; - $user_guid = (int) $user_guid; - $collections = get_write_access_array(); - - if (!($collection = get_access_collection($collection_id))) - return false; - - if ((array_key_exists($collection_id, $collections) || $collection->owner_guid == 0) - && $user = get_user($user_guid)) { - - global $CONFIG; - try { - insert_data("insert into {$CONFIG->dbprefix}access_collection_membership set access_collection_id = {$collection_id}, user_guid = {$user_guid}"); - } catch (DatabaseException $e) {} - return true; - - } - - return false; - - } - - /** - * Removes a user from an access collection - * - * @param int $user_guid The user GUID - * @param int $collection_id The access collection ID - * @return true|false Depending on success - */ - function remove_user_from_access_collection($user_guid, $collection_id) { - - $collection_id = (int) $collection_id; - $user_guid = (int) $user_guid; - $collections = get_write_access_array(); - - if (!($collection = get_access_collection($collection_id))) - return false; - - if ((array_key_exists($collection_id, $collections) || $collection->owner_guid == 0) && $user = get_user($user_guid)) { - - global $CONFIG; - delete_data("delete from {$CONFIG->dbprefix}access_collection_membership where access_collection_id = {$collection_id} and user_guid = {$user_guid}"); - return true; - - } - - return false; - - } - - /** - * Get all of a users collections - * - * @param int $owner_guid The user ID - * @return true|false Depending on success - */ - function get_user_access_collections($owner_guid) { - - $owner_guid = (int) $owner_guid; - - global $CONFIG; - - $collections = get_data("SELECT * FROM {$CONFIG->dbprefix}access_collections WHERE owner_guid = {$owner_guid}"); - - return $collections; - - } - - /** - * Get all of members of a friend collection - * - * @param int $collection The collection's ID - * @param true|false $idonly If set to true, will only return the members' IDs (default: false) - * @return ElggUser entities if successful, false if not - */ - function get_members_of_access_collection($collection, $idonly = false) { - - $collection = (int)$collection; - - global $CONFIG; - - if (!$idonly) { - $query = "SELECT e.* FROM {$CONFIG->dbprefix}access_collection_membership m JOIN {$CONFIG->dbprefix}entities e ON e.guid = m.user_guid WHERE m.access_collection_id = {$collection}"; - $collection_members = get_data($query, "entity_row_to_elggstar"); - } else { - $query = "SELECT e.guid FROM {$CONFIG->dbprefix}access_collection_membership m JOIN {$CONFIG->dbprefix}entities e ON e.guid = m.user_guid WHERE m.access_collection_id = {$collection}"; - $collection_members = get_data($query); - foreach($collection_members as $key => $val) - $collection_members[$key] = $val->guid; - } - - return $collection_members; - - } - - /** - * Displays a user's access collections, using the friends/collections view - * - * @param int $owner_guid The GUID of the owning user - * @return string A formatted rendition of the collections - */ - function elgg_view_access_collections($owner_guid) { - - if ($collections = get_user_access_collections($owner_guid)) { - - foreach($collections as $key => $collection) { - $collections[$key]->members = get_members_of_access_collection($collection->id, true); - $collections[$key]->entities = get_user_friends($owner_guid,"",9999); - } - - } - - return elgg_view('friends/collections',array('collections' => $collections)); - - } - - /** - * Get entities with the specified access collection id. - * - * @param $collection_id - * @param $entity_type - * @param $entity_subtype - * @param $owner_guid - * @param $limit - * @param $offset - * @param $order_by - * @param $site_guid - * @param $count - * @return unknown_type - */ - function get_entities_from_access_collection($collection_id, $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $offset = 0, $order_by = "", $site_guid = 0, $count = false) { - global $CONFIG; - - if (!$collection_id) - return false; - - $entity_type = sanitise_string($entity_type); - $entity_subtype = get_subtype_id($entity_type, $entity_subtype); - $limit = (int)$limit; - $offset = (int)$offset; - if ($order_by == "") - $order_by = "e.time_created desc"; - else - $order_by = "e.time_created, {$order_by}"; - $order_by = sanitise_string($order_by); - $site_guid = (int) $site_guid; - if ((is_array($owner_guid) && (count($owner_guid)))) { - foreach($owner_guid as $key => $guid) { - $owner_guid[$key] = (int) $guid; - } - } else { - $owner_guid = (int) $owner_guid; - } - if ($site_guid == 0) - $site_guid = $CONFIG->site_guid; - - //$access = get_access_list(); - - $where = array("e.access_id = $collection_id"); - - if ($entity_type!=="") - $where[] = "e.type='$entity_type'"; - if ($entity_subtype) - $where[] = "e.subtype=$entity_subtype"; - if ($site_guid > 0) - $where[] = "e.site_guid = {$site_guid}"; - if (is_array($owner_guid)) { - $where[] = "e.container_guid in (".implode(",",$owner_guid).")"; - } else if ($owner_guid > 0) - $where[] = "e.container_guid = {$owner_guid}"; - - if (!$count) { - $query = "SELECT distinct e.* "; - } else { - $query = "SELECT count(distinct e.guid) as total "; - } - - $query .= "from {$CONFIG->dbprefix}entities e where"; - foreach ($where as $w) - $query .= " $w and "; - $query .= get_access_sql_suffix("e"); // Add access controls - //$query .= ' and ' . get_access_sql_suffix("m"); // Add access controls - - if (!$count) { - $query .= " order by $order_by limit $offset, $limit"; // Add order and limit - return get_data($query, "entity_row_to_elggstar"); - } else { - if ($row = get_data_row($query)) - return $row->total; - } - return false; - } - - /** - * Lists entities from an access collection - * - * @param $collection_id - * @param $entity_type - * @param $entity_subtype - * @param $owner_guid - * @param $limit - * @param $fullview - * @param $viewtypetoggle - * @param $pagination - * @return str - */ - function list_entities_from_access_collection($collection_id, $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = true, $pagination = true) { - $offset = (int) get_input('offset'); - $limit = (int) $limit; - $count = get_entities_from_access_collection($collection_id, $entity_type, $entity_subtype, $owner_guid, $limit, $offset, "", 0, true); - $entities = get_entities_from_access_collection($collection_id, $entity_type, $entity_subtype, $owner_guid, $limit, $offset, "", 0, false); - - return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); - } - - global $init_finished; - $init_finished = false; - - /** - * A quick and dirty way to make sure the access permissions have been correctly set up - * - */ - function access_init() { - global $init_finished; - $init_finished = true; - } - - // This function will let us know when 'init' has finished - register_elgg_event_handler('init','system','access_init',9999); - + * @author Curverider Ltd + + * @link http://elgg.org/ + */ + + /** + * Get the list of access restrictions the given user is allowed to see on this site + * + * @uses get_access_array + * @param int $user_id User ID; defaults to currently logged in user + * @param int $site_id Site ID; defaults to current site + * @param boolean $flush If set to true, will refresh the access list from the database + * @return string A list of access collections suitable for injection in an SQL call + */ + function get_access_list($user_id = 0, $site_id = 0, $flush = false) { + + global $CONFIG, $init_finished, $SESSION; + static $access_list; + + if (!isset($access_list) || !$init_finished) + $access_list = array(); + + if ($user_id == 0) $user_id = $SESSION['id']; + if (($site_id == 0) && (isset($CONFIG->site_id))) $site_id = $CONFIG->site_id; + $user_id = (int) $user_id; + $site_id = (int) $site_id; + + if (isset($access_list[$user_id])) return $access_list[$user_id]; + + $access_list[$user_id] = "(" . implode(",",get_access_array($user_id, $site_id, $flush)) . ")"; + + return $access_list[$user_id]; + + } + + /** + * Gets an array of access restrictions the given user is allowed to see on this site + * + * @param int $user_id User ID; defaults to currently logged in user + * @param int $site_id Site ID; defaults to current site + * @param boolean $flush If set to true, will refresh the access list from the database + * @return array An array of access collections suitable for injection in an SQL call + */ + function get_access_array($user_id = 0, $site_id = 0, $flush = false) { + + global $CONFIG, $init_finished; + static $access_array, $acm, $ac; // Caches. $ac* flag whether we have executed a query previously, and stop it being run again if no data is returned. + + if (!isset($access_array) || (!isset($init_finished)) || (!$init_finished)) + $access_array = array(); + + if ($user_id == 0) $user_id = get_loggedin_userid(); + + if (($site_id == 0) && (isset($CONFIG->site_guid))) $site_id = $CONFIG->site_guid; + $user_id = (int) $user_id; + $site_id = (int) $site_id; + + if (empty($access_array[$user_id]) || $flush == true) { + + $query = "SELECT am.access_collection_id FROM {$CONFIG->dbprefix}access_collection_membership am "; + $query .= " LEFT JOIN {$CONFIG->dbprefix}access_collections ag ON ag.id = am.access_collection_id "; + $query .= " WHERE am.user_guid = {$user_id} AND (ag.site_guid = {$site_id} OR ag.site_guid = 0)"; + + $tmp_access_array = array(ACCESS_PUBLIC); + if (isloggedin()) { + $tmp_access_array[] = ACCESS_LOGGED_IN; + + // The following can only return sensible data if the user is logged in. + + if ($collections = get_data($query)) { + foreach($collections as $collection) + if (!empty($collection->access_collection_id)) $tmp_access_array[] = $collection->access_collection_id; + + } + + $query = "SELECT ag.id FROM {$CONFIG->dbprefix}access_collections ag "; + $query .= " WHERE ag.owner_guid = {$user_id} AND (ag.site_guid = {$site_id} OR ag.site_guid = 0)"; + + if ($collections = get_data($query)) { + foreach($collections as $collection) + if (!empty($collection->id)) $tmp_access_array[] = $collection->id; + } + + + global $is_admin; + + if (isset($is_admin) && $is_admin == true) { + $tmp_access_array[] = ACCESS_PRIVATE; + } + + $access_array[$user_id] = $tmp_access_array; + } + else + $tmp_return = $tmp_access_array; // No user id logged in so we can only access public info + + + } else { + $tmp_access_array = $access_array[$user_id]; + } + + $tmp_return = $access_array[$user_id]; + + return trigger_plugin_hook('access:collections:read','user',array('user_id' => $user_id, 'site_id' => $site_id),$tmp_access_array); + } + + /** + * Gets the default access permission for new content + * + * @return int default access id (see ACCESS defines in elgglib.php) + */ + function get_default_access($user=null) + { + global $CONFIG; + + if (!$CONFIG->allow_user_default_access) { + return $CONFIG->default_access; + } + + if (!$user) { + if (isloggedin()) { + $user = $_SESSION['user']; + } else { + return $CONFIG->default_access; + } + } + + if (false !== ($default_access = $user->getPrivateSetting('elgg_default_access'))) { + return $default_access; + } else { + return $CONFIG->default_access; + } + } + + /** + * Override the default behaviour and allow results to show hidden entities as well. + * THIS IS A HACK. + * + * TODO: Replace this with query object! + */ + $ENTITY_SHOW_HIDDEN_OVERRIDE = false; + + /** + * This will be replaced. Do not use in plugins! + * + * @param bool $show + */ + function access_show_hidden_entities($show_hidden) + { + global $ENTITY_SHOW_HIDDEN_OVERRIDE; + $ENTITY_SHOW_HIDDEN_OVERRIDE = $show_hidden; + } + + /** + * This will be replaced. Do not use in plugins! + */ + function access_get_show_hidden_status() + { + global $ENTITY_SHOW_HIDDEN_OVERRIDE; + return $ENTITY_SHOW_HIDDEN_OVERRIDE; + } + + /** + * Add annotation restriction + * + * Returns an SQL fragment that is true (or optionally false) if the given user has + * added an annotation with the given name to the given entity. + * + * TODO: This is fairly generic so perhaps it could be moved to annotations.php + * + * @param string $annotation_name name of the annotation + * @param string $entity_guid SQL string that evaluates to the GUID of the entity the annotation should be attached to + * @param string $owner_guid SQL string that evaluates to the GUID of the owner of the annotation * + * @param boolean $exists If set to true, will return true if the annotation exists, otherwise returns false + * @return string An SQL fragment suitable for inserting into a WHERE clause + */ + + function get_annotation_sql($annotation_name,$entity_guid,$owner_guid,$exists) { + global $CONFIG; + + if ($exists) { + $not = ''; + } else { + $not = 'NOT'; + } + + $sql = <<dbprefix}annotations a +INNER JOIN {$CONFIG->dbprefix}metastrings ms ON (a.name_id = ms.id) +WHERE ms.string = '$annotation_name' +AND a.entity_guid = $entity_guid +AND a.owner_guid = $owner_guid) +END; + return $sql; + } + + /** + * Add access restriction sql code to a given query. + * + * Note that if this code is executed in privileged mode it will return blank. + * + * TODO: DELETE once Query classes are fully integrated + * + * @param string $table_prefix Optional xxx. prefix for the access code. + */ + function get_access_sql_suffix($table_prefix = "",$owner=null) + { + global $ENTITY_SHOW_HIDDEN_OVERRIDE, $CONFIG; + + $sql = ""; + $friends_bit = ""; + $enemies_bit = ""; + + if ($table_prefix) + $table_prefix = sanitise_string($table_prefix) . "."; + + $access = get_access_list(); + + if (!isset($owner)) { + $owner = get_loggedin_userid(); + } + if (!$owner) $owner = -1; + + global $is_admin; + + if (isset($is_admin) && $is_admin == true) { + $sql = " (1 = 1) "; + } else if ($owner != -1) { + $friends_bit = $table_prefix.'access_id = '.ACCESS_FRIENDS.' AND '; + $friends_bit .= "{$table_prefix}owner_guid IN (SELECT guid_one FROM {$CONFIG->dbprefix}entity_relationships WHERE relationship='friend' AND guid_two=$owner)"; + $friends_bit = '('.$friends_bit.') OR '; + + if ((isset($CONFIG->user_block_and_filter_enabled)) && ($CONFIG->user_block_and_filter_enabled)) { + // check to see if the user is in the entity owner's block list + // or if the entity owner is in the user's filter list + // if so, disallow access + + $enemies_bit = get_annotation_sql('elgg_block_list',"{$table_prefix}owner_guid",$owner,false); + $enemies_bit = '('.$enemies_bit. ' AND '.get_annotation_sql('elgg_filter_list',$owner,"{$table_prefix}owner_guid",false).')'; + } + } + + if (empty($sql)) + $sql = " $friends_bit ({$table_prefix}access_id in {$access} or ({$table_prefix}owner_guid = {$owner}) or ({$table_prefix}access_id = " . ACCESS_PRIVATE . " and {$table_prefix}owner_guid = $owner))"; + + if ($enemies_bit) { + $sql = "$enemies_bit AND ($sql)"; + } + + if (!$ENTITY_SHOW_HIDDEN_OVERRIDE) + $sql .= " and {$table_prefix}enabled='yes'"; + return '('.$sql.')'; + } + + /** + * Determines whether the given user has access to the given entity + * + * @param ElggEntity $entity The entity to check access for. + * @param ElggUser $user Optionally the user to check access for. + * + * @return boolean True if the user can access the entity + */ + + function has_access_to_entity($entity,$user = null) { + global $CONFIG; + + if (!isset($user)) { + $access_bit = get_access_sql_suffix("e"); + } else { + $access_bit = get_access_sql_suffix("e",$user->getGUID()); + } + + $query = "SELECT guid from {$CONFIG->dbprefix}entities e WHERE e.guid = ".$entity->getGUID(); + $query .= " AND ".$access_bit; // Add access controls + if (get_data($query)) { + return true; + } else { + return false; + } + } + + /** + * Returns an array of access permissions that the specified user is allowed to save objects with. + * Permissions are of the form ('id' => 'Description') + * + * @param int $user_id The user's GUID. + * @param int $site_id The current site. + * @param true|false $flush If this is set to true, this will shun any cached version + * @return array List of access permissions= + */ + function get_write_access_array($user_id = 0, $site_id = 0, $flush = false) { + + global $CONFIG; + static $access_array; + + if ($user_id == 0) $user_id = get_loggedin_userid(); + if (($site_id == 0) && (isset($CONFIG->site_id))) $site_id = $CONFIG->site_id; + $user_id = (int) $user_id; + $site_id = (int) $site_id; + + if (empty($access_array[$user_id]) || $flush == true) { + + $query = "SELECT ag.* FROM {$CONFIG->dbprefix}access_collections ag "; + $query .= " WHERE (ag.site_guid = {$site_id} OR ag.site_guid = 0)"; + $query .= " AND (ag.owner_guid = {$user_id})"; + $query .= " AND ag.id >= 3"; + + $tmp_access_array = array(0 => elgg_echo("PRIVATE"), ACCESS_FRIENDS => elgg_echo("access:friends:label"), 1 => elgg_echo("LOGGED_IN"), 2 => elgg_echo("PUBLIC")); + if ($collections = get_data($query)) { + foreach($collections as $collection) + $tmp_access_array[$collection->id] = $collection->name; + } + + $access_array[$user_id] = $tmp_access_array; + + } else { + $tmp_access_array = $access_array[$user_id]; + } + + $tmp_access_array = trigger_plugin_hook('access:collections:write','user',array('user_id' => $user_id, 'site_id' => $site_id),$tmp_access_array); + + return $tmp_access_array; + + } + + /** + * Creates a new access control collection owned by the specified user. + * + * @param string $name The name of the collection. + * @param int $owner_guid The GUID of the owner (default: currently logged in user). + * @param int $site_guid The GUID of the site (default: current site). + * @return int|false Depending on success (the collection ID if successful). + */ + function create_access_collection($name, $owner_guid = 0, $site_guid = 0) { + + global $CONFIG; + + $name = trim($name); + if (empty($name)) return false; + + if ($owner_guid == 0) $owner_guid = get_loggedin_userid(); + if (($site_id == 0) && (isset($CONFIG->site_guid))) $site_id = $CONFIG->site_guid; + $name = sanitise_string($name); + + return insert_data("insert into {$CONFIG->dbprefix}access_collections set name = '{$name}', owner_guid = {$owner_guid}, site_guid = {$site_id}"); + + } + + /** + * Updates the membership in an access collection. + * + * @param int $collection_id The ID of the collection. + * @param array $members Array of member GUIDs + * @return true|false Depending on success + */ + function update_access_collection($collection_id, $members) { + + global $CONFIG; + $collection_id = (int) $collection_id; + + $collections = get_write_access_array(); + + if (array_key_exists($collection_id, $collections)) { + + delete_data("delete from {$CONFIG->dbprefix}access_collection_membership where access_collection_id = {$collection_id}"); + + if (is_array($members) && sizeof($members) > 0) { + foreach($members as $member) { + $member = (int) $member; + if (get_user($member)) + insert_data("insert into {$CONFIG->dbprefix}access_collection_membership set access_collection_id = {$collection_id}, user_guid = {$member}"); + } + return true; + } + + } + + return false; + } + + /** + * Deletes a specified access collection + * + * @param int $collection_id The collection ID + * @return true|false Depending on success + */ + function delete_access_collection($collection_id) { + + $collection_id = (int) $collection_id; + $collections = get_write_access_array(); + if (array_key_exists($collection_id, $collections)) { + global $CONFIG; + delete_data("delete from {$CONFIG->dbprefix}access_collection_membership where access_collection_id = {$collection_id}"); + delete_data("delete from {$CONFIG->dbprefix}access_collections where id = {$collection_id}"); + return true; + } else { + return false; + } + + } + + /** + * Get a specified access collection + * + * @param int $collection_id The collection ID + * @return array|false Depending on success + */ + function get_access_collection($collection_id) { + + $collection_id = (int) $collection_id; + global $CONFIG; + $get_collection = get_data_row("SELECT * FROM {$CONFIG->dbprefix}access_collections WHERE id = {$collection_id}"); + + return $get_collection; + + } + + /** + * Adds a user to the specified user collection + * + * @param int $user_guid The GUID of the user to add + * @param int $collection_id The ID of the collection to add them to + * @return true|false Depending on success + */ + function add_user_to_access_collection($user_guid, $collection_id) { + + $collection_id = (int) $collection_id; + $user_guid = (int) $user_guid; + $collections = get_write_access_array(); + + if (!($collection = get_access_collection($collection_id))) + return false; + + if ((array_key_exists($collection_id, $collections) || $collection->owner_guid == 0) + && $user = get_user($user_guid)) { + + global $CONFIG; + try { + insert_data("insert into {$CONFIG->dbprefix}access_collection_membership set access_collection_id = {$collection_id}, user_guid = {$user_guid}"); + } catch (DatabaseException $e) {} + return true; + + } + + return false; + + } + + /** + * Removes a user from an access collection + * + * @param int $user_guid The user GUID + * @param int $collection_id The access collection ID + * @return true|false Depending on success + */ + function remove_user_from_access_collection($user_guid, $collection_id) { + + $collection_id = (int) $collection_id; + $user_guid = (int) $user_guid; + $collections = get_write_access_array(); + + if (!($collection = get_access_collection($collection_id))) + return false; + + if ((array_key_exists($collection_id, $collections) || $collection->owner_guid == 0) && $user = get_user($user_guid)) { + + global $CONFIG; + delete_data("delete from {$CONFIG->dbprefix}access_collection_membership where access_collection_id = {$collection_id} and user_guid = {$user_guid}"); + return true; + + } + + return false; + + } + + /** + * Get all of a users collections + * + * @param int $owner_guid The user ID + * @return true|false Depending on success + */ + function get_user_access_collections($owner_guid) { + + $owner_guid = (int) $owner_guid; + + global $CONFIG; + + $collections = get_data("SELECT * FROM {$CONFIG->dbprefix}access_collections WHERE owner_guid = {$owner_guid}"); + + return $collections; + + } + + /** + * Get all of members of a friend collection + * + * @param int $collection The collection's ID + * @param true|false $idonly If set to true, will only return the members' IDs (default: false) + * @return ElggUser entities if successful, false if not + */ + function get_members_of_access_collection($collection, $idonly = false) { + + $collection = (int)$collection; + + global $CONFIG; + + if (!$idonly) { + $query = "SELECT e.* FROM {$CONFIG->dbprefix}access_collection_membership m JOIN {$CONFIG->dbprefix}entities e ON e.guid = m.user_guid WHERE m.access_collection_id = {$collection}"; + $collection_members = get_data($query, "entity_row_to_elggstar"); + } else { + $query = "SELECT e.guid FROM {$CONFIG->dbprefix}access_collection_membership m JOIN {$CONFIG->dbprefix}entities e ON e.guid = m.user_guid WHERE m.access_collection_id = {$collection}"; + $collection_members = get_data($query); + foreach($collection_members as $key => $val) + $collection_members[$key] = $val->guid; + } + + return $collection_members; + + } + + /** + * Displays a user's access collections, using the friends/collections view + * + * @param int $owner_guid The GUID of the owning user + * @return string A formatted rendition of the collections + */ + function elgg_view_access_collections($owner_guid) { + + if ($collections = get_user_access_collections($owner_guid)) { + + foreach($collections as $key => $collection) { + $collections[$key]->members = get_members_of_access_collection($collection->id, true); + $collections[$key]->entities = get_user_friends($owner_guid,"",9999); + } + + } + + return elgg_view('friends/collections',array('collections' => $collections)); + + } + + /** + * Get entities with the specified access collection id. + * + * @param $collection_id + * @param $entity_type + * @param $entity_subtype + * @param $owner_guid + * @param $limit + * @param $offset + * @param $order_by + * @param $site_guid + * @param $count + * @return unknown_type + */ + function get_entities_from_access_collection($collection_id, $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $offset = 0, $order_by = "", $site_guid = 0, $count = false) { + global $CONFIG; + + if (!$collection_id) + return false; + + $entity_type = sanitise_string($entity_type); + $entity_subtype = get_subtype_id($entity_type, $entity_subtype); + $limit = (int)$limit; + $offset = (int)$offset; + if ($order_by == "") + $order_by = "e.time_created desc"; + else + $order_by = "e.time_created, {$order_by}"; + $order_by = sanitise_string($order_by); + $site_guid = (int) $site_guid; + if ((is_array($owner_guid) && (count($owner_guid)))) { + foreach($owner_guid as $key => $guid) { + $owner_guid[$key] = (int) $guid; + } + } else { + $owner_guid = (int) $owner_guid; + } + if ($site_guid == 0) + $site_guid = $CONFIG->site_guid; + + //$access = get_access_list(); + + $where = array("e.access_id = $collection_id"); + + if ($entity_type!=="") + $where[] = "e.type='$entity_type'"; + if ($entity_subtype) + $where[] = "e.subtype=$entity_subtype"; + if ($site_guid > 0) + $where[] = "e.site_guid = {$site_guid}"; + if (is_array($owner_guid)) { + $where[] = "e.container_guid in (".implode(",",$owner_guid).")"; + } else if ($owner_guid > 0) + $where[] = "e.container_guid = {$owner_guid}"; + + if (!$count) { + $query = "SELECT distinct e.* "; + } else { + $query = "SELECT count(distinct e.guid) as total "; + } + + $query .= "from {$CONFIG->dbprefix}entities e where"; + foreach ($where as $w) + $query .= " $w and "; + $query .= get_access_sql_suffix("e"); // Add access controls + //$query .= ' and ' . get_access_sql_suffix("m"); // Add access controls + + if (!$count) { + $query .= " order by $order_by limit $offset, $limit"; // Add order and limit + return get_data($query, "entity_row_to_elggstar"); + } else { + if ($row = get_data_row($query)) + return $row->total; + } + return false; + } + + /** + * Lists entities from an access collection + * + * @param $collection_id + * @param $entity_type + * @param $entity_subtype + * @param $owner_guid + * @param $limit + * @param $fullview + * @param $viewtypetoggle + * @param $pagination + * @return str + */ + function list_entities_from_access_collection($collection_id, $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = true, $pagination = true) { + $offset = (int) get_input('offset'); + $limit = (int) $limit; + $count = get_entities_from_access_collection($collection_id, $entity_type, $entity_subtype, $owner_guid, $limit, $offset, "", 0, true); + $entities = get_entities_from_access_collection($collection_id, $entity_type, $entity_subtype, $owner_guid, $limit, $offset, "", 0, false); + + return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); + } + + global $init_finished; + $init_finished = false; + + /** + * A quick and dirty way to make sure the access permissions have been correctly set up + * + */ + function access_init() { + global $init_finished; + $init_finished = true; + } + + // This function will let us know when 'init' has finished + register_elgg_event_handler('init','system','access_init',9999); + ?> \ No newline at end of file diff --git a/engine/lib/activity.php b/engine/lib/activity.php index 2528f2d3c..10374e386 100644 --- a/engine/lib/activity.php +++ b/engine/lib/activity.php @@ -1,154 +1,154 @@ -owner_guid" - * @return array An array of system log entries. - */ - function get_activity_stream_data($limit = 10, $offset = 0, $type = "", $subtype = "", $owner_guid = "", $owner_relationship = "") - { - global $CONFIG; - - $limit = (int)$limit; - $offset = (int)$offset; - - if ($type) { - if (!is_array($type)) - $type = array(sanitise_string($type)); - else - foreach ($type as $k => $v) - $type[$k] = sanitise_string($v); - } - - if ($subtype) { - if (!is_array($subtype)) - $subtype = array(sanitise_string($subtype)); - else - foreach ($subtype as $k => $v) - $subtype[$k] = sanitise_string($v); - } - - if ($owner_guid) { - if (is_array($owner_guid)) - foreach ($owner_guid as $k => $v) - $owner_guid[$k] = (int)$v; - else - $owner_guid = array((int)$owner_guid); - } - - $owner_relationship = sanitise_string($owner_relationship); - - // Get a list of possible views - $activity_events= array(); - $activity_views = array_merge(elgg_view_tree('activity', 'default'), elgg_view_tree('river', 'default')); // Join activity with river - - $done = array(); - - foreach ($activity_views as $view) - { - $fragments = explode('/', $view); - $tmp = explode('/',$view, 2); - $tmp = $tmp[1]; - - if ((isset($fragments[0])) && (($fragments[0] == 'river') || ($fragments[0] == 'activity')) - && (!in_array($tmp, $done))) - { - if (isset($fragments[1])) - { - $f = array(); - for ($n = 1; $n < count($fragments); $n++) - { - $val = sanitise_string($fragments[$n]); - switch($n) - { - case 1: $key = 'type'; break; - case 2: $key = 'subtype'; break; - case 3: $key = 'event'; break; - } - $f[$key] = $val; - } - - // Filter result based on parameters - $add = true; - if ($type) { - if (!in_array($f['type'], $type)) $add = false; - } - if (($add) && ($subtype)) { - if (!in_array($f['subtype'], $subtype)) $add = false; - } - if (($add) && ($event)) { - if (!in_array($f['event'], $event)) $add = false; - } - - if ($add) - $activity_events[] = $f; - } - - $done[] = $tmp; - } - - - } - - $n = 0; - foreach ($activity_events as $details) - { - // Get what we're talking about - - if ($details['subtype'] == 'default') $details['subtype'] = ''; - - if (($details['type']) && ($details['event'])) { - if ($n>0) $obj_query .= " or "; - - $access = ""; - if ($details['type']!='relationship') - $access = " and " . get_access_sql_suffix('sl'); - - $obj_query .= "( sl.object_type='{$details['type']}' and sl.object_subtype='{$details['subtype']}' and sl.event='{$details['event']}' $access )"; - - $n++; - } - - } - - // User - if ((count($owner_guid)) && ($owner_guid[0]!=0)) { - $user = " and sl.performed_by_guid in (".implode(',', $owner_guid).")"; - - if ($owner_relationship) - { - $friendsarray = ""; - if ($friends = get_entities_from_relationship($owner_relationship,$owner_guid[0],false,"user",$subtype,0,"time_created desc",9999)) { - $friendsarray = array(); - foreach($friends as $friend) { - $friendsarray[] = $friend->getGUID(); - } - - $user = " and sl.performed_by_guid in (".implode(',', $friendsarray).")"; - } - - } - } - - $query = "SELECT sl.* from {$CONFIG->dbprefix}system_log sl where 1 $user and ($obj_query) order by sl.time_created desc limit $offset, $limit"; - return get_data($query); - } + * @link http://elgg.org/ + */ + + /** + * Construct and execute the query required for the activity stream. + * + * @param int $limit Limit the query. + * @param int $offset Execute from the given object + * @param mixed $type A type, or array of types to look for. Note: This is how they appear in the SYSTEM LOG. + * @param mixed $subtype A subtype, or array of types to look for. Note: This is how they appear in the SYSTEM LOG. + * @param mixed $owner_guid The guid or a collection of GUIDs + * @param string $owner_relationship If defined, the relationship between $owner_guid and the entity owner_guid - so "is $owner_guid $owner_relationship with $entity->owner_guid" + * @return array An array of system log entries. + */ + function get_activity_stream_data($limit = 10, $offset = 0, $type = "", $subtype = "", $owner_guid = "", $owner_relationship = "") + { + global $CONFIG; + + $limit = (int)$limit; + $offset = (int)$offset; + + if ($type) { + if (!is_array($type)) + $type = array(sanitise_string($type)); + else + foreach ($type as $k => $v) + $type[$k] = sanitise_string($v); + } + + if ($subtype) { + if (!is_array($subtype)) + $subtype = array(sanitise_string($subtype)); + else + foreach ($subtype as $k => $v) + $subtype[$k] = sanitise_string($v); + } + + if ($owner_guid) { + if (is_array($owner_guid)) + foreach ($owner_guid as $k => $v) + $owner_guid[$k] = (int)$v; + else + $owner_guid = array((int)$owner_guid); + } + + $owner_relationship = sanitise_string($owner_relationship); + + // Get a list of possible views + $activity_events= array(); + $activity_views = array_merge(elgg_view_tree('activity', 'default'), elgg_view_tree('river', 'default')); // Join activity with river + + $done = array(); + + foreach ($activity_views as $view) + { + $fragments = explode('/', $view); + $tmp = explode('/',$view, 2); + $tmp = $tmp[1]; + + if ((isset($fragments[0])) && (($fragments[0] == 'river') || ($fragments[0] == 'activity')) + && (!in_array($tmp, $done))) + { + if (isset($fragments[1])) + { + $f = array(); + for ($n = 1; $n < count($fragments); $n++) + { + $val = sanitise_string($fragments[$n]); + switch($n) + { + case 1: $key = 'type'; break; + case 2: $key = 'subtype'; break; + case 3: $key = 'event'; break; + } + $f[$key] = $val; + } + + // Filter result based on parameters + $add = true; + if ($type) { + if (!in_array($f['type'], $type)) $add = false; + } + if (($add) && ($subtype)) { + if (!in_array($f['subtype'], $subtype)) $add = false; + } + if (($add) && ($event)) { + if (!in_array($f['event'], $event)) $add = false; + } + + if ($add) + $activity_events[] = $f; + } + + $done[] = $tmp; + } + + + } + + $n = 0; + foreach ($activity_events as $details) + { + // Get what we're talking about + + if ($details['subtype'] == 'default') $details['subtype'] = ''; + + if (($details['type']) && ($details['event'])) { + if ($n>0) $obj_query .= " or "; + + $access = ""; + if ($details['type']!='relationship') + $access = " and " . get_access_sql_suffix('sl'); + + $obj_query .= "( sl.object_type='{$details['type']}' and sl.object_subtype='{$details['subtype']}' and sl.event='{$details['event']}' $access )"; + + $n++; + } + + } + + // User + if ((count($owner_guid)) && ($owner_guid[0]!=0)) { + $user = " and sl.performed_by_guid in (".implode(',', $owner_guid).")"; + + if ($owner_relationship) + { + $friendsarray = ""; + if ($friends = get_entities_from_relationship($owner_relationship,$owner_guid[0],false,"user",$subtype,0,"time_created desc",9999)) { + $friendsarray = array(); + foreach($friends as $friend) { + $friendsarray[] = $friend->getGUID(); + } + + $user = " and sl.performed_by_guid in (".implode(',', $friendsarray).")"; + } + + } + } + + $query = "SELECT sl.* from {$CONFIG->dbprefix}system_log sl where 1 $user and ($obj_query) order by sl.time_created desc limit $offset, $limit"; + return get_data($query); + } ?> \ No newline at end of file diff --git a/engine/lib/admin.php b/engine/lib/admin.php index a8272dc83..f09167bfa 100644 --- a/engine/lib/admin.php +++ b/engine/lib/admin.php @@ -1,177 +1,177 @@ -wwwroot . 'pg/admin/statistics/'); - add_submenu_item(elgg_echo('admin:site'), $CONFIG->wwwroot . 'pg/admin/site/'); - add_submenu_item(elgg_echo('admin:user'), $CONFIG->wwwroot . 'pg/admin/user/'); - add_submenu_item(elgg_echo('admin:plugins'), $CONFIG->wwwroot . 'pg/admin/plugins/'); - - } - - } - - function admin_settings_page_handler($page) - { - global $CONFIG; - - $path = $CONFIG->path . "admin/index.php"; - - if ($page[0]) - { - switch ($page[0]) - { - case 'user' : $path = $CONFIG->path . "admin/user.php"; break; - case 'statistics' : $path = $CONFIG->path . "admin/statistics.php"; break; - case 'plugins' : $path = $CONFIG->path . "admin/plugins.php"; break; - case 'site' : $path = $CONFIG->path . "admin/site.php"; break; - } - } - - if ($page[1]) - set_input('username', $page[1]); - - include($path); - } - - - /** - * Admin permissions system - * - * @return true|null True if the current user is an admin. - */ - function admin_permissions($hook, $type, $returnval, $params) { - - if (is_array($params) && !empty($params['user']) && $params['user'] instanceof ElggUser) { - $admin = $params['user']->admin; - if ($admin) { - return true; - } - } - - } - - /** - * Write a persistent message to the administrator's notification window. - * - * Currently this writes a message to the admin store, we may want to come up with another way at some point. - * - * @param string $subject Subject of the message - * @param string $message Body of the message - */ - function send_admin_message($subject, $message) - { - $subject = sanitise_string($subject); - $message = sanitise_string($message); - - if (($subject) && ($message)) - { - $admin_message = new ElggObject(); - $admin_message->subtype = 'admin_message'; - $admin_message->access_id = ACCESS_PUBLIC; - $admin_message->title = $subject; - $admin_message->description = $message; - - return $admin_message->save(); - } - - return false; - } - - /** - * List all admin messages. - * - * @param int $limit Limit - */ - function list_admin_messages($limit = 10) - { - return list_entities('object','admin_message',0,$limit); - } - - /** - * Remove an admin message. - * - * @param int $guid The - */ - function clear_admin_message($guid) - { - return delete_entity($guid); - } - - /// Register init functions - register_elgg_event_handler('init','system','admin_init'); - register_elgg_event_handler('pagesetup','system','admin_pagesetup'); - - // Register a plugin hook for permissions - register_plugin_hook('permissions_check','all','admin_permissions'); - register_plugin_hook('container_permissions_check','all','admin_permissions'); - -?> + register_action('admin/user/removeadmin', false, "", true); + + // Register some actions + register_action('admin/site/update_basic', false, "", true); // Register basic site admin action + + // Page handler + register_page_handler('admin','admin_settings_page_handler'); + + if (isadminloggedin()) { + global $is_admin; + $is_admin = true; + } + + } + + function admin_pagesetup() { + + if (get_context() == 'admin') { + + global $CONFIG; + add_submenu_item(elgg_echo('admin:statistics'), $CONFIG->wwwroot . 'pg/admin/statistics/'); + add_submenu_item(elgg_echo('admin:site'), $CONFIG->wwwroot . 'pg/admin/site/'); + add_submenu_item(elgg_echo('admin:user'), $CONFIG->wwwroot . 'pg/admin/user/'); + add_submenu_item(elgg_echo('admin:plugins'), $CONFIG->wwwroot . 'pg/admin/plugins/'); + + } + + } + + function admin_settings_page_handler($page) + { + global $CONFIG; + + $path = $CONFIG->path . "admin/index.php"; + + if ($page[0]) + { + switch ($page[0]) + { + case 'user' : $path = $CONFIG->path . "admin/user.php"; break; + case 'statistics' : $path = $CONFIG->path . "admin/statistics.php"; break; + case 'plugins' : $path = $CONFIG->path . "admin/plugins.php"; break; + case 'site' : $path = $CONFIG->path . "admin/site.php"; break; + } + } + + if ($page[1]) + set_input('username', $page[1]); + + include($path); + } + + + /** + * Admin permissions system + * + * @return true|null True if the current user is an admin. + */ + function admin_permissions($hook, $type, $returnval, $params) { + + if (is_array($params) && !empty($params['user']) && $params['user'] instanceof ElggUser) { + $admin = $params['user']->admin; + if ($admin) { + return true; + } + } + + } + + /** + * Write a persistent message to the administrator's notification window. + * + * Currently this writes a message to the admin store, we may want to come up with another way at some point. + * + * @param string $subject Subject of the message + * @param string $message Body of the message + */ + function send_admin_message($subject, $message) + { + $subject = sanitise_string($subject); + $message = sanitise_string($message); + + if (($subject) && ($message)) + { + $admin_message = new ElggObject(); + $admin_message->subtype = 'admin_message'; + $admin_message->access_id = ACCESS_PUBLIC; + $admin_message->title = $subject; + $admin_message->description = $message; + + return $admin_message->save(); + } + + return false; + } + + /** + * List all admin messages. + * + * @param int $limit Limit + */ + function list_admin_messages($limit = 10) + { + return list_entities('object','admin_message',0,$limit); + } + + /** + * Remove an admin message. + * + * @param int $guid The + */ + function clear_admin_message($guid) + { + return delete_entity($guid); + } + + /// Register init functions + register_elgg_event_handler('init','system','admin_init'); + register_elgg_event_handler('pagesetup','system','admin_pagesetup'); + + // Register a plugin hook for permissions + register_plugin_hook('permissions_check','all','admin_permissions'); + register_plugin_hook('container_permissions_check','all','admin_permissions'); + +?> diff --git a/engine/lib/api.php b/engine/lib/api.php index a8e8549fc..3f5cd198f 100644 --- a/engine/lib/api.php +++ b/engine/lib/api.php @@ -259,7 +259,7 @@ /** * Clean out old stuff. * - */ + */ public function __destruct() { global $CONFIG; @@ -270,7 +270,7 @@ $expires = $time-$age; delete_data("DELETE from {$CONFIG->dbprefix}hmac_cache where ts<$expires"); - } + } } // API Call functions ///////////////////////////////////////////////////////////////////// diff --git a/engine/lib/configuration.php b/engine/lib/configuration.php index 0317c821c..9aa5d2174 100644 --- a/engine/lib/configuration.php +++ b/engine/lib/configuration.php @@ -1,17 +1,17 @@ -dbprefix}config where name='$name' and site_guid=$site_guid"); } - - /** - * Sets a configuration value - * - * @param string $name The name of the configuration value - * @param string $value Its value - * @param int $site_guid Optionally, the GUID of the site (current site is assumed by default) - * @return false|int 1 or false depending on success or failure - */ - function set_config($name, $value, $site_guid = 0) { - + + /** + * Sets a configuration value + * + * @param string $name The name of the configuration value + * @param string $value Its value + * @param int $site_guid Optionally, the GUID of the site (current site is assumed by default) + * @return false|int 1 or false depending on success or failure + */ + function set_config($name, $value, $site_guid = 0) { + global $CONFIG; // Unset existing unset_config($name,$site_guid); - - $name = mysql_real_escape_string($name); - $value = mysql_real_escape_string($value); - $site_guid = (int) $site_guid; - if ($site_guid == 0) - $site_guid = (int) $CONFIG->site_id; - $CONFIG->$name = $value; + + $name = mysql_real_escape_string($name); + $value = mysql_real_escape_string($value); + $site_guid = (int) $site_guid; + if ($site_guid == 0) + $site_guid = (int) $CONFIG->site_id; + $CONFIG->$name = $value; $value = sanitise_string(serialize($value)); - - return insert_data("insert into {$CONFIG->dbprefix}config set name = '{$name}', value = '{$value}', site_guid = {$site_guid}"); - - } - - /** - * Gets a configuration value - * - * @param string $name The name of the config value - * @param int $site_guid Optionally, the GUID of the site (current site is assumed by default) - * @return mixed|false Depending on success - */ - function get_config($name, $site_guid = 0) { - - global $CONFIG; - if (isset($CONFIG->$name)) - return $CONFIG->$name; - $name = mysql_real_escape_string($name); - $site_guid = (int) $site_guid; - if ($site_guid == 0) - $site_guid = (int) $CONFIG->site_id; - if ($result = get_data_row("SELECT value from {$CONFIG->dbprefix}config where name = '{$name}' and site_guid = {$site_guid}")) { - $result = $result->value; - $result = unserialize($result->value); - $CONFIG->$name = $result; - return $result; - } - return false; - + + return insert_data("insert into {$CONFIG->dbprefix}config set name = '{$name}', value = '{$value}', site_guid = {$site_guid}"); + + } + + /** + * Gets a configuration value + * + * @param string $name The name of the config value + * @param int $site_guid Optionally, the GUID of the site (current site is assumed by default) + * @return mixed|false Depending on success + */ + function get_config($name, $site_guid = 0) { + + global $CONFIG; + if (isset($CONFIG->$name)) + return $CONFIG->$name; + $name = mysql_real_escape_string($name); + $site_guid = (int) $site_guid; + if ($site_guid == 0) + $site_guid = (int) $CONFIG->site_id; + if ($result = get_data_row("SELECT value from {$CONFIG->dbprefix}config where name = '{$name}' and site_guid = {$site_guid}")) { + $result = $result->value; + $result = unserialize($result->value); + $CONFIG->$name = $result; + return $result; + } + return false; + } /** @@ -110,28 +110,28 @@ return true; } return false; - } - - /** - * If certain configuration elements don't exist, autodetect sensible defaults - * - * @uses $CONFIG The main configuration global - * - */ - function set_default_config() { - - global $CONFIG; - if (empty($CONFIG->path)) - $CONFIG->path = str_replace("\\","/",dirname(dirname(dirname(__FILE__)))) . "/"; - - if (empty($CONFIG->viewpath)) - $CONFIG->viewpath = $CONFIG->path . "views/"; - - if (empty($CONFIG->pluginspath)) - $CONFIG->pluginspath = $CONFIG->path . "mod/"; - - if (empty($CONFIG->wwwroot)) { - /* + } + + /** + * If certain configuration elements don't exist, autodetect sensible defaults + * + * @uses $CONFIG The main configuration global + * + */ + function set_default_config() { + + global $CONFIG; + if (empty($CONFIG->path)) + $CONFIG->path = str_replace("\\","/",dirname(dirname(dirname(__FILE__)))) . "/"; + + if (empty($CONFIG->viewpath)) + $CONFIG->viewpath = $CONFIG->path . "views/"; + + if (empty($CONFIG->pluginspath)) + $CONFIG->pluginspath = $CONFIG->path . "mod/"; + + if (empty($CONFIG->wwwroot)) { + /* $CONFIG->wwwroot = "http://" . $_SERVER['SERVER_NAME']; $request = $_SERVER['REQUEST_URI']; @@ -142,72 +142,72 @@ } $CONFIG->wwwroot .= $request; - */ - $pathpart = str_replace("//","/",str_replace($_SERVER['DOCUMENT_ROOT'],"",$CONFIG->path)); - if (substr($pathpart,0,1) != "/") $pathpart = "/" . $pathpart; + */ + $pathpart = str_replace("//","/",str_replace($_SERVER['DOCUMENT_ROOT'],"",$CONFIG->path)); + if (substr($pathpart,0,1) != "/") $pathpart = "/" . $pathpart; $CONFIG->wwwroot = "http://" . $_SERVER['HTTP_HOST'] . $pathpart; - - } - - if (empty($CONFIG->url)) - $CONFIG->url = $CONFIG->wwwroot; - - if (empty($CONFIG->sitename)) - $CONFIG->sitename = "New Elgg site"; + + } + + if (empty($CONFIG->url)) + $CONFIG->url = $CONFIG->wwwroot; + + if (empty($CONFIG->sitename)) + $CONFIG->sitename = "New Elgg site"; if (empty($CONFIG->language)) $CONFIG->language = "en"; - - } - - /** - * Function that provides some config initialisation on system init - * - */ - - function configuration_init() { - - global $CONFIG; - + + } + + /** + * Function that provides some config initialisation on system init + * + */ + + function configuration_init() { + + global $CONFIG; + if (is_installed() || is_db_installed()) { - - $path = datalist_get('path'); - if (!empty($path)) - $CONFIG->path = $path; - $dataroot = datalist_get('dataroot'); - if (!empty($dataroot)) - $CONFIG->dataroot = $dataroot; - $simplecache_enabled = datalist_get('simplecache_enabled'); - if ($simplecache_enabled !== false) { - $CONFIG->simplecache_enabled = $simplecache_enabled; - } else { - $CONFIG->simplecache_enabled = 1; + + $path = datalist_get('path'); + if (!empty($path)) + $CONFIG->path = $path; + $dataroot = datalist_get('dataroot'); + if (!empty($dataroot)) + $CONFIG->dataroot = $dataroot; + $simplecache_enabled = datalist_get('simplecache_enabled'); + if ($simplecache_enabled !== false) { + $CONFIG->simplecache_enabled = $simplecache_enabled; + } else { + $CONFIG->simplecache_enabled = 1; } $viewpath_cache_enabled = datalist_get('viewpath_cache_enabled'); if ($viewpath_cache_enabled !== false) { $CONFIG->viewpath_cache_enabled = $viewpath_cache_enabled; } else { $CONFIG->viewpath_cache_enabled = 1; - } - if (isset($CONFIG->site) && ($CONFIG->site instanceof ElggSite)) { - $CONFIG->wwwroot = $CONFIG->site->url; + } + if (isset($CONFIG->site) && ($CONFIG->site instanceof ElggSite)) { + $CONFIG->wwwroot = $CONFIG->site->url; $CONFIG->sitename = $CONFIG->site->name; $CONFIG->sitedescription = $CONFIG->site->description; - $CONFIG->siteemail = $CONFIG->site->email; - } - $CONFIG->url = $CONFIG->wwwroot; + $CONFIG->siteemail = $CONFIG->site->email; + } + $CONFIG->url = $CONFIG->wwwroot; // Load default settings from database get_all_config(); - - return true; - } - } - - /** - * Register config_init - */ - - register_elgg_event_handler('boot','system','configuration_init',10); - + + return true; + } + } + + /** + * Register config_init + */ + + register_elgg_event_handler('boot','system','configuration_init',10); + ?> \ No newline at end of file diff --git a/engine/lib/database.php b/engine/lib/database.php index 8b154eefe..fa3a91fbb 100644 --- a/engine/lib/database.php +++ b/engine/lib/database.php @@ -1,60 +1,60 @@ -db[$dblinkname])) { - if (is_array($CONFIG->db[$dblinkname])) { - $index = rand(0,sizeof($CONFIG->db[$dblinkname])); - $dbhost = $CONFIG->db[$dblinkname][$index]->dbhost; - $dbuser = $CONFIG->db[$dblinkname][$index]->dbuser; - $dbpass = $CONFIG->db[$dblinkname][$index]->dbpass; - $dbname = $CONFIG->db[$dblinkname][$index]->dbname; - } else { - $dbhost = $CONFIG->db[$dblinkname]->dbhost; - $dbuser = $CONFIG->db[$dblinkname]->dbuser; - $dbpass = $CONFIG->db[$dblinkname]->dbpass; - $dbname = $CONFIG->db[$dblinkname]->dbname; - } - } else { - $dbhost = $CONFIG->dbhost; - $dbuser = $CONFIG->dbuser; - $dbpass = $CONFIG->dbpass; - $dbname = $CONFIG->dbname; - } - - // Connect to database - if (!$dblink[$dblinkname] = mysql_connect($CONFIG->dbhost, $CONFIG->dbuser, $CONFIG->dbpass, true)) - throw new DatabaseException(sprintf(elgg_echo('DatabaseException:WrongCredentials'), $CONFIG->dbuser, $CONFIG->dbhost, $CONFIG->debug ? $CONFIG->dbpass : "****")); - if (!mysql_select_db($CONFIG->dbname, $dblink[$dblinkname])) - throw new DatabaseException(sprintf(elgg_echo('DatabaseException:NoConnect'), $CONFIG->dbname)); + + /** + * Connect to the database server and use the Elgg database for a particular database link + * + * @param string $dblinkname Default "readwrite"; you can change this to set up additional global database links, eg "read" and "write" + */ + function establish_db_link($dblinkname = "readwrite") { + + // Get configuration, and globalise database link + global $CONFIG, $dblink, $DB_QUERY_CACHE, $dbcalls; + + if (!isset($dblink)) { + $dblink = array(); + } + + if ($dblinkname != "readwrite" && isset($CONFIG->db[$dblinkname])) { + if (is_array($CONFIG->db[$dblinkname])) { + $index = rand(0,sizeof($CONFIG->db[$dblinkname])); + $dbhost = $CONFIG->db[$dblinkname][$index]->dbhost; + $dbuser = $CONFIG->db[$dblinkname][$index]->dbuser; + $dbpass = $CONFIG->db[$dblinkname][$index]->dbpass; + $dbname = $CONFIG->db[$dblinkname][$index]->dbname; + } else { + $dbhost = $CONFIG->db[$dblinkname]->dbhost; + $dbuser = $CONFIG->db[$dblinkname]->dbuser; + $dbpass = $CONFIG->db[$dblinkname]->dbpass; + $dbname = $CONFIG->db[$dblinkname]->dbname; + } + } else { + $dbhost = $CONFIG->dbhost; + $dbuser = $CONFIG->dbuser; + $dbpass = $CONFIG->dbpass; + $dbname = $CONFIG->dbname; + } + + // Connect to database + if (!$dblink[$dblinkname] = mysql_connect($CONFIG->dbhost, $CONFIG->dbuser, $CONFIG->dbpass, true)) + throw new DatabaseException(sprintf(elgg_echo('DatabaseException:WrongCredentials'), $CONFIG->dbuser, $CONFIG->dbhost, $CONFIG->debug ? $CONFIG->dbpass : "****")); + if (!mysql_select_db($CONFIG->dbname, $dblink[$dblinkname])) + throw new DatabaseException(sprintf(elgg_echo('DatabaseException:NoConnect'), $CONFIG->dbname)); // Set up cache if ((!$DB_QUERY_CACHE) && (!$CONFIG->db_disable_query_cache)) @@ -62,29 +62,29 @@ //$DB_QUERY_CACHE = select_default_memcache('db_query_cache'); //array(); //if ($DB_QUERY_CACHE instanceof ElggMemcache) - // $DB_QUERY_CACHE->setDefaultExpiry(30); - } - - /** - * Establish all database connections - * - * If the configuration has been set up for multiple read/write databases, set those - * links up separately; otherwise just create the one database link - * - */ - - function setup_db_connections() { - - // Get configuration and globalise database link - global $CONFIG, $dblink; - - if (!empty($CONFIG->db->split)) { - establish_db_link('read'); - establish_db_link('write'); - } else { - establish_db_link('readwrite'); - } - + // $DB_QUERY_CACHE->setDefaultExpiry(30); + } + + /** + * Establish all database connections + * + * If the configuration has been set up for multiple read/write databases, set those + * links up separately; otherwise just create the one database link + * + */ + + function setup_db_connections() { + + // Get configuration and globalise database link + global $CONFIG, $dblink; + + if (!empty($CONFIG->db->split)) { + establish_db_link('read'); + establish_db_link('write'); + } else { + establish_db_link('readwrite'); + } + } /** @@ -125,43 +125,43 @@ if (isset($CONFIG->debug) && $CONFIG->debug) error_log($e); } } - } - - /** - * Alias to setup_db_connections, for use in the event handler - * - * @param string $event The event type - * @param string $object_type The object type - * @param mixed $object Used for nothing in this context - */ + } + + /** + * Alias to setup_db_connections, for use in the event handler + * + * @param string $event The event type + * @param string $object_type The object type + * @param mixed $object Used for nothing in this context + */ function init_db($event, $object_type, $object = null) { register_shutdown_function('db_delayedexecution_shutdown_hook'); - register_shutdown_function('db_profiling_shutdown_hook'); - //setup_db_connections(); // [Marcus Povey 20090213: Db connection moved to first db connection attempt] - return true; - } - - /** - * Gets the appropriate db link for the operation mode requested - * - * @param string $dblinktype The type of link we want - "read", "write" or "readwrite" (the default) - * @return object Database link - */ - function get_db_link($dblinktype) { - - global $dblink; - - - if (isset($dblink[$dblinktype])) { - return $dblink[$dblinktype]; - } else if (isset($dblink['readwrite'])) { - return $dblink['readwrite']; - } - else - { - setup_db_connections(); - return get_db_link($dblinktype); - } + register_shutdown_function('db_profiling_shutdown_hook'); + //setup_db_connections(); // [Marcus Povey 20090213: Db connection moved to first db connection attempt] + return true; + } + + /** + * Gets the appropriate db link for the operation mode requested + * + * @param string $dblinktype The type of link we want - "read", "write" or "readwrite" (the default) + * @return object Database link + */ + function get_db_link($dblinktype) { + + global $dblink; + + + if (isset($dblink[$dblinktype])) { + return $dblink[$dblinktype]; + } else if (isset($dblink['readwrite'])) { + return $dblink['readwrite']; + } + else + { + setup_db_connections(); + return get_db_link($dblinktype); + } } /** @@ -185,7 +185,7 @@ */ function execute_query($query, $dblink) { - global $CONFIG, $dbcalls, $DB_PROFILE, $DB_QUERY_CACHE; + global $CONFIG, $dbcalls, $DB_PROFILE, $DB_QUERY_CACHE; $dbcalls++; @@ -244,18 +244,18 @@ * @param string $query The query to execute * @param string $handler The handler if you care about the result. */ - function execute_delayed_read_query($query, $handler = "") { return execute_delayed_query($query, get_db_link('read'), $handler); } - - /** - * Use this function to get data from the database - * @param mixed $query The query being passed. - * @param string $call Optionally, the name of a function to call back to on each row (which takes $row as a single parameter) - * @return array An array of database result objects - */ - - function get_data($query, $callback = "") { - - global $CONFIG, $DB_QUERY_CACHE; + function execute_delayed_read_query($query, $handler = "") { return execute_delayed_query($query, get_db_link('read'), $handler); } + + /** + * Use this function to get data from the database + * @param mixed $query The query being passed. + * @param string $call Optionally, the name of a function to call back to on each row (which takes $row as a single parameter) + * @return array An array of database result objects + */ + + function get_data($query, $callback = "") { + + global $CONFIG, $DB_QUERY_CACHE; // Is cached? if ($DB_QUERY_CACHE) $cached_query = $DB_QUERY_CACHE[$query]; @@ -270,17 +270,17 @@ } $dblink = get_db_link('read'); - - $resultarray = array(); - - if ($result = execute_query("$query", $dblink)) { - while ($row = mysql_fetch_object($result)) { - if (!empty($callback) && is_callable($callback)) { - $row = $callback($row); - } - if ($row) $resultarray[] = $row; - } - } + + $resultarray = array(); + + if ($result = execute_query("$query", $dblink)) { + while ($row = mysql_fetch_object($result)) { + if (!empty($callback) && is_callable($callback)) { + $row = $callback($row); + } + if ($row) $resultarray[] = $row; + } + } if (empty($resultarray)) { if ((isset($CONFIG->debug)) && ($CONFIG->debug==true)) @@ -293,18 +293,18 @@ if ((isset($CONFIG->debug)) && ($CONFIG->debug==true)) error_log("$query results cached"); if ($DB_QUERY_CACHE) $DB_QUERY_CACHE[$query] = $resultarray; - - return $resultarray; - } - - /** - * Use this function to get a single data row from the database - * @param mixed $query The query to run. - * @return object A single database result object - */ - - function get_data_row($query, $callback = "") { - + + return $resultarray; + } + + /** + * Use this function to get a single data row from the database + * @param mixed $query The query to run. + * @return object A single database result object + */ + + function get_data_row($query, $callback = "") { + global $CONFIG, $DB_QUERY_CACHE; // Is cached @@ -317,10 +317,10 @@ return false; // Last time this query returned nothing, so return false return $cached_query; - } - + } + $dblink = get_db_link('read'); - + if ($result = execute_query("$query", $dblink)) { $row = mysql_fetch_object($result); @@ -333,127 +333,127 @@ if (!empty($callback) && is_callable($callback)) { $row = $callback($row); } - - if ($row) return $row; + + if ($row) return $row; } if ((isset($CONFIG->debug)) && ($CONFIG->debug==true)) error_log("WARNING: DB query \"$query\" returned no results."); - - return false; - } - - /** - * Use this function to insert database data; returns id or false - * - * @param mixed $query The query to run. - * @return int $id the database id of the inserted row. - */ - - function insert_data($query) { - - global $CONFIG, $DB_QUERY_CACHE; - - $dblink = get_db_link('write'); + + return false; + } + + /** + * Use this function to insert database data; returns id or false + * + * @param mixed $query The query to run. + * @return int $id the database id of the inserted row. + */ + + function insert_data($query) { + + global $CONFIG, $DB_QUERY_CACHE; + + $dblink = get_db_link('write'); // Invalidate query cache if ($DB_QUERY_CACHE) $DB_QUERY_CACHE->clear(); if ((isset($CONFIG->debug)) && ($CONFIG->debug==true)) - error_log("Query cache invalidated"); - - if (execute_query("$query", $dblink)) + error_log("Query cache invalidated"); + + if (execute_query("$query", $dblink)) return mysql_insert_id($dblink); - return false; - } - - /** - * Update database data - * - * @param mixed $query The query to run. - * @return int|false Either the number of affected rows, or false on failure - */ - - function update_data($query) { - - global $CONFIG, $DB_QUERY_CACHE; - + return false; + } + + /** + * Update database data + * + * @param mixed $query The query to run. + * @return int|false Either the number of affected rows, or false on failure + */ + + function update_data($query) { + + global $CONFIG, $DB_QUERY_CACHE; + $dblink = get_db_link('write'); // Invalidate query cache if ($DB_QUERY_CACHE) $DB_QUERY_CACHE->clear(); if ((isset($CONFIG->debug)) && ($CONFIG->debug==true)) - error_log("Query cache invalidated"); - - if (execute_query("$query", $dblink)) + error_log("Query cache invalidated"); + + if (execute_query("$query", $dblink)) return true; //return mysql_affected_rows(); - - return false; - - } - - /** - * Use this function to delete data - * - * @param mixed $query The SQL query to run - * @return int|false Either the number of affected rows, or false on failure - */ - - function delete_data($query) { - - global $CONFIG, $DB_QUERY_CACHE; - - $dblink = get_db_link('write'); + + return false; + + } + + /** + * Use this function to delete data + * + * @param mixed $query The SQL query to run + * @return int|false Either the number of affected rows, or false on failure + */ + + function delete_data($query) { + + global $CONFIG, $DB_QUERY_CACHE; + + $dblink = get_db_link('write'); // Invalidate query cache if ($DB_QUERY_CACHE) $DB_QUERY_CACHE->clear(); if ((isset($CONFIG->debug)) && ($CONFIG->debug==true)) error_log("Query cache invalidated"); - - if (execute_query("$query", $dblink)) - return mysql_affected_rows($dblink); + + if (execute_query("$query", $dblink)) + return mysql_affected_rows($dblink); - return false; - } - - - /** - * Get the tables currently installed in the Elgg database - * - * @return array List of tables - */ - function get_db_tables() { - global $CONFIG; - static $tables, $count; - - if (isset($tables)) { - return $tables; - } + return false; + } + + + /** + * Get the tables currently installed in the Elgg database + * + * @return array List of tables + */ + function get_db_tables() { + global $CONFIG; + static $tables, $count; + + if (isset($tables)) { + return $tables; + } - try{ + try{ $result = get_data("show tables like '" . $CONFIG->dbprefix . "%'"); } catch (DatabaseException $d) { // Likely we can't handle an exception here, so just return false. return false; - } - - $tables = array(); - - if (is_array($result) && !empty($result)) { - foreach($result as $row) { - $row = (array) $row; - if (is_array($row) && !empty($row)) - foreach($row as $element) { - $tables[] = $element; - } - } + } + + $tables = array(); + + if (is_array($result) && !empty($result)) { + foreach($result as $row) { + $row = (array) $row; + if (is_array($row) && !empty($row)) + foreach($row as $element) { + $tables[] = $element; + } + } } else - return false; - - return $tables; + return false; + + return $tables; } /** @@ -464,57 +464,57 @@ { $table = sanitise_string($table); return update_data("optimize table $table"); - } - - /** - * Get the last database error for a particular database link - * - * @param database link $dblink - * @return string Database error message - */ - function get_db_error($dblink) { - return mysql_error($dblink); - } - - /** - * Runs a full database script from disk - * - * @uses $CONFIG - * @param string $scriptlocation The full path to the script - */ - function run_sql_script($scriptlocation) { - - if ($script = file_get_contents($scriptlocation)) { - - global $CONFIG; - - $errors = array(); - - $script = preg_replace('/\-\-.*\n/', '', $script); - $sql_statements = preg_split('/;[\n\r]+/', $script); - foreach($sql_statements as $statement) { - $statement = trim($statement); - $statement = str_replace("prefix_",$CONFIG->dbprefix,$statement); - if (!empty($statement)) { - try { - $result = update_data($statement); - } catch (DatabaseException $e) { - $errors[] = $e->getMessage(); - } - } - } - if (!empty($errors)) { - $errortxt = ""; - foreach($errors as $error) - $errortxt .= " {$error};"; - throw new DatabaseException(elgg_echo('DatabaseException:DBSetupIssues') . $errortxt); - } - - } else { - throw new DatabaseException(sprintf(elgg_echo('DatabaseException:ScriptNotFound'), $scriptlocation)); - } - - } + } + + /** + * Get the last database error for a particular database link + * + * @param database link $dblink + * @return string Database error message + */ + function get_db_error($dblink) { + return mysql_error($dblink); + } + + /** + * Runs a full database script from disk + * + * @uses $CONFIG + * @param string $scriptlocation The full path to the script + */ + function run_sql_script($scriptlocation) { + + if ($script = file_get_contents($scriptlocation)) { + + global $CONFIG; + + $errors = array(); + + $script = preg_replace('/\-\-.*\n/', '', $script); + $sql_statements = preg_split('/;[\n\r]+/', $script); + foreach($sql_statements as $statement) { + $statement = trim($statement); + $statement = str_replace("prefix_",$CONFIG->dbprefix,$statement); + if (!empty($statement)) { + try { + $result = update_data($statement); + } catch (DatabaseException $e) { + $errors[] = $e->getMessage(); + } + } + } + if (!empty($errors)) { + $errortxt = ""; + foreach($errors as $error) + $errortxt .= " {$error};"; + throw new DatabaseException(elgg_echo('DatabaseException:DBSetupIssues') . $errortxt); + } + + } else { + throw new DatabaseException(sprintf(elgg_echo('DatabaseException:ScriptNotFound'), $scriptlocation)); + } + + } /** * Upgrade the database schema in an ordered sequence. @@ -526,49 +526,49 @@ * @param int $version The version you are upgrading from (usually given in the Elgg version format of YYYYMMDDXX - see version.php for example) * @param string $fromdir Optional directory to load upgrades from (default: engine/schema/upgrades/) * @return bool - */ - function db_upgrade($version, $fromdir = "") { - - global $CONFIG; - - // Elgg and its database must be installed to upgrade it! + */ + function db_upgrade($version, $fromdir = "") { + + global $CONFIG; + + // Elgg and its database must be installed to upgrade it! if (!is_db_installed() || !is_installed()) return false; - + $version = (int) $version; if (!$fromdir) - $fromdir = $CONFIG->path . 'engine/schema/upgrades/'; - - if ($handle = opendir($fromdir)) { - - $sqlupgrades = array(); - - while ($sqlfile = readdir($handle)) { - - if (!is_dir($fromdir . $sqlfile)) { - if (preg_match('/([0-9]*)\.sql/',$sqlfile,$matches)) { - $sql_version = (int) $matches[1]; - if ($sql_version > $version) { - $sqlupgrades[] = $sqlfile; - } - } - } - - } - - asort($sqlupgrades); - if (sizeof($sqlupgrades) > 0) { - foreach($sqlupgrades as $sqlfile) { - try { - run_sql_script($fromdir . $sqlfile); - } catch (DatabaseException $e) { - error_log($e->getmessage()); - } - } - } - - } + $fromdir = $CONFIG->path . 'engine/schema/upgrades/'; - return true; + if ($handle = opendir($fromdir)) { + + $sqlupgrades = array(); + + while ($sqlfile = readdir($handle)) { + + if (!is_dir($fromdir . $sqlfile)) { + if (preg_match('/([0-9]*)\.sql/',$sqlfile,$matches)) { + $sql_version = (int) $matches[1]; + if ($sql_version > $version) { + $sqlupgrades[] = $sqlfile; + } + } + } + + } + + asort($sqlupgrades); + if (sizeof($sqlupgrades) > 0) { + foreach($sqlupgrades as $sqlfile) { + try { + run_sql_script($fromdir . $sqlfile); + } catch (DatabaseException $e) { + error_log($e->getmessage()); + } + } + } + + } + + return true; } /** @@ -603,52 +603,52 @@ $string = str_replace($extra_escapeable[$n], "\\" . $extra_escapeable[$n], $string); return $string; - } - - /** - * Sanitise a string for database use - * - * @param string $string The string to sanitise - * @return string Sanitised string - */ - function sanitise_string($string) { - return mysql_real_escape_string(trim($string)); - } - - /** - * Wrapper function for alternate English spelling - * - * @param string $string The string to sanitise - * @return string Sanitised string - * @uses sanitise_string - */ - function sanitize_string($string) { - return sanitise_string($string); - } - - /** - * Sanitises an integer for database use - * - * @param int $int - * @return int Sanitised integer - */ - function sanitise_int($int) { - return (int) $int; - } - - /** - * Wrapper function for alternate English spelling - * - * @param int $int - * @return int Sanitised integer - * @uses sanitise_string - */ - function sanitize_int($int) { - return (int) $int; - } - - // Stuff for initialisation - - register_elgg_event_handler('boot','system','init_db',0); - + } + + /** + * Sanitise a string for database use + * + * @param string $string The string to sanitise + * @return string Sanitised string + */ + function sanitise_string($string) { + return mysql_real_escape_string(trim($string)); + } + + /** + * Wrapper function for alternate English spelling + * + * @param string $string The string to sanitise + * @return string Sanitised string + * @uses sanitise_string + */ + function sanitize_string($string) { + return sanitise_string($string); + } + + /** + * Sanitises an integer for database use + * + * @param int $int + * @return int Sanitised integer + */ + function sanitise_int($int) { + return (int) $int; + } + + /** + * Wrapper function for alternate English spelling + * + * @param int $int + * @return int Sanitised integer + * @uses sanitise_string + */ + function sanitize_int($int) { + return (int) $int; + } + + // Stuff for initialisation + + register_elgg_event_handler('boot','system','init_db',0); + ?> \ No newline at end of file diff --git a/engine/lib/elgglib.php b/engine/lib/elgglib.php index 06af14fcb..fc87c1dc1 100644 --- a/engine/lib/elgglib.php +++ b/engine/lib/elgglib.php @@ -131,13 +131,13 @@ /** * Return the location of a given view. * - * @param string $view The view. + * @param string $view The view. * @param string $viewtype The viewtype */ function elgg_get_view_location($view, $viewtype = '') { global $CONFIG; - + if (empty($viewtype)) $viewtype = elgg_get_viewtype(); @@ -162,7 +162,7 @@ * @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 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 */ @@ -228,7 +228,7 @@ } - // Get the current viewtype + // Get the current viewtype if (empty($viewtype)) $viewtype = elgg_get_viewtype(); @@ -278,7 +278,7 @@ /** * Returns whether the specified view exists * - * @param string $view The view name + * @param string $view The view name * @param string $viewtype If set, forces the viewtype * @return true|false Depending on success */ @@ -286,7 +286,7 @@ global $CONFIG; - // Detect view type + // Detect view type if (empty($viewtype)) $viewtype = elgg_get_viewtype(); @@ -625,14 +625,14 @@ $subtype = $entity->getSubtype(); if (empty($subtype)) { $subtype = $entity_type; } - + $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, @@ -645,7 +645,7 @@ if ($annotations) $contents .= $annotations; - } + } return $contents; } @@ -2303,7 +2303,7 @@ define('ACCESS_DEFAULT',-1); define('ACCESS_PRIVATE',0); define('ACCESS_LOGGED_IN',1); - define('ACCESS_PUBLIC',2); + define('ACCESS_PUBLIC',2); define('ACCESS_FRIENDS',-2); register_elgg_event_handler('init','system','elgg_init'); diff --git a/engine/lib/entities.php b/engine/lib/entities.php index b8c92ec42..4d2e17b56 100644 --- a/engine/lib/entities.php +++ b/engine/lib/entities.php @@ -1,2750 +1,2750 @@ - + + * @link http://elgg.org/ + */ + + /// Cache objects in order to minimise database access. + $ENTITY_CACHE = NULL; + + /// Cache subtype searches + $SUBTYPE_CACHE = NULL; + + /// Require the locatable interface TODO: Move this into start.php? + require_once('location.php'); + + /** + * ElggEntity The elgg entity superclass + * This class holds methods for accessing the main entities table. + * + * @author Curverider Ltd + * @package Elgg + * @subpackage Core + */ + abstract class ElggEntity implements + Notable, // Calendar interface + Locatable, // Geocoding interface + Exportable, // Allow export of data + Importable, // Allow import of data + Loggable, // Can events related to this object class be logged + Iterator, // Override foreach behaviour + ArrayAccess // Override for array access + { + /** + * The main attributes of an entity. + * Blank entries for all database fields should be created by the constructor. + * Subclasses should add to this in their constructors. + * Any field not appearing in this will be viewed as a + */ + protected $attributes; + + /** + * If set, overrides the value of getURL() + */ + protected $url_override; + + /** + * Icon override, overrides the value of getIcon(). + */ + protected $icon_override; + + /** + * Temporary cache for metadata, permitting meta data access before a guid has obtained. + */ + protected $temp_metadata; + + /** + * Temporary cache for annotations, permitting meta data access before a guid has obtained. + */ + protected $temp_annotations; + + /** + * Initialise the attributes array. + * This is vital to distinguish between metadata and base parameters. + * + * Place your base parameters here. + * + * @return void + */ + protected function initialise_attributes() + { + initialise_entity_cache(); + + // Create attributes array if not already created + if (!is_array($this->attributes)) $this->attributes = array(); + if (!is_array($this->temp_metadata)) $this->temp_metadata = array(); + if (!is_array($this->temp_annotations)) $this->temp_annotations = array(); + + $this->attributes['guid'] = ""; + $this->attributes['type'] = ""; + $this->attributes['subtype'] = ""; + + $this->attributes['owner_guid'] = get_loggedin_userid(); + $this->attributes['container_guid'] = get_loggedin_userid(); + + $this->attributes['site_guid'] = 0; + $this->attributes['access_id'] = ACCESS_PRIVATE; + $this->attributes['time_created'] = ""; + $this->attributes['time_updated'] = ""; + $this->attributes['enabled'] = "yes"; + + // There now follows a bit of a hack + /* Problem: To speed things up, some objects are split over several tables, this means that it requires + * n number of database reads to fully populate an entity. This causes problems for caching and create events + * since it is not possible to tell whether a subclassed entity is complete. + * Solution: We have two counters, one 'tables_split' which tells whatever is interested how many tables + * are going to need to be searched in order to fully populate this object, and 'tables_loaded' which is how + * many have been loaded thus far. + * If the two are the same then this object is complete. + * + * Use: isFullyLoaded() to check + */ + $this->attributes['tables_split'] = 1; + $this->attributes['tables_loaded'] = 0; + } + + /** + * Return the value of a given key. + * If $name is a key field (as defined in $this->attributes) that value is returned, otherwise it will + * then look to see if the value is in this object's metadata. + * + * Q: Why are we not using __get overload here? + * A: Because overload operators cause problems during subclassing, so we put the code here and + * create overloads in subclasses. + * + * @param string $name + * @return mixed Returns the value of a given value, or null. + */ + public function get($name) + { + // See if its in our base attribute + if (isset($this->attributes[$name])) { + return $this->attributes[$name]; + } + + // No, so see if its in the meta data for this entity + $meta = $this->getMetaData($name); + if ($meta) + return $meta; + + // Can't find it, so return null + return null; + } - * @author Curverider Ltd + /** + * Set the value of a given key, replacing it if necessary. + * If $name is a base attribute (as defined in $this->attributes) that value is set, otherwise it will + * set the appropriate item of metadata. + * + * Note: It is important that your class populates $this->attributes with keys for all base attributes, anything + * not in their gets set as METADATA. + * + * Q: Why are we not using __set overload here? + * A: Because overload operators cause problems during subclassing, so we put the code here and + * create overloads in subclasses. + * + * @param string $name + * @param mixed $value + */ + public function set($name, $value) + { + if (array_key_exists($name, $this->attributes)) + { + // Check that we're not trying to change the guid! + if ((array_key_exists('guid', $this->attributes)) && ($name=='guid')) + return false; + + $this->attributes[$name] = $value; + } + else + return $this->setMetaData($name, $value); + + return true; + } + + /** + * Get a given piece of metadata. + * + * @param string $name + */ + public function getMetaData($name) + { + if ((int) ($this->guid) > 0) { + $md = get_metadata_byname($this->getGUID(), $name); + } else { + if (isset($this->temp_metadata[$name])) + return $this->temp_metadata[$name]; + } - * @link http://elgg.org/ - */ - - /// Cache objects in order to minimise database access. - $ENTITY_CACHE = NULL; - - /// Cache subtype searches - $SUBTYPE_CACHE = NULL; - - /// Require the locatable interface TODO: Move this into start.php? - require_once('location.php'); - - /** - * ElggEntity The elgg entity superclass - * This class holds methods for accessing the main entities table. - * - * @author Curverider Ltd - * @package Elgg - * @subpackage Core - */ - abstract class ElggEntity implements - Notable, // Calendar interface - Locatable, // Geocoding interface - Exportable, // Allow export of data - Importable, // Allow import of data - Loggable, // Can events related to this object class be logged - Iterator, // Override foreach behaviour - ArrayAccess // Override for array access - { - /** - * The main attributes of an entity. - * Blank entries for all database fields should be created by the constructor. - * Subclasses should add to this in their constructors. - * Any field not appearing in this will be viewed as a - */ - protected $attributes; - - /** - * If set, overrides the value of getURL() - */ - protected $url_override; - - /** - * Icon override, overrides the value of getIcon(). - */ - protected $icon_override; - - /** - * Temporary cache for metadata, permitting meta data access before a guid has obtained. - */ - protected $temp_metadata; - - /** - * Temporary cache for annotations, permitting meta data access before a guid has obtained. - */ - protected $temp_annotations; - - /** - * Initialise the attributes array. - * This is vital to distinguish between metadata and base parameters. - * - * Place your base parameters here. - * - * @return void - */ - protected function initialise_attributes() - { - initialise_entity_cache(); - - // Create attributes array if not already created - if (!is_array($this->attributes)) $this->attributes = array(); - if (!is_array($this->temp_metadata)) $this->temp_metadata = array(); - if (!is_array($this->temp_annotations)) $this->temp_annotations = array(); - - $this->attributes['guid'] = ""; - $this->attributes['type'] = ""; - $this->attributes['subtype'] = ""; - - $this->attributes['owner_guid'] = get_loggedin_userid(); - $this->attributes['container_guid'] = get_loggedin_userid(); - - $this->attributes['site_guid'] = 0; - $this->attributes['access_id'] = ACCESS_PRIVATE; - $this->attributes['time_created'] = ""; - $this->attributes['time_updated'] = ""; - $this->attributes['enabled'] = "yes"; - - // There now follows a bit of a hack - /* Problem: To speed things up, some objects are split over several tables, this means that it requires - * n number of database reads to fully populate an entity. This causes problems for caching and create events - * since it is not possible to tell whether a subclassed entity is complete. - * Solution: We have two counters, one 'tables_split' which tells whatever is interested how many tables - * are going to need to be searched in order to fully populate this object, and 'tables_loaded' which is how - * many have been loaded thus far. - * If the two are the same then this object is complete. - * - * Use: isFullyLoaded() to check - */ - $this->attributes['tables_split'] = 1; - $this->attributes['tables_loaded'] = 0; - } - - /** - * Return the value of a given key. - * If $name is a key field (as defined in $this->attributes) that value is returned, otherwise it will - * then look to see if the value is in this object's metadata. - * - * Q: Why are we not using __get overload here? - * A: Because overload operators cause problems during subclassing, so we put the code here and - * create overloads in subclasses. - * - * @param string $name - * @return mixed Returns the value of a given value, or null. - */ - public function get($name) - { - // See if its in our base attribute - if (isset($this->attributes[$name])) { - return $this->attributes[$name]; - } - - // No, so see if its in the meta data for this entity - $meta = $this->getMetaData($name); - if ($meta) - return $meta; - - // Can't find it, so return null - return null; - } - - /** - * Set the value of a given key, replacing it if necessary. - * If $name is a base attribute (as defined in $this->attributes) that value is set, otherwise it will - * set the appropriate item of metadata. - * - * Note: It is important that your class populates $this->attributes with keys for all base attributes, anything - * not in their gets set as METADATA. - * - * Q: Why are we not using __set overload here? - * A: Because overload operators cause problems during subclassing, so we put the code here and - * create overloads in subclasses. - * - * @param string $name - * @param mixed $value - */ - public function set($name, $value) - { - if (array_key_exists($name, $this->attributes)) - { - // Check that we're not trying to change the guid! - if ((array_key_exists('guid', $this->attributes)) && ($name=='guid')) - return false; - - $this->attributes[$name] = $value; - } - else - return $this->setMetaData($name, $value); - - return true; - } - - /** - * Get a given piece of metadata. - * - * @param string $name - */ - public function getMetaData($name) - { - if ((int) ($this->guid) > 0) { - $md = get_metadata_byname($this->getGUID(), $name); - } else { - if (isset($this->temp_metadata[$name])) - return $this->temp_metadata[$name]; - } - - if ($md && !is_array($md)) { - return $md->value; - } else if ($md && is_array($md)) { - return metadata_array_to_values($md); - } - - return null; - } - - /** - * Class member get overloading - * - * @param string $name - * @return mixed - */ - function __get($name) { return $this->get($name); } - - /** - * Class member set overloading - * - * @param string $name - * @param mixed $value - * @return mixed - */ - function __set($name, $value) { return $this->set($name, $value); } - - /** - * Supporting isset. - * - * @param string $name The name of the attribute or metadata. - * @return bool - */ - function __isset($name) { if ($this->$name!="") return true; else return false; } - - /** - * Supporting unsetting of magic attributes. - * - * @param string $name The name of the attribute or metadata. - */ - function __unset($name) - { - if (array_key_exists($name, $this->attributes)) - $this->attributes[$name] = ""; - else - $this->clearMetaData($name); - } - - /** - * Set a piece of metadata. - * - * @param string $name - * @param mixed $value - * @param string $value_type - * @param bool $multiple - * @return bool - */ - public function setMetaData($name, $value, $value_type = "", $multiple = false) - { - if (is_array($value)) - { - unset($this->temp_metadata[$name]); - remove_metadata($this->getGUID(), $name); - foreach ($value as $v) { - if ((int) $this->guid > 0) { - $multiple = true; - if (!create_metadata($this->getGUID(), $name, $v, $value_type, $this->getOwner(), $this->getAccessID(), $multiple)) return false; - } else { - if (($multiple) && (isset($this->temp_metadata[$name]))) - { - if (!is_array($this->temp_metadata[$name])) - { - $tmp = $this->temp_metadata[$name]; - $this->temp_metadata[$name] = array(); - $this->temp_metadata[$name][] = $tmp; - } - - $this->temp_metadata[$name][] = $value; - } - else - $this->temp_metadata[$name] = $value; - } - } - - return true; - } - else - { - unset($this->temp_metadata[$name]); - if ((int) $this->guid > 0) { - return create_metadata($this->getGUID(), $name, $value, $value_type, $this->getOwner(), $this->getAccessID(), $multiple); - } else { - //$this->temp_metadata[$name] = $value; - - if (($multiple) && (isset($this->temp_metadata[$name]))) - { - if (!is_array($this->temp_metadata[$name])) - { - $tmp = $this->temp_metadata[$name]; - $this->temp_metadata[$name] = array(); - $this->temp_metadata[$name][] = $tmp; - } - - $this->temp_metadata[$name][] = $value; - } - else - $this->temp_metadata[$name] = $value; - - return true; - } - } - } - - /** - * Clear metadata. - */ - public function clearMetaData($name = "") - { - if (empty($name)) { - return clear_metadata($this->getGUID()); - } else { - return remove_metadata($this->getGUID(),$name); - } - } - - /** - * Remove all entities associated with this entity - * - * @return true - */ - public function clearRelationships() { - remove_entity_relationships($this->getGUID()); - remove_entity_relationships($this->getGUID(),"",true); - return true; - } - - /** - * Add a relationship. - * - * @param int $guid Relationship to link to. - * @param string $relationship The type of relationship. - */ - public function addRelationship($guid, $relationship) - { - return add_entity_relationship($this->getGUID(), $relationship, $guid); - } - - function setPrivateSetting($name, $value) { - return set_private_setting($this->getGUID(), $name, $value); - } - - function getPrivateSetting($name) { - return get_private_setting($this->getGUID(), $name); - } - - function removePrivateSetting($name) { - return remove_private_setting($this->getGUID(), $name); - } - - /** - * Adds an annotation to an entity. By default, the type is detected automatically; however, - * it can also be set. Note that by default, annotations are private. - * - * @param string $name - * @param mixed $value - * @param int $access_id - * @param int $owner_id - * @param string $vartype - */ - function annotate($name, $value, $access_id = ACCESS_PRIVATE, $owner_id = 0, $vartype = "") - { - if ((int) $this->guid > 0) { - return create_annotation($this->getGUID(), $name, $value, $vartype, $owner_id, $access_id); - } else { - $this->temp_annotations[$name] = $value; - } - return true; - } - - /** - * Get the annotations for an entity. - * - * @param string $name - * @param int $limit - * @param int $offset - * @param string $order - */ - function getAnnotations($name, $limit = 50, $offset = 0, $order="asc") - { - if ((int) ($this->guid) > 0) { - return get_annotations($this->getGUID(), "", "", $name, "", 0, $limit, $offset, $order); - } else { - return $this->temp_annotations[$name]; - } - } - - /** - * Remove all annotations or all annotations for this entity. - * - * @param string $name - */ - function clearAnnotations($name = "") - { - return clear_annotations($this->getGUID(), $name); - } - - /** - * Return the annotations for the entity. - * - * @param string $name The type of annotation. - */ - function countAnnotations($name = "") - { - return count_annotations($this->getGUID(), "","",$name); - } - - /** - * Get the average of an integer type annotation. - * - * @param string $name - */ - function getAnnotationsAvg($name) - { - return get_annotations_avg($this->getGUID(), "","",$name); - } - - /** - * Get the sum of integer type annotations of a given name. - * - * @param string $name - */ - function getAnnotationsSum($name) - { - return get_annotations_sum($this->getGUID(), "","",$name); - } - - /** - * Get the minimum of integer type annotations of given name. - * - * @param string $name - */ - function getAnnotationsMin($name) - { - return get_annotations_min($this->getGUID(), "","",$name); - } - - /** - * Get the maximum of integer type annotations of a given name. - * - * @param string $name - */ - function getAnnotationsMax($name) - { - return get_annotations_max($this->getGUID(), "","",$name); - } - - /** - * Gets an array of entities from a specific relationship type - * - * @param string $relationship Relationship type (eg "friends") - * @param true|false $inverse Is this an inverse relationship? - * @param int $limit Number of elements to return - * @param int $offset Indexing offset - * @return array|false An array of entities or false on failure - */ - function getEntitiesFromRelationship($relationship, $inverse = false, $limit = 50, $offset = 0) { - return get_entities_from_relationship($relationship,$this->getGUID(),$inverse,"","","","time_created desc",$limit,$offset); - } - - /** - * Gets the number of of entities from a specific relationship type - * - * @param string $relationship Relationship type (eg "friends") - * @return int|false The number of entities or false on failure - */ - function countEntitiesFromRelationship($relationship) { - return get_entities_from_relationship($relationship,$this->getGUID(),false,"","","","time_created desc",null,null,true); - } - - /** - * Determines whether or not the specified user (by default the current one) can edit the entity - * - * @param int $user_guid The user GUID, optionally (defaults to the currently logged in user) - * @return true|false - */ - function canEdit($user_guid = 0) { - return can_edit_entity($this->getGUID(),$user_guid); - } - - /** - * Determines whether or not the specified user (by default the current one) can edit metadata on the entity - * - * @param ElggMetadata $metadata The piece of metadata to specifically check - * @param int $user_guid The user GUID, optionally (defaults to the currently logged in user) - * @return true|false - */ - function canEditMetadata($metadata = null, $user_guid = 0) { - return can_edit_entity_metadata($this->getGUID(), $user_guid, $metadata); - } - - /** - * Returns whether the given user (or current user) has the ability to write to this group. - * - * @param int $user_guid The user. - * @return bool - */ - public function canWriteToContainer($user_guid = 0) - { - return can_write_to_container($user_guid, $this->getGUID()); - } - - /** - * Obtain this entity's access ID - * - * @return int The access ID - */ - public function getAccessID() { return $this->get('access_id'); } - - /** - * Obtain this entity's GUID - * - * @return int GUID - */ - public function getGUID() { return $this->get('guid'); } - - /** - * Get the owner of this entity - * - * @return int The owner GUID - */ - public function getOwner() { return $this->get('owner_guid'); } - - /** - * Returns the actual entity of the user who owns this entity, if any - * - * @return ElggEntity The owning user - */ - public function getOwnerEntity() { return get_entity($this->get('owner_guid')); } - - /** - * Gets the type of entity this is - * - * @return string Entity type - */ - public function getType() { return $this->get('type'); } - - /** - * Returns the subtype of this entity - * - * @return string The entity subtype - */ - public function getSubtype() { - if (!((int) $this->guid > 0)) return $this->get('subtype'); // If this object hasn't been saved, then return the subtype string. - - return get_subtype_from_id($this->get('subtype')); - } - - /** - * Gets the UNIX epoch time that this entity was created - * - * @return int UNIX epoch time - */ - public function getTimeCreated() { return $this->get('time_created'); } - - /** - * Gets the UNIX epoch time that this entity was last updated - * - * @return int UNIX epoch time - */ - public function getTimeUpdated() { return $this->get('time_updated'); } - - /** - * Gets the display URL for this entity - * - * @return string The URL - */ - public function getURL() { - if (!empty($this->url_override)) return $this->url_override; - return get_entity_url($this->getGUID()); - } - - /** - * Overrides the URL returned by getURL - * - * @param string $url The new item URL - * @return string The URL - */ - public function setURL($url) { - $this->url_override = $url; - return $url; - } - - /** - * Return a url for the entity's icon, trying multiple alternatives. - * - * @param string $size Either 'large','medium','small' or 'tiny' - * @return string The url or false if no url could be worked out. - */ - public function getIcon($size = 'medium') - { - if (isset($this->icon_override[$size])) return $this->icon_override[$size]; - return get_entity_icon_url($this, $size); - } - - /** - * Set an icon override for an icon and size. - * - * @param string $url The url of the icon. - * @param string $size The size its for. - * @return bool - */ - public function setIcon($url, $size = 'medium') - { - $url = sanitise_string($url); - $size = sanitise_string($size); - - if (!$this->icon_override) $this->icon_override = array(); - $this->icon_override[$size] = $url; - - return true; - } - - /** - * Tests to see whether the object has been fully loaded. - * - * @return bool - */ - public function isFullyLoaded() { return ! ($this->attributes['tables_loaded'] < $this->attributes['tables_split']); } - - /** - * Save generic attributes to the entities table. - */ - public function save() - { - $guid = (int) $this->guid; - if ($guid > 0) - { - cache_entity($this); - - return update_entity( - $this->get('guid'), - $this->get('owner_guid'), - $this->get('access_id'), - $this->get('container_guid') - ); - } - else - { - $this->attributes['guid'] = create_entity($this->attributes['type'], $this->attributes['subtype'], $this->attributes['owner_guid'], $this->attributes['access_id'], $this->attributes['site_guid'], $this->attributes['container_guid']); // Create a new entity (nb: using attribute array directly 'cos set function does something special!) - if (!$this->attributes['guid']) throw new IOException(elgg_echo('IOException:BaseEntitySaveFailed')); - - // Save any unsaved metadata TODO: How to capture extra information (access id etc) - if (sizeof($this->temp_metadata) > 0) { - foreach($this->temp_metadata as $name => $value) { - $this->$name = $value; - unset($this->temp_metadata[$name]); - } - } - - // Save any unsaved annotations metadata. TODO: How to capture extra information (access id etc) - if (sizeof($this->temp_annotations) > 0) { - foreach($this->temp_annotations as $name => $value) { - $this->annotate($name, $value); - unset($this->temp_annotations[$name]); - } - } - - // Cache object handle - if ($this->attributes['guid']) cache_entity($this); - - return $this->attributes['guid']; - } - } - - /** - * Load the basic entity information and populate base attributes array. - * - * @param int $guid - */ - protected function load($guid) - { - $row = get_entity_as_row($guid); - - if ($row) - { - // Create the array if necessary - all subclasses should test before creating - if (!is_array($this->attributes)) $this->attributes = array(); - - // Now put these into the attributes array as core values - $objarray = (array) $row; - foreach($objarray as $key => $value) - $this->attributes[$key] = $value; - - // Increment the portion counter - if (!$this->isFullyLoaded()) $this->attributes['tables_loaded'] ++; - - // Cache object handle - if ($this->attributes['guid']) cache_entity($this); - - return true; - } - - return false; - } - - /** - * Disable this entity. - * - * @param string $reason Optional reason - * @param bool $recursive Recursively disable all contained entities? - */ - public function disable($reason = "", $recursive = true) - { - return disable_entity($this->get('guid'), $reason, $recursive); - } - - /** - * Re-enable this entity. - */ - public function enable() - { - return enable_entity($this->get('guid')); - } - - /** - * Is this entity enabled? - * - * @return boolean - */ - public function isEnabled() - { - if ($this->enabled == 'yes') - return true; - - return false; - } - - /** - * Delete this entity. - */ - public function delete() - { - return delete_entity($this->get('guid')); - } - - // LOCATABLE INTERFACE ///////////////////////////////////////////////////////////// - - /** Interface to set the location */ - public function setLocation($location) - { - $location = sanitise_string($location); - - $this->location = $location; - - return true; - } - - /** - * Set latitude and longitude tags for a given entity. - * - * @param float $lat - * @param float $long - */ - public function setLatLong($lat, $long) - { - $lat = sanitise_string($lat); - $long = sanitise_string($long); - - $this->set('geo:lat', $lat); - $this->set('geo:long', $long); - - return true; - } - - /** - * Get the contents of the ->geo:lat field. - * - */ - public function getLatitude() { return $this->get('geo:lat'); } - - /** - * Get the contents of the ->geo:lat field. - * - */ - public function getLongitude() { return $this->get('geo:long'); } - - /** - * Get the ->location metadata. - * - */ - public function getLocation() { return $this->get('location'); } - - // NOTABLE INTERFACE /////////////////////////////////////////////////////////////// - - /** - * Calendar functionality. - * This function sets the time of an object on a calendar listing. - * - * @param int $hour If ommitted, now is assumed. - * @param int $minute If ommitted, now is assumed. - * @param int $second If ommitted, now is assumed. - * @param int $day If ommitted, now is assumed. - * @param int $month If ommitted, now is assumed. - * @param int $year If ommitted, now is assumed. - * @param int $duration Duration of event, remainder of the day is assumed. - */ - public function setCalendarTimeAndDuration($hour = NULL, $minute = NULL, $second = NULL, $day = NULL, $month = NULL, $year = NULL, $duration = NULL) - { - $start = mktime($hour, $minute, $second, $month, $day, $year); - $end = $start + abs($duration); - if (!$duration) - $end = get_day_end($day,$month,$year); - - $this->calendar_start = $start; - $this->calendar_end = $end; - - return true; - } - - /** - * Return the start timestamp. - */ - public function getCalendarStartTime() { return (int)$this->calendar_start; } - - /** - * Return the end timestamp. - */ - public function getCalendarEndTime() { return (int)$this->calendar_end; } - - // EXPORTABLE INTERFACE //////////////////////////////////////////////////////////// - - /** - * Return an array of fields which can be exported. - */ - public function getExportableValues() - { - return array( - 'guid', - 'type', - 'subtype', - 'time_created', - 'container_guid', - 'owner_guid', - ); - } - - /** - * Export this class into an array of ODD Elements containing all necessary fields. - * Override if you wish to return more information than can be found in $this->attributes (shouldn't happen) - */ - public function export() - { - $tmp = array(); - - // Generate uuid - $uuid = guid_to_uuid($this->getGUID()); - - // Create entity - $odd = new ODDEntity( - $uuid, - $this->attributes['type'], - get_subtype_from_id($this->attributes['subtype']) - ); - - $tmp[] = $odd; - - $exportable_values = $this->getExportableValues(); - - // Now add its attributes - foreach ($this->attributes as $k => $v) - { - $meta = NULL; - - if (in_array( $k, $exportable_values)) { - switch ($k) - { - case 'guid' : // Dont use guid in OpenDD - case 'type' : // Type and subtype already taken care of - case 'subtype' : - break; - - case 'time_created' : // Created = published - $odd->setAttribute('published', date("r", $v)); - break; - - case 'site_guid' : // Container - $k = 'site_uuid'; - $v = guid_to_uuid($v); - $meta = new ODDMetaData($uuid . "attr/$k/", $uuid, $k, $v); - break; - - case 'container_guid' : // Container - $k = 'container_uuid'; - $v = guid_to_uuid($v); - $meta = new ODDMetaData($uuid . "attr/$k/", $uuid, $k, $v); - break; - - case 'owner_guid' : // Convert owner guid to uuid, this will be stored in metadata - $k = 'owner_uuid'; - $v = guid_to_uuid($v); - $meta = new ODDMetaData($uuid . "attr/$k/", $uuid, $k, $v); - break; - - default : - $meta = new ODDMetaData($uuid . "attr/$k/", $uuid, $k, $v); - } - - // set the time of any metadata created - if ($meta) - { - $meta->setAttribute('published', date("r",$this->time_created)); - $tmp[] = $meta; - } - } - } - - // Now we do something a bit special. - /* - * This provides a rendered view of the entity to foreign sites. - */ - - elgg_set_viewtype('default'); - $view = elgg_view_entity($this, true); - elgg_set_viewtype(); - - $tmp[] = new ODDMetaData($uuid . "volatile/renderedentity/", $uuid, 'renderedentity', $view , 'volatile'); - - - return $tmp; - } - - // IMPORTABLE INTERFACE //////////////////////////////////////////////////////////// - - /** - * Import data from an parsed xml data array. - * - * @param array $data - * @param int $version - */ - public function import(ODD $data) - { - if (!($data instanceof ODDEntity)) - throw new InvalidParameterException(elgg_echo('InvalidParameterException:UnexpectedODDClass')); - - // Set type and subtype - $this->attributes['type'] = $data->getAttribute('class'); - $this->attributes['subtype'] = $data->getAttribute('subclass'); - - // Set owner - $this->attributes['owner_guid'] = get_loggedin_userid(); // Import as belonging to importer. - - // Set time - $this->attributes['time_created'] = strtotime($data->getAttribute('published')); - $this->attributes['time_updated'] = time(); - - return true; - } - - // SYSTEM LOG INTERFACE //////////////////////////////////////////////////////////// - - /** - * Return an identification for the object for storage in the system log. - * This id must be an integer. - * - * @return int - */ - public function getSystemLogID() { return $this->getGUID(); } - - /** - * Return the class name of the object. - */ - public function getClassName() { return get_class($this); } - - /** - * For a given ID, return the object associated with it. - * This is used by the river functionality primarily. - * This is useful for checking access permissions etc on objects. - */ - public function getObjectFromID($id) { return get_entity($id); } - - /** - * Return the GUID of the owner of this object. - */ - public function getObjectOwnerGUID() { return $this->owner_guid; } - - // ITERATOR INTERFACE ////////////////////////////////////////////////////////////// - /* - * This lets an entity's attributes be displayed using foreach as a normal array. - * Example: http://www.sitepoint.com/print/php5-standard-library - */ - - private $valid = FALSE; - - function rewind() - { - $this->valid = (FALSE !== reset($this->attributes)); - } - - function current() - { - return current($this->attributes); - } - - function key() - { - return key($this->attributes); - } - - function next() - { - $this->valid = (FALSE !== next($this->attributes)); - } - - function valid() - { - return $this->valid; - } - - // ARRAY ACCESS INTERFACE ////////////////////////////////////////////////////////// - /* - * This lets an entity's attributes be accessed like an associative array. - * Example: http://www.sitepoint.com/print/php5-standard-library - */ - - function offsetSet($key, $value) - { - if ( array_key_exists($key, $this->attributes) ) { - $this->attributes[$key] = $value; - } - } - - function offsetGet($key) - { - if ( array_key_exists($key, $this->attributes) ) { - return $this->attributes[$key]; - } - } - - function offsetUnset($key) - { - if ( array_key_exists($key, $this->attributes) ) { - $this->attributes[$key] = ""; // Full unsetting is dangerious for our objects - } - } - - function offsetExists($offset) - { - return array_key_exists($offset, $this->attributes); - } - } - - /** - * Initialise the entity cache. - */ - function initialise_entity_cache() - { - global $ENTITY_CACHE; - - if (!$ENTITY_CACHE) - $ENTITY_CACHE = array(); //select_default_memcache('entity_cache'); // TODO: Replace with memcache? - } - - /** - * Invalidate this class' entry in the cache. - * - * @param int $guid The guid - */ - function invalidate_cache_for_entity($guid) - { - global $ENTITY_CACHE; - - $guid = (int)$guid; - - unset($ENTITY_CACHE[$guid]); - //$ENTITY_CACHE->delete($guid); - } - - /** - * Cache an entity. - * - * @param ElggEntity $entity Entity to cache - */ - function cache_entity(ElggEntity $entity) - { - global $ENTITY_CACHE; - - $ENTITY_CACHE[$entity->guid] = $entity; - } - - /** - * Retrieve a entity from the cache. - * - * @param int $guid The guid - */ - function retrieve_cached_entity($guid) - { - global $ENTITY_CACHE; - - $guid = (int)$guid; - - if (isset($ENTITY_CACHE[$guid])) - if ($ENTITY_CACHE[$guid]->isFullyLoaded()) return $ENTITY_CACHE[$guid]; - - return false; - } - - /** - * As retrieve_cached_entity, but returns the result as a stdClass (compatible with load functions that - * expect a database row.) - * - * @param int $guid The guid - */ - function retrieve_cached_entity_row($guid) - { - $obj = retrieve_cached_entity($guid); - if ($obj) - { - $tmp = new stdClass; - - foreach ($obj as $k => $v) - $tmp->$k = $v; - - return $tmp; - } - - return false; - } - - /** - * Return the integer ID for a given subtype, or false. - * - * TODO: Move to a nicer place? - * - * @param string $type - * @param string $subtype - */ - function get_subtype_id($type, $subtype) - { - global $CONFIG, $SUBTYPE_CACHE; - - $type = sanitise_string($type); - $subtype = sanitise_string($subtype); - - if ($subtype=="") return $subtype; - - // Todo: cache here? Or is looping less efficient that going to the db each time? - - $result = get_data_row("SELECT * from {$CONFIG->dbprefix}entity_subtypes where type='$type' and subtype='$subtype'"); - - if ($result) { - - if (!$SUBTYPE_CACHE) - $SUBTYPE_CACHE = array(); //select_default_memcache('subtype_cache'); - - $SUBTYPE_CACHE[$result->id] = $result; - return $result->id; - } - - return 0; - } - - /** - * For a given subtype ID, return its identifier text. - * - * TODO: Move to a nicer place? - * - * @param int $subtype_id - */ - function get_subtype_from_id($subtype_id) - { - global $CONFIG, $SUBTYPE_CACHE; - - $subtype_id = (int)$subtype_id; - - if (!$subtype_id) return false; - - if (isset($SUBTYPE_CACHE[$subtype_id])) - return $SUBTYPE_CACHE[$subtype_id]->subtype; - - $result = get_data_row("SELECT * from {$CONFIG->dbprefix}entity_subtypes where id=$subtype_id"); - if ($result) { - - if (!$SUBTYPE_CACHE) - $SUBTYPE_CACHE = array(); //select_default_memcache('subtype_cache'); - - $SUBTYPE_CACHE[$subtype_id] = $result; - return $result->subtype; - } - - return false; - } - - /** - * This function tests to see if a subtype has a registered class handler. - * - * @param string $type The type - * @param string $subtype The subtype - * @return a class name or null - */ - function get_subtype_class($type, $subtype) - { - global $CONFIG, $SUBTYPE_CACHE; - - $type = sanitise_string($type); - $subtype = sanitise_string($subtype); - - // Todo: cache here? Or is looping less efficient that going to the db each time? - - $result = get_data_row("SELECT * from {$CONFIG->dbprefix}entity_subtypes where type='$type' and subtype='$subtype'"); - if ($result) { - - if (!$SUBTYPE_CACHE) - $SUBTYPE_CACHE = array(); //select_default_memcache('subtype_cache'); - - $SUBTYPE_CACHE[$result->id] = $result; - return $result->class; - } - - return NULL; - } - - /** - * This function tests to see if a subtype has a registered class handler by its id. - * - * @param int $subtype_id The subtype - * @return a class name or null - */ - function get_subtype_class_from_id($subtype_id) - { - global $CONFIG, $SUBTYPE_CACHE; - - $subtype_id = (int)$subtype_id; - - if (!$subtype_id) return false; - - if (isset($SUBTYPE_CACHE[$subtype_id])) - return $SUBTYPE_CACHE[$subtype_id]->class; - - $result = get_data_row("SELECT * from {$CONFIG->dbprefix}entity_subtypes where id=$subtype_id"); - if ($result) { - - if (!$SUBTYPE_CACHE) - $SUBTYPE_CACHE = array(); //select_default_memcache('subtype_cache'); - - $SUBTYPE_CACHE[$subtype_id] = $result; - return $result->class; - } - - return NULL; - } - - /** - * This function will register a new subtype, returning its ID as required. - * - * @param string $type The type you're subtyping - * @param string $subtype The subtype label - * @param string $class Optional class handler (if you don't want it handled by the generic elgg handler for the type) - */ - function add_subtype($type, $subtype, $class = "") - { - global $CONFIG; - $type = sanitise_string($type); - $subtype = sanitise_string($subtype); - $class = sanitise_string($class); - - // Short circuit if no subtype is given - if ($subtype == "") - return 0; - - $id = get_subtype_id($type, $subtype); - - if ($id==0) - return insert_data("insert into {$CONFIG->dbprefix}entity_subtypes (type, subtype, class) values ('$type','$subtype','$class')"); - - return $id; - } - - /** - * Update an existing entity. - * - * @param int $guid - * @param int $owner_guid - * @param int $access_id - * @param int $container_guid - */ - function update_entity($guid, $owner_guid, $access_id, $container_guid = null) - { - global $CONFIG, $ENTITY_CACHE; - - $guid = (int)$guid; - $owner_guid = (int)$owner_guid; - $access_id = (int)$access_id; - $container_guid = (int) $container_guid; - if (is_null($container_guid)) $container_guid = $owner_guid; - $time = time(); - - $entity = get_entity($guid); - - if ($entity->canEdit()) { - - if (trigger_elgg_event('update',$entity->type,$entity)) { - $ret = update_data("UPDATE {$CONFIG->dbprefix}entities set owner_guid='$owner_guid', access_id='$access_id', container_guid='$container_guid', time_updated='$time' WHERE guid=$guid"); - - if ($entity instanceof ElggObject) - update_river_access_by_object($guid,$access_id); - - // If memcache is available then delete this entry from the cache - static $newentity_cache; - if ((!$newentity_cache) && (is_memcache_available())) - $newentity_cache = new ElggMemcache('new_entity_cache'); - if ($newentity_cache) $new_entity = $newentity_cache->delete($guid); - - // Handle cases where there was no error BUT no rows were updated! - if ($ret===false) - return false; - - return true; - } - - } - } - - /** - * Determine whether a given user is able to write to a given container. - * - * @param int $user_guid The user guid, or 0 for get_loggedin_userid() - * @param int $container_guid The container, or 0 for the current page owner. - */ - function can_write_to_container($user_guid = 0, $container_guid = 0, $entity_type = 'all') - { - global $CONFIG; - - $user_guid = (int)$user_guid; - $user = get_entity($user_guid); - if (!$user) $user = get_loggedin_user(); - - $container_guid = (int)$container_guid; - if (!$container_guid) $container_guid = page_owner(); - if (!$container_guid) return true; - - $container = get_entity($container_guid); - - if ($container) - { - - // If the user can edit the container, they can also write to it - if ($container->canEdit($user_guid)) return true; - - // Basics, see if the user is a member of the group. - if ($user && $container instanceof ElggGroup) { - if (!$container->isMember($user)) { - return false; - } else { - return true; - } - } - - // See if anyone else has anything to say - return trigger_plugin_hook('container_permissions_check',$entity_type,array('container' => $container, 'user' => $user), false); - - } - - return false; - } - - /** - * Create a new entity of a given type. - * - * @param string $type The type of the entity (site, user, object). - * @param string $subtype The subtype of the entity. - * @param int $owner_guid The GUID of the object's owner. - * @param int $access_id The access control group to create the entity with. - * @param int $site_guid The site to add this entity to. Leave as 0 (default) for the current site. - * @return mixed The new entity's GUID, or false on failure - */ - function create_entity($type, $subtype, $owner_guid, $access_id, $site_guid = 0, $container_guid = 0) - { - global $CONFIG; - - $type = sanitise_string($type); - $subtype = add_subtype($type, $subtype); - $owner_guid = (int)$owner_guid; - $access_id = (int)$access_id; - $time = time(); - if ($site_guid == 0) - $site_guid = $CONFIG->site_guid; - $site_guid = (int) $site_guid; - if ($container_guid == 0) $container_guid = $owner_guid; - - $user = get_loggedin_user(); - if (!can_write_to_container($user->guid, $owner_guid, $type)) return false; - if ($owner_guid != $container_guid) - if (!can_write_to_container($user->guid, $container_guid, $type)) return false; - - if ($type=="") throw new InvalidParameterException(elgg_echo('InvalidParameterException:EntityTypeNotSet')); - - return insert_data("INSERT into {$CONFIG->dbprefix}entities (type, subtype, owner_guid, site_guid, container_guid, access_id, time_created, time_updated) values ('$type',$subtype, $owner_guid, $site_guid, $container_guid, $access_id, $time, $time)"); - } - - /** - * Retrieve the entity details for a specific GUID, returning it as a stdClass db row. - * - * You will only get an object if a) it exists, b) you have access to it. - * - * @param int $guid The GUID of the object to extract - */ - function get_entity_as_row($guid) - { - global $CONFIG; - - if (!$guid) return false; - - $guid = (int) $guid; - - /*$row = retrieve_cached_entity_row($guid); - if ($row) - { - // We have already cached this object, so retrieve its value from the cache - if (isset($CONFIG->debug) && $CONFIG->debug) - error_log("** Retrieving GUID:$guid from cache"); - - return $row; - } - else - {*/ - // Object not cached, load it. - if (isset($CONFIG->debug) && $CONFIG->debug == true) - error_log("** GUID:$guid loaded from DB"); - - $access = get_access_sql_suffix(); - - return get_data_row("SELECT * from {$CONFIG->dbprefix}entities where guid=$guid and $access"); - //} - } - - /** - * Create an Elgg* object from a given entity row. - */ - function entity_row_to_elggstar($row) - { - if (!($row instanceof stdClass)) - return $row; - - if ((!isset($row->guid)) || (!isset($row->subtype))) - return $row; - - $new_entity = false; - - // Create a memcache cache if we can - static $newentity_cache; - if ((!$newentity_cache) && (is_memcache_available())) - $newentity_cache = new ElggMemcache('new_entity_cache'); - if ($newentity_cache) $new_entity = $newentity_cache->load($row->guid); - if ($new_entity) return $new_entity; - - $classname = get_subtype_class_from_id($row->subtype); - if ($classname!="") - { - if (class_exists($classname)) - { - $new_entity = new $classname($row); - - if (!($new_entity instanceof ElggEntity)) - throw new ClassException(sprintf(elgg_echo('ClassException:ClassnameNotClass'), $classname, 'ElggEntity')); - } - else - error_log(sprintf(elgg_echo('ClassNotFoundException:MissingClass'), $classname)); - } - else - { - switch ($row->type) - { - case 'object' : - $new_entity = new ElggObject($row); break; - case 'user' : - $new_entity = new ElggUser($row); break; - case 'group' : - $new_entity = new ElggGroup($row); break; - case 'site' : - $new_entity = new ElggSite($row); break; - default: throw new InstallationException(sprintf(elgg_echo('InstallationException:TypeNotSupported'), $row->type)); - } - - } - - // Cache entity if we have a cache available - if (($newentity_cache) && ($new_entity)) $newentity_cache->save($new_entity->guid, $new_entity); - - return $new_entity; - } - - /** - * Return the entity for a given guid as the correct object. - * @param int $guid The GUID of the entity - * @return a child of ElggEntity appropriate for the type. - */ - function get_entity($guid) - { - static $newentity_cache; - $new_entity = false; - if ((!$newentity_cache) && (is_memcache_available())) - $newentity_cache = new ElggMemcache('new_entity_cache'); - if ($newentity_cache) $new_entity = $newentity_cache->load($guid); - if ($new_entity) return $new_entity; - - return entity_row_to_elggstar(get_entity_as_row($guid)); - } - - /** - * Return entities matching a given query, or the number thereof - * - * @param string $type The type of entity (eg "user", "object" etc) - * @param string|array $subtype The arbitrary subtype of the entity or array(type1 => array('subtype1', ...'subtypeN'), ...) - * @param int $owner_guid The GUID of the owning user - * @param string $order_by The field to order by; by default, time_created desc - * @param int $limit The number of entities to return; 10 by default - * @param int $offset The indexing offset, 0 by default - * @param boolean $count Set to true to get a count rather than the entities themselves (limits and offsets don't apply in this context). Defaults to false. - * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. - * @param int|array $container_guid The container or containers to get entities from (default: all containers). - * @param int $timelower The earliest time the entity can have been created. Default: all - * @param int $timeupper The latest time the entity can have been created. Default: all - * @return array A list of entities. - */ - function get_entities($type = "", $subtype = "", $owner_guid = 0, $order_by = "", $limit = 10, $offset = 0, $count = false, $site_guid = 0, $container_guid = null, $timelower = 0, $timeupper = 0) - { - global $CONFIG; - - if ($subtype === false || $subtype === null || $subtype === 0) - return false; - - if ($order_by == "") $order_by = "time_created desc"; - $order_by = sanitise_string($order_by); - $limit = (int)$limit; - $offset = (int)$offset; - $site_guid = (int) $site_guid; - $timelower = (int) $timelower; - $timeupper = (int) $timeupper; - if ($site_guid == 0) - $site_guid = $CONFIG->site_guid; - - $where = array(); - - if (is_array($subtype)) { - $tempwhere = ""; - if (sizeof($subtype)) - foreach($subtype as $typekey => $subtypearray) { - foreach($subtypearray as $subtypeval) { - $typekey = sanitise_string($typekey); - if (!empty($subtypeval)) { - if (!$subtypeval = (int) get_subtype_id($typekey, $subtypeval)) - return false; - } else { - // @todo: Setting subtype to 0 when $subtype = '' returns entities with - // no subtype. This is different to the non-array behavior - // but may be required in some cases. - $subtypeval = 0; - } - if (!empty($tempwhere)) $tempwhere .= " or "; - $tempwhere .= "(type = '{$typekey}' and subtype = {$subtypeval})"; - } - } - if (!empty($tempwhere)) $where[] = "({$tempwhere})"; - - } else { - - $type = sanitise_string($type); - if ($subtype !== "" AND !$subtype = get_subtype_id($type, $subtype)) - return false; - - if ($type != "") - $where[] = "type='$type'"; - if ($subtype!=="") - $where[] = "subtype=$subtype"; - } - - if ($owner_guid != "") { - if (!is_array($owner_guid)) { - $owner_array = array($owner_guid); - $owner_guid = (int) $owner_guid; - // $where[] = "owner_guid = '$owner_guid'"; - } else if (sizeof($owner_guid) > 0) { - $owner_array = array_map('sanitise_int', $owner_guid); - // Cast every element to the owner_guid array to int - // $owner_guid = array_map("sanitise_int", $owner_guid); - // $owner_guid = implode(",",$owner_guid); - // $where[] = "owner_guid in ({$owner_guid})"; - } - if (is_null($container_guid)) { - $container_guid = $owner_array; - } - } - if ($site_guid > 0) - $where[] = "site_guid = {$site_guid}"; - - if (!is_null($container_guid)) { - if (is_array($container_guid)) { - foreach($container_guid as $key => $val) $container_guid[$key] = (int) $val; - $where[] = "container_guid in (" . implode(",",$container_guid) . ")"; - } else { - $container_guid = (int) $container_guid; - $where[] = "container_guid = {$container_guid}"; - } - } - if ($timelower) - $where[] = "time_created >= {$timelower}"; - if ($timeupper) - $where[] = "time_created <= {$timeupper}"; - - if (!$count) { - $query = "SELECT * from {$CONFIG->dbprefix}entities where "; - } else { - $query = "SELECT count(guid) as total from {$CONFIG->dbprefix}entities where "; - } - foreach ($where as $w) - $query .= " $w and "; - $query .= get_access_sql_suffix(); // Add access controls - if (!$count) { - $query .= " order by $order_by"; - if ($limit) $query .= " limit $offset, $limit"; // Add order and limit - $dt = get_data($query, "entity_row_to_elggstar"); - return $dt; - } else { - $total = get_data_row($query); - return $total->total; - } - } - - /** - * Returns a viewable list of entities - * - * @see elgg_view_entity_list - * - * @param string $type The type of entity (eg "user", "object" etc) - * @param string $subtype The arbitrary subtype of the entity - * @param int $owner_guid The GUID of the owning user - * @param int $limit The number of entities to display per page (default: 10) - * @param true|false $fullview Whether or not to display the full view (default: true) - * @param true|false $viewtypetoggle Whether or not to allow gallery view - * @param true|false $pagination Display pagination? Default: true - * @return string A viewable list of entities - */ - function list_entities($type= "", $subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = false, $pagination = true) { - - $offset = (int) get_input('offset'); - $count = get_entities($type, $subtype, $owner_guid, "", $limit, $offset, true); - $entities = get_entities($type, $subtype, $owner_guid, "", $limit, $offset); - - return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); - - } - - /** - * Returns a viewable list of entities contained in a number of groups. - * - * @param string $subtype The arbitrary subtype of the entity - * @param int $owner_guid The GUID of the owning user - * @param int $container_guid The GUID of the containing group - * @param int $limit The number of entities to display per page (default: 10) - * @param true|false $fullview Whether or not to display the full view (default: true) - * @return string A viewable list of entities - */ - function list_entities_groups($subtype = "", $owner_guid = 0, $container_guid = 0, $limit = 10, $fullview = true) - { - $offset = (int) get_input('offset'); - $count = get_objects_in_group($container_guid, $subtype, $owner_guid, 0, "", $limit, $offset, true); - $entities = get_objects_in_group($container_guid, $subtype, $owner_guid, 0, "", $limit, $offset); - - return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview); - } - - /** - * Returns a list of months containing content specified by the parameters - * - * @param string $type The type of entity - * @param string $subtype The subtype of entity - * @param int $container_guid The container GUID that the entinties belong to - * @param int $site_guid The site GUID - * @return array|false Either an array of timestamps, or false on failure - */ - function get_entity_dates($type = '', $subtype = '', $container_guid = 0, $site_guid = 0) { - - global $CONFIG; - - $site_guid = (int) $site_guid; - if ($site_guid == 0) - $site_guid = $CONFIG->site_guid; - - $where = array(); - - if ($type != "") { - $type = sanitise_string($type); - $where[] = "type='$type'"; - } - - if (is_array($subtype)) { - $tempwhere = ""; - if (sizeof($subtype)) - foreach($subtype as $typekey => $subtypearray) { - foreach($subtypearray as $subtypeval) { - $typekey = sanitise_string($typekey); - if (!empty($subtypeval)) { - if (!$subtypeval = (int) get_subtype_id($typekey, $subtypeval)) - return false; - } else { - $subtypeval = 0; - } - if (!empty($tempwhere)) $tempwhere .= " or "; - $tempwhere .= "(type = '{$typekey}' and subtype = {$subtypeval})"; - } - } - if (!empty($tempwhere)) $where[] = "({$tempwhere})"; - - } else { - if ($subtype AND !$subtype = get_subtype_id($type, $subtype)) { - return false; - } else { - $where[] = "subtype=$subtype"; - } - } - - if ($container_guid !== 0) { - if (is_array($container_guid)) { - foreach($container_guid as $key => $val) $container_guid[$key] = (int) $val; - $where[] = "container_guid in (" . implode(",",$container_guid) . ")"; - } else { - $container_guid = (int) $container_guid; - $where[] = "container_guid = {$container_guid}"; - } - } - - if ($site_guid > 0) - $where[] = "site_guid = {$site_guid}"; - - $where[] = get_access_sql_suffix(); - - $sql = "SELECT DISTINCT EXTRACT(YEAR_MONTH FROM FROM_UNIXTIME(time_created)) AS yearmonth FROM {$CONFIG->dbprefix}entities where "; - foreach ($where as $w) - $sql .= " $w and "; - $sql .= "1=1"; - if ($result = get_data($sql)) { - $endresult = array(); - foreach($result as $res) { - $endresult[] = $res->yearmonth; - } - return $endresult; - } - return false; - - } - - /** - * Disable an entity but not delete it. - * - * @param int $guid The guid - * @param string $reason Optional reason - */ - function disable_entity($guid, $reason = "", $recursive = true) - { - global $CONFIG; - - $guid = (int)$guid; - $reason = sanitise_string($reason); - - if ($entity = get_entity($guid)) { - if (trigger_elgg_event('disable',$entity->type,$entity)) { - if ($entity->canEdit()) { - - if ($reason) - create_metadata($guid, 'disable_reason', $reason,'', 0, ACCESS_PUBLIC); - - if ($recursive) - { - // Temporary token overriding access controls TODO: Do this better. - static $__RECURSIVE_DELETE_TOKEN; - $__RECURSIVE_DELETE_TOKEN = md5(get_loggedin_userid()); // Make it slightly harder to guess - - $sub_entities = get_data("SELECT * from {$CONFIG->dbprefix}entities WHERE container_guid=$guid or owner_guid=$guid or site_guid=$guid", 'entity_row_to_elggstar'); - if ($sub_entities) { - foreach ($sub_entities as $e) - $e->disable($reason); - } - - $__RECURSIVE_DELETE_TOKEN = null; - } - - $res = update_data("UPDATE {$CONFIG->dbprefix}entities set enabled='no' where guid={$guid}"); - - return $res; - } - } - } - return false; - } - - /** - * Enable an entity again. - * - * @param int $guid - */ - function enable_entity($guid) - { - global $CONFIG; - - $guid = (int)$guid; - - // Override access only visible entities - $access_status = access_get_show_hidden_status(); - access_show_hidden_entities(true); - - if ($entity = get_entity($guid)) { - if (trigger_elgg_event('enable',$entity->type,$entity)) { - if ($entity->canEdit()) { - - access_show_hidden_entities($access_status); - - $result = update_data("UPDATE {$CONFIG->dbprefix}entities set enabled='yes' where guid={$guid}"); - $entity->clearMetaData('disable_reason'); - - return $result; - } - } - } - - access_show_hidden_entities($access_status); - return false; - } - - /** - * Delete a given entity. - * - * @param int $guid - * @param bool $recursive If true (default) then all entities which are owned or contained by $guid will also be deleted. - * Note: this bypasses ownership of sub items. - */ - function delete_entity($guid, $recursive = true) - { - global $CONFIG; - - $guid = (int)$guid; - if ($entity = get_entity($guid)) { - if (trigger_elgg_event('delete',$entity->type,$entity)) { - if ($entity->canEdit()) { - - // Delete contained owned and otherwise releated objects (depth first) - if ($recursive) - { - // Temporary token overriding access controls TODO: Do this better. - static $__RECURSIVE_DELETE_TOKEN; - $__RECURSIVE_DELETE_TOKEN = md5(get_loggedin_userid()); // Make it slightly harder to guess - - $sub_entities = get_data("SELECT * from {$CONFIG->dbprefix}entities WHERE container_guid=$guid or owner_guid=$guid or site_guid=$guid", 'entity_row_to_elggstar'); - if ($sub_entities) { - foreach ($sub_entities as $e) - $e->delete(); - } - - $__RECURSIVE_DELETE_TOKEN = null; - } - - // Now delete the entity itself - $entity->clearMetadata(); - $entity->clearAnnotations(); - $entity->clearRelationships(); - remove_from_river_by_subject($guid); + if ($md && !is_array($md)) { + return $md->value; + } else if ($md && is_array($md)) { + return metadata_array_to_values($md); + } + + return null; + } + + /** + * Class member get overloading + * + * @param string $name + * @return mixed + */ + function __get($name) { return $this->get($name); } + + /** + * Class member set overloading + * + * @param string $name + * @param mixed $value + * @return mixed + */ + function __set($name, $value) { return $this->set($name, $value); } + + /** + * Supporting isset. + * + * @param string $name The name of the attribute or metadata. + * @return bool + */ + function __isset($name) { if ($this->$name!="") return true; else return false; } + + /** + * Supporting unsetting of magic attributes. + * + * @param string $name The name of the attribute or metadata. + */ + function __unset($name) + { + if (array_key_exists($name, $this->attributes)) + $this->attributes[$name] = ""; + else + $this->clearMetaData($name); + } + + /** + * Set a piece of metadata. + * + * @param string $name + * @param mixed $value + * @param string $value_type + * @param bool $multiple + * @return bool + */ + public function setMetaData($name, $value, $value_type = "", $multiple = false) + { + if (is_array($value)) + { + unset($this->temp_metadata[$name]); + remove_metadata($this->getGUID(), $name); + foreach ($value as $v) { + if ((int) $this->guid > 0) { + $multiple = true; + if (!create_metadata($this->getGUID(), $name, $v, $value_type, $this->getOwner(), $this->getAccessID(), $multiple)) return false; + } else { + if (($multiple) && (isset($this->temp_metadata[$name]))) + { + if (!is_array($this->temp_metadata[$name])) + { + $tmp = $this->temp_metadata[$name]; + $this->temp_metadata[$name] = array(); + $this->temp_metadata[$name][] = $tmp; + } + + $this->temp_metadata[$name][] = $value; + } + else + $this->temp_metadata[$name] = $value; + } + } + + return true; + } + else + { + unset($this->temp_metadata[$name]); + if ((int) $this->guid > 0) { + return create_metadata($this->getGUID(), $name, $value, $value_type, $this->getOwner(), $this->getAccessID(), $multiple); + } else { + //$this->temp_metadata[$name] = $value; + + if (($multiple) && (isset($this->temp_metadata[$name]))) + { + if (!is_array($this->temp_metadata[$name])) + { + $tmp = $this->temp_metadata[$name]; + $this->temp_metadata[$name] = array(); + $this->temp_metadata[$name][] = $tmp; + } + + $this->temp_metadata[$name][] = $value; + } + else + $this->temp_metadata[$name] = $value; + + return true; + } + } + } + + /** + * Clear metadata. + */ + public function clearMetaData($name = "") + { + if (empty($name)) { + return clear_metadata($this->getGUID()); + } else { + return remove_metadata($this->getGUID(),$name); + } + } + + /** + * Remove all entities associated with this entity + * + * @return true + */ + public function clearRelationships() { + remove_entity_relationships($this->getGUID()); + remove_entity_relationships($this->getGUID(),"",true); + return true; + } + + /** + * Add a relationship. + * + * @param int $guid Relationship to link to. + * @param string $relationship The type of relationship. + */ + public function addRelationship($guid, $relationship) + { + return add_entity_relationship($this->getGUID(), $relationship, $guid); + } + + function setPrivateSetting($name, $value) { + return set_private_setting($this->getGUID(), $name, $value); + } + + function getPrivateSetting($name) { + return get_private_setting($this->getGUID(), $name); + } + + function removePrivateSetting($name) { + return remove_private_setting($this->getGUID(), $name); + } + + /** + * Adds an annotation to an entity. By default, the type is detected automatically; however, + * it can also be set. Note that by default, annotations are private. + * + * @param string $name + * @param mixed $value + * @param int $access_id + * @param int $owner_id + * @param string $vartype + */ + function annotate($name, $value, $access_id = ACCESS_PRIVATE, $owner_id = 0, $vartype = "") + { + if ((int) $this->guid > 0) { + return create_annotation($this->getGUID(), $name, $value, $vartype, $owner_id, $access_id); + } else { + $this->temp_annotations[$name] = $value; + } + return true; + } + + /** + * Get the annotations for an entity. + * + * @param string $name + * @param int $limit + * @param int $offset + * @param string $order + */ + function getAnnotations($name, $limit = 50, $offset = 0, $order="asc") + { + if ((int) ($this->guid) > 0) { + return get_annotations($this->getGUID(), "", "", $name, "", 0, $limit, $offset, $order); + } else { + return $this->temp_annotations[$name]; + } + } + + /** + * Remove all annotations or all annotations for this entity. + * + * @param string $name + */ + function clearAnnotations($name = "") + { + return clear_annotations($this->getGUID(), $name); + } + + /** + * Return the annotations for the entity. + * + * @param string $name The type of annotation. + */ + function countAnnotations($name = "") + { + return count_annotations($this->getGUID(), "","",$name); + } + + /** + * Get the average of an integer type annotation. + * + * @param string $name + */ + function getAnnotationsAvg($name) + { + return get_annotations_avg($this->getGUID(), "","",$name); + } + + /** + * Get the sum of integer type annotations of a given name. + * + * @param string $name + */ + function getAnnotationsSum($name) + { + return get_annotations_sum($this->getGUID(), "","",$name); + } + + /** + * Get the minimum of integer type annotations of given name. + * + * @param string $name + */ + function getAnnotationsMin($name) + { + return get_annotations_min($this->getGUID(), "","",$name); + } + + /** + * Get the maximum of integer type annotations of a given name. + * + * @param string $name + */ + function getAnnotationsMax($name) + { + return get_annotations_max($this->getGUID(), "","",$name); + } + + /** + * Gets an array of entities from a specific relationship type + * + * @param string $relationship Relationship type (eg "friends") + * @param true|false $inverse Is this an inverse relationship? + * @param int $limit Number of elements to return + * @param int $offset Indexing offset + * @return array|false An array of entities or false on failure + */ + function getEntitiesFromRelationship($relationship, $inverse = false, $limit = 50, $offset = 0) { + return get_entities_from_relationship($relationship,$this->getGUID(),$inverse,"","","","time_created desc",$limit,$offset); + } + + /** + * Gets the number of of entities from a specific relationship type + * + * @param string $relationship Relationship type (eg "friends") + * @return int|false The number of entities or false on failure + */ + function countEntitiesFromRelationship($relationship) { + return get_entities_from_relationship($relationship,$this->getGUID(),false,"","","","time_created desc",null,null,true); + } + + /** + * Determines whether or not the specified user (by default the current one) can edit the entity + * + * @param int $user_guid The user GUID, optionally (defaults to the currently logged in user) + * @return true|false + */ + function canEdit($user_guid = 0) { + return can_edit_entity($this->getGUID(),$user_guid); + } + + /** + * Determines whether or not the specified user (by default the current one) can edit metadata on the entity + * + * @param ElggMetadata $metadata The piece of metadata to specifically check + * @param int $user_guid The user GUID, optionally (defaults to the currently logged in user) + * @return true|false + */ + function canEditMetadata($metadata = null, $user_guid = 0) { + return can_edit_entity_metadata($this->getGUID(), $user_guid, $metadata); + } + + /** + * Returns whether the given user (or current user) has the ability to write to this group. + * + * @param int $user_guid The user. + * @return bool + */ + public function canWriteToContainer($user_guid = 0) + { + return can_write_to_container($user_guid, $this->getGUID()); + } + + /** + * Obtain this entity's access ID + * + * @return int The access ID + */ + public function getAccessID() { return $this->get('access_id'); } + + /** + * Obtain this entity's GUID + * + * @return int GUID + */ + public function getGUID() { return $this->get('guid'); } + + /** + * Get the owner of this entity + * + * @return int The owner GUID + */ + public function getOwner() { return $this->get('owner_guid'); } + + /** + * Returns the actual entity of the user who owns this entity, if any + * + * @return ElggEntity The owning user + */ + public function getOwnerEntity() { return get_entity($this->get('owner_guid')); } + + /** + * Gets the type of entity this is + * + * @return string Entity type + */ + public function getType() { return $this->get('type'); } + + /** + * Returns the subtype of this entity + * + * @return string The entity subtype + */ + public function getSubtype() { + if (!((int) $this->guid > 0)) return $this->get('subtype'); // If this object hasn't been saved, then return the subtype string. + + return get_subtype_from_id($this->get('subtype')); + } + + /** + * Gets the UNIX epoch time that this entity was created + * + * @return int UNIX epoch time + */ + public function getTimeCreated() { return $this->get('time_created'); } + + /** + * Gets the UNIX epoch time that this entity was last updated + * + * @return int UNIX epoch time + */ + public function getTimeUpdated() { return $this->get('time_updated'); } + + /** + * Gets the display URL for this entity + * + * @return string The URL + */ + public function getURL() { + if (!empty($this->url_override)) return $this->url_override; + return get_entity_url($this->getGUID()); + } + + /** + * Overrides the URL returned by getURL + * + * @param string $url The new item URL + * @return string The URL + */ + public function setURL($url) { + $this->url_override = $url; + return $url; + } + + /** + * Return a url for the entity's icon, trying multiple alternatives. + * + * @param string $size Either 'large','medium','small' or 'tiny' + * @return string The url or false if no url could be worked out. + */ + public function getIcon($size = 'medium') + { + if (isset($this->icon_override[$size])) return $this->icon_override[$size]; + return get_entity_icon_url($this, $size); + } + + /** + * Set an icon override for an icon and size. + * + * @param string $url The url of the icon. + * @param string $size The size its for. + * @return bool + */ + public function setIcon($url, $size = 'medium') + { + $url = sanitise_string($url); + $size = sanitise_string($size); + + if (!$this->icon_override) $this->icon_override = array(); + $this->icon_override[$size] = $url; + + return true; + } + + /** + * Tests to see whether the object has been fully loaded. + * + * @return bool + */ + public function isFullyLoaded() { return ! ($this->attributes['tables_loaded'] < $this->attributes['tables_split']); } + + /** + * Save generic attributes to the entities table. + */ + public function save() + { + $guid = (int) $this->guid; + if ($guid > 0) + { + cache_entity($this); + + return update_entity( + $this->get('guid'), + $this->get('owner_guid'), + $this->get('access_id'), + $this->get('container_guid') + ); + } + else + { + $this->attributes['guid'] = create_entity($this->attributes['type'], $this->attributes['subtype'], $this->attributes['owner_guid'], $this->attributes['access_id'], $this->attributes['site_guid'], $this->attributes['container_guid']); // Create a new entity (nb: using attribute array directly 'cos set function does something special!) + if (!$this->attributes['guid']) throw new IOException(elgg_echo('IOException:BaseEntitySaveFailed')); + + // Save any unsaved metadata TODO: How to capture extra information (access id etc) + if (sizeof($this->temp_metadata) > 0) { + foreach($this->temp_metadata as $name => $value) { + $this->$name = $value; + unset($this->temp_metadata[$name]); + } + } + + // Save any unsaved annotations metadata. TODO: How to capture extra information (access id etc) + if (sizeof($this->temp_annotations) > 0) { + foreach($this->temp_annotations as $name => $value) { + $this->annotate($name, $value); + unset($this->temp_annotations[$name]); + } + } + + // Cache object handle + if ($this->attributes['guid']) cache_entity($this); + + return $this->attributes['guid']; + } + } + + /** + * Load the basic entity information and populate base attributes array. + * + * @param int $guid + */ + protected function load($guid) + { + $row = get_entity_as_row($guid); + + if ($row) + { + // Create the array if necessary - all subclasses should test before creating + if (!is_array($this->attributes)) $this->attributes = array(); + + // Now put these into the attributes array as core values + $objarray = (array) $row; + foreach($objarray as $key => $value) + $this->attributes[$key] = $value; + + // Increment the portion counter + if (!$this->isFullyLoaded()) $this->attributes['tables_loaded'] ++; + + // Cache object handle + if ($this->attributes['guid']) cache_entity($this); + + return true; + } + + return false; + } + + /** + * Disable this entity. + * + * @param string $reason Optional reason + * @param bool $recursive Recursively disable all contained entities? + */ + public function disable($reason = "", $recursive = true) + { + return disable_entity($this->get('guid'), $reason, $recursive); + } + + /** + * Re-enable this entity. + */ + public function enable() + { + return enable_entity($this->get('guid')); + } + + /** + * Is this entity enabled? + * + * @return boolean + */ + public function isEnabled() + { + if ($this->enabled == 'yes') + return true; + + return false; + } + + /** + * Delete this entity. + */ + public function delete() + { + return delete_entity($this->get('guid')); + } + + // LOCATABLE INTERFACE ///////////////////////////////////////////////////////////// + + /** Interface to set the location */ + public function setLocation($location) + { + $location = sanitise_string($location); + + $this->location = $location; + + return true; + } + + /** + * Set latitude and longitude tags for a given entity. + * + * @param float $lat + * @param float $long + */ + public function setLatLong($lat, $long) + { + $lat = sanitise_string($lat); + $long = sanitise_string($long); + + $this->set('geo:lat', $lat); + $this->set('geo:long', $long); + + return true; + } + + /** + * Get the contents of the ->geo:lat field. + * + */ + public function getLatitude() { return $this->get('geo:lat'); } + + /** + * Get the contents of the ->geo:lat field. + * + */ + public function getLongitude() { return $this->get('geo:long'); } + + /** + * Get the ->location metadata. + * + */ + public function getLocation() { return $this->get('location'); } + + // NOTABLE INTERFACE /////////////////////////////////////////////////////////////// + + /** + * Calendar functionality. + * This function sets the time of an object on a calendar listing. + * + * @param int $hour If ommitted, now is assumed. + * @param int $minute If ommitted, now is assumed. + * @param int $second If ommitted, now is assumed. + * @param int $day If ommitted, now is assumed. + * @param int $month If ommitted, now is assumed. + * @param int $year If ommitted, now is assumed. + * @param int $duration Duration of event, remainder of the day is assumed. + */ + public function setCalendarTimeAndDuration($hour = NULL, $minute = NULL, $second = NULL, $day = NULL, $month = NULL, $year = NULL, $duration = NULL) + { + $start = mktime($hour, $minute, $second, $month, $day, $year); + $end = $start + abs($duration); + if (!$duration) + $end = get_day_end($day,$month,$year); + + $this->calendar_start = $start; + $this->calendar_end = $end; + + return true; + } + + /** + * Return the start timestamp. + */ + public function getCalendarStartTime() { return (int)$this->calendar_start; } + + /** + * Return the end timestamp. + */ + public function getCalendarEndTime() { return (int)$this->calendar_end; } + + // EXPORTABLE INTERFACE //////////////////////////////////////////////////////////// + + /** + * Return an array of fields which can be exported. + */ + public function getExportableValues() + { + return array( + 'guid', + 'type', + 'subtype', + 'time_created', + 'container_guid', + 'owner_guid', + ); + } + + /** + * Export this class into an array of ODD Elements containing all necessary fields. + * Override if you wish to return more information than can be found in $this->attributes (shouldn't happen) + */ + public function export() + { + $tmp = array(); + + // Generate uuid + $uuid = guid_to_uuid($this->getGUID()); + + // Create entity + $odd = new ODDEntity( + $uuid, + $this->attributes['type'], + get_subtype_from_id($this->attributes['subtype']) + ); + + $tmp[] = $odd; + + $exportable_values = $this->getExportableValues(); + + // Now add its attributes + foreach ($this->attributes as $k => $v) + { + $meta = NULL; + + if (in_array( $k, $exportable_values)) { + switch ($k) + { + case 'guid' : // Dont use guid in OpenDD + case 'type' : // Type and subtype already taken care of + case 'subtype' : + break; + + case 'time_created' : // Created = published + $odd->setAttribute('published', date("r", $v)); + break; + + case 'site_guid' : // Container + $k = 'site_uuid'; + $v = guid_to_uuid($v); + $meta = new ODDMetaData($uuid . "attr/$k/", $uuid, $k, $v); + break; + + case 'container_guid' : // Container + $k = 'container_uuid'; + $v = guid_to_uuid($v); + $meta = new ODDMetaData($uuid . "attr/$k/", $uuid, $k, $v); + break; + + case 'owner_guid' : // Convert owner guid to uuid, this will be stored in metadata + $k = 'owner_uuid'; + $v = guid_to_uuid($v); + $meta = new ODDMetaData($uuid . "attr/$k/", $uuid, $k, $v); + break; + + default : + $meta = new ODDMetaData($uuid . "attr/$k/", $uuid, $k, $v); + } + + // set the time of any metadata created + if ($meta) + { + $meta->setAttribute('published', date("r",$this->time_created)); + $tmp[] = $meta; + } + } + } + + // Now we do something a bit special. + /* + * This provides a rendered view of the entity to foreign sites. + */ + + elgg_set_viewtype('default'); + $view = elgg_view_entity($this, true); + elgg_set_viewtype(); + + $tmp[] = new ODDMetaData($uuid . "volatile/renderedentity/", $uuid, 'renderedentity', $view , 'volatile'); + + + return $tmp; + } + + // IMPORTABLE INTERFACE //////////////////////////////////////////////////////////// + + /** + * Import data from an parsed xml data array. + * + * @param array $data + * @param int $version + */ + public function import(ODD $data) + { + if (!($data instanceof ODDEntity)) + throw new InvalidParameterException(elgg_echo('InvalidParameterException:UnexpectedODDClass')); + + // Set type and subtype + $this->attributes['type'] = $data->getAttribute('class'); + $this->attributes['subtype'] = $data->getAttribute('subclass'); + + // Set owner + $this->attributes['owner_guid'] = get_loggedin_userid(); // Import as belonging to importer. + + // Set time + $this->attributes['time_created'] = strtotime($data->getAttribute('published')); + $this->attributes['time_updated'] = time(); + + return true; + } + + // SYSTEM LOG INTERFACE //////////////////////////////////////////////////////////// + + /** + * Return an identification for the object for storage in the system log. + * This id must be an integer. + * + * @return int + */ + public function getSystemLogID() { return $this->getGUID(); } + + /** + * Return the class name of the object. + */ + public function getClassName() { return get_class($this); } + + /** + * For a given ID, return the object associated with it. + * This is used by the river functionality primarily. + * This is useful for checking access permissions etc on objects. + */ + public function getObjectFromID($id) { return get_entity($id); } + + /** + * Return the GUID of the owner of this object. + */ + public function getObjectOwnerGUID() { return $this->owner_guid; } + + // ITERATOR INTERFACE ////////////////////////////////////////////////////////////// + /* + * This lets an entity's attributes be displayed using foreach as a normal array. + * Example: http://www.sitepoint.com/print/php5-standard-library + */ + + private $valid = FALSE; + + function rewind() + { + $this->valid = (FALSE !== reset($this->attributes)); + } + + function current() + { + return current($this->attributes); + } + + function key() + { + return key($this->attributes); + } + + function next() + { + $this->valid = (FALSE !== next($this->attributes)); + } + + function valid() + { + return $this->valid; + } + + // ARRAY ACCESS INTERFACE ////////////////////////////////////////////////////////// + /* + * This lets an entity's attributes be accessed like an associative array. + * Example: http://www.sitepoint.com/print/php5-standard-library + */ + + function offsetSet($key, $value) + { + if ( array_key_exists($key, $this->attributes) ) { + $this->attributes[$key] = $value; + } + } + + function offsetGet($key) + { + if ( array_key_exists($key, $this->attributes) ) { + return $this->attributes[$key]; + } + } + + function offsetUnset($key) + { + if ( array_key_exists($key, $this->attributes) ) { + $this->attributes[$key] = ""; // Full unsetting is dangerious for our objects + } + } + + function offsetExists($offset) + { + return array_key_exists($offset, $this->attributes); + } + } + + /** + * Initialise the entity cache. + */ + function initialise_entity_cache() + { + global $ENTITY_CACHE; + + if (!$ENTITY_CACHE) + $ENTITY_CACHE = array(); //select_default_memcache('entity_cache'); // TODO: Replace with memcache? + } + + /** + * Invalidate this class' entry in the cache. + * + * @param int $guid The guid + */ + function invalidate_cache_for_entity($guid) + { + global $ENTITY_CACHE; + + $guid = (int)$guid; + + unset($ENTITY_CACHE[$guid]); + //$ENTITY_CACHE->delete($guid); + } + + /** + * Cache an entity. + * + * @param ElggEntity $entity Entity to cache + */ + function cache_entity(ElggEntity $entity) + { + global $ENTITY_CACHE; + + $ENTITY_CACHE[$entity->guid] = $entity; + } + + /** + * Retrieve a entity from the cache. + * + * @param int $guid The guid + */ + function retrieve_cached_entity($guid) + { + global $ENTITY_CACHE; + + $guid = (int)$guid; + + if (isset($ENTITY_CACHE[$guid])) + if ($ENTITY_CACHE[$guid]->isFullyLoaded()) return $ENTITY_CACHE[$guid]; + + return false; + } + + /** + * As retrieve_cached_entity, but returns the result as a stdClass (compatible with load functions that + * expect a database row.) + * + * @param int $guid The guid + */ + function retrieve_cached_entity_row($guid) + { + $obj = retrieve_cached_entity($guid); + if ($obj) + { + $tmp = new stdClass; + + foreach ($obj as $k => $v) + $tmp->$k = $v; + + return $tmp; + } + + return false; + } + + /** + * Return the integer ID for a given subtype, or false. + * + * TODO: Move to a nicer place? + * + * @param string $type + * @param string $subtype + */ + function get_subtype_id($type, $subtype) + { + global $CONFIG, $SUBTYPE_CACHE; + + $type = sanitise_string($type); + $subtype = sanitise_string($subtype); + + if ($subtype=="") return $subtype; + + // Todo: cache here? Or is looping less efficient that going to the db each time? + + $result = get_data_row("SELECT * from {$CONFIG->dbprefix}entity_subtypes where type='$type' and subtype='$subtype'"); + + if ($result) { + + if (!$SUBTYPE_CACHE) + $SUBTYPE_CACHE = array(); //select_default_memcache('subtype_cache'); + + $SUBTYPE_CACHE[$result->id] = $result; + return $result->id; + } + + return 0; + } + + /** + * For a given subtype ID, return its identifier text. + * + * TODO: Move to a nicer place? + * + * @param int $subtype_id + */ + function get_subtype_from_id($subtype_id) + { + global $CONFIG, $SUBTYPE_CACHE; + + $subtype_id = (int)$subtype_id; + + if (!$subtype_id) return false; + + if (isset($SUBTYPE_CACHE[$subtype_id])) + return $SUBTYPE_CACHE[$subtype_id]->subtype; + + $result = get_data_row("SELECT * from {$CONFIG->dbprefix}entity_subtypes where id=$subtype_id"); + if ($result) { + + if (!$SUBTYPE_CACHE) + $SUBTYPE_CACHE = array(); //select_default_memcache('subtype_cache'); + + $SUBTYPE_CACHE[$subtype_id] = $result; + return $result->subtype; + } + + return false; + } + + /** + * This function tests to see if a subtype has a registered class handler. + * + * @param string $type The type + * @param string $subtype The subtype + * @return a class name or null + */ + function get_subtype_class($type, $subtype) + { + global $CONFIG, $SUBTYPE_CACHE; + + $type = sanitise_string($type); + $subtype = sanitise_string($subtype); + + // Todo: cache here? Or is looping less efficient that going to the db each time? + + $result = get_data_row("SELECT * from {$CONFIG->dbprefix}entity_subtypes where type='$type' and subtype='$subtype'"); + if ($result) { + + if (!$SUBTYPE_CACHE) + $SUBTYPE_CACHE = array(); //select_default_memcache('subtype_cache'); + + $SUBTYPE_CACHE[$result->id] = $result; + return $result->class; + } + + return NULL; + } + + /** + * This function tests to see if a subtype has a registered class handler by its id. + * + * @param int $subtype_id The subtype + * @return a class name or null + */ + function get_subtype_class_from_id($subtype_id) + { + global $CONFIG, $SUBTYPE_CACHE; + + $subtype_id = (int)$subtype_id; + + if (!$subtype_id) return false; + + if (isset($SUBTYPE_CACHE[$subtype_id])) + return $SUBTYPE_CACHE[$subtype_id]->class; + + $result = get_data_row("SELECT * from {$CONFIG->dbprefix}entity_subtypes where id=$subtype_id"); + if ($result) { + + if (!$SUBTYPE_CACHE) + $SUBTYPE_CACHE = array(); //select_default_memcache('subtype_cache'); + + $SUBTYPE_CACHE[$subtype_id] = $result; + return $result->class; + } + + return NULL; + } + + /** + * This function will register a new subtype, returning its ID as required. + * + * @param string $type The type you're subtyping + * @param string $subtype The subtype label + * @param string $class Optional class handler (if you don't want it handled by the generic elgg handler for the type) + */ + function add_subtype($type, $subtype, $class = "") + { + global $CONFIG; + $type = sanitise_string($type); + $subtype = sanitise_string($subtype); + $class = sanitise_string($class); + + // Short circuit if no subtype is given + if ($subtype == "") + return 0; + + $id = get_subtype_id($type, $subtype); + + if ($id==0) + return insert_data("insert into {$CONFIG->dbprefix}entity_subtypes (type, subtype, class) values ('$type','$subtype','$class')"); + + return $id; + } + + /** + * Update an existing entity. + * + * @param int $guid + * @param int $owner_guid + * @param int $access_id + * @param int $container_guid + */ + function update_entity($guid, $owner_guid, $access_id, $container_guid = null) + { + global $CONFIG, $ENTITY_CACHE; + + $guid = (int)$guid; + $owner_guid = (int)$owner_guid; + $access_id = (int)$access_id; + $container_guid = (int) $container_guid; + if (is_null($container_guid)) $container_guid = $owner_guid; + $time = time(); + + $entity = get_entity($guid); + + if ($entity->canEdit()) { + + if (trigger_elgg_event('update',$entity->type,$entity)) { + $ret = update_data("UPDATE {$CONFIG->dbprefix}entities set owner_guid='$owner_guid', access_id='$access_id', container_guid='$container_guid', time_updated='$time' WHERE guid=$guid"); + + if ($entity instanceof ElggObject) + update_river_access_by_object($guid,$access_id); + + // If memcache is available then delete this entry from the cache + static $newentity_cache; + if ((!$newentity_cache) && (is_memcache_available())) + $newentity_cache = new ElggMemcache('new_entity_cache'); + if ($newentity_cache) $new_entity = $newentity_cache->delete($guid); + + // Handle cases where there was no error BUT no rows were updated! + if ($ret===false) + return false; + + return true; + } + + } + } + + /** + * Determine whether a given user is able to write to a given container. + * + * @param int $user_guid The user guid, or 0 for get_loggedin_userid() + * @param int $container_guid The container, or 0 for the current page owner. + */ + function can_write_to_container($user_guid = 0, $container_guid = 0, $entity_type = 'all') + { + global $CONFIG; + + $user_guid = (int)$user_guid; + $user = get_entity($user_guid); + if (!$user) $user = get_loggedin_user(); + + $container_guid = (int)$container_guid; + if (!$container_guid) $container_guid = page_owner(); + if (!$container_guid) return true; + + $container = get_entity($container_guid); + + if ($container) + { + + // If the user can edit the container, they can also write to it + if ($container->canEdit($user_guid)) return true; + + // Basics, see if the user is a member of the group. + if ($user && $container instanceof ElggGroup) { + if (!$container->isMember($user)) { + return false; + } else { + return true; + } + } + + // See if anyone else has anything to say + return trigger_plugin_hook('container_permissions_check',$entity_type,array('container' => $container, 'user' => $user), false); + + } + + return false; + } + + /** + * Create a new entity of a given type. + * + * @param string $type The type of the entity (site, user, object). + * @param string $subtype The subtype of the entity. + * @param int $owner_guid The GUID of the object's owner. + * @param int $access_id The access control group to create the entity with. + * @param int $site_guid The site to add this entity to. Leave as 0 (default) for the current site. + * @return mixed The new entity's GUID, or false on failure + */ + function create_entity($type, $subtype, $owner_guid, $access_id, $site_guid = 0, $container_guid = 0) + { + global $CONFIG; + + $type = sanitise_string($type); + $subtype = add_subtype($type, $subtype); + $owner_guid = (int)$owner_guid; + $access_id = (int)$access_id; + $time = time(); + if ($site_guid == 0) + $site_guid = $CONFIG->site_guid; + $site_guid = (int) $site_guid; + if ($container_guid == 0) $container_guid = $owner_guid; + + $user = get_loggedin_user(); + if (!can_write_to_container($user->guid, $owner_guid, $type)) return false; + if ($owner_guid != $container_guid) + if (!can_write_to_container($user->guid, $container_guid, $type)) return false; + + if ($type=="") throw new InvalidParameterException(elgg_echo('InvalidParameterException:EntityTypeNotSet')); + + return insert_data("INSERT into {$CONFIG->dbprefix}entities (type, subtype, owner_guid, site_guid, container_guid, access_id, time_created, time_updated) values ('$type',$subtype, $owner_guid, $site_guid, $container_guid, $access_id, $time, $time)"); + } + + /** + * Retrieve the entity details for a specific GUID, returning it as a stdClass db row. + * + * You will only get an object if a) it exists, b) you have access to it. + * + * @param int $guid The GUID of the object to extract + */ + function get_entity_as_row($guid) + { + global $CONFIG; + + if (!$guid) return false; + + $guid = (int) $guid; + + /*$row = retrieve_cached_entity_row($guid); + if ($row) + { + // We have already cached this object, so retrieve its value from the cache + if (isset($CONFIG->debug) && $CONFIG->debug) + error_log("** Retrieving GUID:$guid from cache"); + + return $row; + } + else + {*/ + // Object not cached, load it. + if (isset($CONFIG->debug) && $CONFIG->debug == true) + error_log("** GUID:$guid loaded from DB"); + + $access = get_access_sql_suffix(); + + return get_data_row("SELECT * from {$CONFIG->dbprefix}entities where guid=$guid and $access"); + //} + } + + /** + * Create an Elgg* object from a given entity row. + */ + function entity_row_to_elggstar($row) + { + if (!($row instanceof stdClass)) + return $row; + + if ((!isset($row->guid)) || (!isset($row->subtype))) + return $row; + + $new_entity = false; + + // Create a memcache cache if we can + static $newentity_cache; + if ((!$newentity_cache) && (is_memcache_available())) + $newentity_cache = new ElggMemcache('new_entity_cache'); + if ($newentity_cache) $new_entity = $newentity_cache->load($row->guid); + if ($new_entity) return $new_entity; + + $classname = get_subtype_class_from_id($row->subtype); + if ($classname!="") + { + if (class_exists($classname)) + { + $new_entity = new $classname($row); + + if (!($new_entity instanceof ElggEntity)) + throw new ClassException(sprintf(elgg_echo('ClassException:ClassnameNotClass'), $classname, 'ElggEntity')); + } + else + error_log(sprintf(elgg_echo('ClassNotFoundException:MissingClass'), $classname)); + } + else + { + switch ($row->type) + { + case 'object' : + $new_entity = new ElggObject($row); break; + case 'user' : + $new_entity = new ElggUser($row); break; + case 'group' : + $new_entity = new ElggGroup($row); break; + case 'site' : + $new_entity = new ElggSite($row); break; + default: throw new InstallationException(sprintf(elgg_echo('InstallationException:TypeNotSupported'), $row->type)); + } + + } + + // Cache entity if we have a cache available + if (($newentity_cache) && ($new_entity)) $newentity_cache->save($new_entity->guid, $new_entity); + + return $new_entity; + } + + /** + * Return the entity for a given guid as the correct object. + * @param int $guid The GUID of the entity + * @return a child of ElggEntity appropriate for the type. + */ + function get_entity($guid) + { + static $newentity_cache; + $new_entity = false; + if ((!$newentity_cache) && (is_memcache_available())) + $newentity_cache = new ElggMemcache('new_entity_cache'); + if ($newentity_cache) $new_entity = $newentity_cache->load($guid); + if ($new_entity) return $new_entity; + + return entity_row_to_elggstar(get_entity_as_row($guid)); + } + + /** + * Return entities matching a given query, or the number thereof + * + * @param string $type The type of entity (eg "user", "object" etc) + * @param string|array $subtype The arbitrary subtype of the entity or array(type1 => array('subtype1', ...'subtypeN'), ...) + * @param int $owner_guid The GUID of the owning user + * @param string $order_by The field to order by; by default, time_created desc + * @param int $limit The number of entities to return; 10 by default + * @param int $offset The indexing offset, 0 by default + * @param boolean $count Set to true to get a count rather than the entities themselves (limits and offsets don't apply in this context). Defaults to false. + * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. + * @param int|array $container_guid The container or containers to get entities from (default: all containers). + * @param int $timelower The earliest time the entity can have been created. Default: all + * @param int $timeupper The latest time the entity can have been created. Default: all + * @return array A list of entities. + */ + function get_entities($type = "", $subtype = "", $owner_guid = 0, $order_by = "", $limit = 10, $offset = 0, $count = false, $site_guid = 0, $container_guid = null, $timelower = 0, $timeupper = 0) + { + global $CONFIG; + + if ($subtype === false || $subtype === null || $subtype === 0) + return false; + + if ($order_by == "") $order_by = "time_created desc"; + $order_by = sanitise_string($order_by); + $limit = (int)$limit; + $offset = (int)$offset; + $site_guid = (int) $site_guid; + $timelower = (int) $timelower; + $timeupper = (int) $timeupper; + if ($site_guid == 0) + $site_guid = $CONFIG->site_guid; + + $where = array(); + + if (is_array($subtype)) { + $tempwhere = ""; + if (sizeof($subtype)) + foreach($subtype as $typekey => $subtypearray) { + foreach($subtypearray as $subtypeval) { + $typekey = sanitise_string($typekey); + if (!empty($subtypeval)) { + if (!$subtypeval = (int) get_subtype_id($typekey, $subtypeval)) + return false; + } else { + // @todo: Setting subtype to 0 when $subtype = '' returns entities with + // no subtype. This is different to the non-array behavior + // but may be required in some cases. + $subtypeval = 0; + } + if (!empty($tempwhere)) $tempwhere .= " or "; + $tempwhere .= "(type = '{$typekey}' and subtype = {$subtypeval})"; + } + } + if (!empty($tempwhere)) $where[] = "({$tempwhere})"; + + } else { + + $type = sanitise_string($type); + if ($subtype !== "" AND !$subtype = get_subtype_id($type, $subtype)) + return false; + + if ($type != "") + $where[] = "type='$type'"; + if ($subtype!=="") + $where[] = "subtype=$subtype"; + } + + if ($owner_guid != "") { + if (!is_array($owner_guid)) { + $owner_array = array($owner_guid); + $owner_guid = (int) $owner_guid; + // $where[] = "owner_guid = '$owner_guid'"; + } else if (sizeof($owner_guid) > 0) { + $owner_array = array_map('sanitise_int', $owner_guid); + // Cast every element to the owner_guid array to int + // $owner_guid = array_map("sanitise_int", $owner_guid); + // $owner_guid = implode(",",$owner_guid); + // $where[] = "owner_guid in ({$owner_guid})"; + } + if (is_null($container_guid)) { + $container_guid = $owner_array; + } + } + if ($site_guid > 0) + $where[] = "site_guid = {$site_guid}"; + + if (!is_null($container_guid)) { + if (is_array($container_guid)) { + foreach($container_guid as $key => $val) $container_guid[$key] = (int) $val; + $where[] = "container_guid in (" . implode(",",$container_guid) . ")"; + } else { + $container_guid = (int) $container_guid; + $where[] = "container_guid = {$container_guid}"; + } + } + if ($timelower) + $where[] = "time_created >= {$timelower}"; + if ($timeupper) + $where[] = "time_created <= {$timeupper}"; + + if (!$count) { + $query = "SELECT * from {$CONFIG->dbprefix}entities where "; + } else { + $query = "SELECT count(guid) as total from {$CONFIG->dbprefix}entities where "; + } + foreach ($where as $w) + $query .= " $w and "; + $query .= get_access_sql_suffix(); // Add access controls + if (!$count) { + $query .= " order by $order_by"; + if ($limit) $query .= " limit $offset, $limit"; // Add order and limit + $dt = get_data($query, "entity_row_to_elggstar"); + return $dt; + } else { + $total = get_data_row($query); + return $total->total; + } + } + + /** + * Returns a viewable list of entities + * + * @see elgg_view_entity_list + * + * @param string $type The type of entity (eg "user", "object" etc) + * @param string $subtype The arbitrary subtype of the entity + * @param int $owner_guid The GUID of the owning user + * @param int $limit The number of entities to display per page (default: 10) + * @param true|false $fullview Whether or not to display the full view (default: true) + * @param true|false $viewtypetoggle Whether or not to allow gallery view + * @param true|false $pagination Display pagination? Default: true + * @return string A viewable list of entities + */ + function list_entities($type= "", $subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = false, $pagination = true) { + + $offset = (int) get_input('offset'); + $count = get_entities($type, $subtype, $owner_guid, "", $limit, $offset, true); + $entities = get_entities($type, $subtype, $owner_guid, "", $limit, $offset); + + return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); + + } + + /** + * Returns a viewable list of entities contained in a number of groups. + * + * @param string $subtype The arbitrary subtype of the entity + * @param int $owner_guid The GUID of the owning user + * @param int $container_guid The GUID of the containing group + * @param int $limit The number of entities to display per page (default: 10) + * @param true|false $fullview Whether or not to display the full view (default: true) + * @return string A viewable list of entities + */ + function list_entities_groups($subtype = "", $owner_guid = 0, $container_guid = 0, $limit = 10, $fullview = true) + { + $offset = (int) get_input('offset'); + $count = get_objects_in_group($container_guid, $subtype, $owner_guid, 0, "", $limit, $offset, true); + $entities = get_objects_in_group($container_guid, $subtype, $owner_guid, 0, "", $limit, $offset); + + return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview); + } + + /** + * Returns a list of months containing content specified by the parameters + * + * @param string $type The type of entity + * @param string $subtype The subtype of entity + * @param int $container_guid The container GUID that the entinties belong to + * @param int $site_guid The site GUID + * @return array|false Either an array of timestamps, or false on failure + */ + function get_entity_dates($type = '', $subtype = '', $container_guid = 0, $site_guid = 0) { + + global $CONFIG; + + $site_guid = (int) $site_guid; + if ($site_guid == 0) + $site_guid = $CONFIG->site_guid; + + $where = array(); + + if ($type != "") { + $type = sanitise_string($type); + $where[] = "type='$type'"; + } + + if (is_array($subtype)) { + $tempwhere = ""; + if (sizeof($subtype)) + foreach($subtype as $typekey => $subtypearray) { + foreach($subtypearray as $subtypeval) { + $typekey = sanitise_string($typekey); + if (!empty($subtypeval)) { + if (!$subtypeval = (int) get_subtype_id($typekey, $subtypeval)) + return false; + } else { + $subtypeval = 0; + } + if (!empty($tempwhere)) $tempwhere .= " or "; + $tempwhere .= "(type = '{$typekey}' and subtype = {$subtypeval})"; + } + } + if (!empty($tempwhere)) $where[] = "({$tempwhere})"; + + } else { + if ($subtype AND !$subtype = get_subtype_id($type, $subtype)) { + return false; + } else { + $where[] = "subtype=$subtype"; + } + } + + if ($container_guid !== 0) { + if (is_array($container_guid)) { + foreach($container_guid as $key => $val) $container_guid[$key] = (int) $val; + $where[] = "container_guid in (" . implode(",",$container_guid) . ")"; + } else { + $container_guid = (int) $container_guid; + $where[] = "container_guid = {$container_guid}"; + } + } + + if ($site_guid > 0) + $where[] = "site_guid = {$site_guid}"; + + $where[] = get_access_sql_suffix(); + + $sql = "SELECT DISTINCT EXTRACT(YEAR_MONTH FROM FROM_UNIXTIME(time_created)) AS yearmonth FROM {$CONFIG->dbprefix}entities where "; + foreach ($where as $w) + $sql .= " $w and "; + $sql .= "1=1"; + if ($result = get_data($sql)) { + $endresult = array(); + foreach($result as $res) { + $endresult[] = $res->yearmonth; + } + return $endresult; + } + return false; + + } + + /** + * Disable an entity but not delete it. + * + * @param int $guid The guid + * @param string $reason Optional reason + */ + function disable_entity($guid, $reason = "", $recursive = true) + { + global $CONFIG; + + $guid = (int)$guid; + $reason = sanitise_string($reason); + + if ($entity = get_entity($guid)) { + if (trigger_elgg_event('disable',$entity->type,$entity)) { + if ($entity->canEdit()) { + + if ($reason) + create_metadata($guid, 'disable_reason', $reason,'', 0, ACCESS_PUBLIC); + + if ($recursive) + { + // Temporary token overriding access controls TODO: Do this better. + static $__RECURSIVE_DELETE_TOKEN; + $__RECURSIVE_DELETE_TOKEN = md5(get_loggedin_userid()); // Make it slightly harder to guess + + $sub_entities = get_data("SELECT * from {$CONFIG->dbprefix}entities WHERE container_guid=$guid or owner_guid=$guid or site_guid=$guid", 'entity_row_to_elggstar'); + if ($sub_entities) { + foreach ($sub_entities as $e) + $e->disable($reason); + } + + $__RECURSIVE_DELETE_TOKEN = null; + } + + $res = update_data("UPDATE {$CONFIG->dbprefix}entities set enabled='no' where guid={$guid}"); + + return $res; + } + } + } + return false; + } + + /** + * Enable an entity again. + * + * @param int $guid + */ + function enable_entity($guid) + { + global $CONFIG; + + $guid = (int)$guid; + + // Override access only visible entities + $access_status = access_get_show_hidden_status(); + access_show_hidden_entities(true); + + if ($entity = get_entity($guid)) { + if (trigger_elgg_event('enable',$entity->type,$entity)) { + if ($entity->canEdit()) { + + access_show_hidden_entities($access_status); + + $result = update_data("UPDATE {$CONFIG->dbprefix}entities set enabled='yes' where guid={$guid}"); + $entity->clearMetaData('disable_reason'); + + return $result; + } + } + } + + access_show_hidden_entities($access_status); + return false; + } + + /** + * Delete a given entity. + * + * @param int $guid + * @param bool $recursive If true (default) then all entities which are owned or contained by $guid will also be deleted. + * Note: this bypasses ownership of sub items. + */ + function delete_entity($guid, $recursive = true) + { + global $CONFIG; + + $guid = (int)$guid; + if ($entity = get_entity($guid)) { + if (trigger_elgg_event('delete',$entity->type,$entity)) { + if ($entity->canEdit()) { + + // Delete contained owned and otherwise releated objects (depth first) + if ($recursive) + { + // Temporary token overriding access controls TODO: Do this better. + static $__RECURSIVE_DELETE_TOKEN; + $__RECURSIVE_DELETE_TOKEN = md5(get_loggedin_userid()); // Make it slightly harder to guess + + $sub_entities = get_data("SELECT * from {$CONFIG->dbprefix}entities WHERE container_guid=$guid or owner_guid=$guid or site_guid=$guid", 'entity_row_to_elggstar'); + if ($sub_entities) { + foreach ($sub_entities as $e) + $e->delete(); + } + + $__RECURSIVE_DELETE_TOKEN = null; + } + + // Now delete the entity itself + $entity->clearMetadata(); + $entity->clearAnnotations(); + $entity->clearRelationships(); + remove_from_river_by_subject($guid); remove_from_river_by_object($guid); - remove_all_private_settings($guid); + remove_all_private_settings($guid); $res = delete_data("DELETE from {$CONFIG->dbprefix}entities where guid={$guid}"); if ($res) { $sub_table = ""; - // Where appropriate delete the sub table - switch ($entity->type) - { - case 'object' : $sub_table = $CONFIG->dbprefix . 'objects_entity'; break; - case 'user' : $sub_table = $CONFIG->dbprefix . 'users_entity'; break; - case 'group' : $sub_table = $CONFIG->dbprefix . 'groups_entity'; break; - case 'site' : $sub_table = $CONFIG->dbprefix . 'sites_entity'; break; - } + // Where appropriate delete the sub table + switch ($entity->type) + { + case 'object' : $sub_table = $CONFIG->dbprefix . 'objects_entity'; break; + case 'user' : $sub_table = $CONFIG->dbprefix . 'users_entity'; break; + case 'group' : $sub_table = $CONFIG->dbprefix . 'groups_entity'; break; + case 'site' : $sub_table = $CONFIG->dbprefix . 'sites_entity'; break; + } + + if ($sub_table) + delete_data("DELETE from $sub_table where guid={$guid}"); + } + + return $res; + } + } + } + return false; + + } + + /** + * Delete multiple entities that match a given query. + * This function itterates through and calls delete_entity on each one, this is somewhat inefficient but lets + * the 'delete' even be called for each entity. + * + * @param string $type The type of entity (eg "user", "object" etc) + * @param string $subtype The arbitrary subtype of the entity + * @param int $owner_guid The GUID of the owning user + */ + function delete_entities($type = "", $subtype = "", $owner_guid = 0) + { + $entities = get_entities($type, $subtype, $owner_guid, "time_created desc", 0); + + foreach ($entities as $entity) + delete_entity($entity->guid); + + return true; + } + + /** + * A plugin hook to get certain volitile (generated on the fly) attributes about an entity in order to export them. + * + * @param unknown_type $hook + * @param unknown_type $entity_type + * @param unknown_type $returnvalue + * @param unknown_type $params The parameters, passed 'guid' and 'varname' + * @return unknown + */ + function volatile_data_export_plugin_hook($hook, $entity_type, $returnvalue, $params) + { + $guid = (int)$params['guid']; + $variable_name = sanitise_string($params['varname']); + + if (($hook == 'volatile') && ($entity_type == 'metadata')) + { + if (($guid) && ($variable_name)) + { + switch ($variable_name) + { + case 'renderedentity' : + elgg_set_viewtype('default'); + $view = elgg_view_entity(get_entity($guid)); + elgg_set_viewtype(); + + $tmp = new ElggMetadata(); + $tmp->type = 'volatile'; + $tmp->name = 'renderedentity'; + $tmp->value = $view; + $tmp->entity_guid = $guid; - if ($sub_table) - delete_data("DELETE from $sub_table where guid={$guid}"); - } - - return $res; - } - } - } - return false; - - } - - /** - * Delete multiple entities that match a given query. - * This function itterates through and calls delete_entity on each one, this is somewhat inefficient but lets - * the 'delete' even be called for each entity. - * - * @param string $type The type of entity (eg "user", "object" etc) - * @param string $subtype The arbitrary subtype of the entity - * @param int $owner_guid The GUID of the owning user - */ - function delete_entities($type = "", $subtype = "", $owner_guid = 0) - { - $entities = get_entities($type, $subtype, $owner_guid, "time_created desc", 0); - - foreach ($entities as $entity) - delete_entity($entity->guid); - - return true; - } - - /** - * A plugin hook to get certain volitile (generated on the fly) attributes about an entity in order to export them. - * - * @param unknown_type $hook - * @param unknown_type $entity_type - * @param unknown_type $returnvalue - * @param unknown_type $params The parameters, passed 'guid' and 'varname' - * @return unknown - */ - function volatile_data_export_plugin_hook($hook, $entity_type, $returnvalue, $params) - { - $guid = (int)$params['guid']; - $variable_name = sanitise_string($params['varname']); - - if (($hook == 'volatile') && ($entity_type == 'metadata')) - { - if (($guid) && ($variable_name)) - { - switch ($variable_name) - { - case 'renderedentity' : - elgg_set_viewtype('default'); - $view = elgg_view_entity(get_entity($guid)); - elgg_set_viewtype(); - - $tmp = new ElggMetadata(); - $tmp->type = 'volatile'; - $tmp->name = 'renderedentity'; - $tmp->value = $view; - $tmp->entity_guid = $guid; - - return $tmp; - - break; - } - } - } - } - - /** - * Handler called by trigger_plugin_hook on the "export" event. - */ - function export_entity_plugin_hook($hook, $entity_type, $returnvalue, $params) - { - // Sanity check values - if ((!is_array($params)) && (!isset($params['guid']))) - throw new InvalidParameterException(elgg_echo('InvalidParameterException:GUIDNotForExport')); - - if (!is_array($returnvalue)) - throw new InvalidParameterException(elgg_echo('InvalidParameterException:NonArrayReturnValue')); - - $guid = (int)$params['guid']; - - // Get the entity - $entity = get_entity($guid); - if (!($entity instanceof ElggEntity)) - throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $guid, get_class())); - - $export = $entity->export(); - - if (is_array($export)) - foreach ($export as $e) - $returnvalue[] = $e; - else - $returnvalue[] = $export; - - return $returnvalue; - } - - /** - * Utility function used by import_entity_plugin_hook() to process an ODDEntity into an unsaved ElggEntity. - * - * @param ODDEntity $element The OpenDD element - * @return ElggEntity the unsaved entity which should be populated by items. - */ - function oddentity_to_elggentity(ODDEntity $element) - { - $class = $element->getAttribute('class'); - $subclass = $element->getAttribute('subclass'); - - // See if we already have imported this uuid - $tmp = get_entity_from_uuid($element->getAttribute('uuid')); - - if (!$tmp) - { - // Construct new class with owner from session - $classname = get_subtype_class($class, $subclass); - if ($classname!="") - { - if (class_exists($classname)) - { - $tmp = new $classname(); - - if (!($tmp instanceof ElggEntity)) - throw new ClassException(sprintf(elgg_echo('ClassException:ClassnameNotClass', $classname, get_class()))); - } - else - error_log(sprintf(elgg_echo('ClassNotFoundException:MissingClass'), $classname)); - } - else - { - switch ($class) - { - case 'object' : $tmp = new ElggObject($row); break; - case 'user' : $tmp = new ElggUser($row); break; - case 'group' : $tmp = new ElggGroup($row); break; - case 'site' : $tmp = new ElggSite($row); break; - default: throw new InstallationException(sprintf(elgg_echo('InstallationException:TypeNotSupported'), $class)); - } - } - } - - if ($tmp) - { - if (!$tmp->import($element)) - throw new ImportException(sprintf(elgg_echo('ImportException:ImportFailed'), $element->getAttribute('uuid'))); - - return $tmp; - } - - return NULL; - } - - /** - * Import an entity. - * This function checks the passed XML doc (as array) to see if it is a user, if so it constructs a new - * elgg user and returns "true" to inform the importer that it's been handled. - */ - function import_entity_plugin_hook($hook, $entity_type, $returnvalue, $params) - { - $element = $params['element']; - - $tmp = NULL; - - if ($element instanceof ODDEntity) - { - $tmp = oddentity_to_elggentity($element); - - if ($tmp) - { - if (!$tmp->save()) // Make sure its saved - throw new ImportException(sprintf(elgg_echo('ImportException:ProblemSaving'), $element->getAttribute('uuid'))); - - // Belts and braces - if (!$tmp->guid) - throw new ImportException(elgg_echo('ImportException:NoGUID')); - - add_uuid_to_guid($tmp->guid, $element->getAttribute('uuid')); // We have saved, so now tag - - return $tmp; - } - - } - } - - /** - * Determines whether or not the specified user can edit the specified entity. - * - * This is extendible by registering a plugin hook taking in the parameters 'entity' and 'user', - * which are the entity and user entities respectively - * - * @see register_plugin_hook - * - * @param int $entity_guid The GUID of the entity - * @param int $user_guid The GUID of the user - * @return true|false Whether the specified user can edit the specified entity. - */ - function can_edit_entity($entity_guid, $user_guid = 0) { - global $CONFIG; - - $user_guid = (int)$user_guid; - $user = get_entity($user_guid); - if (!$user) $user = get_loggedin_user(); - - if ($entity = get_entity($entity_guid)) { - - $return = false; - - // Test user if possible - should default to false unless a plugin hook says otherwise - if (!is_null($user)) - { - if ($entity->getOwner() == $user->getGUID()) $return = true; - if ($entity->container_guid == $user->getGUID()) $return = true; - if ($entity->type == "user" && $entity->getGUID() == $user->getGUID()) $return = true; - if ($container_entity = get_entity($entity->container_guid)) { - if ($container_entity->canEdit()) $return = true; - } - } - - return trigger_plugin_hook('permissions_check',$entity->type,array('entity' => $entity, 'user' => $user), $return); - - } else { - return false; - - } - - } - - /** - * Determines whether or not the specified user can edit metadata on the specified entity. - * - * This is extendible by registering a plugin hook taking in the parameters 'entity' and 'user', - * which are the entity and user entities respectively - * - * @see register_plugin_hook - * - * @param int $entity_guid The GUID of the entity - * @param int $user_guid The GUID of the user - * @param ElggMetadata $metadata The metadata to specifically check (if any; default null) - * @return true|false Whether the specified user can edit the specified entity. - */ - function can_edit_entity_metadata($entity_guid, $user_guid = 0, $metadata = null) { - - if ($entity = get_entity($entity_guid)) { - - $return = null; - - if ($metadata->owner_guid == 0) $return = true; - if (is_null($return)) - $return = can_edit_entity($entity_guid, $user_guid); - - $user = get_entity($user_guid); - $return = trigger_plugin_hook('permissions_check:metadata',$entity->type,array('entity' => $entity, 'user' => $user, 'metadata' => $metadata),$return); - return $return; - - } else { - return false; - } - - } - - - /** - * Get the icon for an entity - * - * @param ElggEntity $entity The entity (passed an entity rather than a guid to handle non-created entities) - * @param string $size - */ - function get_entity_icon_url(ElggEntity $entity, $size = 'medium') - { - global $CONFIG; - - $size = sanitise_string($size); - switch (strtolower($size)) - { + return $tmp; + + break; + } + } + } + } + + /** + * Handler called by trigger_plugin_hook on the "export" event. + */ + function export_entity_plugin_hook($hook, $entity_type, $returnvalue, $params) + { + // Sanity check values + if ((!is_array($params)) && (!isset($params['guid']))) + throw new InvalidParameterException(elgg_echo('InvalidParameterException:GUIDNotForExport')); + + if (!is_array($returnvalue)) + throw new InvalidParameterException(elgg_echo('InvalidParameterException:NonArrayReturnValue')); + + $guid = (int)$params['guid']; + + // Get the entity + $entity = get_entity($guid); + if (!($entity instanceof ElggEntity)) + throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $guid, get_class())); + + $export = $entity->export(); + + if (is_array($export)) + foreach ($export as $e) + $returnvalue[] = $e; + else + $returnvalue[] = $export; + + return $returnvalue; + } + + /** + * Utility function used by import_entity_plugin_hook() to process an ODDEntity into an unsaved ElggEntity. + * + * @param ODDEntity $element The OpenDD element + * @return ElggEntity the unsaved entity which should be populated by items. + */ + function oddentity_to_elggentity(ODDEntity $element) + { + $class = $element->getAttribute('class'); + $subclass = $element->getAttribute('subclass'); + + // See if we already have imported this uuid + $tmp = get_entity_from_uuid($element->getAttribute('uuid')); + + if (!$tmp) + { + // Construct new class with owner from session + $classname = get_subtype_class($class, $subclass); + if ($classname!="") + { + if (class_exists($classname)) + { + $tmp = new $classname(); + + if (!($tmp instanceof ElggEntity)) + throw new ClassException(sprintf(elgg_echo('ClassException:ClassnameNotClass', $classname, get_class()))); + } + else + error_log(sprintf(elgg_echo('ClassNotFoundException:MissingClass'), $classname)); + } + else + { + switch ($class) + { + case 'object' : $tmp = new ElggObject($row); break; + case 'user' : $tmp = new ElggUser($row); break; + case 'group' : $tmp = new ElggGroup($row); break; + case 'site' : $tmp = new ElggSite($row); break; + default: throw new InstallationException(sprintf(elgg_echo('InstallationException:TypeNotSupported'), $class)); + } + } + } + + if ($tmp) + { + if (!$tmp->import($element)) + throw new ImportException(sprintf(elgg_echo('ImportException:ImportFailed'), $element->getAttribute('uuid'))); + + return $tmp; + } + + return NULL; + } + + /** + * Import an entity. + * This function checks the passed XML doc (as array) to see if it is a user, if so it constructs a new + * elgg user and returns "true" to inform the importer that it's been handled. + */ + function import_entity_plugin_hook($hook, $entity_type, $returnvalue, $params) + { + $element = $params['element']; + + $tmp = NULL; + + if ($element instanceof ODDEntity) + { + $tmp = oddentity_to_elggentity($element); + + if ($tmp) + { + if (!$tmp->save()) // Make sure its saved + throw new ImportException(sprintf(elgg_echo('ImportException:ProblemSaving'), $element->getAttribute('uuid'))); + + // Belts and braces + if (!$tmp->guid) + throw new ImportException(elgg_echo('ImportException:NoGUID')); + + add_uuid_to_guid($tmp->guid, $element->getAttribute('uuid')); // We have saved, so now tag + + return $tmp; + } + + } + } + + /** + * Determines whether or not the specified user can edit the specified entity. + * + * This is extendible by registering a plugin hook taking in the parameters 'entity' and 'user', + * which are the entity and user entities respectively + * + * @see register_plugin_hook + * + * @param int $entity_guid The GUID of the entity + * @param int $user_guid The GUID of the user + * @return true|false Whether the specified user can edit the specified entity. + */ + function can_edit_entity($entity_guid, $user_guid = 0) { + global $CONFIG; + + $user_guid = (int)$user_guid; + $user = get_entity($user_guid); + if (!$user) $user = get_loggedin_user(); + + if ($entity = get_entity($entity_guid)) { + + $return = false; + + // Test user if possible - should default to false unless a plugin hook says otherwise + if (!is_null($user)) + { + if ($entity->getOwner() == $user->getGUID()) $return = true; + if ($entity->container_guid == $user->getGUID()) $return = true; + if ($entity->type == "user" && $entity->getGUID() == $user->getGUID()) $return = true; + if ($container_entity = get_entity($entity->container_guid)) { + if ($container_entity->canEdit()) $return = true; + } + } + + return trigger_plugin_hook('permissions_check',$entity->type,array('entity' => $entity, 'user' => $user), $return); + + } else { + return false; + + } + + } + + /** + * Determines whether or not the specified user can edit metadata on the specified entity. + * + * This is extendible by registering a plugin hook taking in the parameters 'entity' and 'user', + * which are the entity and user entities respectively + * + * @see register_plugin_hook + * + * @param int $entity_guid The GUID of the entity + * @param int $user_guid The GUID of the user + * @param ElggMetadata $metadata The metadata to specifically check (if any; default null) + * @return true|false Whether the specified user can edit the specified entity. + */ + function can_edit_entity_metadata($entity_guid, $user_guid = 0, $metadata = null) { + + if ($entity = get_entity($entity_guid)) { + + $return = null; + + if ($metadata->owner_guid == 0) $return = true; + if (is_null($return)) + $return = can_edit_entity($entity_guid, $user_guid); + + $user = get_entity($user_guid); + $return = trigger_plugin_hook('permissions_check:metadata',$entity->type,array('entity' => $entity, 'user' => $user, 'metadata' => $metadata),$return); + return $return; + + } else { + return false; + } + + } + + + /** + * Get the icon for an entity + * + * @param ElggEntity $entity The entity (passed an entity rather than a guid to handle non-created entities) + * @param string $size + */ + function get_entity_icon_url(ElggEntity $entity, $size = 'medium') + { + global $CONFIG; + + $size = sanitise_string($size); + switch (strtolower($size)) + { case 'master': $size = 'master'; break; - - case 'large' : $size = 'large'; break; - - case 'topbar' : $size = 'topbar'; break; - - case 'tiny' : $size = 'tiny'; break; - - case 'small' : $size = 'small'; break; - - case 'medium' : - default: $size = 'medium'; - } - - $url = false; - - $viewtype = elgg_get_viewtype(); - - // Step one, see if anyone knows how to render this in the current view - $url = trigger_plugin_hook('entity:icon:url', $entity->getType(), array('entity' => $entity, 'viewtype' => $viewtype, 'size' => $size), $url); - - // Fail, so use default - if (!$url) { - - $type = $entity->getType(); - $subtype = $entity->getSubtype(); - - if (!empty($subtype)) { - $overrideurl = elgg_view("icon/{$type}/{$subtype}/{$size}",array('entity' => $entity)); - if (!empty($overrideurl)) return $overrideurl; - } - - $overrideurl = elgg_view("icon/{$type}/default/{$size}",array('entity' => $entity)); - if (!empty($overrideurl)) return $overrideurl; - - $url = $CONFIG->url . "_graphics/icons/default/$size.png"; - } - - return $url; - } - - /** - * Gets the URL for an entity, given a particular GUID - * - * @param int $entity_guid The GUID of the entity - * @return string The URL of the entity - */ - function get_entity_url($entity_guid) { - - global $CONFIG; - if ($entity = get_entity($entity_guid)) { - - $url = ""; - - if (isset($CONFIG->entity_url_handler[$entity->getType()][$entity->getSubType()])) { - $function = $CONFIG->entity_url_handler[$entity->getType()][$entity->getSubType()]; - if (is_callable($function)) { - $url = $function($entity); - } - } elseif (isset($CONFIG->entity_url_handler[$entity->getType()]['all'])) { - $function = $CONFIG->entity_url_handler[$entity->getType()]['all']; - if (is_callable($function)) { - $url = $function($entity); - } - } elseif (isset($CONFIG->entity_url_handler['all']['all'])) { - $function = $CONFIG->entity_url_handler['all']['all']; - if (is_callable($function)) { - $url = $function($entity); - } - } - - if ($url == "") { - $url = $CONFIG->url . "pg/view/" . $entity_guid; - } - return $url; - - } - return false; - - } - - /** - * Sets the URL handler for a particular entity type and subtype - * - * @param string $function_name The function to register - * @param string $entity_type The entity type - * @param string $entity_subtype The entity subtype - * @return true|false Depending on success - */ - function register_entity_url_handler($function_name, $entity_type = "all", $entity_subtype = "all") { - global $CONFIG; - - if (!is_callable($function_name)) return false; - - if (!isset($CONFIG->entity_url_handler)) { - $CONFIG->entity_url_handler = array(); - } - if (!isset($CONFIG->entity_url_handler[$entity_type])) { - $CONFIG->entity_url_handler[$entity_type] = array(); - } - $CONFIG->entity_url_handler[$entity_type][$entity_subtype] = $function_name; - - return true; - - } - - /** - * Default Icon URL handler for entities. - * This will attempt to find a default entity for the current view and return a url. This is registered at - * a low priority so that other handlers will pick it up first. - * - * @param unknown_type $hook - * @param unknown_type $entity_type - * @param unknown_type $returnvalue - * @param unknown_type $params - */ - function default_entity_icon_hook($hook, $entity_type, $returnvalue, $params) - { - global $CONFIG; - - if ((!$returnvalue) && ($hook == 'entity:icon:url')) - { - $entity = $params['entity']; - $type = $entity->type; - $subtype = get_subtype_from_id($entity->subtype); - $viewtype = $params['viewtype']; - $size = $params['size']; - - $url = "views/$viewtype/graphics/icons/$type/$subtype/$size.png"; - - if (!@file_exists($CONFIG->path . $url)) - $url = "views/$viewtype/graphics/icons/$type/default/$size.png"; - - if(!@file_exists($CONFIG->path . $url)) - $url = "views/$viewtype/graphics/icons/default/$size.png"; - - if (@file_exists($CONFIG->path . $url)) - return $CONFIG->url . $url; - } - } - - /** - * Registers and entity type and subtype to return in search and other places. - * A description in the elgg_echo languages file of the form item:type:subtype - * is also expected. - * - * @param string $type The type of entity (object, site, user, group) - * @param string $subtype The subtype to register (may be blank) - * @return true|false Depending on success - */ - function register_entity_type($type, $subtype) { - - global $CONFIG; - - $type = strtolower($type); - if (!in_array($type,array('object','site','group','user'))) return false; - - if (!isset($CONFIG->registered_entities)) $CONFIG->registered_entities = array(); - $CONFIG->registered_entities[$type][] = $subtype; - - return true; - - } - - /** - * Returns registered entity types and subtypes - * - * @see register_entity_type - * - * @param string $type The type of entity (object, site, user, group) or blank for all - * @return array|false Depending on whether entities have been registered - */ - function get_registered_entity_types($type = '') { - - global $CONFIG; - - if (!isset($CONFIG->registered_entities)) return false; - if (!empty($type)) $type = strtolower($type); - if (!empty($type) && empty($CONFIG->registered_entities[$type])) return false; - - if (empty($type)) - return $CONFIG->registered_entities; - - return $CONFIG->registered_entities[$type]; - - } - - /** - * Determines whether or not the specified entity type and subtype have been registered in the system - * - * @param string $type The type of entity (object, site, user, group) - * @param string $subtype The subtype (may be blank) - * @return true|false Depending on whether or not the type has been registered - */ - function is_registered_entity_type($type, $subtype) { - - global $CONFIG; - - if (!isset($CONFIG->registered_entities)) return false; - $type = strtolower($type); - if (empty($CONFIG->registered_entities[$type])) return false; - if (in_array($subtype, $CONFIG->registered_entities[$type])) return true; - - } - - /** - * Page handler for generic entities view system - * - * @param array $page Page elements from pain page handler - */ - function entities_page_handler($page) { - if (isset($page[0])) { - global $CONFIG; - set_input('guid',$page[0]); - @include($CONFIG->path . "entities/index.php"); - } - } - - /** - * Returns a viewable list of entities based on the registered types - * - * @see elgg_view_entity_list - * - * @param string $type The type of entity (eg "user", "object" etc) - * @param string $subtype The arbitrary subtype of the entity - * @param int $owner_guid The GUID of the owning user - * @param int $limit The number of entities to display per page (default: 10) - * @param true|false $fullview Whether or not to display the full view (default: true) - * @param true|false $viewtypetoggle Whether or not to allow gallery view - * @return string A viewable list of entities - */ - function list_registered_entities($owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = false, $allowedtypes = true) { - - $typearray = array(); - - if ($object_types = get_registered_entity_types()) { - foreach($object_types as $object_type => $subtype_array) { - if (is_array($subtype_array) && sizeof($subtype_array) && (in_array($object_type,$allowedtypes) || $allowedtypes === true)) - foreach($subtype_array as $object_subtype) { - $typearray[$object_type][] = $object_subtype; - } - } - } - - $offset = (int) get_input('offset'); - $count = get_entities('', $typearray, $owner_guid, "", $limit, $offset, true); - $entities = get_entities('', $typearray,$owner_guid, "", $limit, $offset); - - return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle); - - } - - /** - * Get entities based on their private data, in a similar way to metadata. - * - * @param string $name The name of the setting - * @param string $value The value of the setting - * @param string $type The type of entity (eg "user", "object" etc) - * @param string $subtype The arbitrary subtype of the entity - * @param int $owner_guid The GUID of the owning user - * @param string $order_by The field to order by; by default, time_created desc - * @param int $limit The number of entities to return; 10 by default - * @param int $offset The indexing offset, 0 by default - * @param boolean $count Set to true to get a count rather than the entities themselves (limits and offsets don't apply in this context). Defaults to false. - * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. - * @param int|array $container_guid The container or containers to get entities from (default: all containers). - * @return array A list of entities. - */ - function get_entities_from_private_setting($name = "", $value = "", $type = "", $subtype = "", $owner_guid = 0, $order_by = "", $limit = 10, $offset = 0, $count = false, $site_guid = 0, $container_guid = null) - { - global $CONFIG; - - if ($subtype === false || $subtype === null || $subtype === 0) - return false; - - $name = sanitise_string($name); - $value = sanitise_string($value); - - if ($order_by == "") $order_by = "e.time_created desc"; - $order_by = sanitise_string($order_by); - $limit = (int)$limit; - $offset = (int)$offset; - $site_guid = (int) $site_guid; - if ($site_guid == 0) - $site_guid = $CONFIG->site_guid; - - $where = array(); - - if (is_array($type)) { - $tempwhere = ""; - if (sizeof($type)) - foreach($type as $typekey => $subtypearray) { - foreach($subtypearray as $subtypeval) { - $typekey = sanitise_string($typekey); - if (!empty($subtypeval)) { - if (!$subtypeval = (int) get_subtype_id($typekey, $subtypeval)) { - return false; - } - } else { - $subtypeval = 0; - } - if (!empty($tempwhere)) $tempwhere .= " or "; - $tempwhere .= "(e.type = '{$typekey}' and e.subtype = {$subtypeval})"; - } - } - if (!empty($tempwhere)) $where[] = "({$tempwhere})"; - - } else { - - $type = sanitise_string($type); - if ($subtype AND !$subtype = get_subtype_id($type, $subtype)) { - return false; - } - - if ($type != "") - $where[] = "e.type='$type'"; - if ($subtype!=="") - $where[] = "e.subtype=$subtype"; - - } - - if ($owner_guid != "") { - if (!is_array($owner_guid)) { - $owner_array = array($owner_guid); - $owner_guid = (int) $owner_guid; - // $where[] = "owner_guid = '$owner_guid'"; - } else if (sizeof($owner_guid) > 0) { - $owner_array = array_map('sanitise_int', $owner_guid); - // Cast every element to the owner_guid array to int - // $owner_guid = array_map("sanitise_int", $owner_guid); - // $owner_guid = implode(",",$owner_guid); - // $where[] = "owner_guid in ({$owner_guid})"; - } - if (is_null($container_guid)) { - $container_guid = $owner_array; - } - } - if ($site_guid > 0) - $where[] = "e.site_guid = {$site_guid}"; - - if (!is_null($container_guid)) { - if (is_array($container_guid)) { - foreach($container_guid as $key => $val) $container_guid[$key] = (int) $val; - $where[] = "e.container_guid in (" . implode(",",$container_guid) . ")"; - } else { - $container_guid = (int) $container_guid; - $where[] = "e.container_guid = {$container_guid}"; - } - } - - if ($name!="") - $where[] = "s.name = '$name'"; - if ($value!="") - $where[] = "s.value='$value'"; - - if (!$count) { - $query = "SELECT distinct e.* from {$CONFIG->dbprefix}entities e JOIN {$CONFIG->dbprefix}private_settings s ON e.guid=s.entity_guid where "; - } else { - $query = "SELECT count(distinct e.guid) as total from {$CONFIG->dbprefix}entities e JOIN {$CONFIG->dbprefix}private_settings s ON e.guid=s.entity_guid where "; - } - foreach ($where as $w) - $query .= " $w and "; - $query .= get_access_sql_suffix('e'); // Add access controls - if (!$count) { - $query .= " order by $order_by"; - if ($limit) $query .= " limit $offset, $limit"; // Add order and limit - - $dt = get_data($query, "entity_row_to_elggstar"); - return $dt; - } else { - $total = get_data_row($query); - return $total->total; - } - } - - /** - * Get entities based on their private data by multiple keys, in a similar way to metadata. - * - * @param string $name The name of the setting - * @param string $value The value of the setting - * @param string|array $type The type of entity (eg "user", "object" etc) or array(type1 => array('subtype1', ...'subtypeN'), ...) - * @param string $subtype The arbitrary subtype of the entity - * @param int $owner_guid The GUID of the owning user - * @param string $order_by The field to order by; by default, time_created desc - * @param int $limit The number of entities to return; 10 by default - * @param int $offset The indexing offset, 0 by default - * @param boolean $count Set to true to get a count rather than the entities themselves (limits and offsets don't apply in this context). Defaults to false. - * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. - * @param int|array $container_guid The container or containers to get entities from (default: all containers). - * @return array A list of entities. - */ - function get_entities_from_private_setting_multi(array $name, $type = "", $subtype = "", $owner_guid = 0, $order_by = "", $limit = 10, $offset = 0, $count = false, $site_guid = 0, $container_guid = null) - { - global $CONFIG; - - if ($subtype === false || $subtype === null || $subtype === 0) - return false; - - if ($order_by == "") $order_by = "e.time_created desc"; - $order_by = sanitise_string($order_by); - $limit = (int)$limit; - $offset = (int)$offset; - $site_guid = (int) $site_guid; - if ($site_guid == 0) - $site_guid = $CONFIG->site_guid; - - $where = array(); - - if (is_array($type)) { - $tempwhere = ""; - if (sizeof($type)) - foreach($type as $typekey => $subtypearray) { - foreach($subtypearray as $subtypeval) { - $typekey = sanitise_string($typekey); - if (!empty($subtypeval)) { - if (!$subtypeval = (int) get_subtype_id($typekey, $subtypeval)) { - return false; - } - } else { - $subtypeval = 0; - } - if (!empty($tempwhere)) $tempwhere .= " or "; - $tempwhere .= "(e.type = '{$typekey}' and e.subtype = {$subtypeval})"; - } - } - if (!empty($tempwhere)) $where[] = "({$tempwhere})"; - - } else { - $type = sanitise_string($type); - if ($subtype AND !$subtype = get_subtype_id($type, $subtype)) - return false; - - if ($type != "") - $where[] = "e.type='$type'"; - if ($subtype!=="") - $where[] = "e.subtype=$subtype"; - - } - - if ($owner_guid != "") { - if (!is_array($owner_guid)) { - $owner_array = array($owner_guid); - $owner_guid = (int) $owner_guid; - // $where[] = "owner_guid = '$owner_guid'"; - } else if (sizeof($owner_guid) > 0) { - $owner_array = array_map('sanitise_int', $owner_guid); - // Cast every element to the owner_guid array to int - // $owner_guid = array_map("sanitise_int", $owner_guid); - // $owner_guid = implode(",",$owner_guid); - // $where[] = "owner_guid in ({$owner_guid})"; - } - if (is_null($container_guid)) { - $container_guid = $owner_array; - } - } - if ($site_guid > 0) - $where[] = "e.site_guid = {$site_guid}"; - - if (!is_null($container_guid)) { - if (is_array($container_guid)) { - foreach($container_guid as $key => $val) $container_guid[$key] = (int) $val; - $where[] = "e.container_guid in (" . implode(",",$container_guid) . ")"; - } else { - $container_guid = (int) $container_guid; - $where[] = "e.container_guid = {$container_guid}"; - } - } - - if ($name) - { - $s_join = ""; - $i = 1; - foreach ($name as $k => $n) - { - $k = sanitise_string($k); - $s_join .= " JOIN {$CONFIG->dbprefix}private_settings s$i ON e.guid=s$i.entity_guid"; - $where[] = "s$i.name = '$k'"; - $where[] = "s$i.value = '$n'"; - $i++; - } - } - - if (!$count) { - $query = "SELECT distinct e.* from {$CONFIG->dbprefix}entities e $s_join where "; - } else { - $query = "SELECT count(distinct e.guid) as total from {$CONFIG->dbprefix}entities e $s_join where "; - } - foreach ($where as $w) - $query .= " $w and "; - $query .= get_access_sql_suffix('e'); // Add access controls - if (!$count) { - $query .= " order by $order_by"; - if ($limit) $query .= " limit $offset, $limit"; // Add order and limit - - $dt = get_data($query, "entity_row_to_elggstar"); - return $dt; - } else { - $total = get_data_row($query); - return $total->total; - } - } - - /** - * Gets a private setting for an entity. - * - * @param int $entity_guid The entity GUID - * @param string $name The name of the setting - * @return mixed The setting value, or false on failure - */ - function get_private_setting($entity_guid, $name) { - - global $CONFIG; - $entity_guid = (int) $entity_guid; - $name = sanitise_string($name); - - if ($setting = get_data_row("SELECT value from {$CONFIG->dbprefix}private_settings where name = '{$name}' and entity_guid = {$entity_guid}")) { - return $setting->value; - } - return false; - - } - - /** - * Return an array of all private settings for a given - * - * @param int $entity_guid The entity GUID - */ - function get_all_private_settings($entity_guid) { - global $CONFIG; - - $entity_guid = (int) $entity_guid; - - $result = get_data("SELECT * from {$CONFIG->dbprefix}private_settings where entity_guid = {$entity_guid}"); - if ($result) - { - $return = array(); - foreach ($result as $r) - $return[$r->name] = $r->value; - - return $return; - } - - return false; - } - - /** - * Sets a private setting for an entity. - * - * @param int $entity_guid The entity GUID - * @param string $name The name of the setting - * @param string $value The value of the setting - * @return mixed The setting ID, or false on failure - */ - function set_private_setting($entity_guid, $name, $value) { - - global $CONFIG; - $entity_guid = (int) $entity_guid; - $name = sanitise_string($name); - $value = sanitise_string($value); - - $result = insert_data("INSERT into {$CONFIG->dbprefix}private_settings (entity_guid, name, value) VALUES ($entity_guid, '{$name}', '{$value}') ON DUPLICATE KEY UPDATE value='$value'"); - if ($result === 0) return true; - return $result; - - } - - /** - * Deletes a private setting for an entity. - * - * @param int $entity_guid The Entity GUID - * @param string $name The name of the setting - * @return true|false depending on success - * - */ - function remove_private_setting($entity_guid, $name) { - - global $CONFIG; - $entity_guid = (int) $entity_guid; - $name = sanitise_string($name); - return delete_data("DELETE from {$CONFIG->dbprefix}private_settings where name = '{$name}' and entity_guid = {$entity_guid}"); - - } - - /** - * Deletes all private settings for an entity. - * - * @param int $entity_guid The Entity GUID - * @return true|false depending on success - * - */ - function remove_all_private_settings($entity_guid) { - - global $CONFIG; - $entity_guid = (int) $entity_guid; - return delete_data("DELETE from {$CONFIG->dbprefix}private_settings where entity_guid = {$entity_guid}"); - } - - function recursive_delete_permissions_check($hook, $entity_type, $returnvalue, $params) - { - static $__RECURSIVE_DELETE_TOKEN; - - $entity = $params['entity']; - - if ((isloggedin()) && ($__RECURSIVE_DELETE_TOKEN) && (strcmp($__RECURSIVE_DELETE_TOKEN, md5(get_loggedin_userid())))) - return true; - + + case 'large' : $size = 'large'; break; + + case 'topbar' : $size = 'topbar'; break; + + case 'tiny' : $size = 'tiny'; break; + + case 'small' : $size = 'small'; break; + + case 'medium' : + default: $size = 'medium'; + } + + $url = false; + + $viewtype = elgg_get_viewtype(); + + // Step one, see if anyone knows how to render this in the current view + $url = trigger_plugin_hook('entity:icon:url', $entity->getType(), array('entity' => $entity, 'viewtype' => $viewtype, 'size' => $size), $url); + + // Fail, so use default + if (!$url) { + + $type = $entity->getType(); + $subtype = $entity->getSubtype(); + + if (!empty($subtype)) { + $overrideurl = elgg_view("icon/{$type}/{$subtype}/{$size}",array('entity' => $entity)); + if (!empty($overrideurl)) return $overrideurl; + } + + $overrideurl = elgg_view("icon/{$type}/default/{$size}",array('entity' => $entity)); + if (!empty($overrideurl)) return $overrideurl; + + $url = $CONFIG->url . "_graphics/icons/default/$size.png"; + } + + return $url; + } + + /** + * Gets the URL for an entity, given a particular GUID + * + * @param int $entity_guid The GUID of the entity + * @return string The URL of the entity + */ + function get_entity_url($entity_guid) { + + global $CONFIG; + if ($entity = get_entity($entity_guid)) { + + $url = ""; + + if (isset($CONFIG->entity_url_handler[$entity->getType()][$entity->getSubType()])) { + $function = $CONFIG->entity_url_handler[$entity->getType()][$entity->getSubType()]; + if (is_callable($function)) { + $url = $function($entity); + } + } elseif (isset($CONFIG->entity_url_handler[$entity->getType()]['all'])) { + $function = $CONFIG->entity_url_handler[$entity->getType()]['all']; + if (is_callable($function)) { + $url = $function($entity); + } + } elseif (isset($CONFIG->entity_url_handler['all']['all'])) { + $function = $CONFIG->entity_url_handler['all']['all']; + if (is_callable($function)) { + $url = $function($entity); + } + } + + if ($url == "") { + $url = $CONFIG->url . "pg/view/" . $entity_guid; + } + return $url; + + } + return false; + + } + + /** + * Sets the URL handler for a particular entity type and subtype + * + * @param string $function_name The function to register + * @param string $entity_type The entity type + * @param string $entity_subtype The entity subtype + * @return true|false Depending on success + */ + function register_entity_url_handler($function_name, $entity_type = "all", $entity_subtype = "all") { + global $CONFIG; + + if (!is_callable($function_name)) return false; + + if (!isset($CONFIG->entity_url_handler)) { + $CONFIG->entity_url_handler = array(); + } + if (!isset($CONFIG->entity_url_handler[$entity_type])) { + $CONFIG->entity_url_handler[$entity_type] = array(); + } + $CONFIG->entity_url_handler[$entity_type][$entity_subtype] = $function_name; + + return true; + + } + + /** + * Default Icon URL handler for entities. + * This will attempt to find a default entity for the current view and return a url. This is registered at + * a low priority so that other handlers will pick it up first. + * + * @param unknown_type $hook + * @param unknown_type $entity_type + * @param unknown_type $returnvalue + * @param unknown_type $params + */ + function default_entity_icon_hook($hook, $entity_type, $returnvalue, $params) + { + global $CONFIG; + + if ((!$returnvalue) && ($hook == 'entity:icon:url')) + { + $entity = $params['entity']; + $type = $entity->type; + $subtype = get_subtype_from_id($entity->subtype); + $viewtype = $params['viewtype']; + $size = $params['size']; + + $url = "views/$viewtype/graphics/icons/$type/$subtype/$size.png"; + + if (!@file_exists($CONFIG->path . $url)) + $url = "views/$viewtype/graphics/icons/$type/default/$size.png"; + + if(!@file_exists($CONFIG->path . $url)) + $url = "views/$viewtype/graphics/icons/default/$size.png"; + + if (@file_exists($CONFIG->path . $url)) + return $CONFIG->url . $url; + } + } + + /** + * Registers and entity type and subtype to return in search and other places. + * A description in the elgg_echo languages file of the form item:type:subtype + * is also expected. + * + * @param string $type The type of entity (object, site, user, group) + * @param string $subtype The subtype to register (may be blank) + * @return true|false Depending on success + */ + function register_entity_type($type, $subtype) { + + global $CONFIG; + + $type = strtolower($type); + if (!in_array($type,array('object','site','group','user'))) return false; + + if (!isset($CONFIG->registered_entities)) $CONFIG->registered_entities = array(); + $CONFIG->registered_entities[$type][] = $subtype; + + return true; + + } + + /** + * Returns registered entity types and subtypes + * + * @see register_entity_type + * + * @param string $type The type of entity (object, site, user, group) or blank for all + * @return array|false Depending on whether entities have been registered + */ + function get_registered_entity_types($type = '') { + + global $CONFIG; + + if (!isset($CONFIG->registered_entities)) return false; + if (!empty($type)) $type = strtolower($type); + if (!empty($type) && empty($CONFIG->registered_entities[$type])) return false; + + if (empty($type)) + return $CONFIG->registered_entities; + + return $CONFIG->registered_entities[$type]; + + } + + /** + * Determines whether or not the specified entity type and subtype have been registered in the system + * + * @param string $type The type of entity (object, site, user, group) + * @param string $subtype The subtype (may be blank) + * @return true|false Depending on whether or not the type has been registered + */ + function is_registered_entity_type($type, $subtype) { + + global $CONFIG; + + if (!isset($CONFIG->registered_entities)) return false; + $type = strtolower($type); + if (empty($CONFIG->registered_entities[$type])) return false; + if (in_array($subtype, $CONFIG->registered_entities[$type])) return true; + + } + + /** + * Page handler for generic entities view system + * + * @param array $page Page elements from pain page handler + */ + function entities_page_handler($page) { + if (isset($page[0])) { + global $CONFIG; + set_input('guid',$page[0]); + @include($CONFIG->path . "entities/index.php"); + } + } + + /** + * Returns a viewable list of entities based on the registered types + * + * @see elgg_view_entity_list + * + * @param string $type The type of entity (eg "user", "object" etc) + * @param string $subtype The arbitrary subtype of the entity + * @param int $owner_guid The GUID of the owning user + * @param int $limit The number of entities to display per page (default: 10) + * @param true|false $fullview Whether or not to display the full view (default: true) + * @param true|false $viewtypetoggle Whether or not to allow gallery view + * @return string A viewable list of entities + */ + function list_registered_entities($owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = false, $allowedtypes = true) { + + $typearray = array(); + + if ($object_types = get_registered_entity_types()) { + foreach($object_types as $object_type => $subtype_array) { + if (is_array($subtype_array) && sizeof($subtype_array) && (in_array($object_type,$allowedtypes) || $allowedtypes === true)) + foreach($subtype_array as $object_subtype) { + $typearray[$object_type][] = $object_subtype; + } + } + } + + $offset = (int) get_input('offset'); + $count = get_entities('', $typearray, $owner_guid, "", $limit, $offset, true); + $entities = get_entities('', $typearray,$owner_guid, "", $limit, $offset); + + return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle); + + } + + /** + * Get entities based on their private data, in a similar way to metadata. + * + * @param string $name The name of the setting + * @param string $value The value of the setting + * @param string $type The type of entity (eg "user", "object" etc) + * @param string $subtype The arbitrary subtype of the entity + * @param int $owner_guid The GUID of the owning user + * @param string $order_by The field to order by; by default, time_created desc + * @param int $limit The number of entities to return; 10 by default + * @param int $offset The indexing offset, 0 by default + * @param boolean $count Set to true to get a count rather than the entities themselves (limits and offsets don't apply in this context). Defaults to false. + * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. + * @param int|array $container_guid The container or containers to get entities from (default: all containers). + * @return array A list of entities. + */ + function get_entities_from_private_setting($name = "", $value = "", $type = "", $subtype = "", $owner_guid = 0, $order_by = "", $limit = 10, $offset = 0, $count = false, $site_guid = 0, $container_guid = null) + { + global $CONFIG; + + if ($subtype === false || $subtype === null || $subtype === 0) + return false; + + $name = sanitise_string($name); + $value = sanitise_string($value); + + if ($order_by == "") $order_by = "e.time_created desc"; + $order_by = sanitise_string($order_by); + $limit = (int)$limit; + $offset = (int)$offset; + $site_guid = (int) $site_guid; + if ($site_guid == 0) + $site_guid = $CONFIG->site_guid; + + $where = array(); + + if (is_array($type)) { + $tempwhere = ""; + if (sizeof($type)) + foreach($type as $typekey => $subtypearray) { + foreach($subtypearray as $subtypeval) { + $typekey = sanitise_string($typekey); + if (!empty($subtypeval)) { + if (!$subtypeval = (int) get_subtype_id($typekey, $subtypeval)) { + return false; + } + } else { + $subtypeval = 0; + } + if (!empty($tempwhere)) $tempwhere .= " or "; + $tempwhere .= "(e.type = '{$typekey}' and e.subtype = {$subtypeval})"; + } + } + if (!empty($tempwhere)) $where[] = "({$tempwhere})"; + + } else { + + $type = sanitise_string($type); + if ($subtype AND !$subtype = get_subtype_id($type, $subtype)) { + return false; + } + + if ($type != "") + $where[] = "e.type='$type'"; + if ($subtype!=="") + $where[] = "e.subtype=$subtype"; + + } + + if ($owner_guid != "") { + if (!is_array($owner_guid)) { + $owner_array = array($owner_guid); + $owner_guid = (int) $owner_guid; + // $where[] = "owner_guid = '$owner_guid'"; + } else if (sizeof($owner_guid) > 0) { + $owner_array = array_map('sanitise_int', $owner_guid); + // Cast every element to the owner_guid array to int + // $owner_guid = array_map("sanitise_int", $owner_guid); + // $owner_guid = implode(",",$owner_guid); + // $where[] = "owner_guid in ({$owner_guid})"; + } + if (is_null($container_guid)) { + $container_guid = $owner_array; + } + } + if ($site_guid > 0) + $where[] = "e.site_guid = {$site_guid}"; + + if (!is_null($container_guid)) { + if (is_array($container_guid)) { + foreach($container_guid as $key => $val) $container_guid[$key] = (int) $val; + $where[] = "e.container_guid in (" . implode(",",$container_guid) . ")"; + } else { + $container_guid = (int) $container_guid; + $where[] = "e.container_guid = {$container_guid}"; + } + } + + if ($name!="") + $where[] = "s.name = '$name'"; + if ($value!="") + $where[] = "s.value='$value'"; + + if (!$count) { + $query = "SELECT distinct e.* from {$CONFIG->dbprefix}entities e JOIN {$CONFIG->dbprefix}private_settings s ON e.guid=s.entity_guid where "; + } else { + $query = "SELECT count(distinct e.guid) as total from {$CONFIG->dbprefix}entities e JOIN {$CONFIG->dbprefix}private_settings s ON e.guid=s.entity_guid where "; + } + foreach ($where as $w) + $query .= " $w and "; + $query .= get_access_sql_suffix('e'); // Add access controls + if (!$count) { + $query .= " order by $order_by"; + if ($limit) $query .= " limit $offset, $limit"; // Add order and limit + + $dt = get_data($query, "entity_row_to_elggstar"); + return $dt; + } else { + $total = get_data_row($query); + return $total->total; + } + } + + /** + * Get entities based on their private data by multiple keys, in a similar way to metadata. + * + * @param string $name The name of the setting + * @param string $value The value of the setting + * @param string|array $type The type of entity (eg "user", "object" etc) or array(type1 => array('subtype1', ...'subtypeN'), ...) + * @param string $subtype The arbitrary subtype of the entity + * @param int $owner_guid The GUID of the owning user + * @param string $order_by The field to order by; by default, time_created desc + * @param int $limit The number of entities to return; 10 by default + * @param int $offset The indexing offset, 0 by default + * @param boolean $count Set to true to get a count rather than the entities themselves (limits and offsets don't apply in this context). Defaults to false. + * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. + * @param int|array $container_guid The container or containers to get entities from (default: all containers). + * @return array A list of entities. + */ + function get_entities_from_private_setting_multi(array $name, $type = "", $subtype = "", $owner_guid = 0, $order_by = "", $limit = 10, $offset = 0, $count = false, $site_guid = 0, $container_guid = null) + { + global $CONFIG; + + if ($subtype === false || $subtype === null || $subtype === 0) + return false; + + if ($order_by == "") $order_by = "e.time_created desc"; + $order_by = sanitise_string($order_by); + $limit = (int)$limit; + $offset = (int)$offset; + $site_guid = (int) $site_guid; + if ($site_guid == 0) + $site_guid = $CONFIG->site_guid; + + $where = array(); + + if (is_array($type)) { + $tempwhere = ""; + if (sizeof($type)) + foreach($type as $typekey => $subtypearray) { + foreach($subtypearray as $subtypeval) { + $typekey = sanitise_string($typekey); + if (!empty($subtypeval)) { + if (!$subtypeval = (int) get_subtype_id($typekey, $subtypeval)) { + return false; + } + } else { + $subtypeval = 0; + } + if (!empty($tempwhere)) $tempwhere .= " or "; + $tempwhere .= "(e.type = '{$typekey}' and e.subtype = {$subtypeval})"; + } + } + if (!empty($tempwhere)) $where[] = "({$tempwhere})"; + + } else { + $type = sanitise_string($type); + if ($subtype AND !$subtype = get_subtype_id($type, $subtype)) + return false; + + if ($type != "") + $where[] = "e.type='$type'"; + if ($subtype!=="") + $where[] = "e.subtype=$subtype"; + + } + + if ($owner_guid != "") { + if (!is_array($owner_guid)) { + $owner_array = array($owner_guid); + $owner_guid = (int) $owner_guid; + // $where[] = "owner_guid = '$owner_guid'"; + } else if (sizeof($owner_guid) > 0) { + $owner_array = array_map('sanitise_int', $owner_guid); + // Cast every element to the owner_guid array to int + // $owner_guid = array_map("sanitise_int", $owner_guid); + // $owner_guid = implode(",",$owner_guid); + // $where[] = "owner_guid in ({$owner_guid})"; + } + if (is_null($container_guid)) { + $container_guid = $owner_array; + } + } + if ($site_guid > 0) + $where[] = "e.site_guid = {$site_guid}"; + + if (!is_null($container_guid)) { + if (is_array($container_guid)) { + foreach($container_guid as $key => $val) $container_guid[$key] = (int) $val; + $where[] = "e.container_guid in (" . implode(",",$container_guid) . ")"; + } else { + $container_guid = (int) $container_guid; + $where[] = "e.container_guid = {$container_guid}"; + } + } + + if ($name) + { + $s_join = ""; + $i = 1; + foreach ($name as $k => $n) + { + $k = sanitise_string($k); + $s_join .= " JOIN {$CONFIG->dbprefix}private_settings s$i ON e.guid=s$i.entity_guid"; + $where[] = "s$i.name = '$k'"; + $where[] = "s$i.value = '$n'"; + $i++; + } + } + + if (!$count) { + $query = "SELECT distinct e.* from {$CONFIG->dbprefix}entities e $s_join where "; + } else { + $query = "SELECT count(distinct e.guid) as total from {$CONFIG->dbprefix}entities e $s_join where "; + } + foreach ($where as $w) + $query .= " $w and "; + $query .= get_access_sql_suffix('e'); // Add access controls + if (!$count) { + $query .= " order by $order_by"; + if ($limit) $query .= " limit $offset, $limit"; // Add order and limit + + $dt = get_data($query, "entity_row_to_elggstar"); + return $dt; + } else { + $total = get_data_row($query); + return $total->total; + } + } + + /** + * Gets a private setting for an entity. + * + * @param int $entity_guid The entity GUID + * @param string $name The name of the setting + * @return mixed The setting value, or false on failure + */ + function get_private_setting($entity_guid, $name) { + + global $CONFIG; + $entity_guid = (int) $entity_guid; + $name = sanitise_string($name); + + if ($setting = get_data_row("SELECT value from {$CONFIG->dbprefix}private_settings where name = '{$name}' and entity_guid = {$entity_guid}")) { + return $setting->value; + } + return false; + + } + + /** + * Return an array of all private settings for a given + * + * @param int $entity_guid The entity GUID + */ + function get_all_private_settings($entity_guid) { + global $CONFIG; + + $entity_guid = (int) $entity_guid; + + $result = get_data("SELECT * from {$CONFIG->dbprefix}private_settings where entity_guid = {$entity_guid}"); + if ($result) + { + $return = array(); + foreach ($result as $r) + $return[$r->name] = $r->value; + + return $return; + } + + return false; + } + + /** + * Sets a private setting for an entity. + * + * @param int $entity_guid The entity GUID + * @param string $name The name of the setting + * @param string $value The value of the setting + * @return mixed The setting ID, or false on failure + */ + function set_private_setting($entity_guid, $name, $value) { + + global $CONFIG; + $entity_guid = (int) $entity_guid; + $name = sanitise_string($name); + $value = sanitise_string($value); + + $result = insert_data("INSERT into {$CONFIG->dbprefix}private_settings (entity_guid, name, value) VALUES ($entity_guid, '{$name}', '{$value}') ON DUPLICATE KEY UPDATE value='$value'"); + if ($result === 0) return true; + return $result; + + } + + /** + * Deletes a private setting for an entity. + * + * @param int $entity_guid The Entity GUID + * @param string $name The name of the setting + * @return true|false depending on success + * + */ + function remove_private_setting($entity_guid, $name) { + + global $CONFIG; + $entity_guid = (int) $entity_guid; + $name = sanitise_string($name); + return delete_data("DELETE from {$CONFIG->dbprefix}private_settings where name = '{$name}' and entity_guid = {$entity_guid}"); + + } + + /** + * Deletes all private settings for an entity. + * + * @param int $entity_guid The Entity GUID + * @return true|false depending on success + * + */ + function remove_all_private_settings($entity_guid) { + + global $CONFIG; + $entity_guid = (int) $entity_guid; + return delete_data("DELETE from {$CONFIG->dbprefix}private_settings where entity_guid = {$entity_guid}"); + } + + function recursive_delete_permissions_check($hook, $entity_type, $returnvalue, $params) + { + static $__RECURSIVE_DELETE_TOKEN; + + $entity = $params['entity']; + + if ((isloggedin()) && ($__RECURSIVE_DELETE_TOKEN) && (strcmp($__RECURSIVE_DELETE_TOKEN, md5(get_loggedin_userid())))) + return true; + } /** @@ -2763,37 +2763,37 @@ foreach ($tables as $table) { delete_data("DELETE from {$CONFIG->dbprefix}{$table} where guid NOT IN (SELECT guid from {$CONFIG->dbprefix}entities)"); } - } - - /** - * Entities init function; establishes the page handler - * - */ + } + + /** + * Entities init function; establishes the page handler + * + */ function entities_init() - { - register_page_handler('view','entities_page_handler'); - - // Allow a permission override for recursive entity deletion - // TODO: Can this be done better? + { + register_page_handler('view','entities_page_handler'); + + // Allow a permission override for recursive entity deletion + // TODO: Can this be done better? register_plugin_hook('permissions_check','all','recursive_delete_permissions_check'); register_plugin_hook('permissions_check:metadata','all','recursive_delete_permissions_check'); - register_plugin_hook('gc','system','entities_gc'); - } - - /** Register the import hook */ - register_plugin_hook("import", "all", "import_entity_plugin_hook", 0); - - /** Register the hook, ensuring entities are serialised first */ - register_plugin_hook("export", "all", "export_entity_plugin_hook", 0); - - /** Hook to get certain named bits of volatile data about an entity */ - register_plugin_hook('volatile', 'metadata', 'volatile_data_export_plugin_hook'); - - /** Hook for rendering a default icon for entities */ - register_plugin_hook('entity:icon:url', 'all', 'default_entity_icon_hook', 1000); - - /** Register init system event **/ - register_elgg_event_handler('init','system','entities_init'); - -?> + register_plugin_hook('gc','system','entities_gc'); + } + + /** Register the import hook */ + register_plugin_hook("import", "all", "import_entity_plugin_hook", 0); + + /** Register the hook, ensuring entities are serialised first */ + register_plugin_hook("export", "all", "export_entity_plugin_hook", 0); + + /** Hook to get certain named bits of volatile data about an entity */ + register_plugin_hook('volatile', 'metadata', 'volatile_data_export_plugin_hook'); + + /** Hook for rendering a default icon for entities */ + register_plugin_hook('entity:icon:url', 'all', 'default_entity_icon_hook', 1000); + + /** Register init system event **/ + register_elgg_event_handler('init','system','entities_init'); + +?> diff --git a/engine/lib/extender.php b/engine/lib/extender.php index a298671f3..f3f3753bc 100644 --- a/engine/lib/extender.php +++ b/engine/lib/extender.php @@ -66,7 +66,7 @@ */ protected function set($name, $value, $value_type = "") { - $this->attributes[$name] = $value; + $this->attributes[$name] = $value; if ($name == 'value') $this->attributes['value_type'] = detect_extender_valuetype($value, $value_type); @@ -82,15 +82,15 @@ { return get_user($this->owner_guid); } - - /** - * Returns the entity this is attached to - * - * @return ElggEntity The enttiy - */ - public function getEntity() { - return get_entity($this->entity_guid); - } + + /** + * Returns the entity this is attached to + * + * @return ElggEntity The enttiy + */ + public function getEntity() { + return get_entity($this->entity_guid); + } /** * Save this data to the appropriate database table. @@ -101,15 +101,15 @@ * Delete this data. */ abstract public function delete(); - - /** - * Determines whether or not the specified user can edit this - * - * @param int $user_guid The GUID of the user (defaults to currently logged in user) - * @return true|false - */ - public function canEdit($user_guid = 0) { - return can_edit_extender($this->id,$this->type,$user_guid); + + /** + * Determines whether or not the specified user can edit this + * + * @param int $user_guid The GUID of the user (defaults to currently logged in user) + * @return true|false + */ + public function canEdit($user_guid = 0) { + return can_edit_extender($this->id,$this->type,$user_guid); } /** @@ -333,40 +333,40 @@ return true; } } - - /** - * Determines whether or not the specified user can edit the specified piece of extender - * - * @param int $extender_id The ID of the piece of extender - * @param string $type 'metadata' or 'annotation' - * @param int $user_guid The GUID of the user - * @return true|false - */ + + /** + * Determines whether or not the specified user can edit the specified piece of extender + * + * @param int $extender_id The ID of the piece of extender + * @param string $type 'metadata' or 'annotation' + * @param int $user_guid The GUID of the user + * @return true|false + */ function can_edit_extender($extender_id, $type, $user_guid = 0) { - - if (!isloggedin()) - return false; + + if (!isloggedin()) + return false; $user_guid = (int)$user_guid; $user = get_entity($user_guid); - if (!$user) $user = get_loggedin_user(); - - $functionname = "get_{$type}"; - if (is_callable($functionname)) { - $extender = $functionname($extender_id); - } else return false; - - if (!is_a($extender,"ElggExtender")) return false; - - // If the owner is the specified user, great! They can edit. - if ($extender->getOwner() == $user->getGUID()) return true; - - // If the user can edit the entity this is attached to, great! They can edit. - if (can_edit_entity($extender->entity_guid,$user->getGUID())) return true; - - // Trigger plugin hooks - return trigger_plugin_hook('permissions_check',$type,array('entity' => $entity, 'user' => $user),false); - + if (!$user) $user = get_loggedin_user(); + + $functionname = "get_{$type}"; + if (is_callable($functionname)) { + $extender = $functionname($extender_id); + } else return false; + + if (!is_a($extender,"ElggExtender")) return false; + + // If the owner is the specified user, great! They can edit. + if ($extender->getOwner() == $user->getGUID()) return true; + + // If the user can edit the entity this is attached to, great! They can edit. + if (can_edit_entity($extender->entity_guid,$user->getGUID())) return true; + + // Trigger plugin hooks + return trigger_plugin_hook('permissions_check',$type,array('entity' => $entity, 'user' => $user),false); + } /** @@ -432,7 +432,7 @@ $url = $CONFIG->wwwroot . "export/$view/$guid/$type/$nameid/"; } return $url; - } + } /** Register the hook */ register_plugin_hook("import", "all", "import_extender_plugin_hook", 2); diff --git a/engine/lib/input.php b/engine/lib/input.php index 338df2a08..71abbb330 100644 --- a/engine/lib/input.php +++ b/engine/lib/input.php @@ -1,66 +1,66 @@ - - * @author Curverider Ltd + * @link http://elgg.org/ + */ - * @link http://elgg.org/ - */ - - /** - * Get some input from variables passed on the GET or POST line. - * - * @param $variable string The variable we want to return. + /** + * Get some input from variables passed on the GET or POST line. + * + * @param $variable string The variable we want to return. * @param $default mixed A default value for the variable if it is not found. - * @param $filter_result If true then the result is filtered for bad tags. - */ - function get_input($variable, $default = "", $filter_result = true) - { - - global $CONFIG; - - if (isset($CONFIG->input[$variable])) { + * @param $filter_result If true then the result is filtered for bad tags. + */ + function get_input($variable, $default = "", $filter_result = true) + { + + global $CONFIG; + + if (isset($CONFIG->input[$variable])) { $var = $CONFIG->input[$variable]; if ($filter_result) $var = filter_tags($var); return $var; - } - + } + if (isset($_REQUEST[$variable])) { - + if (is_array($_REQUEST[$variable])) { $var = $_REQUEST[$variable]; } else { - $var = trim($_REQUEST[$variable]); - } + $var = trim($_REQUEST[$variable]); + } if ($filter_result) - $var = filter_tags($var); - - return $var; - - } - - return $default; - - } - - /** - * Sets an input value that may later be retrieved by get_input - * - * @param string $variable The name of the variable - * @param string $value The value of the variable - */ - function set_input($variable, $value) { - - global $CONFIG; - if (!isset($CONFIG->input)) + $var = filter_tags($var); + + return $var; + + } + + return $default; + + } + + /** + * Sets an input value that may later be retrieved by get_input + * + * @param string $variable The name of the variable + * @param string $value The value of the variable + */ + function set_input($variable, $value) { + + global $CONFIG; + if (!isset($CONFIG->input)) $CONFIG->input = array(); if (is_array($value)) @@ -70,19 +70,19 @@ $CONFIG->input[trim($variable)] = $value; } - else - $CONFIG->input[trim($variable)] = trim($value); - - } - - /** - * Filter tags from a given string based on registered hooks. - * @param $var - * @return mixed The filtered result - */ - function filter_tags($var) - { - return trigger_plugin_hook('validate', 'input', null, $var); + else + $CONFIG->input[trim($variable)] = trim($value); + + } + + /** + * Filter tags from a given string based on registered hooks. + * @param $var + * @return mixed The filtered result + */ + function filter_tags($var) + { + return trigger_plugin_hook('validate', 'input', null, $var); } /** @@ -102,15 +102,15 @@ $path = $path . "/"; return $path; - } + } + - - /** - * Takes a string and turns any URLs into formatted links - * - * @param string $text The input string - * @return string The output stirng with formatted links - **/ + /** + * Takes a string and turns any URLs into formatted links + * + * @param string $text The input string + * @return string The output stirng with formatted links + **/ function parse_urls($text) { return preg_replace_callback('/(?"\'\!\(\)]+)/i', @@ -121,110 +121,110 @@ $urltext = str_replace("/", "/", $url); return "$urltext"; ' - ), $text); - } - - function autop($pee, $br = 1) { - $pee = $pee . "\n"; // just to make things a little easier, pad the end - $pee = preg_replace('|
\s*
|', "\n\n", $pee); - // Space things out a little - $allblocks = '(?:table|thead|tfoot|caption|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|map|area|blockquote|address|math|style|input|p|h[1-6]|hr)'; - $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee); - $pee = preg_replace('!()!', "$1\n\n", $pee); - $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines - if ( strpos($pee, ']*)>\s*|', "", $pee); // no pee inside object/embed - $pee = preg_replace('|\s*\s*|', '', $pee); - } - $pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates - $pee = preg_replace('/\n?(.+?)(?:\n\s*\n|\z)/s', "

$1

\n", $pee); // make paragraphs, including one at the end - $pee = preg_replace('|

\s*?

|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace - $pee = preg_replace('!

([^<]+)\s*?(]*>)!', "

$1

$2", $pee); - $pee = preg_replace( '|

|', "$1

", $pee ); - $pee = preg_replace('!

\s*(]*>)\s*

!', "$1", $pee); // don't pee all over a tag - $pee = preg_replace("|

(|", "$1", $pee); // problem with nested lists - $pee = preg_replace('|

]*)>|i', "

", $pee); - $pee = str_replace('

', '

', $pee); - $pee = preg_replace('!

\s*(]*>)!', "$1", $pee); - $pee = preg_replace('!(]*>)\s*

!', "$1", $pee); - if ($br) { - $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', create_function('$matches', 'return str_replace("\n", "", $matches[0]);'), $pee); - $pee = preg_replace('|(?)\s*\n|', "
\n", $pee); // optionally make line breaks - $pee = str_replace('', "\n", $pee); - } - $pee = preg_replace('!(]*>)\s*
!', "$1", $pee); - $pee = preg_replace('!
(\s*]*>)!', '$1', $pee); - if (strpos($pee, ')(.*?)!is', 'clean_pre', $pee ); - $pee = preg_replace( "|\n

$|", '

', $pee ); - - return $pee; - } - - function input_init() { - - if (ini_get_bool('magic_quotes_gpc') ) { - - //do keys as well, cos array_map ignores them - function stripslashes_arraykeys($array) { - if (is_array($array)) { - $array2 = array(); - foreach ($array as $key => $data) { - if ($key != stripslashes($key)) { - $array2[stripslashes($key)] = $data; - } else { - $array2[$key] = $data; - } - } - return $array2; - } else { - return $array; - } - } - - function stripslashes_deep($value) { - if (is_array($value)) { - $value = stripslashes_arraykeys($value); - $value = array_map('stripslashes_deep', $value); - } else { - $value = stripslashes($value); - } - return $value; - } - - $_POST = stripslashes_arraykeys($_POST); - $_GET = stripslashes_arraykeys($_GET); - $_COOKIE = stripslashes_arraykeys($_COOKIE); - $_REQUEST = stripslashes_arraykeys($_REQUEST); - - $_POST = array_map('stripslashes_deep', $_POST); - $_GET = array_map('stripslashes_deep', $_GET); - $_COOKIE = array_map('stripslashes_deep', $_COOKIE); - $_REQUEST = array_map('stripslashes_deep', $_REQUEST); - if (!empty($_SERVER['REQUEST_URI'])) { - $_SERVER['REQUEST_URI'] = stripslashes($_SERVER['REQUEST_URI']); - } - if (!empty($_SERVER['QUERY_STRING'])) { - $_SERVER['QUERY_STRING'] = stripslashes($_SERVER['QUERY_STRING']); - } - if (!empty($_SERVER['HTTP_REFERER'])) { - $_SERVER['HTTP_REFERER'] = stripslashes($_SERVER['HTTP_REFERER']); - } - if (!empty($_SERVER['PATH_INFO'])) { - $_SERVER['PATH_INFO'] = stripslashes($_SERVER['PATH_INFO']); - } - if (!empty($_SERVER['PHP_SELF'])) { - $_SERVER['PHP_SELF'] = stripslashes($_SERVER['PHP_SELF']); - } - if (!empty($_SERVER['PATH_TRANSLATED'])) { - $_SERVER['PATH_TRANSLATED'] = stripslashes($_SERVER['PATH_TRANSLATED']); - } - + ), $text); + } + + function autop($pee, $br = 1) { + $pee = $pee . "\n"; // just to make things a little easier, pad the end + $pee = preg_replace('|
\s*
|', "\n\n", $pee); + // Space things out a little + $allblocks = '(?:table|thead|tfoot|caption|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|map|area|blockquote|address|math|style|input|p|h[1-6]|hr)'; + $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee); + $pee = preg_replace('!()!', "$1\n\n", $pee); + $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines + if ( strpos($pee, ']*)>\s*|', "", $pee); // no pee inside object/embed + $pee = preg_replace('|\s*\s*|', '', $pee); + } + $pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates + $pee = preg_replace('/\n?(.+?)(?:\n\s*\n|\z)/s', "

$1

\n", $pee); // make paragraphs, including one at the end + $pee = preg_replace('|

\s*?

|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace + $pee = preg_replace('!

([^<]+)\s*?(]*>)!', "

$1

$2", $pee); + $pee = preg_replace( '|

|', "$1

", $pee ); + $pee = preg_replace('!

\s*(]*>)\s*

!', "$1", $pee); // don't pee all over a tag + $pee = preg_replace("|

(|", "$1", $pee); // problem with nested lists + $pee = preg_replace('|

]*)>|i', "

", $pee); + $pee = str_replace('

', '

', $pee); + $pee = preg_replace('!

\s*(]*>)!', "$1", $pee); + $pee = preg_replace('!(]*>)\s*

!', "$1", $pee); + if ($br) { + $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', create_function('$matches', 'return str_replace("\n", "", $matches[0]);'), $pee); + $pee = preg_replace('|(?)\s*\n|', "
\n", $pee); // optionally make line breaks + $pee = str_replace('', "\n", $pee); + } + $pee = preg_replace('!(]*>)\s*
!', "$1", $pee); + $pee = preg_replace('!
(\s*]*>)!', '$1', $pee); + if (strpos($pee, ')(.*?)!is', 'clean_pre', $pee ); + $pee = preg_replace( "|\n

$|", '

', $pee ); + + return $pee; + } + + function input_init() { + + if (ini_get_bool('magic_quotes_gpc') ) { + + //do keys as well, cos array_map ignores them + function stripslashes_arraykeys($array) { + if (is_array($array)) { + $array2 = array(); + foreach ($array as $key => $data) { + if ($key != stripslashes($key)) { + $array2[stripslashes($key)] = $data; + } else { + $array2[$key] = $data; + } + } + return $array2; + } else { + return $array; + } + } + + function stripslashes_deep($value) { + if (is_array($value)) { + $value = stripslashes_arraykeys($value); + $value = array_map('stripslashes_deep', $value); + } else { + $value = stripslashes($value); + } + return $value; + } + + $_POST = stripslashes_arraykeys($_POST); + $_GET = stripslashes_arraykeys($_GET); + $_COOKIE = stripslashes_arraykeys($_COOKIE); + $_REQUEST = stripslashes_arraykeys($_REQUEST); + + $_POST = array_map('stripslashes_deep', $_POST); + $_GET = array_map('stripslashes_deep', $_GET); + $_COOKIE = array_map('stripslashes_deep', $_COOKIE); + $_REQUEST = array_map('stripslashes_deep', $_REQUEST); + if (!empty($_SERVER['REQUEST_URI'])) { + $_SERVER['REQUEST_URI'] = stripslashes($_SERVER['REQUEST_URI']); + } + if (!empty($_SERVER['QUERY_STRING'])) { + $_SERVER['QUERY_STRING'] = stripslashes($_SERVER['QUERY_STRING']); + } + if (!empty($_SERVER['HTTP_REFERER'])) { + $_SERVER['HTTP_REFERER'] = stripslashes($_SERVER['HTTP_REFERER']); + } + if (!empty($_SERVER['PATH_INFO'])) { + $_SERVER['PATH_INFO'] = stripslashes($_SERVER['PATH_INFO']); + } + if (!empty($_SERVER['PHP_SELF'])) { + $_SERVER['PHP_SELF'] = stripslashes($_SERVER['PHP_SELF']); + } + if (!empty($_SERVER['PATH_TRANSLATED'])) { + $_SERVER['PATH_TRANSLATED'] = stripslashes($_SERVER['PATH_TRANSLATED']); + } + } - - } - - register_elgg_event_handler('init','system','input_init'); - - + + } + + register_elgg_event_handler('init','system','input_init'); + + ?> \ No newline at end of file diff --git a/engine/lib/install.php b/engine/lib/install.php index 6faa70ef5..03abede14 100644 --- a/engine/lib/install.php +++ b/engine/lib/install.php @@ -1,16 +1,16 @@ -=')) && (version_compare(phpversion(), '5.2.0', '<')) ) - register_error(elgg_echo('configurationwarning:phpversion')); + register_error(elgg_echo('configurationwarning:phpversion')); */ if (version_compare(phpversion(), '5.1.2', '>=')) @@ -53,12 +53,12 @@ return true; } - - /** - * Returns whether or not the database has been installed - * - * @return true|false Whether the database has been installed - */ + + /** + * Returns whether or not the database has been installed + * + * @return true|false Whether the database has been installed + */ function is_db_installed() { global $CONFIG; @@ -66,29 +66,29 @@ if (isset($CONFIG->db_installed)) { return $CONFIG->db_installed; } - - if ($dblink = get_db_link('read')) { - mysql_query("select name from {$CONFIG->dbprefix}datalists limit 1",$dblink); - if (mysql_errno($dblink) > 0) return false; + + if ($dblink = get_db_link('read')) { + mysql_query("select name from {$CONFIG->dbprefix}datalists limit 1",$dblink); + if (mysql_errno($dblink) > 0) return false; } else return false; $CONFIG->db_installed = true; // Set flag if db is installed (if false then we want to check every time) - - return true; - - } - - /** - * Returns whether or not other settings have been set - * - * @return true|false Whether or not the rest of the installation has been followed through with - */ - function is_installed() { - - global $CONFIG; - return datalist_get('installed'); - - } + + return true; + + } + + /** + * Returns whether or not other settings have been set + * + * @return true|false Whether or not the rest of the installation has been followed through with + */ + function is_installed() { + + global $CONFIG; + return datalist_get('installed'); + + } /** * Copy and create a new settings.php from settings.example.php, substituting the variables in @@ -112,15 +112,15 @@ return $file; } - - /** - * Initialisation for installation functions - * - */ - function install_init() { - register_action("systemsettings/install",true); - } - - register_elgg_event_handler("boot","system","install_init"); - + + /** + * Initialisation for installation functions + * + */ + function install_init() { + register_action("systemsettings/install",true); + } + + register_elgg_event_handler("boot","system","install_init"); + ?> \ No newline at end of file diff --git a/engine/lib/languages.php b/engine/lib/languages.php index bca0466ea..dd97d0927 100644 --- a/engine/lib/languages.php +++ b/engine/lib/languages.php @@ -1,51 +1,51 @@ - 'message1', 'message2' => 'message2'); + * $german = array('message1' => 'Nachricht1','message2' => 'Nachricht2'); + * + * @param string $country_code Standard country code (eg 'en', 'nl', 'es') + * @param array $language_array Formatted array of strings + * @return true|false Depending on success + */ - * @link http://elgg.org/ - */ - - /** - * Add a translation. - * - * Translations are arrays in the Zend Translation array format, eg: - * - * $english = array('message1' => 'message1', 'message2' => 'message2'); - * $german = array('message1' => 'Nachricht1','message2' => 'Nachricht2'); - * - * @param string $country_code Standard country code (eg 'en', 'nl', 'es') - * @param array $language_array Formatted array of strings - * @return true|false Depending on success - */ - - function add_translation($country_code, $language_array) { - - global $CONFIG; - if (!isset($CONFIG->translations)) - $CONFIG->translations = array(); - - $country_code = strtolower($country_code); - $country_code = trim($country_code); - if (is_array($language_array) && sizeof($language_array) > 0 && $country_code != "") { - - if (!isset($CONFIG->translations[$country_code])) { - $CONFIG->translations[$country_code] = $language_array; - } else { - $CONFIG->translations[$country_code] = $language_array + $CONFIG->translations[$country_code]; - } - - return true; - - } - return false; - + function add_translation($country_code, $language_array) { + + global $CONFIG; + if (!isset($CONFIG->translations)) + $CONFIG->translations = array(); + + $country_code = strtolower($country_code); + $country_code = trim($country_code); + if (is_array($language_array) && sizeof($language_array) > 0 && $country_code != "") { + + if (!isset($CONFIG->translations[$country_code])) { + $CONFIG->translations[$country_code] = $language_array; + } else { + $CONFIG->translations[$country_code] = $language_array + $CONFIG->translations[$country_code]; + } + + return true; + + } + return false; + } /** @@ -62,130 +62,130 @@ $language = 'en'; return $language; - } - - /** - * Gets the current language in use by the system or user. - * - * [Marcus Povey 20090216: Not sure why this func is necessary.] - * - * @return string The language code (eg "en") - */ - function get_language() { - - global $CONFIG; - + } + + /** + * Gets the current language in use by the system or user. + * + * [Marcus Povey 20090216: Not sure why this func is necessary.] + * + * @return string The language code (eg "en") + */ + function get_language() { + + global $CONFIG; + $user = get_loggedin_user(); - $language = false; - - if (($user) && ($user->language)) - $language = $user->language; - - if ((!$language) && (isset($CONFIG->language)) && ($CONFIG->language)) + $language = false; + + if (($user) && ($user->language)) + $language = $user->language; + + if ((!$language) && (isset($CONFIG->language)) && ($CONFIG->language)) $language = $CONFIG->language; - if ($language) { - return $language; - } - return false; - - } - - /** - * Given a message shortcode, returns an appropriately translated full-text string - * - * @param string $message_key The short message code - * @param string $language Optionally, the standard language code (defaults to the site default, then English) - * @return string Either the translated string, or the original English string, or an empty string - */ - function elgg_echo($message_key, $language = "") { - + if ($language) { + return $language; + } + return false; + + } + + /** + * Given a message shortcode, returns an appropriately translated full-text string + * + * @param string $message_key The short message code + * @param string $language Optionally, the standard language code (defaults to the site default, then English) + * @return string Either the translated string, or the original English string, or an empty string + */ + function elgg_echo($message_key, $language = "") { + global $CONFIG; static $CURRENT_LANGUAGE; - if ((!$CURRENT_LANGUAGE) && (!$language)) + if ((!$CURRENT_LANGUAGE) && (!$language)) $CURRENT_LANGUAGE = $language = get_language(); else - $language = $CURRENT_LANGUAGE; - - if (isset($CONFIG->translations[$language][$message_key])) { - return $CONFIG->translations[$language][$message_key]; - } else if (isset($CONFIG->translations["en"][$message_key])) { - return $CONFIG->translations["en"][$message_key]; - } - - return $message_key; - - } - - /** - * When given a full path, finds translation files and loads them - * - * @param string $path Full path - * @param bool $load_all If true all languages are loaded, if false only the current language + en are loaded - */ + $language = $CURRENT_LANGUAGE; + + if (isset($CONFIG->translations[$language][$message_key])) { + return $CONFIG->translations[$language][$message_key]; + } else if (isset($CONFIG->translations["en"][$message_key])) { + return $CONFIG->translations["en"][$message_key]; + } + + return $message_key; + + } + + /** + * When given a full path, finds translation files and loads them + * + * @param string $path Full path + * @param bool $load_all If true all languages are loaded, if false only the current language + en are loaded + */ function register_translations($path, $load_all = false) { global $CONFIG; - - // Make a note of this path just incase we need to register this language later - if(!isset($CONFIG->language_paths)) $CONFIG->language_paths = array(); - $CONFIG->language_paths[$path] = true; - - // Get the current language based on site defaults and user preference - $current_language = get_current_language(); - - if (isset($CONFIG->debug) && $CONFIG->debug == true) error_log("Translations loaded from : $path"); + + // Make a note of this path just incase we need to register this language later + if(!isset($CONFIG->language_paths)) $CONFIG->language_paths = array(); + $CONFIG->language_paths[$path] = true; + + // Get the current language based on site defaults and user preference + $current_language = get_current_language(); + + if (isset($CONFIG->debug) && $CONFIG->debug == true) error_log("Translations loaded from : $path"); - if ($handle = opendir($path)) { - while ($language = readdir($handle)) { - - if ( - ((in_array($language, array('en.php', $current_language . '.php'))) /*&& (!is_dir($path . $language))*/) || - (($load_all) && (strpos($language, '.php')!==false)/* && (!is_dir($path . $language))*/) - ) - include_once($path . $language); - - } + if ($handle = opendir($path)) { + while ($language = readdir($handle)) { + + if ( + ((in_array($language, array('en.php', $current_language . '.php'))) /*&& (!is_dir($path . $language))*/) || + (($load_all) && (strpos($language, '.php')!==false)/* && (!is_dir($path . $language))*/) + ) + include_once($path . $language); + + } } else - error_log("Missing translation path $path"); - - } - - /** - * Reload all translations from all registered paths. - * - * This is only called by functions which need to know all possible translations, namely the - * statistic gathering ones. - * - * TODO: Better on demand loading based on language_paths array - * - * @return bool - */ - function reload_all_translations() - { - global $CONFIG; - - static $LANG_RELOAD_ALL_RUN; - if ($LANG_RELOAD_ALL_RUN) return null; - - foreach ($CONFIG->language_paths as $path => $dummy) - register_translations($path, true); - - $LANG_RELOAD_ALL_RUN = true; - } + error_log("Missing translation path $path"); + + } + + /** + * Reload all translations from all registered paths. + * + * This is only called by functions which need to know all possible translations, namely the + * statistic gathering ones. + * + * TODO: Better on demand loading based on language_paths array + * + * @return bool + */ + function reload_all_translations() + { + global $CONFIG; + + static $LANG_RELOAD_ALL_RUN; + if ($LANG_RELOAD_ALL_RUN) return null; + + foreach ($CONFIG->language_paths as $path => $dummy) + register_translations($path, true); + + $LANG_RELOAD_ALL_RUN = true; + } /** * Return an array of installed translations as an associative array "two letter code" => "native language name". */ function get_installed_translations() { - global $CONFIG; - - // Ensure that all possible translations are loaded + global $CONFIG; + + // Ensure that all possible translations are loaded reload_all_translations(); - $installed = array(); + $installed = array(); foreach ($CONFIG->translations as $k => $v) { @@ -204,9 +204,9 @@ */ function get_language_completeness($language) { - global $CONFIG; - - // Ensure that all possible translations are loaded + global $CONFIG; + + // Ensure that all possible translations are loaded reload_all_translations(); $language = sanitise_string($language); @@ -227,9 +227,9 @@ */ function get_missing_language_keys($language) { - global $CONFIG; - - // Ensure that all possible translations are loaded + global $CONFIG; + + // Ensure that all possible translations are loaded reload_all_translations(); $missing = array(); @@ -248,5 +248,5 @@ } register_translations(dirname(dirname(dirname(__FILE__))) . "/languages/"); - + ?> \ No newline at end of file diff --git a/engine/lib/metadata.php b/engine/lib/metadata.php index 9aa033061..c6e5db4cd 100644 --- a/engine/lib/metadata.php +++ b/engine/lib/metadata.php @@ -1,912 +1,912 @@ - + * @author Curverider Ltd - * @link http://elgg.org/ - */ - - /** - * ElggMetadata - * This class describes metadata that can be attached to ElggEntities. - * - * @author Curverider Ltd - * @package Elgg - * @subpackage Core - */ - class ElggMetadata extends ElggExtender - { - - /** - * Construct a new site object, optionally from a given id value or row. - * - * @param mixed $id - */ - function __construct($id = null) - { - $this->attributes = array(); - - if (!empty($id)) { - - if ($id instanceof stdClass) - $metadata = $id; // Create from db row - else - $metadata = get_metadata($id); - - if ($metadata) { - $objarray = (array) $metadata; - foreach($objarray as $key => $value) { - $this->attributes[$key] = $value; - } - $this->attributes['type'] = "metadata"; - } - } - } - - /** - * Class member get overloading - * - * @param string $name - * @return mixed - */ - function __get($name) { - return $this->get($name); - } - - /** - * Class member set overloading - * - * @param string $name - * @param mixed $value - * @return mixed - */ - function __set($name, $value) { - return $this->set($name, $value); - } - - /** - * Determines whether or not the user can edit this piece of metadata - * - * @return true|false Depending on permissions - */ - function canEdit() { - - if ($entity = get_entity($this->get('entity_guid'))) { - return $entity->canEditMetadata($this); - } - return false; - - } - - /** - * Save matadata object - * - * @return int the metadata object id - */ - function save() - { - if ($this->id > 0) - return update_metadata($this->id, $this->name, $this->value, $this->value_type, $this->owner_guid, $this->access_id); - else - { - $this->id = create_metadata($this->entity_guid, $this->name, $this->value, $this->value_type, $this->owner_guid, $this->access_id); - if (!$this->id) throw new IOException(sprintf(elgg_new('IOException:UnableToSaveNew'), get_class())); - return $this->id; - } - - } - - /** - * Delete a given metadata. - */ - function delete() - { - return delete_metadata($this->id); - } - - /** - * Get a url for this item of metadata. - * - * @return string - */ - public function getURL() { return get_metadata_url($this->id); } - - // SYSTEM LOG INTERFACE //////////////////////////////////////////////////////////// - - /** - * For a given ID, return the object associated with it. - * This is used by the river functionality primarily. - * This is useful for checking access permissions etc on objects. - */ - public function getObjectFromID($id) { return get_metadata($id); } - } - - /** - * Convert a database row to a new ElggMetadata - * - * @param stdClass $row - * @return stdClass or ElggMetadata - */ - function row_to_elggmetadata($row) - { - if (!($row instanceof stdClass)) - return $row; - - return new ElggMetadata($row); - } - - - /** - * Get a specific item of metadata. - * - * @param $id int The item of metadata being retrieved. - */ - function get_metadata($id) - { - global $CONFIG; - - $id = (int)$id; - $access = get_access_sql_suffix("e"); - $md_access = get_access_sql_suffix("m"); - - return row_to_elggmetadata(get_data_row("SELECT m.*, n.string as name, v.string as value from {$CONFIG->dbprefix}metadata m JOIN {$CONFIG->dbprefix}entities e on e.guid = m.entity_guid JOIN {$CONFIG->dbprefix}metastrings v on m.value_id = v.id JOIN {$CONFIG->dbprefix}metastrings n on m.name_id = n.id where m.id=$id and $access and $md_access")); - } - - /** - * Removes metadata on an entity with a particular name, optionally with a given value. - * - * @param int $entity_guid The entity GUID - * @param string $name The name of the metadata - * @param string $value The optional value of the item (useful for removing a single item in a multiple set) - * @return true|false Depending on success - */ - function remove_metadata($entity_guid, $name, $value = "") { - - global $CONFIG; - $entity_guid = (int) $entity_guid; - $name = sanitise_string($name); - $value = sanitise_string($value); - - $query = "SELECT * from {$CONFIG->dbprefix}metadata WHERE entity_guid = $entity_guid and name_id=" . add_metastring($name); - if ($value!="") - $query .= " and value_id=" . add_metastring($value); - - if ($existing = get_data($query)) { - foreach($existing as $ex) - delete_metadata($ex->id); - return true; - } - return false; - - } - - /** - * Create a new metadata object, or update an existing one. - * - * @param int $entity_guid - * @param string $name - * @param string $value - * @param string $value_type - * @param int $owner_guid - * @param int $access_id - * @param bool $allow_multiple - */ - function create_metadata($entity_guid, $name, $value, $value_type, $owner_guid, $access_id = ACCESS_PRIVATE, $allow_multiple = false) - { - global $CONFIG; - - $entity_guid = (int)$entity_guid; - //$name = sanitise_string(trim($name)); - //$value = sanitise_string(trim($value)); - $value_type = detect_extender_valuetype($value, sanitise_string(trim($value_type))); - $time = time(); - $owner_guid = (int)$owner_guid; - $allow_multiple = (boolean)$allow_multiple; - - if ($owner_guid==0) $owner_guid = get_loggedin_userid(); - - $access_id = (int)$access_id; - - $id = false; - - $existing = get_data_row("SELECT * from {$CONFIG->dbprefix}metadata WHERE entity_guid = $entity_guid and name_id=" . add_metastring($name) . " limit 1"); - if (($existing) && (!$allow_multiple) && (isset($value))) - { - $id = $existing->id; - $result = update_metadata($id, $name, $value, $value_type, $owner_guid, $access_id); - - if (!$result) return false; - } - else if (isset($value)) - { - // Support boolean types - if (is_bool($value)) { - if ($value) - $value = 1; - else - $value = 0; - } - - // Add the metastrings - $value = add_metastring($value); - if (!$value) return false; - - $name = add_metastring($name); - if (!$name) return false; - - // If ok then add it - $id = insert_data("INSERT into {$CONFIG->dbprefix}metadata (entity_guid, name_id, value_id, value_type, owner_guid, time_created, access_id) VALUES ($entity_guid, '$name','$value','$value_type', $owner_guid, $time, $access_id)"); - - if ($id!==false) { - $obj = get_metadata($id); - if (trigger_elgg_event('create', 'metadata', $obj)) { - return true; - } else { - delete_metadata($id); - } - } - - } else if ($existing) { -// TODO: Check... are you sure you meant to do this Ben? :) - $id = $existing->id; - delete_metadata($id); - - } - - return $id; - } - - /** - * Update an item of metadata. - * - * @param int $id - * @param string $name - * @param string $value - * @param string $value_type - * @param int $owner_guid - * @param int $access_id - */ - function update_metadata($id, $name, $value, $value_type, $owner_guid, $access_id) - { - global $CONFIG; - - $id = (int)$id; - - if (!$md = get_metadata($id)) return false; - if (!$md->canEdit()) return false; - - // If memcached then we invalidate the cache for this entry - static $metabyname_memcache; - if ((!$metabyname_memcache) && (is_memcache_available())) - $metabyname_memcache = new ElggMemcache('metabyname_memcache'); - if ($metabyname_memcache) $metabyname_memcache->delete("{$md->entity_guid}:{$md->name_id}"); - - //$name = sanitise_string(trim($name)); - //$value = sanitise_string(trim($value)); - $value_type = detect_extender_valuetype($value, sanitise_string(trim($value_type))); - - $owner_guid = (int)$owner_guid; - if ($owner_guid==0) $owner_guid = get_loggedin_userid(); - - $access_id = (int)$access_id; - - $access = get_access_sql_suffix(); - - // Support boolean types (as integers) - if (is_bool($value)) { - if ($value) - $value = 1; - else - $value = 0; - } - - // Add the metastring - $value = add_metastring($value); - if (!$value) return false; - - $name = add_metastring($name); - if (!$name) return false; - - // If ok then add it - $result = update_data("UPDATE {$CONFIG->dbprefix}metadata set value_id='$value', value_type='$value_type', access_id=$access_id, owner_guid=$owner_guid where id=$id and name_id='$name'"); - if ($result!==false) { - $obj = get_metadata($id); - if (trigger_elgg_event('update', 'metadata', $obj)) { - return true; - } else { - delete_metadata($id); - } - } - - return $result; - } - - /** - * This function creates metadata from an associative array of "key => value" pairs. - * - * @param int $entity_guid - * @param string $name_and_values - * @param string $value_type - * @param int $owner_guid - * @param int $access_id - * @param bool $allow_multiple - */ - function create_metadata_from_array($entity_guid, array $name_and_values, $value_type, $owner_guid, $access_id = ACCESS_PRIVATE, $allow_multiple = false) - { - foreach ($name_and_values as $k => $v) - if (!create_metadata($entity_guid, $k, $v, $value_type, $owner_guid, $access_id, $allow_multiple)) return false; - - return true; - } - - /** - * Delete an item of metadata, where the current user has access. - * - * @param $id int The item of metadata to delete. - */ - function delete_metadata($id) - { - global $CONFIG; - - $id = (int)$id; - $metadata = get_metadata($id); - - if ($metadata) { - // Tidy up if memcache is enabled. - static $metabyname_memcache; - if ((!$metabyname_memcache) && (is_memcache_available())) - $metabyname_memcache = new ElggMemcache('metabyname_memcache'); - if ($metabyname_memcache) $metabyname_memcache->delete("{$metadata->entity_guid}:{$metadata->name_id}"); - - if (($metadata->canEdit()) && (trigger_elgg_event('delete', 'metadata', $metadata))) - return delete_data("DELETE from {$CONFIG->dbprefix}metadata where id=$id"); - } - - return false; - } - - /** - * Return the metadata values that match your query. - * - * @param string $meta_name - * @return mixed either a value, an array of ElggMetadata or false. - */ - function get_metadata_byname($entity_guid, $meta_name) - { - global $CONFIG; - - $meta_name = get_metastring_id($meta_name); - - if (empty($meta_name)) return false; - - $entity_guid = (int)$entity_guid; - $access = get_access_sql_suffix("e"); - $md_access = get_access_sql_suffix("m"); - - // If memcache is available then cache this (cache only by name for now since this is the most common query) - $meta = null; - static $metabyname_memcache; - if ((!$metabyname_memcache) && (is_memcache_available())) - $metabyname_memcache = new ElggMemcache('metabyname_memcache'); - if ($metabyname_memcache) $meta = $metabyname_memcache->load("{$entity_guid}:{$meta_name}"); - if ($meta) return $meta; - - $result = get_data("SELECT m.*, n.string as name, v.string as value from {$CONFIG->dbprefix}metadata m JOIN {$CONFIG->dbprefix}entities e ON e.guid = m.entity_guid JOIN {$CONFIG->dbprefix}metastrings v on m.value_id = v.id JOIN {$CONFIG->dbprefix}metastrings n on m.name_id = n.id where m.entity_guid=$entity_guid and m.name_id='$meta_name' and $access and $md_access", "row_to_elggmetadata"); - if (!$result) - return false; - - // Cache if memcache available - if ($metabyname_memcache) - { - if (count($result) == 1) $r = $result[0]; else $r = $result; - $metabyname_memcache->setDefaultExpiry(3600); // This is a bit of a hack - we shorten the expiry on object metadata so that it'll be gone in an hour. This means that deletions and more importantly updates will filter through eventually. - $metabyname_memcache->save("{$entity_guid}:{$meta_name}", $r); - - } - if (count($result) == 1) - return $result[0]; - - return $result; - } - - /** - * Return all the metadata for a given GUID. - * - * @param int $entity_guid - */ - function get_metadata_for_entity($entity_guid) - { - global $CONFIG; - - $entity_guid = (int)$entity_guid; - $access = get_access_sql_suffix("e"); - $md_access = get_access_sql_suffix("m"); - - return get_data("SELECT m.*, n.string as name, v.string as value from {$CONFIG->dbprefix}metadata m JOIN {$CONFIG->dbprefix}entities e ON e.guid = m.entity_guid JOIN {$CONFIG->dbprefix}metastrings v on m.value_id = v.id JOIN {$CONFIG->dbprefix}metastrings n on m.name_id = n.id where m.entity_guid=$entity_guid and $access and $md_access", "row_to_elggmetadata"); - } - - /** - * Get the metadata where the entities they are referring to match a given criteria. - * - * @param mixed $meta_name - * @param mixed $meta_value - * @param string $entity_type The type of entity to look for, eg 'site' or 'object' - * @param string $entity_subtype The subtype of the entity. - * @param int $limit - * @param int $offset - * @param string $order_by Optional ordering. - * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. - */ - function find_metadata($meta_name = "", $meta_value = "", $entity_type = "", $entity_subtype = "", $limit = 10, $offset = 0, $order_by = "", $site_guid = 0) - { - global $CONFIG; - - $meta_n = get_metastring_id($meta_name); - $meta_v = get_metastring_id($meta_value); - - $entity_type = sanitise_string($entity_type); - $entity_subtype = get_subtype_id($entity_type, $entity_subtype); - $limit = (int)$limit; - $offset = (int)$offset; - if ($order_by == "") $order_by = "e.time_created desc"; - $order_by = sanitise_string($order_by); - $site_guid = (int) $site_guid; - if ($site_guid == 0) - $site_guid = $CONFIG->site_guid; - - - $where = array(); - - if ($entity_type!="") - $where[] = "e.type='$entity_type'"; - if ($entity_subtype) - $where[] = "e.subtype=$entity_subtype"; - if ($meta_name!="") { - if (!$meta_v) return false; // The value is set, but we didn't get a value... so something went wrong. - $where[] = "m.name_id='$meta_n'"; - } - if ($meta_value!="") { - if (!$meta_v) return false; // The value is set, but we didn't get a value... so something went wrong. - $where[] = "m.value_id='$meta_v'"; - } - if ($site_guid > 0) - $where[] = "e.site_guid = {$site_guid}"; - - $query = "SELECT m.*, n.string as name, v.string as value from {$CONFIG->dbprefix}entities e JOIN {$CONFIG->dbprefix}metadata m on e.guid = m.entity_guid JOIN {$CONFIG->dbprefix}metastrings v on m.value_id = v.id JOIN {$CONFIG->dbprefix}metastrings n on m.name_id = n.id where"; - foreach ($where as $w) - $query .= " $w and "; - $query .= get_access_sql_suffix("e"); // Add access controls - $query .= ' and ' . get_access_sql_suffix("m"); // Add access controls - $query .= " order by $order_by limit $offset, $limit"; // Add order and limit - - return get_data($query, "row_to_elggmetadata"); - } - - /** - * Return a list of entities based on the given search criteria. - * - * @param mixed $meta_name - * @param mixed $meta_value - * @param string $entity_type The type of entity to look for, eg 'site' or 'object' - * @param string $entity_subtype The subtype of the entity. - * @param int $limit - * @param int $offset - * @param string $order_by Optional ordering. - * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. - * @param true|false $count If set to true, returns the total number of entities rather than a list. (Default: false) - * - * @return int|array A list of entities, or a count if $count is set to true - */ - function get_entities_from_metadata($meta_name, $meta_value = "", $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $offset = 0, $order_by = "", $site_guid = 0, $count = false) - { - global $CONFIG; - - $meta_n = get_metastring_id($meta_name); - $meta_v = get_metastring_id($meta_value); - - $entity_type = sanitise_string($entity_type); - $entity_subtype = get_subtype_id($entity_type, $entity_subtype); - $limit = (int)$limit; - $offset = (int)$offset; - if ($order_by == "") - $order_by = "e.time_created desc"; - else - $order_by = "e.time_created, {$order_by}"; - $order_by = sanitise_string($order_by); - $site_guid = (int) $site_guid; - if ((is_array($owner_guid) && (count($owner_guid)))) { - foreach($owner_guid as $key => $guid) { - $owner_guid[$key] = (int) $guid; - } - } else { - $owner_guid = (int) $owner_guid; - } - if ($site_guid == 0) - $site_guid = $CONFIG->site_guid; - - //$access = get_access_list(); - - $where = array(); - - if ($entity_type!=="") - $where[] = "e.type='$entity_type'"; - if ($entity_subtype) - $where[] = "e.subtype=$entity_subtype"; - if ($meta_name!=="") - $where[] = "m.name_id='$meta_n'"; - if ($meta_value!=="") - $where[] = "m.value_id='$meta_v'"; - if ($site_guid > 0) - $where[] = "e.site_guid = {$site_guid}"; - if (is_array($owner_guid)) { - $where[] = "e.container_guid in (".implode(",",$owner_guid).")"; - } else if ($owner_guid > 0) - $where[] = "e.container_guid = {$owner_guid}"; - - if (!$count) { - $query = "SELECT distinct e.* "; - } else { - $query = "SELECT count(distinct e.guid) as total "; - } - - $query .= "from {$CONFIG->dbprefix}entities e JOIN {$CONFIG->dbprefix}metadata m on e.guid = m.entity_guid where"; - foreach ($where as $w) - $query .= " $w and "; - $query .= get_access_sql_suffix("e"); // Add access controls - $query .= ' and ' . get_access_sql_suffix("m"); // Add access controls - - if (!$count) { - $query .= " order by $order_by limit $offset, $limit"; // Add order and limit - return get_data($query, "entity_row_to_elggstar"); - } else { - if ($row = get_data_row($query)) - return $row->total; - } - return false; - } - - /** - * Return a list of entities suitable for display based on the given search criteria. - * - * @see elgg_view_entity_list - * - * @param mixed $meta_name Metadata name to search on - * @param mixed $meta_value The value to match, optionally - * @param string $entity_type The type of entity to look for, eg 'site' or 'object' - * @param string $entity_subtype The subtype of the entity - * @param int $limit 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 the gallery view. Default: true - * @param true|false $pagination Display pagination? Default: true - * - * @return string A list of entities suitable for display - */ - function list_entities_from_metadata($meta_name, $meta_value = "", $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = true, $pagination = true) { - - $offset = (int) get_input('offset'); - $limit = (int) $limit; - $count = get_entities_from_metadata($meta_name, $meta_value, $entity_type, $entity_subtype, $owner_guid, $limit, $offset, "", 0, true); - $entities = get_entities_from_metadata($meta_name, $meta_value, $entity_type, $entity_subtype, $owner_guid, $limit, $offset, "", 0, false); - - return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); - - } - - /** - * Returns a list of entities based on the given search criteria. - * - * @param array $meta_array Array of 'name' => 'value' pairs - * @param string $entity_type The type of entity to look for, eg 'site' or 'object' - * @param string $entity_subtype The subtype of the entity. - * @param int $limit - * @param int $offset - * @param string $order_by Optional ordering. - * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. - * @param true|false $count If set to true, returns the total number of entities rather than a list. (Default: false) - * @param string $meta_array_operator Operator used for joining the metadata array together - * @return int|array List of ElggEntities, or the total number if count is set to false - */ - function get_entities_from_metadata_multi($meta_array, $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $offset = 0, $order_by = "", $site_guid = 0, $count = false, $meta_array_operator = 'and') - { - global $CONFIG; - - if (!is_array($meta_array) || sizeof($meta_array) == 0) { - return false; - } - - $where = array(); - - $mindex = 1; - $join = ""; - $metawhere = array(); - $meta_array_operator = sanitise_string($meta_array_operator); - foreach($meta_array as $meta_name => $meta_value) { - $meta_n = get_metastring_id($meta_name); - $meta_v = get_metastring_id($meta_value); - $join .= " JOIN {$CONFIG->dbprefix}metadata m{$mindex} on e.guid = m{$mindex}.entity_guid "; - /*if ($meta_name!=="") - $where[] = "m{$mindex}.name_id='$meta_n'"; - if ($meta_value!=="") - $where[] = "m{$mindex}.value_id='$meta_v'";*/ - $metawhere[] = "(m{$mindex}.name_id='$meta_n' AND m{$mindex}.value_id='$meta_v')"; - $mindex++; - } - $where[] = "(".implode($meta_array_operator, $metawhere).")"; - - $entity_type = sanitise_string($entity_type); - $entity_subtype = get_subtype_id($entity_type, $entity_subtype); - $limit = (int)$limit; - $offset = (int)$offset; - if ($order_by == "") $order_by = "e.time_created desc"; - $order_by = sanitise_string($order_by); - if ((is_array($owner_guid) && (count($owner_guid)))) { - foreach($owner_guid as $key => $guid) { - $owner_guid[$key] = (int) $guid; - } - } else { - $owner_guid = (int) $owner_guid; - } - - $site_guid = (int) $site_guid; - if ($site_guid == 0) - $site_guid = $CONFIG->site_guid; - - //$access = get_access_list(); - - if ($entity_type!="") - $where[] = "e.type = '{$entity_type}'"; - if ($entity_subtype) - $where[] = "e.subtype = {$entity_subtype}"; - if ($site_guid > 0) - $where[] = "e.site_guid = {$site_guid}"; - if (is_array($owner_guid)) { - $where[] = "e.container_guid in (".implode(",",$owner_guid).")"; - } else if ($owner_guid > 0) - $where[] = "e.container_guid = {$owner_guid}"; - //if ($owner_guid > 0) - // $where[] = "e.container_guid = {$owner_guid}"; - - if ($count) { - $query = "SELECT count(distinct e.guid) as total "; - } else { - $query = "SELECT distinct e.* "; - } - - $query .= " from {$CONFIG->dbprefix}entities e {$join} where"; - foreach ($where as $w) - $query .= " $w and "; - $query .= get_access_sql_suffix("e"); // Add access controls - - $mindex = 1; - foreach($meta_array as $meta_name => $meta_value) { - $query .= ' and ' . get_access_sql_suffix("m{$mindex}"); // Add access controls - $mindex++; - } - - if (!$count) { - $query .= " order by $order_by limit $offset, $limit"; // Add order and limit - return get_data($query, "entity_row_to_elggstar"); - } else { - if ($count = get_data_row($query)) { - return $count->total; - } - } - return false; - } - - /** - * Returns a viewable list of entities based on the given search criteria. - * - * @see elgg_view_entity_list - * - * @param array $meta_array Array of 'name' => 'value' pairs - * @param string $entity_type The type of entity to look for, eg 'site' or 'object' - * @param string $entity_subtype The subtype of the entity. - * @param int $limit - * @param int $offset - * @param string $order_by Optional ordering. - * @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 the gallery view. Default: true - * @param true|false $pagination Display pagination? Default: true - * @return string List of ElggEntities suitable for display - */ - function list_entities_from_metadata_multi($meta_array, $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = true, $pagination = true) { - - $offset = (int) get_input('offset'); - $limit = (int) $limit; - $count = get_entities_from_metadata_multi($meta_array, $entity_type, $entity_subtype, $owner_guid, $limit, $offset, "", $site_guid, true); - $entities = get_entities_from_metadata_multi($meta_array, $entity_type, $entity_subtype, $owner_guid, $limit, $offset, "", $site_guid, false); - - return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); - - } - - /** - * Clear all the metadata for a given entity, assuming you have access to that metadata. - * - * @param int $guid - */ - function clear_metadata($entity_guid) - { - global $CONFIG; - - $entity_guid = (int)$entity_guid; - if ($entity = get_entity($entity_guid)) { - if ($entity->canEdit()) - return delete_data("DELETE from {$CONFIG->dbprefix}metadata where entity_guid={$entity_guid}"); - } - return false; - } - - /** - * Clear all annotations belonging to a given owner_guid - * - * @param int $owner_guid The owner - */ - function clear_metadata_by_owner($owner_guid) - { - global $CONFIG; - - $owner_guid = (int)$owner_guid; - - $metas = get_data("SELECT id from {$CONFIG->dbprefix}metadata WHERE owner_guid=$owner_guid"); - $deleted = 0; - - foreach ($metas as $id) - { - if (delete_metadata($id->id)) // Is this the best way? - $deleted++; - } - - return $deleted; - } - - /** - * Handler called by trigger_plugin_hook on the "export" event. - */ - function export_metadata_plugin_hook($hook, $entity_type, $returnvalue, $params) - { - // Sanity check values - if ((!is_array($params)) && (!isset($params['guid']))) - throw new InvalidParameterException(elgg_echo('InvalidParameterException:GUIDNotForExport')); - - if (!is_array($returnvalue)) - throw new InvalidParameterException(elgg_echo('InvalidParameterException:NonArrayReturnValue')); - - $guid = (int)$params['guid']; - $name = $params['name']; - - $result = get_metadata_for_entity($guid); - - if ($result) - { - foreach ($result as $r) - $returnvalue[] = $r->export(); - } - - return $returnvalue; - } - - /** - * Takes in a comma-separated string and returns an array of tags which have been trimmed and set to lower case - * - * @param string $string Comma-separated tag string - * @return array|false An array of strings, or false on failure - */ - function string_to_tag_array($string) { - - if (is_string($string)) { - $ar = explode(",",$string); - $ar = array_map('trim', $ar); // trim blank spaces - $ar = array_map('elgg_strtolower', $ar); // make lower case : [Marcus Povey 20090605 - Using mb wrapper function using UTF8 safe function where available] - $ar = array_filter($ar, 'is_not_null'); // Remove null values - return $ar; - } - return false; - - } - - /** - * Takes a metadata array (which has all kinds of properties) and turns it into a simple array of strings - * - * @param array $array Metadata array - * @return array Array of strings - */ - function metadata_array_to_values($array) { - - $valuearray = array(); - - if (is_array($array)) { - foreach($array as $element) { - $valuearray[] = $element->value; - } - } - - return $valuearray; - - } - - /** - * Get the URL for this item of metadata, by default this links to the export handler in the current view. - * - * @param int $id - */ - function get_metadata_url($id) - { - $id = (int)$id; - - if ($extender = get_metadata($id)) { - return get_extender_url($extender); - } - return false; - } - - /** - * Mark entities with a particular type and subtype as having access permissions - * that can be changed independently from their parent entity - * - * @param string $type The type - object, user, etc - * @param string $subtype The subtype; all subtypes by default - */ - function register_metadata_as_independent($type, $subtype = '*') { - global $CONFIG; - if (!isset($CONFIG->independents)) $CONFIG->independents = array(); - $CONFIG->independents[$type][$subtype] = true; - } - - /** - * Determines whether entities of a given type and subtype should not change - * their metadata in line with their parent entity - * - * @param string $type The type - object, user, etc - * @param string $subtype The entity subtype - * @return true|false - */ - function is_metadata_independent($type, $subtype) { - global $CONFIG; - if (empty($CONFIG->independents)) return false; - if (!empty($CONFIG->independents[$type][$subtype]) - || !empty($CONFIG->independents[$type]['*'])) return true; - return false; - } - - /** - * When an entity is updated, resets the access ID on all of its child metadata - * - * @param string $event The name of the event - * @param string $object_type The type of object - * @param ElggEntity $object The entity itself - */ - function metadata_update($event, $object_type, $object) { - if ($object instanceof ElggEntity) { - if (!is_metadata_independent($object->getType(), $object->getSubtype())) { - global $CONFIG; - $access_id = (int) $object->access_id; - $guid = (int) $object->getGUID(); - update_data("update {$CONFIG->dbprefix}metadata set access_id = {$access_id} where entity_guid = {$guid}"); - } - } - return true; - } - - /** - * Register a metadata url handler. - * - * @param string $function_name The function. - * @param string $extender_name The name, default 'all'. - */ - function register_metadata_url_handler($function_name, $extender_name = "all") { - return register_extender_url_handler($function_name, 'metadata', $extender_name); - } - - /** Register the hook */ - register_plugin_hook("export", "all", "export_metadata_plugin_hook", 2); - /** Call a function whenever an entity is updated **/ - register_elgg_event_handler('update','all','metadata_update'); - -?> + * @link http://elgg.org/ + */ + + /** + * ElggMetadata + * This class describes metadata that can be attached to ElggEntities. + * + * @author Curverider Ltd + * @package Elgg + * @subpackage Core + */ + class ElggMetadata extends ElggExtender + { + + /** + * Construct a new site object, optionally from a given id value or row. + * + * @param mixed $id + */ + function __construct($id = null) + { + $this->attributes = array(); + + if (!empty($id)) { + + if ($id instanceof stdClass) + $metadata = $id; // Create from db row + else + $metadata = get_metadata($id); + + if ($metadata) { + $objarray = (array) $metadata; + foreach($objarray as $key => $value) { + $this->attributes[$key] = $value; + } + $this->attributes['type'] = "metadata"; + } + } + } + + /** + * Class member get overloading + * + * @param string $name + * @return mixed + */ + function __get($name) { + return $this->get($name); + } + + /** + * Class member set overloading + * + * @param string $name + * @param mixed $value + * @return mixed + */ + function __set($name, $value) { + return $this->set($name, $value); + } + + /** + * Determines whether or not the user can edit this piece of metadata + * + * @return true|false Depending on permissions + */ + function canEdit() { + + if ($entity = get_entity($this->get('entity_guid'))) { + return $entity->canEditMetadata($this); + } + return false; + + } + + /** + * Save matadata object + * + * @return int the metadata object id + */ + function save() + { + if ($this->id > 0) + return update_metadata($this->id, $this->name, $this->value, $this->value_type, $this->owner_guid, $this->access_id); + else + { + $this->id = create_metadata($this->entity_guid, $this->name, $this->value, $this->value_type, $this->owner_guid, $this->access_id); + if (!$this->id) throw new IOException(sprintf(elgg_new('IOException:UnableToSaveNew'), get_class())); + return $this->id; + } + + } + + /** + * Delete a given metadata. + */ + function delete() + { + return delete_metadata($this->id); + } + + /** + * Get a url for this item of metadata. + * + * @return string + */ + public function getURL() { return get_metadata_url($this->id); } + + // SYSTEM LOG INTERFACE //////////////////////////////////////////////////////////// + + /** + * For a given ID, return the object associated with it. + * This is used by the river functionality primarily. + * This is useful for checking access permissions etc on objects. + */ + public function getObjectFromID($id) { return get_metadata($id); } + } + + /** + * Convert a database row to a new ElggMetadata + * + * @param stdClass $row + * @return stdClass or ElggMetadata + */ + function row_to_elggmetadata($row) + { + if (!($row instanceof stdClass)) + return $row; + + return new ElggMetadata($row); + } + + + /** + * Get a specific item of metadata. + * + * @param $id int The item of metadata being retrieved. + */ + function get_metadata($id) + { + global $CONFIG; + + $id = (int)$id; + $access = get_access_sql_suffix("e"); + $md_access = get_access_sql_suffix("m"); + + return row_to_elggmetadata(get_data_row("SELECT m.*, n.string as name, v.string as value from {$CONFIG->dbprefix}metadata m JOIN {$CONFIG->dbprefix}entities e on e.guid = m.entity_guid JOIN {$CONFIG->dbprefix}metastrings v on m.value_id = v.id JOIN {$CONFIG->dbprefix}metastrings n on m.name_id = n.id where m.id=$id and $access and $md_access")); + } + + /** + * Removes metadata on an entity with a particular name, optionally with a given value. + * + * @param int $entity_guid The entity GUID + * @param string $name The name of the metadata + * @param string $value The optional value of the item (useful for removing a single item in a multiple set) + * @return true|false Depending on success + */ + function remove_metadata($entity_guid, $name, $value = "") { + + global $CONFIG; + $entity_guid = (int) $entity_guid; + $name = sanitise_string($name); + $value = sanitise_string($value); + + $query = "SELECT * from {$CONFIG->dbprefix}metadata WHERE entity_guid = $entity_guid and name_id=" . add_metastring($name); + if ($value!="") + $query .= " and value_id=" . add_metastring($value); + + if ($existing = get_data($query)) { + foreach($existing as $ex) + delete_metadata($ex->id); + return true; + } + return false; + + } + + /** + * Create a new metadata object, or update an existing one. + * + * @param int $entity_guid + * @param string $name + * @param string $value + * @param string $value_type + * @param int $owner_guid + * @param int $access_id + * @param bool $allow_multiple + */ + function create_metadata($entity_guid, $name, $value, $value_type, $owner_guid, $access_id = ACCESS_PRIVATE, $allow_multiple = false) + { + global $CONFIG; + + $entity_guid = (int)$entity_guid; + //$name = sanitise_string(trim($name)); + //$value = sanitise_string(trim($value)); + $value_type = detect_extender_valuetype($value, sanitise_string(trim($value_type))); + $time = time(); + $owner_guid = (int)$owner_guid; + $allow_multiple = (boolean)$allow_multiple; + + if ($owner_guid==0) $owner_guid = get_loggedin_userid(); + + $access_id = (int)$access_id; + + $id = false; + + $existing = get_data_row("SELECT * from {$CONFIG->dbprefix}metadata WHERE entity_guid = $entity_guid and name_id=" . add_metastring($name) . " limit 1"); + if (($existing) && (!$allow_multiple) && (isset($value))) + { + $id = $existing->id; + $result = update_metadata($id, $name, $value, $value_type, $owner_guid, $access_id); + + if (!$result) return false; + } + else if (isset($value)) + { + // Support boolean types + if (is_bool($value)) { + if ($value) + $value = 1; + else + $value = 0; + } + + // Add the metastrings + $value = add_metastring($value); + if (!$value) return false; + + $name = add_metastring($name); + if (!$name) return false; + + // If ok then add it + $id = insert_data("INSERT into {$CONFIG->dbprefix}metadata (entity_guid, name_id, value_id, value_type, owner_guid, time_created, access_id) VALUES ($entity_guid, '$name','$value','$value_type', $owner_guid, $time, $access_id)"); + + if ($id!==false) { + $obj = get_metadata($id); + if (trigger_elgg_event('create', 'metadata', $obj)) { + return true; + } else { + delete_metadata($id); + } + } + + } else if ($existing) { +// TODO: Check... are you sure you meant to do this Ben? :) + $id = $existing->id; + delete_metadata($id); + + } + + return $id; + } + + /** + * Update an item of metadata. + * + * @param int $id + * @param string $name + * @param string $value + * @param string $value_type + * @param int $owner_guid + * @param int $access_id + */ + function update_metadata($id, $name, $value, $value_type, $owner_guid, $access_id) + { + global $CONFIG; + + $id = (int)$id; + + if (!$md = get_metadata($id)) return false; + if (!$md->canEdit()) return false; + + // If memcached then we invalidate the cache for this entry + static $metabyname_memcache; + if ((!$metabyname_memcache) && (is_memcache_available())) + $metabyname_memcache = new ElggMemcache('metabyname_memcache'); + if ($metabyname_memcache) $metabyname_memcache->delete("{$md->entity_guid}:{$md->name_id}"); + + //$name = sanitise_string(trim($name)); + //$value = sanitise_string(trim($value)); + $value_type = detect_extender_valuetype($value, sanitise_string(trim($value_type))); + + $owner_guid = (int)$owner_guid; + if ($owner_guid==0) $owner_guid = get_loggedin_userid(); + + $access_id = (int)$access_id; + + $access = get_access_sql_suffix(); + + // Support boolean types (as integers) + if (is_bool($value)) { + if ($value) + $value = 1; + else + $value = 0; + } + + // Add the metastring + $value = add_metastring($value); + if (!$value) return false; + + $name = add_metastring($name); + if (!$name) return false; + + // If ok then add it + $result = update_data("UPDATE {$CONFIG->dbprefix}metadata set value_id='$value', value_type='$value_type', access_id=$access_id, owner_guid=$owner_guid where id=$id and name_id='$name'"); + if ($result!==false) { + $obj = get_metadata($id); + if (trigger_elgg_event('update', 'metadata', $obj)) { + return true; + } else { + delete_metadata($id); + } + } + + return $result; + } + + /** + * This function creates metadata from an associative array of "key => value" pairs. + * + * @param int $entity_guid + * @param string $name_and_values + * @param string $value_type + * @param int $owner_guid + * @param int $access_id + * @param bool $allow_multiple + */ + function create_metadata_from_array($entity_guid, array $name_and_values, $value_type, $owner_guid, $access_id = ACCESS_PRIVATE, $allow_multiple = false) + { + foreach ($name_and_values as $k => $v) + if (!create_metadata($entity_guid, $k, $v, $value_type, $owner_guid, $access_id, $allow_multiple)) return false; + + return true; + } + + /** + * Delete an item of metadata, where the current user has access. + * + * @param $id int The item of metadata to delete. + */ + function delete_metadata($id) + { + global $CONFIG; + + $id = (int)$id; + $metadata = get_metadata($id); + + if ($metadata) { + // Tidy up if memcache is enabled. + static $metabyname_memcache; + if ((!$metabyname_memcache) && (is_memcache_available())) + $metabyname_memcache = new ElggMemcache('metabyname_memcache'); + if ($metabyname_memcache) $metabyname_memcache->delete("{$metadata->entity_guid}:{$metadata->name_id}"); + + if (($metadata->canEdit()) && (trigger_elgg_event('delete', 'metadata', $metadata))) + return delete_data("DELETE from {$CONFIG->dbprefix}metadata where id=$id"); + } + + return false; + } + + /** + * Return the metadata values that match your query. + * + * @param string $meta_name + * @return mixed either a value, an array of ElggMetadata or false. + */ + function get_metadata_byname($entity_guid, $meta_name) + { + global $CONFIG; + + $meta_name = get_metastring_id($meta_name); + + if (empty($meta_name)) return false; + + $entity_guid = (int)$entity_guid; + $access = get_access_sql_suffix("e"); + $md_access = get_access_sql_suffix("m"); + + // If memcache is available then cache this (cache only by name for now since this is the most common query) + $meta = null; + static $metabyname_memcache; + if ((!$metabyname_memcache) && (is_memcache_available())) + $metabyname_memcache = new ElggMemcache('metabyname_memcache'); + if ($metabyname_memcache) $meta = $metabyname_memcache->load("{$entity_guid}:{$meta_name}"); + if ($meta) return $meta; + + $result = get_data("SELECT m.*, n.string as name, v.string as value from {$CONFIG->dbprefix}metadata m JOIN {$CONFIG->dbprefix}entities e ON e.guid = m.entity_guid JOIN {$CONFIG->dbprefix}metastrings v on m.value_id = v.id JOIN {$CONFIG->dbprefix}metastrings n on m.name_id = n.id where m.entity_guid=$entity_guid and m.name_id='$meta_name' and $access and $md_access", "row_to_elggmetadata"); + if (!$result) + return false; + + // Cache if memcache available + if ($metabyname_memcache) + { + if (count($result) == 1) $r = $result[0]; else $r = $result; + $metabyname_memcache->setDefaultExpiry(3600); // This is a bit of a hack - we shorten the expiry on object metadata so that it'll be gone in an hour. This means that deletions and more importantly updates will filter through eventually. + $metabyname_memcache->save("{$entity_guid}:{$meta_name}", $r); + + } + if (count($result) == 1) + return $result[0]; + + return $result; + } + + /** + * Return all the metadata for a given GUID. + * + * @param int $entity_guid + */ + function get_metadata_for_entity($entity_guid) + { + global $CONFIG; + + $entity_guid = (int)$entity_guid; + $access = get_access_sql_suffix("e"); + $md_access = get_access_sql_suffix("m"); + + return get_data("SELECT m.*, n.string as name, v.string as value from {$CONFIG->dbprefix}metadata m JOIN {$CONFIG->dbprefix}entities e ON e.guid = m.entity_guid JOIN {$CONFIG->dbprefix}metastrings v on m.value_id = v.id JOIN {$CONFIG->dbprefix}metastrings n on m.name_id = n.id where m.entity_guid=$entity_guid and $access and $md_access", "row_to_elggmetadata"); + } + + /** + * Get the metadata where the entities they are referring to match a given criteria. + * + * @param mixed $meta_name + * @param mixed $meta_value + * @param string $entity_type The type of entity to look for, eg 'site' or 'object' + * @param string $entity_subtype The subtype of the entity. + * @param int $limit + * @param int $offset + * @param string $order_by Optional ordering. + * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. + */ + function find_metadata($meta_name = "", $meta_value = "", $entity_type = "", $entity_subtype = "", $limit = 10, $offset = 0, $order_by = "", $site_guid = 0) + { + global $CONFIG; + + $meta_n = get_metastring_id($meta_name); + $meta_v = get_metastring_id($meta_value); + + $entity_type = sanitise_string($entity_type); + $entity_subtype = get_subtype_id($entity_type, $entity_subtype); + $limit = (int)$limit; + $offset = (int)$offset; + if ($order_by == "") $order_by = "e.time_created desc"; + $order_by = sanitise_string($order_by); + $site_guid = (int) $site_guid; + if ($site_guid == 0) + $site_guid = $CONFIG->site_guid; + + + $where = array(); + + if ($entity_type!="") + $where[] = "e.type='$entity_type'"; + if ($entity_subtype) + $where[] = "e.subtype=$entity_subtype"; + if ($meta_name!="") { + if (!$meta_v) return false; // The value is set, but we didn't get a value... so something went wrong. + $where[] = "m.name_id='$meta_n'"; + } + if ($meta_value!="") { + if (!$meta_v) return false; // The value is set, but we didn't get a value... so something went wrong. + $where[] = "m.value_id='$meta_v'"; + } + if ($site_guid > 0) + $where[] = "e.site_guid = {$site_guid}"; + + $query = "SELECT m.*, n.string as name, v.string as value from {$CONFIG->dbprefix}entities e JOIN {$CONFIG->dbprefix}metadata m on e.guid = m.entity_guid JOIN {$CONFIG->dbprefix}metastrings v on m.value_id = v.id JOIN {$CONFIG->dbprefix}metastrings n on m.name_id = n.id where"; + foreach ($where as $w) + $query .= " $w and "; + $query .= get_access_sql_suffix("e"); // Add access controls + $query .= ' and ' . get_access_sql_suffix("m"); // Add access controls + $query .= " order by $order_by limit $offset, $limit"; // Add order and limit + + return get_data($query, "row_to_elggmetadata"); + } + + /** + * Return a list of entities based on the given search criteria. + * + * @param mixed $meta_name + * @param mixed $meta_value + * @param string $entity_type The type of entity to look for, eg 'site' or 'object' + * @param string $entity_subtype The subtype of the entity. + * @param int $limit + * @param int $offset + * @param string $order_by Optional ordering. + * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. + * @param true|false $count If set to true, returns the total number of entities rather than a list. (Default: false) + * + * @return int|array A list of entities, or a count if $count is set to true + */ + function get_entities_from_metadata($meta_name, $meta_value = "", $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $offset = 0, $order_by = "", $site_guid = 0, $count = false) + { + global $CONFIG; + + $meta_n = get_metastring_id($meta_name); + $meta_v = get_metastring_id($meta_value); + + $entity_type = sanitise_string($entity_type); + $entity_subtype = get_subtype_id($entity_type, $entity_subtype); + $limit = (int)$limit; + $offset = (int)$offset; + if ($order_by == "") + $order_by = "e.time_created desc"; + else + $order_by = "e.time_created, {$order_by}"; + $order_by = sanitise_string($order_by); + $site_guid = (int) $site_guid; + if ((is_array($owner_guid) && (count($owner_guid)))) { + foreach($owner_guid as $key => $guid) { + $owner_guid[$key] = (int) $guid; + } + } else { + $owner_guid = (int) $owner_guid; + } + if ($site_guid == 0) + $site_guid = $CONFIG->site_guid; + + //$access = get_access_list(); + + $where = array(); + + if ($entity_type!=="") + $where[] = "e.type='$entity_type'"; + if ($entity_subtype) + $where[] = "e.subtype=$entity_subtype"; + if ($meta_name!=="") + $where[] = "m.name_id='$meta_n'"; + if ($meta_value!=="") + $where[] = "m.value_id='$meta_v'"; + if ($site_guid > 0) + $where[] = "e.site_guid = {$site_guid}"; + if (is_array($owner_guid)) { + $where[] = "e.container_guid in (".implode(",",$owner_guid).")"; + } else if ($owner_guid > 0) + $where[] = "e.container_guid = {$owner_guid}"; + + if (!$count) { + $query = "SELECT distinct e.* "; + } else { + $query = "SELECT count(distinct e.guid) as total "; + } + + $query .= "from {$CONFIG->dbprefix}entities e JOIN {$CONFIG->dbprefix}metadata m on e.guid = m.entity_guid where"; + foreach ($where as $w) + $query .= " $w and "; + $query .= get_access_sql_suffix("e"); // Add access controls + $query .= ' and ' . get_access_sql_suffix("m"); // Add access controls + + if (!$count) { + $query .= " order by $order_by limit $offset, $limit"; // Add order and limit + return get_data($query, "entity_row_to_elggstar"); + } else { + if ($row = get_data_row($query)) + return $row->total; + } + return false; + } + + /** + * Return a list of entities suitable for display based on the given search criteria. + * + * @see elgg_view_entity_list + * + * @param mixed $meta_name Metadata name to search on + * @param mixed $meta_value The value to match, optionally + * @param string $entity_type The type of entity to look for, eg 'site' or 'object' + * @param string $entity_subtype The subtype of the entity + * @param int $limit 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 the gallery view. Default: true + * @param true|false $pagination Display pagination? Default: true + * + * @return string A list of entities suitable for display + */ + function list_entities_from_metadata($meta_name, $meta_value = "", $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = true, $pagination = true) { + + $offset = (int) get_input('offset'); + $limit = (int) $limit; + $count = get_entities_from_metadata($meta_name, $meta_value, $entity_type, $entity_subtype, $owner_guid, $limit, $offset, "", 0, true); + $entities = get_entities_from_metadata($meta_name, $meta_value, $entity_type, $entity_subtype, $owner_guid, $limit, $offset, "", 0, false); + + return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); + + } + + /** + * Returns a list of entities based on the given search criteria. + * + * @param array $meta_array Array of 'name' => 'value' pairs + * @param string $entity_type The type of entity to look for, eg 'site' or 'object' + * @param string $entity_subtype The subtype of the entity. + * @param int $limit + * @param int $offset + * @param string $order_by Optional ordering. + * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. + * @param true|false $count If set to true, returns the total number of entities rather than a list. (Default: false) + * @param string $meta_array_operator Operator used for joining the metadata array together + * @return int|array List of ElggEntities, or the total number if count is set to false + */ + function get_entities_from_metadata_multi($meta_array, $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $offset = 0, $order_by = "", $site_guid = 0, $count = false, $meta_array_operator = 'and') + { + global $CONFIG; + + if (!is_array($meta_array) || sizeof($meta_array) == 0) { + return false; + } + + $where = array(); + + $mindex = 1; + $join = ""; + $metawhere = array(); + $meta_array_operator = sanitise_string($meta_array_operator); + foreach($meta_array as $meta_name => $meta_value) { + $meta_n = get_metastring_id($meta_name); + $meta_v = get_metastring_id($meta_value); + $join .= " JOIN {$CONFIG->dbprefix}metadata m{$mindex} on e.guid = m{$mindex}.entity_guid "; + /*if ($meta_name!=="") + $where[] = "m{$mindex}.name_id='$meta_n'"; + if ($meta_value!=="") + $where[] = "m{$mindex}.value_id='$meta_v'";*/ + $metawhere[] = "(m{$mindex}.name_id='$meta_n' AND m{$mindex}.value_id='$meta_v')"; + $mindex++; + } + $where[] = "(".implode($meta_array_operator, $metawhere).")"; + + $entity_type = sanitise_string($entity_type); + $entity_subtype = get_subtype_id($entity_type, $entity_subtype); + $limit = (int)$limit; + $offset = (int)$offset; + if ($order_by == "") $order_by = "e.time_created desc"; + $order_by = sanitise_string($order_by); + if ((is_array($owner_guid) && (count($owner_guid)))) { + foreach($owner_guid as $key => $guid) { + $owner_guid[$key] = (int) $guid; + } + } else { + $owner_guid = (int) $owner_guid; + } + + $site_guid = (int) $site_guid; + if ($site_guid == 0) + $site_guid = $CONFIG->site_guid; + + //$access = get_access_list(); + + if ($entity_type!="") + $where[] = "e.type = '{$entity_type}'"; + if ($entity_subtype) + $where[] = "e.subtype = {$entity_subtype}"; + if ($site_guid > 0) + $where[] = "e.site_guid = {$site_guid}"; + if (is_array($owner_guid)) { + $where[] = "e.container_guid in (".implode(",",$owner_guid).")"; + } else if ($owner_guid > 0) + $where[] = "e.container_guid = {$owner_guid}"; + //if ($owner_guid > 0) + // $where[] = "e.container_guid = {$owner_guid}"; + + if ($count) { + $query = "SELECT count(distinct e.guid) as total "; + } else { + $query = "SELECT distinct e.* "; + } + + $query .= " from {$CONFIG->dbprefix}entities e {$join} where"; + foreach ($where as $w) + $query .= " $w and "; + $query .= get_access_sql_suffix("e"); // Add access controls + + $mindex = 1; + foreach($meta_array as $meta_name => $meta_value) { + $query .= ' and ' . get_access_sql_suffix("m{$mindex}"); // Add access controls + $mindex++; + } + + if (!$count) { + $query .= " order by $order_by limit $offset, $limit"; // Add order and limit + return get_data($query, "entity_row_to_elggstar"); + } else { + if ($count = get_data_row($query)) { + return $count->total; + } + } + return false; + } + + /** + * Returns a viewable list of entities based on the given search criteria. + * + * @see elgg_view_entity_list + * + * @param array $meta_array Array of 'name' => 'value' pairs + * @param string $entity_type The type of entity to look for, eg 'site' or 'object' + * @param string $entity_subtype The subtype of the entity. + * @param int $limit + * @param int $offset + * @param string $order_by Optional ordering. + * @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 the gallery view. Default: true + * @param true|false $pagination Display pagination? Default: true + * @return string List of ElggEntities suitable for display + */ + function list_entities_from_metadata_multi($meta_array, $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = true, $pagination = true) { + + $offset = (int) get_input('offset'); + $limit = (int) $limit; + $count = get_entities_from_metadata_multi($meta_array, $entity_type, $entity_subtype, $owner_guid, $limit, $offset, "", $site_guid, true); + $entities = get_entities_from_metadata_multi($meta_array, $entity_type, $entity_subtype, $owner_guid, $limit, $offset, "", $site_guid, false); + + return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); + + } + + /** + * Clear all the metadata for a given entity, assuming you have access to that metadata. + * + * @param int $guid + */ + function clear_metadata($entity_guid) + { + global $CONFIG; + + $entity_guid = (int)$entity_guid; + if ($entity = get_entity($entity_guid)) { + if ($entity->canEdit()) + return delete_data("DELETE from {$CONFIG->dbprefix}metadata where entity_guid={$entity_guid}"); + } + return false; + } + + /** + * Clear all annotations belonging to a given owner_guid + * + * @param int $owner_guid The owner + */ + function clear_metadata_by_owner($owner_guid) + { + global $CONFIG; + + $owner_guid = (int)$owner_guid; + + $metas = get_data("SELECT id from {$CONFIG->dbprefix}metadata WHERE owner_guid=$owner_guid"); + $deleted = 0; + + foreach ($metas as $id) + { + if (delete_metadata($id->id)) // Is this the best way? + $deleted++; + } + + return $deleted; + } + + /** + * Handler called by trigger_plugin_hook on the "export" event. + */ + function export_metadata_plugin_hook($hook, $entity_type, $returnvalue, $params) + { + // Sanity check values + if ((!is_array($params)) && (!isset($params['guid']))) + throw new InvalidParameterException(elgg_echo('InvalidParameterException:GUIDNotForExport')); + + if (!is_array($returnvalue)) + throw new InvalidParameterException(elgg_echo('InvalidParameterException:NonArrayReturnValue')); + + $guid = (int)$params['guid']; + $name = $params['name']; + + $result = get_metadata_for_entity($guid); + + if ($result) + { + foreach ($result as $r) + $returnvalue[] = $r->export(); + } + + return $returnvalue; + } + + /** + * Takes in a comma-separated string and returns an array of tags which have been trimmed and set to lower case + * + * @param string $string Comma-separated tag string + * @return array|false An array of strings, or false on failure + */ + function string_to_tag_array($string) { + + if (is_string($string)) { + $ar = explode(",",$string); + $ar = array_map('trim', $ar); // trim blank spaces + $ar = array_map('elgg_strtolower', $ar); // make lower case : [Marcus Povey 20090605 - Using mb wrapper function using UTF8 safe function where available] + $ar = array_filter($ar, 'is_not_null'); // Remove null values + return $ar; + } + return false; + + } + + /** + * Takes a metadata array (which has all kinds of properties) and turns it into a simple array of strings + * + * @param array $array Metadata array + * @return array Array of strings + */ + function metadata_array_to_values($array) { + + $valuearray = array(); + + if (is_array($array)) { + foreach($array as $element) { + $valuearray[] = $element->value; + } + } + + return $valuearray; + + } + + /** + * Get the URL for this item of metadata, by default this links to the export handler in the current view. + * + * @param int $id + */ + function get_metadata_url($id) + { + $id = (int)$id; + + if ($extender = get_metadata($id)) { + return get_extender_url($extender); + } + return false; + } + + /** + * Mark entities with a particular type and subtype as having access permissions + * that can be changed independently from their parent entity + * + * @param string $type The type - object, user, etc + * @param string $subtype The subtype; all subtypes by default + */ + function register_metadata_as_independent($type, $subtype = '*') { + global $CONFIG; + if (!isset($CONFIG->independents)) $CONFIG->independents = array(); + $CONFIG->independents[$type][$subtype] = true; + } + + /** + * Determines whether entities of a given type and subtype should not change + * their metadata in line with their parent entity + * + * @param string $type The type - object, user, etc + * @param string $subtype The entity subtype + * @return true|false + */ + function is_metadata_independent($type, $subtype) { + global $CONFIG; + if (empty($CONFIG->independents)) return false; + if (!empty($CONFIG->independents[$type][$subtype]) + || !empty($CONFIG->independents[$type]['*'])) return true; + return false; + } + + /** + * When an entity is updated, resets the access ID on all of its child metadata + * + * @param string $event The name of the event + * @param string $object_type The type of object + * @param ElggEntity $object The entity itself + */ + function metadata_update($event, $object_type, $object) { + if ($object instanceof ElggEntity) { + if (!is_metadata_independent($object->getType(), $object->getSubtype())) { + global $CONFIG; + $access_id = (int) $object->access_id; + $guid = (int) $object->getGUID(); + update_data("update {$CONFIG->dbprefix}metadata set access_id = {$access_id} where entity_guid = {$guid}"); + } + } + return true; + } + + /** + * Register a metadata url handler. + * + * @param string $function_name The function. + * @param string $extender_name The name, default 'all'. + */ + function register_metadata_url_handler($function_name, $extender_name = "all") { + return register_extender_url_handler($function_name, 'metadata', $extender_name); + } + + /** Register the hook */ + register_plugin_hook("export", "all", "export_metadata_plugin_hook", 2); + /** Call a function whenever an entity is updated **/ + register_elgg_event_handler('update','all','metadata_update'); + +?> diff --git a/engine/lib/metastrings.php b/engine/lib/metastrings.php index 94529e16f..31981efab 100644 --- a/engine/lib/metastrings.php +++ b/engine/lib/metastrings.php @@ -68,18 +68,18 @@ $METASTRINGS_DEADNAME_CACHE[$string] = $string; return false; - } - - /** - * When given an ID, returns the corresponding metastring - * - * @param int $id Metastring ID - * @return string Metastring - */ - function get_metastring($id) { - - global $CONFIG, $METASTRINGS_CACHE; - + } + + /** + * When given an ID, returns the corresponding metastring + * + * @param int $id Metastring ID + * @return string Metastring + */ + function get_metastring($id) { + + global $CONFIG, $METASTRINGS_CACHE; + $id = (int) $id; if (isset($METASTRINGS_CACHE[$id])) { @@ -88,20 +88,20 @@ error_log("** Returning string for id:$id from cache."); return $METASTRINGS_CACHE[$id]; - } - - $row = get_data_row("SELECT * from {$CONFIG->dbprefix}metastrings where id='$id' limit 1"); + } + + $row = get_data_row("SELECT * from {$CONFIG->dbprefix}metastrings where id='$id' limit 1"); if ($row) { $METASTRINGS_CACHE[$id] = $row->string; // Cache it if ($CONFIG->debug) error_log("** Cacheing string '{$row->string}'"); - + return $row->string; - } - - return false; - + } + + return false; + } /** diff --git a/engine/lib/notification.php b/engine/lib/notification.php index f1336d1b8..6b91a67cf 100644 --- a/engine/lib/notification.php +++ b/engine/lib/notification.php @@ -1,430 +1,430 @@ -handler = $handler; - if ($params) - { - foreach ($params as $k => $v) - $NOTIFICATION_HANDLERS[$method]->$k = $v; - } - - return true; - } - - return false; - } - - /** - * Notify a user via their preferences. - * - * @param mixed $to Either a guid or an array of guid's to notify. - * @param int $from GUID of the sender, which may be a user, site or object. - * @param string $subject Message subject. - * @param string $message Message body. - * @param array $params Misc additional parameters specific to various methods. - * @param mixed $methods_override A string, or an array of strings specifying the delivery methods to use - or leave blank - * for delivery using the user's chosen delivery methods. - * @return array Compound array of each delivery user/delivery method's success or failure. - * @throws NotificationException - */ - function notify_user($to, $from, $subject, $message, array $params = NULL, $methods_override = "") - { - global $NOTIFICATION_HANDLERS, $CONFIG; - - // Sanitise - if (!is_array($to)) - $to = array((int)$to); - $from = (int)$from; - //$subject = sanitise_string($subject); - - // Get notification methods - if (($methods_override) && (!is_array($methods_override))) - $methods_override = array($methods_override); - - $result = array(); - - foreach ($to as $guid) - { - // Results for a user are... - $result[$guid] = array(); - - if ($guid) { // Is the guid > 0? - // Are we overriding delivery? - $methods = $methods_override; - if (!$methods) - { - $tmp = (array)get_user_notification_settings($guid); - $methods = array(); - foreach($tmp as $k => $v) - if ($v) $methods[] = $k; // Add method if method is turned on for user! - } - - if ($methods) - { - // Deliver - foreach ($methods as $method) - { - // Extract method details from list - $details = $NOTIFICATION_HANDLERS[$method]; - $handler = $details->handler; - - if ((!$NOTIFICATION_HANDLERS[$method]) || (!$handler)) - error_log(sprintf(elgg_echo('NotificationException:NoHandlerFound'), $method)); - - if ($CONFIG->debug) - error_log("Sending message to $guid using $method"); - - // Trigger handler and retrieve result. - try { - $result[$guid][$method] = $handler( - $from ? get_entity($from) : NULL, // From entity - get_entity($guid), // To entity - $subject, // The subject - $message, // Message - $params // Params - ); - } catch (Exception $e) { - error_log($e->getMessage()); - } - - } - } - } - } - - return $result; - } - - /** - * Get the notification settings for a given user. - * - * @param int $user_guid The user id - * @return stdClass - */ - function get_user_notification_settings($user_guid = 0) - { - $user_guid = (int)$user_guid; - - if ($user_guid == 0) $user_guid = get_loggedin_userid(); - - $all_metadata = get_metadata_for_entity($user_guid); - if ($all_metadata) - { - $prefix = "notification:method:"; - $return = new stdClass; - - foreach ($all_metadata as $meta) - { - $name = substr($meta->name, strlen($prefix)); - $value = $meta->value; - - if (strpos($meta->name, $prefix) === 0) - $return->$name = $value; - } - - return $return; - } - - return false; - } - - /** - * Set a user notification pref. - * - * @param int $user_guid The user id. - * @param string $method The delivery method (eg. email) - * @param bool $value On(true) or off(false). - * @return bool - */ - function set_user_notification_setting($user_guid, $method, $value) - { - $user_guid = (int)$user_guid; - $method = sanitise_string($method); - - $user = get_entity($user_guid); - if (!$user) $user = get_loggedin_user(); - - if (($user) && ($user instanceof ElggUser)) - { - $prefix = "notification:method:$method"; - $user->$prefix = $value; - $user->save(); - - return true; - } - - return false; - } - - /** - * Notification exception. - * @author Curverider Ltd - */ - class NotificationException extends Exception {} - - - /** - * Send a notification via email. - * - * @param ElggEntity $from The from user/site/object - * @param ElggUser $to To which user? - * @param string $subject The subject of the message. - * @param string $message The message body - * @param array $params Optional parameters (none taken in this instance) - * @return bool - */ - function email_notify_handler(ElggEntity $from, ElggUser $to, $subject, $message, array $params = NULL) - { - global $CONFIG; - - if (!$from) - throw new NotificationException(sprintf(elgg_echo('NotificationException:MissingParameter'), 'from')); - - if (!$to) - throw new NotificationException(sprintf(elgg_echo('NotificationException:MissingParameter'), 'to')); - - if ($to->email=="") - throw new NotificationException(sprintf(elgg_echo('NotificationException:NoEmailAddress'), $to->guid)); - - // Sanitise subject - $subject = preg_replace("/(\r\n|\r|\n)/", " ", $subject); // Strip line endings - - // To - $to = $to->email; - - // From - $site = get_entity($CONFIG->site_guid); - if ((isset($from->email)) && (!($from instanceof ElggUser))) // If there's an email address, use it - but only if its not from a user. - $from = $from->email; - else if (($site) && (isset($site->email))) // Has the current site got a from email address? - $from = $site->email; - else if (isset($from->url)) // If we have a url then try and use that. - { - $breakdown = parse_url($from->url); - $from = 'noreply@' . $breakdown['host']; // Handle anything with a url - } - else // If all else fails, use the domain of the site. - $from = 'noreply@' . get_site_domain($CONFIG->site_guid); - - if (is_callable('mb_internal_encoding')) { - mb_internal_encoding('UTF-8'); - } - $site = get_entity($CONFIG->site_guid); - $sitename = $site->name; - if (is_callable('mb_encode_mimeheader')) { - $sitename = mb_encode_mimeheader($site->name,"UTF-8", "B"); - } - - $header_eol = "\r\n"; - if ( - (isset($CONFIG->broken_mta)) && - ($CONFIG->broken_mta) - ) - $header_eol = "\n"; // Allow non-RFC 2822 mail headers to support some broken MTAs + * @link http://elgg.org/ + */ + + /** Notification handlers */ + $NOTIFICATION_HANDLERS = array(); + + /** + * This function registers a handler for a given notification type (eg "email") + * + * @param string $method The method + * @param string $handler The handler function, in the format "handler(ElggEntity $from, ElggUser $to, $subject, $message, array $params = NULL)". This function should return false on failure, and true/a tracking message ID on success. + * @param array $params A associated array of other parameters for this handler defining some properties eg. supported message length or rich text support. + */ + function register_notification_handler($method, $handler, $params = NULL) + { + global $NOTIFICATION_HANDLERS; + + if (is_callable($handler)) + { + $NOTIFICATION_HANDLERS[$method] = new stdClass; + + $NOTIFICATION_HANDLERS[$method]->handler = $handler; + if ($params) + { + foreach ($params as $k => $v) + $NOTIFICATION_HANDLERS[$method]->$k = $v; + } + + return true; + } + + return false; + } + + /** + * Notify a user via their preferences. + * + * @param mixed $to Either a guid or an array of guid's to notify. + * @param int $from GUID of the sender, which may be a user, site or object. + * @param string $subject Message subject. + * @param string $message Message body. + * @param array $params Misc additional parameters specific to various methods. + * @param mixed $methods_override A string, or an array of strings specifying the delivery methods to use - or leave blank + * for delivery using the user's chosen delivery methods. + * @return array Compound array of each delivery user/delivery method's success or failure. + * @throws NotificationException + */ + function notify_user($to, $from, $subject, $message, array $params = NULL, $methods_override = "") + { + global $NOTIFICATION_HANDLERS, $CONFIG; + + // Sanitise + if (!is_array($to)) + $to = array((int)$to); + $from = (int)$from; + //$subject = sanitise_string($subject); + + // Get notification methods + if (($methods_override) && (!is_array($methods_override))) + $methods_override = array($methods_override); + + $result = array(); + + foreach ($to as $guid) + { + // Results for a user are... + $result[$guid] = array(); + + if ($guid) { // Is the guid > 0? + // Are we overriding delivery? + $methods = $methods_override; + if (!$methods) + { + $tmp = (array)get_user_notification_settings($guid); + $methods = array(); + foreach($tmp as $k => $v) + if ($v) $methods[] = $k; // Add method if method is turned on for user! + } + + if ($methods) + { + // Deliver + foreach ($methods as $method) + { + // Extract method details from list + $details = $NOTIFICATION_HANDLERS[$method]; + $handler = $details->handler; + + if ((!$NOTIFICATION_HANDLERS[$method]) || (!$handler)) + error_log(sprintf(elgg_echo('NotificationException:NoHandlerFound'), $method)); + + if ($CONFIG->debug) + error_log("Sending message to $guid using $method"); + + // Trigger handler and retrieve result. + try { + $result[$guid][$method] = $handler( + $from ? get_entity($from) : NULL, // From entity + get_entity($guid), // To entity + $subject, // The subject + $message, // Message + $params // Params + ); + } catch (Exception $e) { + error_log($e->getMessage()); + } + + } + } + } + } + + return $result; + } + + /** + * Get the notification settings for a given user. + * + * @param int $user_guid The user id + * @return stdClass + */ + function get_user_notification_settings($user_guid = 0) + { + $user_guid = (int)$user_guid; + + if ($user_guid == 0) $user_guid = get_loggedin_userid(); + + $all_metadata = get_metadata_for_entity($user_guid); + if ($all_metadata) + { + $prefix = "notification:method:"; + $return = new stdClass; + + foreach ($all_metadata as $meta) + { + $name = substr($meta->name, strlen($prefix)); + $value = $meta->value; + + if (strpos($meta->name, $prefix) === 0) + $return->$name = $value; + } + + return $return; + } + + return false; + } + + /** + * Set a user notification pref. + * + * @param int $user_guid The user id. + * @param string $method The delivery method (eg. email) + * @param bool $value On(true) or off(false). + * @return bool + */ + function set_user_notification_setting($user_guid, $method, $value) + { + $user_guid = (int)$user_guid; + $method = sanitise_string($method); + + $user = get_entity($user_guid); + if (!$user) $user = get_loggedin_user(); + + if (($user) && ($user instanceof ElggUser)) + { + $prefix = "notification:method:$method"; + $user->$prefix = $value; + $user->save(); + + return true; + } + + return false; + } + + /** + * Notification exception. + * @author Curverider Ltd + */ + class NotificationException extends Exception {} + + + /** + * Send a notification via email. + * + * @param ElggEntity $from The from user/site/object + * @param ElggUser $to To which user? + * @param string $subject The subject of the message. + * @param string $message The message body + * @param array $params Optional parameters (none taken in this instance) + * @return bool + */ + function email_notify_handler(ElggEntity $from, ElggUser $to, $subject, $message, array $params = NULL) + { + global $CONFIG; + + if (!$from) + throw new NotificationException(sprintf(elgg_echo('NotificationException:MissingParameter'), 'from')); + + if (!$to) + throw new NotificationException(sprintf(elgg_echo('NotificationException:MissingParameter'), 'to')); + + if ($to->email=="") + throw new NotificationException(sprintf(elgg_echo('NotificationException:NoEmailAddress'), $to->guid)); + + // Sanitise subject + $subject = preg_replace("/(\r\n|\r|\n)/", " ", $subject); // Strip line endings + + // To + $to = $to->email; + + // From + $site = get_entity($CONFIG->site_guid); + if ((isset($from->email)) && (!($from instanceof ElggUser))) // If there's an email address, use it - but only if its not from a user. + $from = $from->email; + else if (($site) && (isset($site->email))) // Has the current site got a from email address? + $from = $site->email; + else if (isset($from->url)) // If we have a url then try and use that. + { + $breakdown = parse_url($from->url); + $from = 'noreply@' . $breakdown['host']; // Handle anything with a url + } + else // If all else fails, use the domain of the site. + $from = 'noreply@' . get_site_domain($CONFIG->site_guid); + + if (is_callable('mb_internal_encoding')) { + mb_internal_encoding('UTF-8'); + } + $site = get_entity($CONFIG->site_guid); + $sitename = $site->name; + if (is_callable('mb_encode_mimeheader')) { + $sitename = mb_encode_mimeheader($site->name,"UTF-8", "B"); + } + + $header_eol = "\r\n"; + if ( + (isset($CONFIG->broken_mta)) && + ($CONFIG->broken_mta) + ) + $header_eol = "\n"; // Allow non-RFC 2822 mail headers to support some broken MTAs $from_email = "\"$sitename\" <$from>"; if (strtolower(substr(PHP_OS, 0 , 3)) == 'win') $from_email = "$from"; // Windows is somewhat broken, so we use a different format from header - - $headers = "From: $from_email{$header_eol}" - . "Content-Type: text/plain; charset=UTF-8; format=flowed{$header_eol}" - . "MIME-Version: 1.0{$header_eol}" - . "Content-Transfer-Encoding: 8bit{$header_eol}"; - - if (is_callable('mb_encode_mimeheader')) { - $subject = mb_encode_mimeheader($subject,"UTF-8", "B"); - } - + + $headers = "From: $from_email{$header_eol}" + . "Content-Type: text/plain; charset=UTF-8; format=flowed{$header_eol}" + . "MIME-Version: 1.0{$header_eol}" + . "Content-Transfer-Encoding: 8bit{$header_eol}"; + + if (is_callable('mb_encode_mimeheader')) { + $subject = mb_encode_mimeheader($subject,"UTF-8", "B"); + } + // Format message - $message = html_entity_decode($message, ENT_COMPAT, 'UTF-8'); // Decode any html entities - $message = strip_tags($message); // Strip tags from message - $message = preg_replace("/(\r\n|\r)/", "\n", $message); // Convert to unix line endings in body - $message = preg_replace("/^From/", ">From", $message); // Change lines starting with From to >From - - return mail($to, $subject, wordwrap($message), $headers); - } - - /** - * Correctly initialise notifications and register the email handler. - * - */ - function notification_init() - { - // Register a notification handler for the default email method - register_notification_handler("email", "email_notify_handler"); - - // Add settings view to user settings & register action - extend_elgg_settings_page('notifications/settings/usersettings', 'usersettings/user'); - - register_plugin_hook('usersettings:save','user','notification_user_settings_save'); - - //register_action("notifications/settings/usersettings/save"); - - - // Register some APIs - expose_function('user.notification.get', 'get_user_notification_settings', array( - 'user_guid' => array ('type' => 'int') - ), elgg_echo('user.notification.get')); - - expose_function('user.notification.set', 'set_user_notification_settings', array( - 'user_guid' => array ('type' => 'int'), - 'method' => array ('type' => 'string'), - 'value' => array ('type' => 'bool') - ), elgg_echo('user.notification.set')); - - } - - function notification_user_settings_save() { - - global $CONFIG; - @include($CONFIG->path . "actions/notifications/settings/usersettings/save.php"); - - } - - /** - * Register an entity type and subtype to be eligible for notifications - * - * @param string $entity_type The type of entity - * @param string $object_subtype Its subtype - * @param string $english_name It's English notification string (eg "New blog post") - */ - function register_notification_object($entity_type, $object_subtype, $english_name) { - global $CONFIG; - - if ($entity_type == '') $entity_type = '__BLANK__'; - if ($object_subtype == '') $object_subtype = '__BLANK__'; - - if (!isset($CONFIG->register_objects)) { - $CONFIG->register_objects = array(); - } - if (!isset($CONFIG->register_objects[$entity_type])) { - $CONFIG->register_objects[$entity_type] = array(); - } - $CONFIG->register_objects[$entity_type][$object_subtype] = $english_name; - } - - /** - * Establish a 'notify' relationship between the user and a content author - * - * @param int $user_guid The GUID of the user who wants to follow a user's content - * @param int $author_guid The GUID of the user whose content the user wants to follow - * @return true|false Depending on success - */ - function register_notification_interest($user_guid, $author_guid) { - return add_entity_relationship($user_guid, 'notify', $author_guid); - } - - /** - * Remove a 'notify' relationship between the user and a content author - * - * @param int $user_guid The GUID of the user who is following a user's content - * @param int $author_guid The GUID of the user whose content the user wants to unfollow - * @return true|false Depending on success - */ - function remove_notification_interest($user_guid, $author_guid) { - return remove_entity_relationship($user_guid, 'notify', $author_guid); - } - - /** - * Automatically triggered notification on 'create' events that looks at registered - * objects and attempts to send notifications to anybody who's interested - * - * @see register_notification_object - */ - function object_notifications($event, $object_type, $object) { - - // We only want to trigger notification events for ElggEntities - if ($object instanceof ElggEntity) { - - // Get config data - global $CONFIG, $SESSION, $NOTIFICATION_HANDLERS; - - $hookresult = trigger_plugin_hook('object:notifications',$object_type,array( - 'event' => $event, - 'object_type' => $object_type, - 'object' => $object, - ),false); - if ($hookresult === true) return true; - - // Have we registered notifications for this type of entity? - $object_type = $object->getType(); if (empty($object_type)) $object_type = '__BLANK__'; - $object_subtype = $object->getSubtype(); if (empty($object_subtype)) $object_subtype = '__BLANK__'; - if (isset($CONFIG->register_objects[$object_type][$object_subtype])) { - - $descr = $CONFIG->register_objects[$object_type][$object_subtype]; - $string = $descr . ": " . $object->getURL(); - - // Get users interested in content from this person and notify them - // (Person defined by container_guid so we can also subscribe to groups if we want) - foreach($NOTIFICATION_HANDLERS as $method => $foo) - if ($interested_users = get_entities_from_relationship('notify' . $method,$object->container_guid,true,'user','',0,'',99999)) { - - if (is_array($interested_users)) - foreach($interested_users as $user) { - if ($user instanceof ElggUser) { - - if (!$user->isBanned()) - if (($user->guid != $SESSION['user']->guid) && has_access_to_entity($object,$user) - && $object->access_id != ACCESS_PRIVATE) { - - $methodstring = trigger_plugin_hook('notify:entity:message',$object->getType(),array( - 'entity' => $object, - 'to_entity' => $user, - 'method' => $method),$string); - if (empty($methodstring) && $methodstring !== false) $methodstring = $string; - if ($methodstring !== false) - notify_user($user->guid,$object->container_guid,$descr,$methodstring,NULL,array($method)); - } - } - } - } - - } - - } - - } - - // Register a startup event - register_elgg_event_handler('init','system','notification_init',0); - register_elgg_event_handler('create','object','object_notifications'); - -?> + $message = html_entity_decode($message, ENT_COMPAT, 'UTF-8'); // Decode any html entities + $message = strip_tags($message); // Strip tags from message + $message = preg_replace("/(\r\n|\r)/", "\n", $message); // Convert to unix line endings in body + $message = preg_replace("/^From/", ">From", $message); // Change lines starting with From to >From + + return mail($to, $subject, wordwrap($message), $headers); + } + + /** + * Correctly initialise notifications and register the email handler. + * + */ + function notification_init() + { + // Register a notification handler for the default email method + register_notification_handler("email", "email_notify_handler"); + + // Add settings view to user settings & register action + extend_elgg_settings_page('notifications/settings/usersettings', 'usersettings/user'); + + register_plugin_hook('usersettings:save','user','notification_user_settings_save'); + + //register_action("notifications/settings/usersettings/save"); + + + // Register some APIs + expose_function('user.notification.get', 'get_user_notification_settings', array( + 'user_guid' => array ('type' => 'int') + ), elgg_echo('user.notification.get')); + + expose_function('user.notification.set', 'set_user_notification_settings', array( + 'user_guid' => array ('type' => 'int'), + 'method' => array ('type' => 'string'), + 'value' => array ('type' => 'bool') + ), elgg_echo('user.notification.set')); + + } + + function notification_user_settings_save() { + + global $CONFIG; + @include($CONFIG->path . "actions/notifications/settings/usersettings/save.php"); + + } + + /** + * Register an entity type and subtype to be eligible for notifications + * + * @param string $entity_type The type of entity + * @param string $object_subtype Its subtype + * @param string $english_name It's English notification string (eg "New blog post") + */ + function register_notification_object($entity_type, $object_subtype, $english_name) { + global $CONFIG; + + if ($entity_type == '') $entity_type = '__BLANK__'; + if ($object_subtype == '') $object_subtype = '__BLANK__'; + + if (!isset($CONFIG->register_objects)) { + $CONFIG->register_objects = array(); + } + if (!isset($CONFIG->register_objects[$entity_type])) { + $CONFIG->register_objects[$entity_type] = array(); + } + $CONFIG->register_objects[$entity_type][$object_subtype] = $english_name; + } + + /** + * Establish a 'notify' relationship between the user and a content author + * + * @param int $user_guid The GUID of the user who wants to follow a user's content + * @param int $author_guid The GUID of the user whose content the user wants to follow + * @return true|false Depending on success + */ + function register_notification_interest($user_guid, $author_guid) { + return add_entity_relationship($user_guid, 'notify', $author_guid); + } + + /** + * Remove a 'notify' relationship between the user and a content author + * + * @param int $user_guid The GUID of the user who is following a user's content + * @param int $author_guid The GUID of the user whose content the user wants to unfollow + * @return true|false Depending on success + */ + function remove_notification_interest($user_guid, $author_guid) { + return remove_entity_relationship($user_guid, 'notify', $author_guid); + } + + /** + * Automatically triggered notification on 'create' events that looks at registered + * objects and attempts to send notifications to anybody who's interested + * + * @see register_notification_object + */ + function object_notifications($event, $object_type, $object) { + + // We only want to trigger notification events for ElggEntities + if ($object instanceof ElggEntity) { + + // Get config data + global $CONFIG, $SESSION, $NOTIFICATION_HANDLERS; + + $hookresult = trigger_plugin_hook('object:notifications',$object_type,array( + 'event' => $event, + 'object_type' => $object_type, + 'object' => $object, + ),false); + if ($hookresult === true) return true; + + // Have we registered notifications for this type of entity? + $object_type = $object->getType(); if (empty($object_type)) $object_type = '__BLANK__'; + $object_subtype = $object->getSubtype(); if (empty($object_subtype)) $object_subtype = '__BLANK__'; + if (isset($CONFIG->register_objects[$object_type][$object_subtype])) { + + $descr = $CONFIG->register_objects[$object_type][$object_subtype]; + $string = $descr . ": " . $object->getURL(); + + // Get users interested in content from this person and notify them + // (Person defined by container_guid so we can also subscribe to groups if we want) + foreach($NOTIFICATION_HANDLERS as $method => $foo) + if ($interested_users = get_entities_from_relationship('notify' . $method,$object->container_guid,true,'user','',0,'',99999)) { + + if (is_array($interested_users)) + foreach($interested_users as $user) { + if ($user instanceof ElggUser) { + + if (!$user->isBanned()) + if (($user->guid != $SESSION['user']->guid) && has_access_to_entity($object,$user) + && $object->access_id != ACCESS_PRIVATE) { + + $methodstring = trigger_plugin_hook('notify:entity:message',$object->getType(),array( + 'entity' => $object, + 'to_entity' => $user, + 'method' => $method),$string); + if (empty($methodstring) && $methodstring !== false) $methodstring = $string; + if ($methodstring !== false) + notify_user($user->guid,$object->container_guid,$descr,$methodstring,NULL,array($method)); + } + } + } + } + + } + + } + + } + + // Register a startup event + register_elgg_event_handler('init','system','notification_init',0); + register_elgg_event_handler('create','object','object_notifications'); + +?> diff --git a/engine/lib/objects.php b/engine/lib/objects.php index 4090c1c24..7e7e956a4 100644 --- a/engine/lib/objects.php +++ b/engine/lib/objects.php @@ -1,147 +1,147 @@ -attributes['type'] = "object"; - $this->attributes['title'] = ""; + * @subpackage Core + */ + class ElggObject extends ElggEntity + { + /** + * Initialise the attributes array. + * This is vital to distinguish between metadata and base parameters. + * + * Place your base parameters here. + */ + protected function initialise_attributes() + { + parent::initialise_attributes(); + + $this->attributes['type'] = "object"; + $this->attributes['title'] = ""; $this->attributes['description'] = ""; - $this->attributes['tables_split'] = 2; - } - - /** - * Construct a new object entity, optionally from a given id value. - * - * @param mixed $guid If an int, load that GUID. - * If a db row then will attempt to load the rest of the data. - * @throws Exception if there was a problem creating the object. - */ - function __construct($guid = null) - { + $this->attributes['tables_split'] = 2; + } + + /** + * Construct a new object entity, optionally from a given id value. + * + * @param mixed $guid If an int, load that GUID. + * If a db row then will attempt to load the rest of the data. + * @throws Exception if there was a problem creating the object. + */ + function __construct($guid = null) + { $this->initialise_attributes(); - - if (!empty($guid)) - { - // Is $guid is a DB row - either a entity row, or a object table row. - if ($guid instanceof stdClass) { - // Load the rest + + if (!empty($guid)) + { + // Is $guid is a DB row - either a entity row, or a object table row. + if ($guid instanceof stdClass) { + // Load the rest if (!$this->load($guid->guid)) - throw new IOException(sprintf(elgg_echo('IOException:FailedToLoadGUID'), get_class(), $guid->guid)); - } - - // Is $guid is an ElggObject? Use a copy constructor - else if ($guid instanceof ElggObject) - { - foreach ($guid->attributes as $key => $value) - $this->attributes[$key] = $value; - } - - // Is this is an ElggEntity but not an ElggObject = ERROR! - else if ($guid instanceof ElggEntity) - throw new InvalidParameterException(elgg_echo('InvalidParameterException:NonElggObject')); - - // We assume if we have got this far, $guid is an int - else if (is_numeric($guid)) { - if (!$this->load($guid)) IOException(sprintf(elgg_echo('IOException:FailedToLoadGUID'), get_class(), $guid)); + throw new IOException(sprintf(elgg_echo('IOException:FailedToLoadGUID'), get_class(), $guid->guid)); + } + + // Is $guid is an ElggObject? Use a copy constructor + else if ($guid instanceof ElggObject) + { + foreach ($guid->attributes as $key => $value) + $this->attributes[$key] = $value; + } + + // Is this is an ElggEntity but not an ElggObject = ERROR! + else if ($guid instanceof ElggEntity) + throw new InvalidParameterException(elgg_echo('InvalidParameterException:NonElggObject')); + + // We assume if we have got this far, $guid is an int + else if (is_numeric($guid)) { + if (!$this->load($guid)) IOException(sprintf(elgg_echo('IOException:FailedToLoadGUID'), get_class(), $guid)); } else - throw new InvalidParameterException(elgg_echo('InvalidParameterException:UnrecognisedValue')); - } - } - - /** - * Override the load function. - * This function will ensure that all data is loaded (were possible), so - * if only part of the ElggObject is loaded, it'll load the rest. - * - * @param int $guid - * @return true|false - */ - protected function load($guid) - { - // Test to see if we have the generic stuff - if (!parent::load($guid)) - return false; - - // Check the type - if ($this->attributes['type']!='object') - throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $guid, get_class())); - - // Load missing data + throw new InvalidParameterException(elgg_echo('InvalidParameterException:UnrecognisedValue')); + } + } + + /** + * Override the load function. + * This function will ensure that all data is loaded (were possible), so + * if only part of the ElggObject is loaded, it'll load the rest. + * + * @param int $guid + * @return true|false + */ + protected function load($guid) + { + // Test to see if we have the generic stuff + if (!parent::load($guid)) + return false; + + // Check the type + if ($this->attributes['type']!='object') + throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $guid, get_class())); + + // Load missing data $row = get_object_entity_as_row($guid); - if (($row) && (!$this->isFullyLoaded())) $this->attributes['tables_loaded'] ++; // If $row isn't a cached copy then increment the counter - - // Now put these into the attributes array as core values - $objarray = (array) $row; - foreach($objarray as $key => $value) - $this->attributes[$key] = $value; - - return true; - } - - /** - * Override the save function. - * @return true|false - */ - public function save() - { - // Save generic stuff - if (!parent::save()) - return false; - - // Now save specific stuff + if (($row) && (!$this->isFullyLoaded())) $this->attributes['tables_loaded'] ++; // If $row isn't a cached copy then increment the counter + + // Now put these into the attributes array as core values + $objarray = (array) $row; + foreach($objarray as $key => $value) + $this->attributes[$key] = $value; + + return true; + } + + /** + * Override the save function. + * @return true|false + */ + public function save() + { + // Save generic stuff + if (!parent::save()) + return false; + + // Now save specific stuff return create_object_entity($this->get('guid'), $this->get('title'), $this->get('description'), $this->get('container_guid')); } - - /** - * Get sites that this object is a member of - * - * @param string $subtype Optionally, the subtype of result we want to limit to - * @param int $limit The number of results to return - * @param int $offset Any indexing offset - */ - function getSites($subtype="", $limit = 10, $offset = 0) { - return get_site_objects($this->getGUID(), $subtype, $limit, $offset); - } - - /** - * Add this object to a particular site - * - * @param int $site_guid The guid of the site to add it to - * @return true|false - */ - function addToSite($site_guid) { - return add_site_object($this->getGUID(), $site_guid); - } + + /** + * Get sites that this object is a member of + * + * @param string $subtype Optionally, the subtype of result we want to limit to + * @param int $limit The number of results to return + * @param int $offset Any indexing offset + */ + function getSites($subtype="", $limit = 10, $offset = 0) { + return get_site_objects($this->getGUID(), $subtype, $limit, $offset); + } + + /** + * Add this object to a particular site + * + * @param int $site_guid The guid of the site to add it to + * @return true|false + */ + function addToSite($site_guid) { + return add_site_object($this->getGUID(), $site_guid); + } /** * Set the container for this object. @@ -180,16 +180,16 @@ return false; } - - /** - * Get the collections associated with a object. - * - * @param string $subtype Optionally, the subtype of result we want to limit to - * @param int $limit The number of results to return - * @param int $offset Any indexing offset - * @return unknown - */ - //public function getCollections($subtype="", $limit = 10, $offset = 0) { get_object_collections($this->getGUID(), $subtype, $limit, $offset); } + + /** + * Get the collections associated with a object. + * + * @param string $subtype Optionally, the subtype of result we want to limit to + * @param int $limit The number of results to return + * @param int $offset Any indexing offset + * @return unknown + */ + //public function getCollections($subtype="", $limit = 10, $offset = 0) { get_object_collections($this->getGUID(), $subtype, $limit, $offset); } // EXPORTABLE INTERFACE //////////////////////////////////////////////////////////// @@ -202,18 +202,18 @@ 'title', 'description', )); - } - } - - /** - * Return the object specific details of a object by a row. - * - * @param int $guid - */ - function get_object_entity_as_row($guid) - { - global $CONFIG; - + } + } + + /** + * Return the object specific details of a object by a row. + * + * @param int $guid + */ + function get_object_entity_as_row($guid) + { + global $CONFIG; + $guid = (int)$guid; /*$row = retrieve_cached_entity_row($guid); @@ -229,31 +229,31 @@ {*/ // Object not cached, load it. if ($CONFIG->debug) - error_log("** Sub part of GUID:$guid loaded from DB"); - + error_log("** Sub part of GUID:$guid loaded from DB"); + return get_data_row("SELECT * from {$CONFIG->dbprefix}objects_entity where guid=$guid"); - //} - } - - /** - * Create or update the extras table for a given object. - * Call create_entity first. - * - * @param int $guid The guid of the entity you're creating (as obtained by create_entity) - * @param string $title The title of the object - * @param string $description The object's description - */ - function create_object_entity($guid, $title, $description) - { - global $CONFIG; - - $guid = (int)$guid; - $title = sanitise_string($title); + //} + } + + /** + * Create or update the extras table for a given object. + * Call create_entity first. + * + * @param int $guid The guid of the entity you're creating (as obtained by create_entity) + * @param string $title The title of the object + * @param string $description The object's description + */ + function create_object_entity($guid, $title, $description) + { + global $CONFIG; + + $guid = (int)$guid; + $title = sanitise_string($title); $description = sanitise_string($description); - - $row = get_entity_as_row($guid); - - if ($row) + + $row = get_entity_as_row($guid); + + if ($row) { // Core entities row exists and we have access to it if ($exists = get_data_row("SELECT guid from {$CONFIG->dbprefix}objects_entity where guid = {$guid}")) { @@ -267,7 +267,7 @@ } else { $entity->delete(); } - } + } } else { @@ -283,25 +283,25 @@ //delete_entity($guid); } } - } - - } - - return false; - } - + } + + } + + return false; + } + /** * THIS FUNCTION IS DEPRECATED. - * - * Delete a object's extra data. - * - * @param int $guid - */ - function delete_object_entity($guid) + * + * Delete a object's extra data. + * + * @param int $guid + */ + function delete_object_entity($guid) { system_message(sprintf(elgg_echo('deprecatedfunction'), 'delete_user_entity')); - return 1; // Always return that we have deleted one row in order to not break existing code. + return 1; // Always return that we have deleted one row in order to not break existing code. } /** @@ -347,22 +347,22 @@ } } return false; - } - - /** - * Get the sites this object is part of - * - * @param int $object_guid The object's GUID - * @param int $limit Number of results to return - * @param int $offset Any indexing offset - * @return false|array On success, an array of ElggSites - */ - function get_object_sites($object_guid, $limit = 10, $offset = 0) { - $object_guid = (int)$object_guid; - $limit = (int)$limit; - $offset = (int)$offset; - - return get_entities_from_relationship("member_of_site", $object_guid, false, "site", "", 0, "time_created desc", $limit, $offset); - } - + } + + /** + * Get the sites this object is part of + * + * @param int $object_guid The object's GUID + * @param int $limit Number of results to return + * @param int $offset Any indexing offset + * @return false|array On success, an array of ElggSites + */ + function get_object_sites($object_guid, $limit = 10, $offset = 0) { + $object_guid = (int)$object_guid; + $limit = (int)$limit; + $offset = (int)$offset; + + return get_entities_from_relationship("member_of_site", $object_guid, false, "site", "", 0, "time_created desc", $limit, $offset); + } + ?> \ No newline at end of file diff --git a/engine/lib/pagehandler.php b/engine/lib/pagehandler.php index 3669635e2..e602590b3 100644 --- a/engine/lib/pagehandler.php +++ b/engine/lib/pagehandler.php @@ -1,120 +1,120 @@ - $val) { - set_input($name, $val); - } - } - } - $page = explode('/',$page); - - if (!isset($CONFIG->pagehandler) || empty($handler)) { - $result = false; - } else if (isset($CONFIG->pagehandler[$handler]) && is_callable($CONFIG->pagehandler[$handler])) { - $function = $CONFIG->pagehandler[$handler]; - $result = $function($page, $handler); - if ($result !== false) { - $result = true; - } - } else { - $result = false; - } - - if (!$result) { - $result = default_page_handler($page, $handler); - } - if ($result !== false) $result = true; - - return $result; - - } - - /** - * Registers a page handler for a particular identifier - * - * eg, you can register a function called 'blog_page_handler' for handler type 'blog' - * - * Now for all URLs of type http://yoururl/blog/*, the blog_page_handler function will be called. - * The part of the URL marked with * above will be exploded on '/' characters and passed as an - * array to that function, eg: - * - * For the URL http://yoururl/blog/username/friends/: - * blog_page_handler('blog', array('username','friends')); - * - * @param string $handler The page type to handle - * @param string $function Your function name - * @return true|false Depending on success - */ - function register_page_handler($handler, $function) { - - global $CONFIG; - if (!isset($CONFIG->pagehandler)) - $CONFIG->pagehandler = array(); - if (is_callable($function)) { - $CONFIG->pagehandler[$handler] = $function; - return true; - } - return false; - - } - - /** - * A default page handler that attempts to load the actual file at a given page handler location - * - * @param array $page The page URL elements - * @param string $handler The base handler - * @return true|false Depending on success - */ - function default_page_handler($page, $handler) { - + * @author Curverider Ltd + + * @link http://elgg.org/ + */ + + /** + * Turns the current page over to the page handler, allowing registered handlers to take over + * + * @param string $handler The name of the handler type (eg 'blog') + * @param array $page The parameters to the page, as an array (exploded by '/' slashes) + * @return true|false Depending on whether a registered page handler was found + */ + function page_handler($handler, $page) { + + global $CONFIG; + + set_context($handler); + + $query = substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], '?')+1);//parse_url($_SERVER['REQUEST_URI']); + if (isset($query)) { + parse_str($query, $query_arr); + if (is_array($query_arr)) { + foreach($query_arr as $name => $val) { + set_input($name, $val); + } + } + } + $page = explode('/',$page); + + if (!isset($CONFIG->pagehandler) || empty($handler)) { + $result = false; + } else if (isset($CONFIG->pagehandler[$handler]) && is_callable($CONFIG->pagehandler[$handler])) { + $function = $CONFIG->pagehandler[$handler]; + $result = $function($page, $handler); + if ($result !== false) { + $result = true; + } + } else { + $result = false; + } + + if (!$result) { + $result = default_page_handler($page, $handler); + } + if ($result !== false) $result = true; + + return $result; + + } + + /** + * Registers a page handler for a particular identifier + * + * eg, you can register a function called 'blog_page_handler' for handler type 'blog' + * + * Now for all URLs of type http://yoururl/blog/*, the blog_page_handler function will be called. + * The part of the URL marked with * above will be exploded on '/' characters and passed as an + * array to that function, eg: + * + * For the URL http://yoururl/blog/username/friends/: + * blog_page_handler('blog', array('username','friends')); + * + * @param string $handler The page type to handle + * @param string $function Your function name + * @return true|false Depending on success + */ + function register_page_handler($handler, $function) { + + global $CONFIG; + if (!isset($CONFIG->pagehandler)) + $CONFIG->pagehandler = array(); + if (is_callable($function)) { + $CONFIG->pagehandler[$handler] = $function; + return true; + } + return false; + + } + + /** + * A default page handler that attempts to load the actual file at a given page handler location + * + * @param array $page The page URL elements + * @param string $handler The base handler + * @return true|false Depending on success + */ + function default_page_handler($page, $handler) { + global $CONFIG; $script = ""; - - $page = implode('/',$page); - if (($questionmark = strripos($page, '?'))) - $page = substr($page, 0, $questionmark); - - $script = str_replace("..","",$script); - $callpath = $CONFIG->path . $handler . "/" . $page; - if (!file_exists($callpath) || is_dir($callpath) || substr_count($callpath,'.php') == 0) { - if (substr($callpath,strlen($callpath) - 1, 1) != "/") - $callpath .= "/"; - $callpath .= "index.php"; - if (!include($callpath)) - return false; - } else { - include($callpath); - } - - return true; - - } - + + $page = implode('/',$page); + if (($questionmark = strripos($page, '?'))) + $page = substr($page, 0, $questionmark); + + $script = str_replace("..","",$script); + $callpath = $CONFIG->path . $handler . "/" . $page; + if (!file_exists($callpath) || is_dir($callpath) || substr_count($callpath,'.php') == 0) { + if (substr($callpath,strlen($callpath) - 1, 1) != "/") + $callpath .= "/"; + $callpath .= "index.php"; + if (!include($callpath)) + return false; + } else { + include($callpath); + } + + return true; + + } + ?> \ No newline at end of file diff --git a/engine/lib/pageowner.php b/engine/lib/pageowner.php index 3737f42f4..cc3e2e8a3 100644 --- a/engine/lib/pageowner.php +++ b/engine/lib/pageowner.php @@ -1,61 +1,61 @@ -getGUID(); - } - } - if ((!isset($returnval)) && ($user = get_user_by_username($username))) { - $returnval = $user->getGUID(); - } + $returnval = $entity->getGUID(); + } + } + if ((!isset($returnval)) && ($user = get_user_by_username($username))) { + $returnval = $user->getGUID(); + } } - - if ((!isset($returnval)) && ($owner = get_input("owner_guid"))) { - if ($user = get_entity($owner)) { - $returnval = $user->getGUID(); - } + + if ((!isset($returnval)) && ($owner = get_input("owner_guid"))) { + if ($user = get_entity($owner)) { + $returnval = $user->getGUID(); + } } - - if ((!isset($returnval)) && (!empty($CONFIG->page_owner_handlers) && is_array($CONFIG->page_owner_handlers))) { - foreach($CONFIG->page_owner_handlers as $handler) { - if ((!isset($returnval)) && ($guid = $handler())) { - $returnval = $guid; - } - } + + if ((!isset($returnval)) && (!empty($CONFIG->page_owner_handlers) && is_array($CONFIG->page_owner_handlers))) { + foreach($CONFIG->page_owner_handlers as $handler) { + if ((!isset($returnval)) && ($guid = $handler())) { + $returnval = $guid; + } + } } if (isset($returnval)) { @@ -78,109 +78,109 @@ return $returnval; } - - return 0; - - } - - /** - * Gets the page owner for the current page. - * @uses $CONFIG - * @return ElggUser|false The current page owner (false if none). - */ - function page_owner_entity() { - - global $CONFIG; - $page_owner = page_owner(); - if ($page_owner > 0) - return get_entity($page_owner); - - return false; - //return new ElggDummy(); - } - - /** - * Adds a page owner handler - a function that will - * return the page owner if required - * (Such functions are required to return false if they don't know) - * @uses $CONFIG + + return 0; + + } + + /** + * Gets the page owner for the current page. + * @uses $CONFIG + * @return ElggUser|false The current page owner (false if none). + */ + function page_owner_entity() { + + global $CONFIG; + $page_owner = page_owner(); + if ($page_owner > 0) + return get_entity($page_owner); + + return false; + //return new ElggDummy(); + } + + /** + * Adds a page owner handler - a function that will + * return the page owner if required + * (Such functions are required to return false if they don't know) + * @uses $CONFIG * @param string $functionname The name of the function to call - * @return mixed The guid of the owner or false - */ - - function add_page_owner_handler($functionname) { - - global $CONFIG; - if (empty($CONFIG->page_owner_handlers)) { - $CONFIG->page_owner_handlers = array(); - } - if (is_callable($functionname)) { - $CONFIG->page_owner_handlers[] = $functionname; - } - - } - - /** - * Allows a page to manually set a page owner - * - * @param int $entitytoset The GUID of the page owner - * @return int|false Either the page owner we've just set, or false if unset - */ - function set_page_owner($entitytoset = -1) { - - static $entity; - - if (!isset($entity)) $entity = false; - - if ($entitytoset > -1) { - $entity = $entitytoset; - } - - return $entity; - - } - - /** - * Sets the functional context of a page - * - * @param string $context The context of the page - * @return string|false Either the context string, or false on failure - */ - function set_context($context) { - - global $CONFIG; - if (!empty($context)) { - $context = trim($context); - $context = strtolower($context); - $CONFIG->context = $context; - return $context; - } else { - return false; - } - - } - - /** - * Returns the functional context of a page - * - * @return string The context, or 'main' if no context has been provided - */ - function get_context() { - - global $CONFIG; - if (isset($CONFIG->context) && !empty($CONFIG->context)) { - return $CONFIG->context; - } - if ($context = get_plugin_name(true)) { - return $context; - } - return "main"; - - } - - if (defined('context')) { - global $CONFIG; - $CONFIG->context = context; - } - + * @return mixed The guid of the owner or false + */ + + function add_page_owner_handler($functionname) { + + global $CONFIG; + if (empty($CONFIG->page_owner_handlers)) { + $CONFIG->page_owner_handlers = array(); + } + if (is_callable($functionname)) { + $CONFIG->page_owner_handlers[] = $functionname; + } + + } + + /** + * Allows a page to manually set a page owner + * + * @param int $entitytoset The GUID of the page owner + * @return int|false Either the page owner we've just set, or false if unset + */ + function set_page_owner($entitytoset = -1) { + + static $entity; + + if (!isset($entity)) $entity = false; + + if ($entitytoset > -1) { + $entity = $entitytoset; + } + + return $entity; + + } + + /** + * Sets the functional context of a page + * + * @param string $context The context of the page + * @return string|false Either the context string, or false on failure + */ + function set_context($context) { + + global $CONFIG; + if (!empty($context)) { + $context = trim($context); + $context = strtolower($context); + $CONFIG->context = $context; + return $context; + } else { + return false; + } + + } + + /** + * Returns the functional context of a page + * + * @return string The context, or 'main' if no context has been provided + */ + function get_context() { + + global $CONFIG; + if (isset($CONFIG->context) && !empty($CONFIG->context)) { + return $CONFIG->context; + } + if ($context = get_plugin_name(true)) { + return $context; + } + return "main"; + + } + + if (defined('context')) { + global $CONFIG; + $CONFIG->context = context; + } + ?> \ No newline at end of file diff --git a/engine/lib/pam.php b/engine/lib/pam.php index 255a10089..efebb45ec 100644 --- a/engine/lib/pam.php +++ b/engine/lib/pam.php @@ -1,16 +1,16 @@ - \ No newline at end of file diff --git a/engine/lib/plugins.php b/engine/lib/plugins.php index 4f8cd8bbe..1fcd2d138 100644 --- a/engine/lib/plugins.php +++ b/engine/lib/plugins.php @@ -1,739 +1,739 @@ -attributes['subtype'] = "plugin"; + } + + public function __construct($guid = null) + { + parent::__construct($guid); + } + + /** + * Override entity get and sets in order to save data to private data store. + */ + public function get($name) + { + // See if its in our base attribute + if (isset($this->attributes[$name])) { + return $this->attributes[$name]; + } + + // No, so see if its in the private data store. + $meta = get_private_setting($this->guid, $name); + if ($meta) + return $meta; + + // Can't find it, so return null + return null; + } + + /** + * Override entity get and sets in order to save data to private data store. + */ + public function set($name, $value) + { + if (array_key_exists($name, $this->attributes)) + { + // Check that we're not trying to change the guid! + if ((array_key_exists('guid', $this->attributes)) && ($name=='guid')) + return false; + + $this->attributes[$name] = $value; + } + else + return set_private_setting($this->guid, $name, $value); + + return true; + } + } + + /** + * Returns a list of plugins to load, in the order that they should be loaded. + * + * @return array List of plugins + */ + function get_plugin_list() { - * @link http://elgg.org/ - */ - - - /// Cache enabled plugins per page - $ENABLED_PLUGINS_CACHE = NULL; - - /** - * PluginException - * - * A plugin Exception, thrown when an Exception occurs relating to the plugin mechanism. Subclass for specific plugin Exceptions. - * - * @package Elgg - * @subpackage Exceptions - */ - class PluginException extends Exception {} - - /** - * @class ElggPlugin Object representing a plugin's settings for a given site. - * This class is currently a stub, allowing a plugin to saving settings in an object's metadata for each site. - * @author Curverider Ltd - */ - class ElggPlugin extends ElggObject - { - protected function initialise_attributes() - { - parent::initialise_attributes(); - - $this->attributes['subtype'] = "plugin"; - } - - public function __construct($guid = null) - { - parent::__construct($guid); - } - - /** - * Override entity get and sets in order to save data to private data store. - */ - public function get($name) - { - // See if its in our base attribute - if (isset($this->attributes[$name])) { - return $this->attributes[$name]; - } - - // No, so see if its in the private data store. - $meta = get_private_setting($this->guid, $name); - if ($meta) - return $meta; - - // Can't find it, so return null - return null; - } - - /** - * Override entity get and sets in order to save data to private data store. - */ - public function set($name, $value) - { - if (array_key_exists($name, $this->attributes)) - { - // Check that we're not trying to change the guid! - if ((array_key_exists('guid', $this->attributes)) && ($name=='guid')) - return false; - - $this->attributes[$name] = $value; - } - else - return set_private_setting($this->guid, $name, $value); - - return true; - } - } - - /** - * Returns a list of plugins to load, in the order that they should be loaded. - * - * @return array List of plugins - */ - function get_plugin_list() { - - global $CONFIG; - - if (!empty($CONFIG->pluginlistcache)) - return $CONFIG->pluginlistcache; - - if ($site = get_entity($CONFIG->site_guid)) { - - $pluginorder = $site->pluginorder; - if (!empty($pluginorder)) { - - $plugins = unserialize($pluginorder); - - $CONFIG->pluginlistcache = $plugins; - return $plugins; - - } else { - - $plugins = array(); - - if ($handle = opendir($CONFIG->pluginspath)) { - while ($mod = readdir($handle)) { - if (!in_array($mod,array('.','..','.svn','CVS')) && is_dir($CONFIG->pluginspath . "/" . $mod)) { - $plugins[] = $mod; - } - } - } - - sort($plugins); - - $CONFIG->pluginlistcache = $plugins; - return $plugins; - - } - - } - - return false; - - } - - /** + global $CONFIG; + + if (!empty($CONFIG->pluginlistcache)) + return $CONFIG->pluginlistcache; + + if ($site = get_entity($CONFIG->site_guid)) { + + $pluginorder = $site->pluginorder; + if (!empty($pluginorder)) { + + $plugins = unserialize($pluginorder); + + $CONFIG->pluginlistcache = $plugins; + return $plugins; + + } else { + + $plugins = array(); + + if ($handle = opendir($CONFIG->pluginspath)) { + while ($mod = readdir($handle)) { + if (!in_array($mod,array('.','..','.svn','CVS')) && is_dir($CONFIG->pluginspath . "/" . $mod)) { + $plugins[] = $mod; + } + } + } + + sort($plugins); + + $CONFIG->pluginlistcache = $plugins; + return $plugins; + + } + + } + + return false; + + } + + /** * Regenerates the list of known plugins and saves it to the current site * * Important: You should regenerate simplecache and the viewpath cache after executing this function * otherwise you may experience view display artifacts. Do this with the following code: * * elgg_view_regenerate_simplecache(); - * elgg_filepath_cache_reset(); - * - * @param array $pluginorder Optionally, a list of existing plugins and their orders - * @return array The new list of plugins and their orders - */ - function regenerate_plugin_list($pluginorder = false) { - - global $CONFIG; - - $CONFIG->pluginlistcache = null; - - if ($site = get_entity($CONFIG->site_guid)) { - - if (empty($pluginorder)) { - $pluginorder = $site->pluginorder; - $pluginorder = unserialize($pluginorder); - } else { - ksort($pluginorder); - } - - if (empty($pluginorder)) { - $pluginorder = array(); - } - - $max = 0; - if (sizeof($pluginorder)) - foreach($pluginorder as $key => $plugin) { - if (is_dir($CONFIG->pluginspath . "/" . $plugin)) { - if ($key > $max) - $max = $key; - } else { - unset($pluginorder[$key]); - } - } - - // Add new plugins to the end - if ($handle = opendir($CONFIG->pluginspath)) { - while ($mod = readdir($handle)) { - if (!in_array($mod,array('.','..','.svn','CVS')) && is_dir($CONFIG->pluginspath . "/" . $mod)) { - if (!in_array($mod, $pluginorder)) { - $max = $max + 10; - $pluginorder[$max] = $mod; - } - } - } - } - - ksort($pluginorder); - - // Now reorder the keys .. - $key = 10; - $plugins = array(); - if (sizeof($pluginorder)) - foreach($pluginorder as $plugin) { - $plugins[$key] = $plugin; - $key = $key + 10; - } - - $plugins = serialize($plugins); - + * elgg_filepath_cache_reset(); + * + * @param array $pluginorder Optionally, a list of existing plugins and their orders + * @return array The new list of plugins and their orders + */ + function regenerate_plugin_list($pluginorder = false) { + + global $CONFIG; + + $CONFIG->pluginlistcache = null; + + if ($site = get_entity($CONFIG->site_guid)) { + + if (empty($pluginorder)) { + $pluginorder = $site->pluginorder; + $pluginorder = unserialize($pluginorder); + } else { + ksort($pluginorder); + } + + if (empty($pluginorder)) { + $pluginorder = array(); + } + + $max = 0; + if (sizeof($pluginorder)) + foreach($pluginorder as $key => $plugin) { + if (is_dir($CONFIG->pluginspath . "/" . $plugin)) { + if ($key > $max) + $max = $key; + } else { + unset($pluginorder[$key]); + } + } + + // Add new plugins to the end + if ($handle = opendir($CONFIG->pluginspath)) { + while ($mod = readdir($handle)) { + if (!in_array($mod,array('.','..','.svn','CVS')) && is_dir($CONFIG->pluginspath . "/" . $mod)) { + if (!in_array($mod, $pluginorder)) { + $max = $max + 10; + $pluginorder[$max] = $mod; + } + } + } + } + + ksort($pluginorder); + + // Now reorder the keys .. + $key = 10; + $plugins = array(); + if (sizeof($pluginorder)) + foreach($pluginorder as $plugin) { + $plugins[$key] = $plugin; + $key = $key + 10; + } + + $plugins = serialize($plugins); + $site->pluginorder = $plugins; // Regenerate caches elgg_view_regenerate_simplecache(); - elgg_filepath_cache_reset(); - - return $plugins; - - } - - return false; - - } - - - /** - * For now, loads plugins directly - * - * @todo Add proper plugin handler that launches plugins in an admin-defined order and activates them on admin request - * @package Elgg - * @subpackage Core - */ + elgg_filepath_cache_reset(); + + return $plugins; + + } + + return false; + + } + + + /** + * For now, loads plugins directly + * + * @todo Add proper plugin handler that launches plugins in an admin-defined order and activates them on admin request + * @package Elgg + * @subpackage Core + */ function load_plugins() { - + global $CONFIG; - + if (!empty($CONFIG->pluginspath)) { // See if we have cached values for things $cached_view_paths = elgg_filepath_cache_load(); if ($cached_view_paths) $CONFIG->views = unserialize($cached_view_paths); - - // temporary disable all plugins if there is a file called 'disabled' in the plugin dir - if (file_exists($CONFIG->pluginspath . "disabled")) - return; - - $plugins = get_plugin_list(); - + + // temporary disable all plugins if there is a file called 'disabled' in the plugin dir + if (file_exists($CONFIG->pluginspath . "disabled")) + return; + + $plugins = get_plugin_list(); + if (sizeof($plugins)) - { - foreach($plugins as $mod) { - if (is_plugin_enabled($mod)) { - if (file_exists($CONFIG->pluginspath . $mod)) { - if (!include($CONFIG->pluginspath . $mod . "/start.php")) + { + foreach($plugins as $mod) { + if (is_plugin_enabled($mod)) { + if (file_exists($CONFIG->pluginspath . $mod)) { + if (!include($CONFIG->pluginspath . $mod . "/start.php")) throw new PluginException(sprintf(elgg_echo('PluginException:MisconfiguredPlugin'), $mod)); if (!$cached_view_paths) - { - if (is_dir($CONFIG->pluginspath . $mod . "/views")) { - if ($handle = opendir($CONFIG->pluginspath . $mod . "/views")) { - while ($viewtype = readdir($handle)) { - if (!in_array($viewtype,array('.','..','.svn','CVS')) && is_dir($CONFIG->pluginspath . $mod . "/views/" . $viewtype)) { - autoregister_views("",$CONFIG->pluginspath . $mod . "/views/" . $viewtype,$CONFIG->pluginspath . $mod . "/views/", $viewtype); - } - } - } + { + if (is_dir($CONFIG->pluginspath . $mod . "/views")) { + if ($handle = opendir($CONFIG->pluginspath . $mod . "/views")) { + while ($viewtype = readdir($handle)) { + if (!in_array($viewtype,array('.','..','.svn','CVS')) && is_dir($CONFIG->pluginspath . $mod . "/views/" . $viewtype)) { + autoregister_views("",$CONFIG->pluginspath . $mod . "/views/" . $viewtype,$CONFIG->pluginspath . $mod . "/views/", $viewtype); + } + } + } } } - - if (is_dir($CONFIG->pluginspath . $mod . "/languages")) { - register_translations($CONFIG->pluginspath . $mod . "/languages/"); - } - } - } - } + + if (is_dir($CONFIG->pluginspath . $mod . "/languages")) { + register_translations($CONFIG->pluginspath . $mod . "/languages/"); + } + } + } + } } // Cache results if (!$cached_view_paths) elgg_filepath_cache_save(serialize($CONFIG->views)); - } - - } - - /** - * Get the name of the most recent plugin to be called in the call stack (or the plugin that owns the current page, if any). - * - * i.e., if the last plugin was in /mod/foobar/, get_plugin_name would return foo_bar. - * - * @param boolean $mainfilename If set to true, this will instead determine the context from the main script filename called by the browser. Default = false. - * @return string|false Plugin name, or false if no plugin name was called - */ - function get_plugin_name($mainfilename = false) { - if (!$mainfilename) { - if ($backtrace = debug_backtrace()) { - foreach($backtrace as $step) { - $file = $step['file']; - $file = str_replace("\\","/",$file); - $file = str_replace("//","/",$file); - if (preg_match("/mod\/([a-zA-Z0-9\-\_]*)\/start\.php$/",$file,$matches)) { - return $matches[1]; - } - } - } - } else { - //if (substr_count($file,'handlers/pagehandler')) { - if (preg_match("/pg\/([a-zA-Z0-9\-\_]*)\//",$_SERVER['REQUEST_URI'],$matches)) { - return $matches[1]; - } else { - $file = $_SERVER["SCRIPT_NAME"]; - $file = str_replace("\\","/",$file); - $file = str_replace("//","/",$file); - if (preg_match("/mod\/([a-zA-Z0-9\-\_]*)\//",$file,$matches)) { - return $matches[1]; - } - } - } - return false; - } - - /** - * Load and parse a plugin manifest from a plugin XML file. - * - * Example file: - * - * - * - * - * - * - * - * - * - * - * @param string $plugin Plugin name. - * @return array of values - */ - function load_plugin_manifest($plugin) - { - global $CONFIG; - - $xml = xml_2_object(file_get_contents($CONFIG->pluginspath . $plugin. "/manifest.xml")); - - if ($xml) - { - $elements = array(); - - foreach ($xml->children as $element) - { - $key = $element->attributes['key']; - $value = $element->attributes['value']; - - $elements[$key] = $value; - } - - return $elements; - } - - return false; - } - - /** - * This function checks a plugin manifest 'elgg_version' value against the current install - * returning TRUE if the elgg_version is <= the current install's version. - * @param $manifest_elgg_version_string The build version (eg 2009010201). - * @return bool - */ - function check_plugin_compatibility($manifest_elgg_version_string) - { - $version = get_version(); - - if (strpos($manifest_elgg_version_string, '.')===false) - { - // Using version - $req_version = (int)$manifest_elgg_version_string; - - return ($version >= $req_version); - } - - return false; - } - - /** - * Shorthand function for finding the plugin settings. - * - * @param string $plugin_name Optional plugin name, if not specified then it is detected from where you - * are calling from. - */ - function find_plugin_settings($plugin_name = "") - { - $plugins = get_entities('object', 'plugin', 0, "", 9999); - $plugin_name = sanitise_string($plugin_name); - if (!$plugin_name) - $plugin_name = get_plugin_name(); - - if ($plugins) - { - foreach ($plugins as $plugin) - if (strcmp($plugin->title, $plugin_name)==0) - return $plugin; - } - - return false; - } - - /** - * Find the plugin settings for a user. - * - * @param string $plugin_name Plugin name. - * @param int $user_guid The guid who's settings to retrieve. - * @return array of settings in an associative array minus prefix. - */ - function find_plugin_usersettings($plugin_name = "", $user_guid = 0) - { - $plugin_name = sanitise_string($plugin_name); - $user_guid = (int)$user_guid; - - if (!$plugin_name) - $plugin_name = get_plugin_name(); - - if ($user_guid == 0) $user_guid = get_loggedin_userid(); - - // Get metadata for user - $all_metadata = get_all_private_settings($user_guid); //get_metadata_for_entity($user_guid); - if ($all_metadata) - { - $prefix = "plugin:settings:$plugin_name:"; - $return = new stdClass; - - foreach ($all_metadata as $key => $meta) - { - $name = substr($key, strlen($prefix)); - $value = $meta; - - if (strpos($key, $prefix) === 0) - $return->$name = $value; - } - - return $return; - } - - return false; - } - - /** - * Set a user specific setting for a plugin. - * - * @param string $name The name - note, can't be "title". - * @param mixed $value The value. - * @param int $user_guid Optional user. - * @param string $plugin_name Optional plugin name, if not specified then it is detected from where you are calling from. - */ - function set_plugin_usersetting($name, $value, $user_guid = 0, $plugin_name = "") - { - $plugin_name = sanitise_string($plugin_name); - $user_guid = (int)$user_guid; - $name = sanitise_string($name); - - if (!$plugin_name) - $plugin_name = get_plugin_name(); - - $user = get_entity($user_guid); - if (!$user) $user = get_loggedin_user(); - - if (($user) && ($user instanceof ElggUser)) - { - $prefix = "plugin:settings:$plugin_name:$name"; - //$user->$prefix = $value; - //$user->save(); - - // Hook to validate setting - $value = trigger_plugin_hook('plugin:usersetting', 'user', array( - 'user' => $user, - 'plugin' => $plugin_name, - 'name' => $name, - 'value' => $value - ), $value); - - return set_private_setting($user->guid, $prefix, $value); - } - - return false; - } - - /** - * Get a user specific setting for a plugin. - * - * @param string $name The name. - * @param string $plugin_name Optional plugin name, if not specified then it is detected from where you are calling from. - */ - function get_plugin_usersetting($name, $user_guid = 0, $plugin_name = "") - { - $plugin_name = sanitise_string($plugin_name); - $user_guid = (int)$user_guid; - $name = sanitise_string($name); - - if (!$plugin_name) - $plugin_name = get_plugin_name(); - - $user = get_entity($user_guid); - if (!$user) $user = get_loggedin_user(); - - if (($user) && ($user instanceof ElggUser)) - { - $prefix = "plugin:settings:$plugin_name:$name"; - return get_private_setting($user->guid, $prefix); //$user->$prefix; - } - - return false; - } - - /** - * Set a setting for a plugin. - * - * @param string $name The name - note, can't be "title". - * @param mixed $value The value. - * @param string $plugin_name Optional plugin name, if not specified then it is detected from where you are calling from. - */ - function set_plugin_setting($name, $value, $plugin_name = "") - { - if (!$plugin_name) $plugin_name = get_plugin_name(); - $plugin = find_plugin_settings($plugin_name); - - if (!$plugin) - $plugin = new ElggPlugin(); - - if ($name!='title') - { - // Hook to validate setting - $value = trigger_plugin_hook('plugin:setting', 'plugin', array( - 'plugin' => $plugin_name, - 'name' => $name, - 'value' => $value - ), $value); - - $plugin->title = $plugin_name; - $plugin->access_id = ACCESS_PUBLIC; - $plugin->save(); - $plugin->$name = $value; - - return $plugin->getGUID(); - } - - return false; - } - - /** - * Get setting for a plugin. - * - * @param string $name The name. - * @param string $plugin_name Optional plugin name, if not specified then it is detected from where you are calling from. - */ - function get_plugin_setting($name, $plugin_name = "") - { - $plugin = find_plugin_settings($plugin_name); - - if ($plugin) - return $plugin->$name; - - return false; - } - - /** - * Clear a plugin setting. - * - * @param string $name The name. - * @param string $plugin_name Optional plugin name, if not specified then it is detected from where you are calling from. - */ - function clear_plugin_setting($name, $plugin_name = "") - { - $plugin = find_plugin_settings($plugin_name); - - if ($plugin) - return remove_all_private_settings($plugin->guid); //$plugin->clearMetaData($name); - - return false; - } - - /** - * Return an array of installed plugins. - */ - function get_installed_plugins() - { - global $CONFIG; - - $installed_plugins = array(); - - if (!empty($CONFIG->pluginspath)) { - - $plugins = get_plugin_list(); - - foreach($plugins as $mod) { - $installed_plugins[$mod] = array(); - $installed_plugins[$mod]['active'] = is_plugin_enabled($mod); - $installed_plugins[$mod]['manifest'] = load_plugin_manifest($mod); - } - - } - - return $installed_plugins; - } - - /** + } + + } + + /** + * Get the name of the most recent plugin to be called in the call stack (or the plugin that owns the current page, if any). + * + * i.e., if the last plugin was in /mod/foobar/, get_plugin_name would return foo_bar. + * + * @param boolean $mainfilename If set to true, this will instead determine the context from the main script filename called by the browser. Default = false. + * @return string|false Plugin name, or false if no plugin name was called + */ + function get_plugin_name($mainfilename = false) { + if (!$mainfilename) { + if ($backtrace = debug_backtrace()) { + foreach($backtrace as $step) { + $file = $step['file']; + $file = str_replace("\\","/",$file); + $file = str_replace("//","/",$file); + if (preg_match("/mod\/([a-zA-Z0-9\-\_]*)\/start\.php$/",$file,$matches)) { + return $matches[1]; + } + } + } + } else { + //if (substr_count($file,'handlers/pagehandler')) { + if (preg_match("/pg\/([a-zA-Z0-9\-\_]*)\//",$_SERVER['REQUEST_URI'],$matches)) { + return $matches[1]; + } else { + $file = $_SERVER["SCRIPT_NAME"]; + $file = str_replace("\\","/",$file); + $file = str_replace("//","/",$file); + if (preg_match("/mod\/([a-zA-Z0-9\-\_]*)\//",$file,$matches)) { + return $matches[1]; + } + } + } + return false; + } + + /** + * Load and parse a plugin manifest from a plugin XML file. + * + * Example file: + * + * + * + * + * + * + * + * + * + * + * @param string $plugin Plugin name. + * @return array of values + */ + function load_plugin_manifest($plugin) + { + global $CONFIG; + + $xml = xml_2_object(file_get_contents($CONFIG->pluginspath . $plugin. "/manifest.xml")); + + if ($xml) + { + $elements = array(); + + foreach ($xml->children as $element) + { + $key = $element->attributes['key']; + $value = $element->attributes['value']; + + $elements[$key] = $value; + } + + return $elements; + } + + return false; + } + + /** + * This function checks a plugin manifest 'elgg_version' value against the current install + * returning TRUE if the elgg_version is <= the current install's version. + * @param $manifest_elgg_version_string The build version (eg 2009010201). + * @return bool + */ + function check_plugin_compatibility($manifest_elgg_version_string) + { + $version = get_version(); + + if (strpos($manifest_elgg_version_string, '.')===false) + { + // Using version + $req_version = (int)$manifest_elgg_version_string; + + return ($version >= $req_version); + } + + return false; + } + + /** + * Shorthand function for finding the plugin settings. + * + * @param string $plugin_name Optional plugin name, if not specified then it is detected from where you + * are calling from. + */ + function find_plugin_settings($plugin_name = "") + { + $plugins = get_entities('object', 'plugin', 0, "", 9999); + $plugin_name = sanitise_string($plugin_name); + if (!$plugin_name) + $plugin_name = get_plugin_name(); + + if ($plugins) + { + foreach ($plugins as $plugin) + if (strcmp($plugin->title, $plugin_name)==0) + return $plugin; + } + + return false; + } + + /** + * Find the plugin settings for a user. + * + * @param string $plugin_name Plugin name. + * @param int $user_guid The guid who's settings to retrieve. + * @return array of settings in an associative array minus prefix. + */ + function find_plugin_usersettings($plugin_name = "", $user_guid = 0) + { + $plugin_name = sanitise_string($plugin_name); + $user_guid = (int)$user_guid; + + if (!$plugin_name) + $plugin_name = get_plugin_name(); + + if ($user_guid == 0) $user_guid = get_loggedin_userid(); + + // Get metadata for user + $all_metadata = get_all_private_settings($user_guid); //get_metadata_for_entity($user_guid); + if ($all_metadata) + { + $prefix = "plugin:settings:$plugin_name:"; + $return = new stdClass; + + foreach ($all_metadata as $key => $meta) + { + $name = substr($key, strlen($prefix)); + $value = $meta; + + if (strpos($key, $prefix) === 0) + $return->$name = $value; + } + + return $return; + } + + return false; + } + + /** + * Set a user specific setting for a plugin. + * + * @param string $name The name - note, can't be "title". + * @param mixed $value The value. + * @param int $user_guid Optional user. + * @param string $plugin_name Optional plugin name, if not specified then it is detected from where you are calling from. + */ + function set_plugin_usersetting($name, $value, $user_guid = 0, $plugin_name = "") + { + $plugin_name = sanitise_string($plugin_name); + $user_guid = (int)$user_guid; + $name = sanitise_string($name); + + if (!$plugin_name) + $plugin_name = get_plugin_name(); + + $user = get_entity($user_guid); + if (!$user) $user = get_loggedin_user(); + + if (($user) && ($user instanceof ElggUser)) + { + $prefix = "plugin:settings:$plugin_name:$name"; + //$user->$prefix = $value; + //$user->save(); + + // Hook to validate setting + $value = trigger_plugin_hook('plugin:usersetting', 'user', array( + 'user' => $user, + 'plugin' => $plugin_name, + 'name' => $name, + 'value' => $value + ), $value); + + return set_private_setting($user->guid, $prefix, $value); + } + + return false; + } + + /** + * Get a user specific setting for a plugin. + * + * @param string $name The name. + * @param string $plugin_name Optional plugin name, if not specified then it is detected from where you are calling from. + */ + function get_plugin_usersetting($name, $user_guid = 0, $plugin_name = "") + { + $plugin_name = sanitise_string($plugin_name); + $user_guid = (int)$user_guid; + $name = sanitise_string($name); + + if (!$plugin_name) + $plugin_name = get_plugin_name(); + + $user = get_entity($user_guid); + if (!$user) $user = get_loggedin_user(); + + if (($user) && ($user instanceof ElggUser)) + { + $prefix = "plugin:settings:$plugin_name:$name"; + return get_private_setting($user->guid, $prefix); //$user->$prefix; + } + + return false; + } + + /** + * Set a setting for a plugin. + * + * @param string $name The name - note, can't be "title". + * @param mixed $value The value. + * @param string $plugin_name Optional plugin name, if not specified then it is detected from where you are calling from. + */ + function set_plugin_setting($name, $value, $plugin_name = "") + { + if (!$plugin_name) $plugin_name = get_plugin_name(); + $plugin = find_plugin_settings($plugin_name); + + if (!$plugin) + $plugin = new ElggPlugin(); + + if ($name!='title') + { + // Hook to validate setting + $value = trigger_plugin_hook('plugin:setting', 'plugin', array( + 'plugin' => $plugin_name, + 'name' => $name, + 'value' => $value + ), $value); + + $plugin->title = $plugin_name; + $plugin->access_id = ACCESS_PUBLIC; + $plugin->save(); + $plugin->$name = $value; + + return $plugin->getGUID(); + } + + return false; + } + + /** + * Get setting for a plugin. + * + * @param string $name The name. + * @param string $plugin_name Optional plugin name, if not specified then it is detected from where you are calling from. + */ + function get_plugin_setting($name, $plugin_name = "") + { + $plugin = find_plugin_settings($plugin_name); + + if ($plugin) + return $plugin->$name; + + return false; + } + + /** + * Clear a plugin setting. + * + * @param string $name The name. + * @param string $plugin_name Optional plugin name, if not specified then it is detected from where you are calling from. + */ + function clear_plugin_setting($name, $plugin_name = "") + { + $plugin = find_plugin_settings($plugin_name); + + if ($plugin) + return remove_all_private_settings($plugin->guid); //$plugin->clearMetaData($name); + + return false; + } + + /** + * Return an array of installed plugins. + */ + function get_installed_plugins() + { + global $CONFIG; + + $installed_plugins = array(); + + if (!empty($CONFIG->pluginspath)) { + + $plugins = get_plugin_list(); + + foreach($plugins as $mod) { + $installed_plugins[$mod] = array(); + $installed_plugins[$mod]['active'] = is_plugin_enabled($mod); + $installed_plugins[$mod]['manifest'] = load_plugin_manifest($mod); + } + + } + + return $installed_plugins; + } + + /** * Enable a plugin for a site (default current site) * * Important: You should regenerate simplecache and the viewpath cache after executing this function * otherwise you may experience view display artifacts. Do this with the following code: * * elgg_view_regenerate_simplecache(); - * elgg_filepath_cache_reset(); - * - * @param string $plugin The plugin name. - * @param int $site_guid The site id, if not specified then this is detected. - */ - function enable_plugin($plugin, $site_guid = 0) - { - global $CONFIG, $ENABLED_PLUGINS_CACHE; - - $plugin = sanitise_string($plugin); - $site_guid = (int) $site_guid; - if ($site_guid == 0) - $site_guid = $CONFIG->site_guid; - - $site = get_entity($site_guid); - if (!($site instanceof ElggSite)) - throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $site_guid, "ElggSite")); - - $enabled = $site->getMetaData('enabled_plugins'); - $new_enabled = array(); - if ($enabled) - { - if (!is_array($enabled)) - $new_enabled[] = $enabled; - else - $new_enabled = $enabled; - } - $new_enabled[] = $plugin; - $new_enabled = array_unique($new_enabled); - + * elgg_filepath_cache_reset(); + * + * @param string $plugin The plugin name. + * @param int $site_guid The site id, if not specified then this is detected. + */ + function enable_plugin($plugin, $site_guid = 0) + { + global $CONFIG, $ENABLED_PLUGINS_CACHE; + + $plugin = sanitise_string($plugin); + $site_guid = (int) $site_guid; + if ($site_guid == 0) + $site_guid = $CONFIG->site_guid; + + $site = get_entity($site_guid); + if (!($site instanceof ElggSite)) + throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $site_guid, "ElggSite")); + + $enabled = $site->getMetaData('enabled_plugins'); + $new_enabled = array(); + if ($enabled) + { + if (!is_array($enabled)) + $new_enabled[] = $enabled; + else + $new_enabled = $enabled; + } + $new_enabled[] = $plugin; + $new_enabled = array_unique($new_enabled); + $return = $site->setMetaData('enabled_plugins', $new_enabled); - $ENABLED_PLUGINS_CACHE = $new_enabled; - - return $return; - } - - /** - * Disable a plugin for a site (default current site) + $ENABLED_PLUGINS_CACHE = $new_enabled; + + return $return; + } + + /** + * Disable a plugin for a site (default current site) * * Important: You should regenerate simplecache and the viewpath cache after executing this function * otherwise you may experience view display artifacts. Do this with the following code: * * elgg_view_regenerate_simplecache(); * elgg_filepath_cache_reset(); - * - * @param string $plugin The plugin name. - * @param int $site_guid The site id, if not specified then this is detected. - */ - function disable_plugin($plugin, $site_guid = 0) - { - global $CONFIG, $ENABLED_PLUGINS_CACHE; - - $plugin = sanitise_string($plugin); - $site_guid = (int) $site_guid; - if ($site_guid == 0) - $site_guid = $CONFIG->site_guid; - - $site = get_entity($site_guid); - if (!($site instanceof ElggSite)) - throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $site_guid, "ElggSite")); - - $enabled = $site->getMetaData('enabled_plugins'); - $new_enabled = array(); - - foreach ($enabled as $plug) - if ($plugin != $plug) - $new_enabled[] = $plug; - + * + * @param string $plugin The plugin name. + * @param int $site_guid The site id, if not specified then this is detected. + */ + function disable_plugin($plugin, $site_guid = 0) + { + global $CONFIG, $ENABLED_PLUGINS_CACHE; + + $plugin = sanitise_string($plugin); + $site_guid = (int) $site_guid; + if ($site_guid == 0) + $site_guid = $CONFIG->site_guid; + + $site = get_entity($site_guid); + if (!($site instanceof ElggSite)) + throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $site_guid, "ElggSite")); + + $enabled = $site->getMetaData('enabled_plugins'); + $new_enabled = array(); + + foreach ($enabled as $plug) + if ($plugin != $plug) + $new_enabled[] = $plug; + $return = $site->setMetaData('enabled_plugins', $new_enabled); - $ENABLED_PLUGINS_CACHE = $new_enabled; - - return $return; - } - - /** - * Return whether a plugin is enabled or not. - * - * @param string $plugin The plugin name. - * @param int $site_guid The site id, if not specified then this is detected. - * @return bool - */ - function is_plugin_enabled($plugin, $site_guid = 0) - { - global $CONFIG, $ENABLED_PLUGINS_CACHE; - - if (!file_exists($CONFIG->pluginspath . $plugin)) return false; - - $site_guid = (int) $site_guid; - if ($site_guid == 0) - $site_guid = $CONFIG->site_guid; - - - if (!$ENABLED_PLUGINS_CACHE) { - $site = get_entity($site_guid); - if (!($site instanceof ElggSite)) - throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $site_guid, "ElggSite")); - - $ENABLED_PLUGINS_CACHE = $site->enabled_plugins; - } - - foreach ($ENABLED_PLUGINS_CACHE as $e) - if ($e == $plugin) return true; - - return false; - } - - /** - * Run once and only once. - */ - function plugin_run_once() - { - // Register a class - add_subtype("object", "plugin", "ElggPlugin"); - } - - /** - * Initialise the file modules. - * Listens to system boot and registers any appropriate file types and classes - */ - function plugin_init() - { - // Now run this stuff, but only once - run_function_once("plugin_run_once"); - - // Register some actions - register_action("plugins/settings/save", false, "", true); - register_action("plugins/usersettings/save"); - - register_action('admin/plugins/enable', false, "", true); // Enable + $ENABLED_PLUGINS_CACHE = $new_enabled; + + return $return; + } + + /** + * Return whether a plugin is enabled or not. + * + * @param string $plugin The plugin name. + * @param int $site_guid The site id, if not specified then this is detected. + * @return bool + */ + function is_plugin_enabled($plugin, $site_guid = 0) + { + global $CONFIG, $ENABLED_PLUGINS_CACHE; + + if (!file_exists($CONFIG->pluginspath . $plugin)) return false; + + $site_guid = (int) $site_guid; + if ($site_guid == 0) + $site_guid = $CONFIG->site_guid; + + + if (!$ENABLED_PLUGINS_CACHE) { + $site = get_entity($site_guid); + if (!($site instanceof ElggSite)) + throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $site_guid, "ElggSite")); + + $ENABLED_PLUGINS_CACHE = $site->enabled_plugins; + } + + foreach ($ENABLED_PLUGINS_CACHE as $e) + if ($e == $plugin) return true; + + return false; + } + + /** + * Run once and only once. + */ + function plugin_run_once() + { + // Register a class + add_subtype("object", "plugin", "ElggPlugin"); + } + + /** + * Initialise the file modules. + * Listens to system boot and registers any appropriate file types and classes + */ + function plugin_init() + { + // Now run this stuff, but only once + run_function_once("plugin_run_once"); + + // Register some actions + register_action("plugins/settings/save", false, "", true); + register_action("plugins/usersettings/save"); + + register_action('admin/plugins/enable', false, "", true); // Enable register_action('admin/plugins/disable', false, "", true); // Disable register_action('admin/plugins/enableall', false, "", true); // Enable all - register_action('admin/plugins/disableall', false, "", true); // Disable all - - register_action('admin/plugins/reorder', false, "", true); // Reorder - - } - - // Register a startup event - register_elgg_event_handler('init','system','plugin_init'); + register_action('admin/plugins/disableall', false, "", true); // Disable all + + register_action('admin/plugins/reorder', false, "", true); // Reorder + + } + + // Register a startup event + register_elgg_event_handler('init','system','plugin_init'); ?> \ No newline at end of file diff --git a/engine/lib/query.php b/engine/lib/query.php index 9d8b00be2..75b9eddeb 100644 --- a/engine/lib/query.php +++ b/engine/lib/query.php @@ -178,12 +178,12 @@ function __toString() { - //$access = get_access_list(); - // KJ - changed to use get_access_sql_suffix - // Note: currently get_access_sql_suffix is hardwired to use - // $acl_field = "access_id", $object_owner_table = $acl_table, and - // $object_owner_id_field = "owner_guid" - // TODO: recode get_access_sql_suffix to make it possible to specify alternate field names + //$access = get_access_list(); + // KJ - changed to use get_access_sql_suffix + // Note: currently get_access_sql_suffix is hardwired to use + // $acl_field = "access_id", $object_owner_table = $acl_table, and + // $object_owner_id_field = "owner_guid" + // TODO: recode get_access_sql_suffix to make it possible to specify alternate field names return "and ".get_access_sql_suffix($this->acl_table); // Add access controls //return "and ({$this->acl_table}.{$this->acl_field} in {$access} or ({$this->acl_table}.{$this->acl_field} = 0 and {$this->object_owner_table}.{$this->object_owner_id_field} = {$_SESSION['id']}))"; diff --git a/engine/lib/relationships.php b/engine/lib/relationships.php index 92a88781f..2ba8a553e 100644 --- a/engine/lib/relationships.php +++ b/engine/lib/relationships.php @@ -415,14 +415,14 @@ $guid_one = (int)$guid_one; $relationship = sanitise_string($relationship); $guid_two = (int)$guid_two; - - $obj = check_entity_relationship($guid_one, $relationship, $guid_two); - if ($obj == false) return false; - - if (trigger_elgg_event('delete', $relationship, $obj)) { - return delete_data("DELETE from {$CONFIG->dbprefix}entity_relationships where guid_one=$guid_one and relationship='$relationship' and guid_two=$guid_two"); - } else { - return false; + + $obj = check_entity_relationship($guid_one, $relationship, $guid_two); + if ($obj == false) return false; + + if (trigger_elgg_event('delete', $relationship, $obj)) { + return delete_data("DELETE from {$CONFIG->dbprefix}entity_relationships where guid_one=$guid_one and relationship='$relationship' and guid_two=$guid_two"); + } else { + return false; } } @@ -431,7 +431,7 @@ * * @param int $guid_one The GUID of the entity * @param string $relationship The name of the relationship (optionally) - * @param true|false $inverse Whether we're deleting inverse relationships (default false) + * @param true|false $inverse Whether we're deleting inverse relationships (default false) * @param string $type The type of entity to limit this relationship delete to (defaults to all) * @return true|false Depending on success */ @@ -446,25 +446,25 @@ $where = "and er.relationship='$relationship'"; } else { $where = ""; - } - - if (!empty($type)) { - $type = sanitise_string($type); - if (!$inverse) { - $join = " join {$CONFIG->dbprefix}entities e on e.guid = er.guid_two "; - } else { - $join = " join {$CONFIG->dbprefix}entities e on e.guid = er.guid_one "; - $where .= " and "; - } - $where .= " and e.type = '{$type}' "; - } else { - $join = ""; } - if (!$inverse) { + if (!empty($type)) { + $type = sanitise_string($type); + if (!$inverse) { + $join = " join {$CONFIG->dbprefix}entities e on e.guid = er.guid_two "; + } else { + $join = " join {$CONFIG->dbprefix}entities e on e.guid = er.guid_one "; + $where .= " and "; + } + $where .= " and e.type = '{$type}' "; + } else { + $join = ""; + } + + if (!$inverse) { $sql = "DELETE er from {$CONFIG->dbprefix}entity_relationships as er {$join} where guid_one={$guid_one} {$where}"; return delete_data($sql); - } else { + } else { $sql = "DELETE er from {$CONFIG->dbprefix}entity_relationships as er {$join} where guid_two={$guid_one} {$where}"; return delete_data($sql); } @@ -513,7 +513,7 @@ $type = sanitise_string($type); if ($subtype AND !$subtype = get_subtype_id($type, $subtype)) return false; - $owner_guid = (int)$owner_guid; + $owner_guid = (int)$owner_guid; if ($order_by == "") $order_by = "time_created desc"; $order_by = sanitise_string($order_by); $limit = (int)$limit; @@ -563,140 +563,140 @@ } return false; - } - - /** - * Returns a viewable list of entities by relationship - * - * @see elgg_view_entity_list - * - * @param string $relationship The relationship eg "friends_of" - * @param int $relationship_guid The guid of the entity to use query - * @param bool $inverse_relationship Reverse the normal function of the query to instead say "give me all entities for whome $relationship_guid is a $relationship of" - * @param string $type The type of entity (eg 'object') - * @param string $subtype The entity subtype - * @param int $owner_guid The owner (default: all) - * @param int $limit The number of entities to display on a page - * @param true|false $fullview Whether or not to display the full view (default: true) - * @param true|false $viewtypetoggle Whether or not to allow gallery view - * @param true|false $pagination Whether to display pagination (default: true) - * @return string The viewable list of entities - */ - function list_entities_from_relationship($relationship, $relationship_guid, $inverse_relationship = false, $type = "", $subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = false, $pagination = true) { - - $limit = (int) $limit; - $offset = (int) get_input('offset'); - $count = get_entities_from_relationship($relationship, $relationship_guid, $inverse_relationship, $type, $subtype, $owner_guid, "", $limit, $offset, true); - $entities = get_entities_from_relationship($relationship, $relationship_guid, $inverse_relationship, $type, $subtype, $owner_guid, "", $limit, $offset); - - return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); - - } - - /** - * Gets the number of entities by a the number of entities related to them in a particular way. - * This is a good way to get out the users with the most friends, or the groups with the most members. - * - * @param string $relationship The relationship eg "friends_of" - * @param bool $inverse_relationship Reverse the normal function of the query to instead say "give me all entities for whome $relationship_guid is a $relationship of" (default: true) - * @param string $type The type of entity (default: all) - * @param string $subtype The entity subtype (default: all) - * @param int $owner_guid The owner of the entities (default: none) - * @param int $limit - * @param int $offset - * @param boolean $count Set to true if you want to count the number of entities instead (default false) - * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. - * @return array|int|false An array of entities, or the number of entities, or false on failure - */ - - function get_entities_by_relationship_count($relationship, $inverse_relationship = true, $type = "", $subtype = "", $owner_guid = 0, $limit = 10, $offset = 0, $count = false, $site_guid = 0) { - - global $CONFIG; - - $relationship = sanitise_string($relationship); - $inverse_relationship = (bool)$inverse_relationship; - $type = sanitise_string($type); + } + + /** + * Returns a viewable list of entities by relationship + * + * @see elgg_view_entity_list + * + * @param string $relationship The relationship eg "friends_of" + * @param int $relationship_guid The guid of the entity to use query + * @param bool $inverse_relationship Reverse the normal function of the query to instead say "give me all entities for whome $relationship_guid is a $relationship of" + * @param string $type The type of entity (eg 'object') + * @param string $subtype The entity subtype + * @param int $owner_guid The owner (default: all) + * @param int $limit The number of entities to display on a page + * @param true|false $fullview Whether or not to display the full view (default: true) + * @param true|false $viewtypetoggle Whether or not to allow gallery view + * @param true|false $pagination Whether to display pagination (default: true) + * @return string The viewable list of entities + */ + function list_entities_from_relationship($relationship, $relationship_guid, $inverse_relationship = false, $type = "", $subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = false, $pagination = true) { + + $limit = (int) $limit; + $offset = (int) get_input('offset'); + $count = get_entities_from_relationship($relationship, $relationship_guid, $inverse_relationship, $type, $subtype, $owner_guid, "", $limit, $offset, true); + $entities = get_entities_from_relationship($relationship, $relationship_guid, $inverse_relationship, $type, $subtype, $owner_guid, "", $limit, $offset); + + return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); + + } + + /** + * Gets the number of entities by a the number of entities related to them in a particular way. + * This is a good way to get out the users with the most friends, or the groups with the most members. + * + * @param string $relationship The relationship eg "friends_of" + * @param bool $inverse_relationship Reverse the normal function of the query to instead say "give me all entities for whome $relationship_guid is a $relationship of" (default: true) + * @param string $type The type of entity (default: all) + * @param string $subtype The entity subtype (default: all) + * @param int $owner_guid The owner of the entities (default: none) + * @param int $limit + * @param int $offset + * @param boolean $count Set to true if you want to count the number of entities instead (default false) + * @param int $site_guid The site to get entities for. Leave as 0 (default) for the current site; -1 for all sites. + * @return array|int|false An array of entities, or the number of entities, or false on failure + */ + + function get_entities_by_relationship_count($relationship, $inverse_relationship = true, $type = "", $subtype = "", $owner_guid = 0, $limit = 10, $offset = 0, $count = false, $site_guid = 0) { + + global $CONFIG; + + $relationship = sanitise_string($relationship); + $inverse_relationship = (bool)$inverse_relationship; + $type = sanitise_string($type); if ($subtype AND !$subtype = get_subtype_id($type, $subtype)) - return false; - $owner_guid = (int)$owner_guid; - $order_by = sanitise_string($order_by); - $limit = (int)$limit; - $offset = (int)$offset; - $site_guid = (int) $site_guid; - if ($site_guid == 0) - $site_guid = $CONFIG->site_guid; - - //$access = get_access_list(); - - $where = array(); - - if ($relationship!="") - $where[] = "r.relationship='$relationship'"; - if ($inverse_relationship) { - $on = 'e.guid = r.guid_two'; - } else { - $on = 'e.guid = r.guid_one'; - } - if ($type != "") - $where[] = "e.type='$type'"; - if ($subtype) - $where[] = "e.subtype=$subtype"; - if ($owner_guid != "") - $where[] = "e.container_guid='$owner_guid'"; - if ($site_guid > 0) - $where[] = "e.site_guid = {$site_guid}"; - - if ($count) { - $query = "SELECT count(distinct e.guid) as total "; - } else { - $query = "SELECT e.*, count(e.guid) as total "; - } - - $query .= " from {$CONFIG->dbprefix}entity_relationships r JOIN {$CONFIG->dbprefix}entities e on {$on} where "; - - if (!empty($where)) - foreach ($where as $w) - $query .= " $w and "; - $query .= get_access_sql_suffix("e"); // Add access controls - - if (!$count) { - $query .= " group by e.guid "; - $query .= " order by total desc limit {$offset}, {$limit}"; // Add order and limit - return get_data($query, "entity_row_to_elggstar"); - } else { - if ($count = get_data_row($query)) { - return $count->total; - } - } - - return false; - - } - - /** - * Displays a human-readable list of entities - * - * @param string $relationship The relationship eg "friends_of" - * @param bool $inverse_relationship Reverse the normal function of the query to instead say "give me all entities for whome $relationship_guid is a $relationship of" (default: true) - * @param string $type The type of entity (eg 'object') - * @param string $subtype The entity subtype - * @param int $owner_guid The owner (default: all) - * @param int $limit The number of entities to display on a page - * @param true|false $fullview Whether or not to display the full view (default: true) - * @param true|false $viewtypetoggle Whether or not to allow gallery view - * @param true|false $pagination Whether to display pagination (default: true) - * @return string The viewable list of entities - */ - - function list_entities_by_relationship_count($relationship, $inverse_relationship = true, $type = "", $subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = false, $pagination = true) { - - $limit = (int) $limit; - $offset = (int) get_input('offset'); - $count = get_entities_by_relationship_count($relationship,$inverse_relationship,$type,$subtype,$owner_guid,0,0,true); - $entities = get_entities_by_relationship_count($relationship,$inverse_relationship,$type,$subtype,$owner_guid,$limit,$offset); - - return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); - + return false; + $owner_guid = (int)$owner_guid; + $order_by = sanitise_string($order_by); + $limit = (int)$limit; + $offset = (int)$offset; + $site_guid = (int) $site_guid; + if ($site_guid == 0) + $site_guid = $CONFIG->site_guid; + + //$access = get_access_list(); + + $where = array(); + + if ($relationship!="") + $where[] = "r.relationship='$relationship'"; + if ($inverse_relationship) { + $on = 'e.guid = r.guid_two'; + } else { + $on = 'e.guid = r.guid_one'; + } + if ($type != "") + $where[] = "e.type='$type'"; + if ($subtype) + $where[] = "e.subtype=$subtype"; + if ($owner_guid != "") + $where[] = "e.container_guid='$owner_guid'"; + if ($site_guid > 0) + $where[] = "e.site_guid = {$site_guid}"; + + if ($count) { + $query = "SELECT count(distinct e.guid) as total "; + } else { + $query = "SELECT e.*, count(e.guid) as total "; + } + + $query .= " from {$CONFIG->dbprefix}entity_relationships r JOIN {$CONFIG->dbprefix}entities e on {$on} where "; + + if (!empty($where)) + foreach ($where as $w) + $query .= " $w and "; + $query .= get_access_sql_suffix("e"); // Add access controls + + if (!$count) { + $query .= " group by e.guid "; + $query .= " order by total desc limit {$offset}, {$limit}"; // Add order and limit + return get_data($query, "entity_row_to_elggstar"); + } else { + if ($count = get_data_row($query)) { + return $count->total; + } + } + + return false; + + } + + /** + * Displays a human-readable list of entities + * + * @param string $relationship The relationship eg "friends_of" + * @param bool $inverse_relationship Reverse the normal function of the query to instead say "give me all entities for whome $relationship_guid is a $relationship of" (default: true) + * @param string $type The type of entity (eg 'object') + * @param string $subtype The entity subtype + * @param int $owner_guid The owner (default: all) + * @param int $limit The number of entities to display on a page + * @param true|false $fullview Whether or not to display the full view (default: true) + * @param true|false $viewtypetoggle Whether or not to allow gallery view + * @param true|false $pagination Whether to display pagination (default: true) + * @return string The viewable list of entities + */ + + function list_entities_by_relationship_count($relationship, $inverse_relationship = true, $type = "", $subtype = "", $owner_guid = 0, $limit = 10, $fullview = true, $viewtypetoggle = false, $pagination = true) { + + $limit = (int) $limit; + $offset = (int) get_input('offset'); + $count = get_entities_by_relationship_count($relationship,$inverse_relationship,$type,$subtype,$owner_guid,0,0,true); + $entities = get_entities_by_relationship_count($relationship,$inverse_relationship,$type,$subtype,$owner_guid,$limit,$offset); + + return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); + } /** diff --git a/engine/lib/river2.php b/engine/lib/river2.php index dd0d2f76f..1a982e6a4 100644 --- a/engine/lib/river2.php +++ b/engine/lib/river2.php @@ -1,301 +1,301 @@ -access_id; + + $type = $object->getType(); + $subtype = $object->getSubtype(); + + $action_type = sanitise_string($action_type); + + // Load config + global $CONFIG; + + // Attempt to save river item; return success status + return insert_data("insert into {$CONFIG->dbprefix}river " . + " set type = '{$type}', " . + " subtype = '{$subtype}', " . + " action_type = '{$action_type}', " . + " access_id = {$access_id}, " . + " view = '{$view}', " . + " subject_guid = {$subject_guid}, " . + " object_guid = {$object_guid}, " . + " posted = {$posted} "); + + } + + /** + * Removes all items relating to a particular acting entity from the river + * + * @param int $subject_guid The GUID of the entity + * @return true|false Depending on success + */ + function remove_from_river_by_subject( + $subject_guid + ) { + + // Sanitise + $subject_guid = (int) $subject_guid; + + // Load config + global $CONFIG; + + // Remove + return delete_data("delete from {$CONFIG->dbprefix}river where subject_guid = {$subject_guid}"); + + } + + /** + * Removes all items relating to a particular entity being acted upon from the river + * + * @param int $object_guid The GUID of the entity + * @return true|false Depending on success + */ + function remove_from_river_by_object( + $object_guid + ) { + + // Sanitise + $object_guid = (int) $object_guid; + + // Load config + global $CONFIG; + + // Remove + return delete_data("delete from {$CONFIG->dbprefix}river where object_guid = {$object_guid}"); + + } + + /** + * Sets the access ID on river items for a particular object + * + * @param int $object_guid The GUID of the entity + * @param int $access_id The access ID + * @return true|false Depending on success + */ + function update_river_access_by_object( + $object_guid, $access_id + ) { + + // Sanitise + $object_guid = (int) $object_guid; + $access_id = (int) $access_id; + + // Load config + global $CONFIG; + + // Remove + return update_data("update {$CONFIG->dbprefix}river set access_id = {$access_id} where object_guid = {$object_guid}"); + + } + + /** + * Retrieves items from the river. All parameters are optional. + * + * @param int|array $subject_guid Acting entity to restrict to. Default: all + * @param int|array $object_guid Entity being acted on to restrict to. Default: all + * @param string $subject_relationship If set to a relationship type, this will use $subject_guid as the starting point and set the subjects to be all users this entity has this relationship with (eg 'friend'). Default: blank + * @param string $type The type of entity to restrict to. Default: all + * @param string $subtype The subtype of entity to restrict to. Default: all + * @param string $action_type The type of river action to restrict to. Default: all + * @param int $limit The number of items to retrieve. Default: 20 + * @param int $offset The page offset. Default: 0 + * @param int $posted_min The minimum time period to look at. Default: none + * @param int $posted_max The maximum time period to look at. Default: none + * @return array|false Depending on success + */ + function get_river_items( + $subject_guid = 0, + $object_guid = 0, + $subject_relationship = '', + $type = '', + $subtype = '', + $action_type = '', + $limit = 20, + $offset = 0, + $posted_min = 0, + $posted_max = 0 + ) { + + // Get config + global $CONFIG; + + // Sanitise variables + if (!is_array($subject_guid)) { + $subject_guid = (int) $subject_guid; + } else { + foreach($subject_guid as $key => $temp) { + $subject_guid[$key] = (int) $temp; + } + } + if (!is_array($object_guid)) { + $object_guid = (int) $object_guid; + } else { + foreach($object_guid as $key => $temp) { + $object_guid[$key] = (int) $temp; + } + } + if (!empty($type)) $type = sanitise_string($type); + if (!empty($subtype)) $subtype = sanitise_string($subtype); + if (!empty($action_type)) $action_type = sanitise_string($action_type); + $limit = (int) $limit; + $offset = (int) $offset; + $posted_min = (int) $posted_min; + $posted_max = (int) $posted_max; + + // Construct 'where' clauses for the river + $where = array(); + $where[] = str_replace("and enabled='yes'",'',str_replace('owner_guid','subject_guid',get_access_sql_suffix())); + + if (empty($subject_relationship)) { + if (!empty($subject_guid)) + if (!is_array($subject_guid)) { + $where[] = " subject_guid = {$subject_guid} "; + } else { + $where[] = " subject_guid in (" . implode(',',$subject_guid) . ") "; + } + } else { + if (!is_array($subject_guid)) + if ($entities = get_entities_from_relationship($subject_relationship,$subject_guid,false,'','',0,'',9999)) { + $guids = array(); + foreach($entities as $entity) $guids[] = (int) $entity->guid; + // $guids[] = $subject_guid; + $where[] = " subject_guid in (" . implode(',',$guids) . ") "; + } else { + return array(); + } + } + if (!empty($object_guid)) + if (!is_array($object_guid)) { + $where[] = " object_guid = {$object_guid} "; + } else { + $where[] = " object_guid in (" . implode(',',$object_guid) . ") "; + } + if (!empty($type)) $where[] = " type = '{$type}' "; + if (!empty($subtype)) $where[] = " subtype = '{$subtype}' "; + if (!empty($action_type)) $where[] = " action_type = '{$action_type}' "; + if (!empty($posted_min)) $where[] = " posted > {$posted_min} "; + if (!empty($posted_max)) $where[] = " posted < {$posted_max} "; + + $whereclause = implode(' and ', $where); + + // Construct main SQL + $sql = "select id,type,subtype,action_type,access_id,view,subject_guid,object_guid,posted from {$CONFIG->dbprefix}river where {$whereclause} order by posted desc limit {$offset},{$limit}"; + + // Get data + return get_data($sql); + + } + + /** + * Returns a human-readable representation of a river item + * + * @see get_river_items + * + * @param stdClass $item A river item object as returned from get_river_items + * @return string|false Depending on success + */ + function elgg_view_river_item($item) { + if (isset($item->view)) { + + $object = get_entity($item->object_guid); + if (!$object) { + $body = elgg_view('river/item/noaccess'); + } else { + if (elgg_view_exists($item->view)) { + $body = elgg_view($item->view,array( + 'item' => $item + )); + } + } + return elgg_view('river/item/wrapper',array( + 'item' => $item, + 'body' => $body + )); + + } + return false; + } + + /** + * Returns a human-readable version of the river. + * + * @param int|array $subject_guid Acting entity to restrict to. Default: all + * @param int|array $object_guid Entity being acted on to restrict to. Default: all + * @param string $subject_relationship If set to a relationship type, this will use $subject_guid as the starting point and set the subjects to be all users this entity has this relationship with (eg 'friend'). Default: blank + * @param string $type The type of entity to restrict to. Default: all + * @param string $subtype The subtype of entity to restrict to. Default: all + * @param string $action_type The type of river action to restrict to. Default: all + * @param int $limit The number of items to retrieve. Default: 20 + * @param int $posted_min The minimum time period to look at. Default: none + * @param int $posted_max The maximum time period to look at. Default: none + * @return string Human-readable river. + */ + function elgg_view_river_items($subject_guid = 0, + $object_guid = 0, + $subject_relationship = '', + $type = '', + $subtype = '', + $action_type = '', + $limit = 20, + $posted_min = 0, + $posted_max = 0, + $pagination = true) { + + // Get input from outside world and sanitise it + $offset = (int) get_input('offset',0); + + // Get river items, if they exist + if ($riveritems = get_river_items($subject_guid,$object_guid,$subject_relationship,$type,$subtype,$action_type,($limit + 1),$offset,$posted_min,$posted_max)) { + + return elgg_view('river/item/list',array( + 'limit' => $limit, + 'offset' => $offset, + 'items' => $riveritems, + 'pagination' => $pagination + )); + + } + + return ''; + + } - * @link http://elgg.org/ - */ - - /** - * Adds an item to the river. - * - * @param string $view The view that will handle the river item (must exist) - * @param string $action_type An arbitrary one-word string to define the action (eg 'comment', 'create') - * @param int $subject_guid The GUID of the entity doing the action - * @param int $object_guid The GUID of the entity being acted upon - * @param int $access_id The access ID of the river item (default: same as the object) - * @param int $posted The UNIX epoch timestamp of the river item (default: now) - * @return true|false Depending on success - */ - function add_to_river( - $view, - $action_type, - $subject_guid, - $object_guid, - $access_id = "", - $posted = 0 - ) { - - // Sanitise variables - if (!elgg_view_exists($view)) return false; - if (!($subject = get_entity($subject_guid))) return false; - if (!($object = get_entity($object_guid))) return false; - if (empty($action_type)) return false; - if ($posted == 0) $posted = time(); - if ($access_id === "") $access_id = $object->access_id; - - $type = $object->getType(); - $subtype = $object->getSubtype(); - - $action_type = sanitise_string($action_type); - - // Load config - global $CONFIG; - - // Attempt to save river item; return success status - return insert_data("insert into {$CONFIG->dbprefix}river " . - " set type = '{$type}', " . - " subtype = '{$subtype}', " . - " action_type = '{$action_type}', " . - " access_id = {$access_id}, " . - " view = '{$view}', " . - " subject_guid = {$subject_guid}, " . - " object_guid = {$object_guid}, " . - " posted = {$posted} "); - - } - - /** - * Removes all items relating to a particular acting entity from the river - * - * @param int $subject_guid The GUID of the entity - * @return true|false Depending on success - */ - function remove_from_river_by_subject( - $subject_guid - ) { - - // Sanitise - $subject_guid = (int) $subject_guid; - - // Load config - global $CONFIG; - - // Remove - return delete_data("delete from {$CONFIG->dbprefix}river where subject_guid = {$subject_guid}"); - - } - - /** - * Removes all items relating to a particular entity being acted upon from the river - * - * @param int $object_guid The GUID of the entity - * @return true|false Depending on success - */ - function remove_from_river_by_object( - $object_guid - ) { - - // Sanitise - $object_guid = (int) $object_guid; - - // Load config - global $CONFIG; - - // Remove - return delete_data("delete from {$CONFIG->dbprefix}river where object_guid = {$object_guid}"); - - } - - /** - * Sets the access ID on river items for a particular object - * - * @param int $object_guid The GUID of the entity - * @param int $access_id The access ID - * @return true|false Depending on success - */ - function update_river_access_by_object( - $object_guid, $access_id - ) { - - // Sanitise - $object_guid = (int) $object_guid; - $access_id = (int) $access_id; - - // Load config - global $CONFIG; - - // Remove - return update_data("update {$CONFIG->dbprefix}river set access_id = {$access_id} where object_guid = {$object_guid}"); - - } - - /** - * Retrieves items from the river. All parameters are optional. - * - * @param int|array $subject_guid Acting entity to restrict to. Default: all - * @param int|array $object_guid Entity being acted on to restrict to. Default: all - * @param string $subject_relationship If set to a relationship type, this will use $subject_guid as the starting point and set the subjects to be all users this entity has this relationship with (eg 'friend'). Default: blank - * @param string $type The type of entity to restrict to. Default: all - * @param string $subtype The subtype of entity to restrict to. Default: all - * @param string $action_type The type of river action to restrict to. Default: all - * @param int $limit The number of items to retrieve. Default: 20 - * @param int $offset The page offset. Default: 0 - * @param int $posted_min The minimum time period to look at. Default: none - * @param int $posted_max The maximum time period to look at. Default: none - * @return array|false Depending on success - */ - function get_river_items( - $subject_guid = 0, - $object_guid = 0, - $subject_relationship = '', - $type = '', - $subtype = '', - $action_type = '', - $limit = 20, - $offset = 0, - $posted_min = 0, - $posted_max = 0 - ) { - - // Get config - global $CONFIG; - - // Sanitise variables - if (!is_array($subject_guid)) { - $subject_guid = (int) $subject_guid; - } else { - foreach($subject_guid as $key => $temp) { - $subject_guid[$key] = (int) $temp; - } - } - if (!is_array($object_guid)) { - $object_guid = (int) $object_guid; - } else { - foreach($object_guid as $key => $temp) { - $object_guid[$key] = (int) $temp; - } - } - if (!empty($type)) $type = sanitise_string($type); - if (!empty($subtype)) $subtype = sanitise_string($subtype); - if (!empty($action_type)) $action_type = sanitise_string($action_type); - $limit = (int) $limit; - $offset = (int) $offset; - $posted_min = (int) $posted_min; - $posted_max = (int) $posted_max; - - // Construct 'where' clauses for the river - $where = array(); - $where[] = str_replace("and enabled='yes'",'',str_replace('owner_guid','subject_guid',get_access_sql_suffix())); - - if (empty($subject_relationship)) { - if (!empty($subject_guid)) - if (!is_array($subject_guid)) { - $where[] = " subject_guid = {$subject_guid} "; - } else { - $where[] = " subject_guid in (" . implode(',',$subject_guid) . ") "; - } - } else { - if (!is_array($subject_guid)) - if ($entities = get_entities_from_relationship($subject_relationship,$subject_guid,false,'','',0,'',9999)) { - $guids = array(); - foreach($entities as $entity) $guids[] = (int) $entity->guid; - // $guids[] = $subject_guid; - $where[] = " subject_guid in (" . implode(',',$guids) . ") "; - } else { - return array(); - } - } - if (!empty($object_guid)) - if (!is_array($object_guid)) { - $where[] = " object_guid = {$object_guid} "; - } else { - $where[] = " object_guid in (" . implode(',',$object_guid) . ") "; - } - if (!empty($type)) $where[] = " type = '{$type}' "; - if (!empty($subtype)) $where[] = " subtype = '{$subtype}' "; - if (!empty($action_type)) $where[] = " action_type = '{$action_type}' "; - if (!empty($posted_min)) $where[] = " posted > {$posted_min} "; - if (!empty($posted_max)) $where[] = " posted < {$posted_max} "; - - $whereclause = implode(' and ', $where); - - // Construct main SQL - $sql = "select id,type,subtype,action_type,access_id,view,subject_guid,object_guid,posted from {$CONFIG->dbprefix}river where {$whereclause} order by posted desc limit {$offset},{$limit}"; - - // Get data - return get_data($sql); - - } - - /** - * Returns a human-readable representation of a river item - * - * @see get_river_items - * - * @param stdClass $item A river item object as returned from get_river_items - * @return string|false Depending on success - */ - function elgg_view_river_item($item) { - if (isset($item->view)) { - - $object = get_entity($item->object_guid); - if (!$object) { - $body = elgg_view('river/item/noaccess'); - } else { - if (elgg_view_exists($item->view)) { - $body = elgg_view($item->view,array( - 'item' => $item - )); - } - } - return elgg_view('river/item/wrapper',array( - 'item' => $item, - 'body' => $body - )); - - } - return false; - } - - /** - * Returns a human-readable version of the river. - * - * @param int|array $subject_guid Acting entity to restrict to. Default: all - * @param int|array $object_guid Entity being acted on to restrict to. Default: all - * @param string $subject_relationship If set to a relationship type, this will use $subject_guid as the starting point and set the subjects to be all users this entity has this relationship with (eg 'friend'). Default: blank - * @param string $type The type of entity to restrict to. Default: all - * @param string $subtype The subtype of entity to restrict to. Default: all - * @param string $action_type The type of river action to restrict to. Default: all - * @param int $limit The number of items to retrieve. Default: 20 - * @param int $posted_min The minimum time period to look at. Default: none - * @param int $posted_max The maximum time period to look at. Default: none - * @return string Human-readable river. - */ - function elgg_view_river_items($subject_guid = 0, - $object_guid = 0, - $subject_relationship = '', - $type = '', - $subtype = '', - $action_type = '', - $limit = 20, - $posted_min = 0, - $posted_max = 0, - $pagination = true) { - - // Get input from outside world and sanitise it - $offset = (int) get_input('offset',0); - - // Get river items, if they exist - if ($riveritems = get_river_items($subject_guid,$object_guid,$subject_relationship,$type,$subtype,$action_type,($limit + 1),$offset,$posted_min,$posted_max)) { - - return elgg_view('river/item/list',array( - 'limit' => $limit, - 'offset' => $offset, - 'items' => $riveritems, - 'pagination' => $pagination - )); - - } - - return ''; - - } - ?> \ No newline at end of file diff --git a/engine/lib/sessions.php b/engine/lib/sessions.php index fd569a0e1..18fb9e73c 100644 --- a/engine/lib/sessions.php +++ b/engine/lib/sessions.php @@ -1,19 +1,19 @@ -guid > 0)) + + if ((isset($user)) && ($user instanceof ElggUser) && ($user->guid > 0)) return true; - - return false; - - } + + return false; + + } /** * Returns whether or not the user is currently logged in and that they are an admin user. @@ -155,24 +155,24 @@ return false; } - - /** - * Perform standard authentication with a given username and password. - * Returns an ElggUser object for use with login. - * - * @see login - * @param string $username The username, optionally (for standard logins) - * @param string $password The password, optionally (for standard logins) - * @return ElggUser|false The authenticated user object, or false on failure. - */ - - function authenticate($username, $password) { + + /** + * Perform standard authentication with a given username and password. + * Returns an ElggUser object for use with login. + * + * @see login + * @param string $username The username, optionally (for standard logins) + * @param string $password The password, optionally (for standard logins) + * @return ElggUser|false The authenticated user object, or false on failure. + */ + + function authenticate($username, $password) { if (pam_authenticate(array('username' => $username, 'password' => $password))) - return get_user_by_username($username); - - return false; - + return get_user_by_username($username); + + return false; + } /** @@ -198,9 +198,9 @@ // Let admins log in without validating their email, but normal users must have validated their email or been admin created if ((!$user->admin) && (!$user->validated) && (!$user->admin_created)) return false; - - // User has been banned, so bin them. - if ($user->isBanned()) return false; + + // User has been banned, so bin them. + if ($user->isBanned()) return false; if ($user->password == generate_user_password($user, $credentials['password'])) @@ -274,52 +274,52 @@ } return false; - } - - /** - * Logs in a specified ElggUser. For standard registration, use in conjunction - * with authenticate. - * - * @see authenticate - * @param ElggUser $user A valid Elgg user object - * @param boolean $persistent Should this be a persistent login? - * @return true|false Whether login was successful - */ - function login(ElggUser $user, $persistent = false) { - + } + + /** + * Logs in a specified ElggUser. For standard registration, use in conjunction + * with authenticate. + * + * @see authenticate + * @param ElggUser $user A valid Elgg user object + * @param boolean $persistent Should this be a persistent login? + * @return true|false Whether login was successful + */ + function login(ElggUser $user, $persistent = false) { + global $CONFIG; if ($user->isBanned()) return false; // User is banned, return false. if (check_rate_limit_exceeded($user->guid)) return false; // Check rate limit - - $_SESSION['user'] = $user; - $_SESSION['guid'] = $user->getGUID(); - $_SESSION['id'] = $_SESSION['guid']; - $_SESSION['username'] = $user->username; - $_SESSION['name'] = $user->name; - - $code = (md5($user->name . $user->username . time() . rand())); - - $user->code = md5($code); - - $_SESSION['code'] = $code; - - if (($persistent)) - setcookie("elggperm", $code, (time()+(86400 * 30)),"/"); - - if (!$user->save() || !trigger_elgg_event('login','user',$user)) { - unset($_SESSION['username']); - unset($_SESSION['name']); - unset($_SESSION['code']); - unset($_SESSION['guid']); - unset($_SESSION['id']); - unset($_SESSION['user']); - setcookie("elggperm", "", (time()-(86400 * 30)),"/"); - return false; + + $_SESSION['user'] = $user; + $_SESSION['guid'] = $user->getGUID(); + $_SESSION['id'] = $_SESSION['guid']; + $_SESSION['username'] = $user->username; + $_SESSION['name'] = $user->name; + + $code = (md5($user->name . $user->username . time() . rand())); + + $user->code = md5($code); + + $_SESSION['code'] = $code; + + if (($persistent)) + setcookie("elggperm", $code, (time()+(86400 * 30)),"/"); + + if (!$user->save() || !trigger_elgg_event('login','user',$user)) { + unset($_SESSION['username']); + unset($_SESSION['name']); + unset($_SESSION['code']); + unset($_SESSION['guid']); + unset($_SESSION['id']); + unset($_SESSION['user']); + setcookie("elggperm", "", (time()-(86400 * 30)),"/"); + return false; } // Users privilege has been elevated, so change the session id (help prevent session hijacking) - session_regenerate_id(); + session_regenerate_id(); // Update statistics set_last_login($_SESSION['guid']); @@ -330,37 +330,37 @@ global $is_admin; $is_admin = true; } - - return true; - - } - - /** - * Log the current user out - * - * @return true|false - */ - function logout() { - global $CONFIG; - - if (isset($_SESSION['user'])) { - if (!trigger_elgg_event('logout','user',$_SESSION['user'])) return false; - $_SESSION['user']->code = ""; - $_SESSION['user']->save(); + + return true; + + } + + /** + * Log the current user out + * + * @return true|false + */ + function logout() { + global $CONFIG; + + if (isset($_SESSION['user'])) { + if (!trigger_elgg_event('logout','user',$_SESSION['user'])) return false; + $_SESSION['user']->code = ""; + $_SESSION['user']->save(); } - - unset($_SESSION['username']); - unset($_SESSION['name']); - unset($_SESSION['code']); - unset($_SESSION['guid']); - unset($_SESSION['id']); - unset($_SESSION['user']); - + + unset($_SESSION['username']); + unset($_SESSION['name']); + unset($_SESSION['code']); + unset($_SESSION['guid']); + unset($_SESSION['id']); + unset($_SESSION['user']); + setcookie("elggperm", "", (time()-(86400 * 30)),"/"); - session_destroy(); - - return true; + session_destroy(); + + return true; } function get_session_fingerprint() @@ -368,33 +368,33 @@ global $CONFIG; return md5($_SERVER['HTTP_USER_AGENT'] . get_site_secret()); - } - - /** - * Initialises the system session and potentially logs the user in - * - * This function looks for: - * - * 1. $_SESSION['id'] - if not present, we're logged out, and this is set to 0 - * 2. The cookie 'elggperm' - if present, checks it for an authentication token, validates it, and potentially logs the user in - * - * @uses $_SESSION - * @param unknown_type $event - * @param unknown_type $object_type - * @param unknown_type $object - */ - function session_init($event, $object_type, $object) { + } + + /** + * Initialises the system session and potentially logs the user in + * + * This function looks for: + * + * 1. $_SESSION['id'] - if not present, we're logged out, and this is set to 0 + * 2. The cookie 'elggperm' - if present, checks it for an authentication token, validates it, and potentially logs the user in + * + * @uses $_SESSION + * @param unknown_type $event + * @param unknown_type $object_type + * @param unknown_type $object + */ + function session_init($event, $object_type, $object) { global $DB_PREFIX, $CONFIG; - + if (!is_db_installed()) return false; // Use database for sessions $DB_PREFIX = $CONFIG->dbprefix; // HACK to allow access to prefix after object distruction if ((!isset($CONFIG->use_file_sessions))) session_set_save_handler("__elgg_session_open", "__elgg_session_close", "__elgg_session_read", "__elgg_session_write", "__elgg_session_destroy", "__elgg_session_gc"); - - session_name('Elgg'); + + session_name('Elgg'); session_start(); // Do some sanity checking by generating a fingerprint (makes some XSS attacks harder) @@ -413,50 +413,50 @@ // Generate a simple token (private from potentially public session id) if (!isset($_SESSION['__elgg_session'])) $_SESSION['__elgg_session'] = md5(microtime().rand()); - - if (empty($_SESSION['guid'])) { - if (isset($_COOKIE['elggperm'])) { - $code = $_COOKIE['elggperm']; - $code = md5($code); - unset($_SESSION['guid']);//$_SESSION['guid'] = 0; - unset($_SESSION['id']);//$_SESSION['id'] = 0; - if ($user = get_user_by_code($code)) { - $_SESSION['user'] = $user; - $_SESSION['id'] = $user->getGUID(); - $_SESSION['guid'] = $_SESSION['id']; - $_SESSION['code'] = $_COOKIE['elggperm']; - } + + if (empty($_SESSION['guid'])) { + if (isset($_COOKIE['elggperm'])) { + $code = $_COOKIE['elggperm']; + $code = md5($code); + unset($_SESSION['guid']);//$_SESSION['guid'] = 0; + unset($_SESSION['id']);//$_SESSION['id'] = 0; + if ($user = get_user_by_code($code)) { + $_SESSION['user'] = $user; + $_SESSION['id'] = $user->getGUID(); + $_SESSION['guid'] = $_SESSION['id']; + $_SESSION['code'] = $_COOKIE['elggperm']; + } } else { - unset($_SESSION['id']); //$_SESSION['id'] = 0; + unset($_SESSION['id']); //$_SESSION['id'] = 0; unset($_SESSION['guid']);//$_SESSION['guid'] = 0; - unset($_SESSION['code']);//$_SESSION['code'] = ""; - } - } else { - if (!empty($_SESSION['code'])) { - $code = md5($_SESSION['code']); - if ($user = get_user_by_code($code)) { + unset($_SESSION['code']);//$_SESSION['code'] = ""; + } + } else { + if (!empty($_SESSION['code'])) { + $code = md5($_SESSION['code']); + if ($user = get_user_by_code($code)) { $_SESSION['user'] = $user; $_SESSION['id'] = $user->getGUID(); - $_SESSION['guid'] = $_SESSION['id']; - } else { - unset($_SESSION['user']); + $_SESSION['guid'] = $_SESSION['id']; + } else { + unset($_SESSION['user']); unset($_SESSION['id']); //$_SESSION['id'] = 0; unset($_SESSION['guid']);//$_SESSION['guid'] = 0; - unset($_SESSION['code']);//$_SESSION['code'] = ""; - } + unset($_SESSION['code']);//$_SESSION['code'] = ""; + } } else { - //$_SESSION['user'] = new ElggDummy(); + //$_SESSION['user'] = new ElggDummy(); unset($_SESSION['id']); //$_SESSION['id'] = 0; unset($_SESSION['guid']);//$_SESSION['guid'] = 0; - unset($_SESSION['code']);//$_SESSION['code'] = ""; - } - } - if ($_SESSION['id'] > 0) { - set_last_action($_SESSION['id']); - } - - register_action("login",true); - register_action("logout"); + unset($_SESSION['code']);//$_SESSION['code'] = ""; + } + } + if ($_SESSION['id'] > 0) { + set_last_action($_SESSION['id']); + } + + register_action("login",true); + register_action("logout"); // Register a default PAM handler register_pam_handler('pam_auth_userpass'); @@ -470,24 +470,24 @@ { session_destroy(); return false; - } - - // Since we have loaded a new user, this user may have different language preferences + } + + // Since we have loaded a new user, this user may have different language preferences register_translations(dirname(dirname(dirname(__FILE__))) . "/languages/"); - - return true; - + + return true; + } - - /** - * Used at the top of a page to mark it as logged in users only. - * - */ - function gatekeeper() { - if (!isloggedin()) { - $_SESSION['last_forward_from'] = current_page_url(); - forward(); - } + + /** + * Used at the top of a page to mark it as logged in users only. + * + */ + function gatekeeper() { + if (!isloggedin()) { + $_SESSION['last_forward_from'] = current_page_url(); + forward(); + } } /** @@ -497,11 +497,11 @@ function admin_gatekeeper() { gatekeeper(); - if (!isadminloggedin()) { - $_SESSION['last_forward_from'] = current_page_url(); - forward(); + if (!isadminloggedin()) { + $_SESSION['last_forward_from'] = current_page_url(); + forward(); } - } + } /** * DB Based session handling code. @@ -627,8 +627,8 @@ return true; } - - register_elgg_event_handler("boot","system","session_init",20); - - + + register_elgg_event_handler("boot","system","session_init",20); + + ?> \ No newline at end of file diff --git a/engine/lib/sites.php b/engine/lib/sites.php index c088e2476..14cc2039d 100644 --- a/engine/lib/sites.php +++ b/engine/lib/sites.php @@ -1,16 +1,16 @@ - + /** + * Elgg sites + * Functions to manage multiple or single sites in an Elgg install + * + * @package Elgg + * @subpackage Core - * @link http://elgg.org/ - */ + * @author Curverider Ltd + + * @link http://elgg.org/ + */ /** * ElggSite @@ -280,7 +280,7 @@ if ($row) { - // Exists and you have access to it + // Exists and you have access to it if ($exists = get_data_row("SELECT guid from {$CONFIG->dbprefix}sites_entity where guid = {$guid}")) { $result = update_data("UPDATE {$CONFIG->dbprefix}sites_entity set name='$name', description='$description', url='$url' where guid=$guid"); if ($result!=false) @@ -293,7 +293,7 @@ $entity->delete(); //delete_entity($guid); } - } + } } else { @@ -372,25 +372,25 @@ $offset = (int)$offset; return get_entities_from_relationship("member_of_site", $site_guid, true, "user", "", 0, "time_created desc", $limit, $offset); - } - - /** - * Display a list of site members - * - * @param int $site_guid The GUID of the site - * @param int $limit The number of members to display on a page - * @param true|false $fullview Whether or not to display the full view (default: true) - * @return string A displayable list of members - */ - function list_site_members($site_guid, $limit = 10, $fullview = true) { - - $offset = (int) get_input('offset'); - $limit = (int) $limit; - $count = (int) get_entities_from_relationship("member_of_site", $site_guid, true, "user", "", 0, "time_created desc", $limit, $offset, true); - $entities = get_site_members($site_guid, $limit, $offset); - - return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview); - + } + + /** + * Display a list of site members + * + * @param int $site_guid The GUID of the site + * @param int $limit The number of members to display on a page + * @param true|false $fullview Whether or not to display the full view (default: true) + * @return string A displayable list of members + */ + function list_site_members($site_guid, $limit = 10, $fullview = true) { + + $offset = (int) get_input('offset'); + $limit = (int) $limit; + $count = (int) get_entities_from_relationship("member_of_site", $site_guid, true, "user", "", 0, "time_created desc", $limit, $offset, true); + $entities = get_site_members($site_guid, $limit, $offset); + + return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview); + } /** @@ -439,8 +439,8 @@ $offset = (int)$offset; return get_entities_from_relationship("member_of_site", $site_guid, true, "object", $subtype, 0, "time_created desc", $limit, $offset); - } - + } + /** * Add a collection to a site. * @@ -567,43 +567,43 @@ return false; } - - /** - * Initialise site handling - * - * Called at the beginning of system running, to set the ID of the current site. - * This is 0 by default, but plugins may alter this behaviour by attaching functions - * to the sites init event and changing $CONFIG->site_id. - * - * @uses $CONFIG - * @param string $event Event API required parameter - * @param string $object_type Event API required parameter - * @param null $object Event API required parameter - * @return true - */ - function sites_init($event, $object_type, $object) { - - global $CONFIG; - + + /** + * Initialise site handling + * + * Called at the beginning of system running, to set the ID of the current site. + * This is 0 by default, but plugins may alter this behaviour by attaching functions + * to the sites init event and changing $CONFIG->site_id. + * + * @uses $CONFIG + * @param string $event Event API required parameter + * @param string $object_type Event API required parameter + * @param null $object Event API required parameter + * @return true + */ + function sites_init($event, $object_type, $object) { + + global $CONFIG; + if (is_installed() && is_db_installed()) { - - $site = trigger_plugin_hook("siteid","system"); - if ($site === null || $site === false) { - $CONFIG->site_id = (int) datalist_get('default_site'); - } else { - $CONFIG->site_id = $site; - } - $CONFIG->site_guid = $CONFIG->site_id; - $CONFIG->site = get_entity($CONFIG->site_guid); - - return true; + + $site = trigger_plugin_hook("siteid","system"); + if ($site === null || $site === false) { + $CONFIG->site_id = (int) datalist_get('default_site'); + } else { + $CONFIG->site_id = $site; + } + $CONFIG->site_guid = $CONFIG->site_id; + $CONFIG->site = get_entity($CONFIG->site_guid); + + return true; } - return true; - } - - // Register event handlers - - register_elgg_event_handler('boot','system','sites_init',2); - + return true; + } + + // Register event handlers + + register_elgg_event_handler('boot','system','sites_init',2); + ?> \ No newline at end of file diff --git a/engine/lib/social.php b/engine/lib/social.php index b00b56d79..e8bfccda5 100644 --- a/engine/lib/social.php +++ b/engine/lib/social.php @@ -1,76 +1,76 @@ -wordblacklist)) - return $input; - - if (strlen($input) < 3 || in_array($input,$CONFIG->wordblacklist)) - return false; - - return true; - - } - + * @author Curverider + + * @link http://elgg.org/ + + /** + * Filters a string into an array of significant words + * + * @param string $string + * @return array + */ + function filter_string($string) { + + // Convert it to lower and trim + $string = strtolower($string); + $string = trim($string); + + // Remove links and email addresses + // match protocol://address/path/file.extension?some=variable&another=asf% + $string = preg_replace("/\s([a-zA-Z]+:\/\/[a-z][a-z0-9\_\.\-]*[a-z]{2,6}[a-zA-Z0-9\/\*\-\?\&\%\=]*)([\s|\.|\,])/iu"," ", $string); + // match www.something.domain/path/file.extension?some=variable&another=asf% + $string = preg_replace("/\s(www\.[a-z][a-z0-9\_\.\-]*[a-z]{2,6}[a-zA-Z0-9\/\*\-\?\&\%\=]*)([\s|\.|\,])/iu"," ", $string); + // match name@address + $string = preg_replace("/\s([a-zA-Z][a-zA-Z0-9\_\.\-]*[a-zA-Z]*\@[a-zA-Z][a-zA-Z0-9\_\.\-]*[a-zA-Z]{2,6})([\s|\.|\,])/iu"," ", $string); + + // Sanitise the string; remove unwanted characters + $string = preg_replace('/\W/ui', ' ', $string); + + // Explode it into an array + $terms = explode(' ',$string); + + // Remove any blacklist terms + //$terms = array_filter($terms, 'remove_blacklist'); + + return $terms; + + } + + /** + * Returns true if the word in $input is considered significant + * + * @param string $input + * @return true|false + */ + function remove_blacklist($input) { + + global $CONFIG; + + if (!is_array($CONFIG->wordblacklist)) + return $input; + + if (strlen($input) < 3 || in_array($input,$CONFIG->wordblacklist)) + return false; + + return true; + + } + /** * Initialise. * * Sets a blacklist of words in the current language. This is a comma separated list in word:blacklist. - */ - function social_init() { + */ + function social_init() { global $CONFIG; $CONFIG->wordblacklist = array(); @@ -83,46 +83,46 @@ } else { - // Fallback - shouldn't happen - $CONFIG->wordblacklist = array( - 'and', - 'the', - 'then', - 'but', - 'she', - 'his', - 'her', - 'him', - 'one', - 'not', - 'also', - 'about', - 'now', - 'hence', - 'however', - 'still', - 'likewise', - 'otherwise', - 'therefore', - 'conversely', - 'rather', - 'consequently', - 'furthermore', - 'nevertheless', - 'instead', - 'meanwhile', - 'accordingly', - 'this', - 'seems', - 'what', - 'whom', - 'whose', - 'whoever', - 'whomever', + // Fallback - shouldn't happen + $CONFIG->wordblacklist = array( + 'and', + 'the', + 'then', + 'but', + 'she', + 'his', + 'her', + 'him', + 'one', + 'not', + 'also', + 'about', + 'now', + 'hence', + 'however', + 'still', + 'likewise', + 'otherwise', + 'therefore', + 'conversely', + 'rather', + 'consequently', + 'furthermore', + 'nevertheless', + 'instead', + 'meanwhile', + 'accordingly', + 'this', + 'seems', + 'what', + 'whom', + 'whose', + 'whoever', + 'whomever', ); - } - } - - register_elgg_event_handler("init","system","social_init"); - + } + } + + register_elgg_event_handler("init","system","social_init"); + ?> \ No newline at end of file diff --git a/engine/lib/statistics.php b/engine/lib/statistics.php index b79938aab..24d2e4155 100644 --- a/engine/lib/statistics.php +++ b/engine/lib/statistics.php @@ -79,8 +79,8 @@ * Return a list of how many users are currently online, rendered as a view. */ function get_online_users() - { - $offset = get_input('offset',0); + { + $offset = get_input('offset',0); $count = count(find_active_users(600,9999)); $objects = find_active_users(600,10,$offset); diff --git a/engine/lib/tags.php b/engine/lib/tags.php index 8fdb6ecb7..d3db842d1 100644 --- a/engine/lib/tags.php +++ b/engine/lib/tags.php @@ -1,138 +1,138 @@ - + * @author Curverider Ltd - * @link http://elgg.org/ - */ - - - /** - * The algorithm working out the size of font based on the number of tags. - * This is quick and dirty. - */ - function calculate_tag_size($min, $max, $number_of_tags, $buckets = 6) - { - - $delta = (($max - $min) / $buckets); - $thresholds = array(); - - for ($n=1; $n <= $buckets; $n++) { - $thresholds[$n-1] = ($min + $n) * $delta; - } - - // Correction - if ($thresholds[$buckets-1]>$max) $thresholds[$buckets-1] = $max; - - $size = 0; - for ($n = 0; $n < count($thresholds); $n++) { - if ($number_of_tags >= $thresholds[$n]) - $size = $n; - } - - return $size; - } - - /** - * This function generates an array of tags with a weighting. - * - * @param array $tags The array of tags. - * @return An associated array of tags with a weighting, this can then be mapped to a display class. - */ - function generate_tag_cloud(array $tags, $buckets = 6) - { - $cloud = array(); - - $min = 65535; - $max = 0; - - foreach ($tags as $tag) - { - $cloud[$tag]++; - - if ($cloud[$tag]>$max) $max = $cloud[$tag]; - if ($cloud[$tag]<$min) $min = $cloud[$tag]; - } - - foreach ($cloud as $k => $v) - $cloud[$k] = calculate_tag_size($min, $max, $v, $buckets); - - return $cloud; - } - - /** - * Get an array of tags with weights for use with the output/tagcloud view. - * - * @param int $threshold Get the threshold of minimum number of each tags to bother with (ie only show tags where there are more than $threshold occurances) - * @param int $limit Number of tags to return - * @param string $metadata_name Optionally, the name of the field you want to grab for - * @param string $entity_type Optionally, the entity type ('object' etc) - * @param string $entity_subtype The entity subtype, optionally - * @param int $owner_guid The GUID of the tags owner, optionally + * @link http://elgg.org/ + */ + + + /** + * The algorithm working out the size of font based on the number of tags. + * This is quick and dirty. + */ + function calculate_tag_size($min, $max, $number_of_tags, $buckets = 6) + { + + $delta = (($max - $min) / $buckets); + $thresholds = array(); + + for ($n=1; $n <= $buckets; $n++) { + $thresholds[$n-1] = ($min + $n) * $delta; + } + + // Correction + if ($thresholds[$buckets-1]>$max) $thresholds[$buckets-1] = $max; + + $size = 0; + for ($n = 0; $n < count($thresholds); $n++) { + if ($number_of_tags >= $thresholds[$n]) + $size = $n; + } + + return $size; + } + + /** + * This function generates an array of tags with a weighting. + * + * @param array $tags The array of tags. + * @return An associated array of tags with a weighting, this can then be mapped to a display class. + */ + function generate_tag_cloud(array $tags, $buckets = 6) + { + $cloud = array(); + + $min = 65535; + $max = 0; + + foreach ($tags as $tag) + { + $cloud[$tag]++; + + if ($cloud[$tag]>$max) $max = $cloud[$tag]; + if ($cloud[$tag]<$min) $min = $cloud[$tag]; + } + + foreach ($cloud as $k => $v) + $cloud[$k] = calculate_tag_size($min, $max, $v, $buckets); + + return $cloud; + } + + /** + * Get an array of tags with weights for use with the output/tagcloud view. + * + * @param int $threshold Get the threshold of minimum number of each tags to bother with (ie only show tags where there are more than $threshold occurances) + * @param int $limit Number of tags to return + * @param string $metadata_name Optionally, the name of the field you want to grab for + * @param string $entity_type Optionally, the entity type ('object' etc) + * @param string $entity_subtype The entity subtype, optionally + * @param int $owner_guid The GUID of the tags owner, optionally * @param int $site_guid Optionally, the site to restrict to (default is the current site) * @param int $start_ts Optionally specify a start timestamp for tags used to generate cloud. - * @param int $ent_ts Optionally specify an end timestamp for tags used to generate cloud. - * @return array|false Array of objects with ->tag and ->total values, or false on failure - */ - - function get_tags($threshold = 1, $limit = 10, $metadata_name = "", $entity_type = "object", $entity_subtype = "", $owner_guid = "", $site_guid = -1, $start_ts = "", $end_ts = "") { - - global $CONFIG; - - $threshold = (int) $threshold; - $limit = (int) $limit; - - if (!empty($metadata_name)) { - $metadata_name = (int) get_metastring_id($metadata_name); - } else { - $metadata_name = 0; - } - $entity_subtype = get_subtype_id($entity_type, $entity_subtype); - $entity_type = sanitise_string($entity_type); - - if ($owner_guid != "") - if (is_array($owner_guid)) { - foreach($owner_guid as $key => $val) - $owner_guid[$key] = (int) $val; - } else { - $owner_guid = (int) $owner_guid; - } - - if ($site_guid < 0) { - $site_guid = $CONFIG->site_id; - } - - //$access = get_access_list(); - - $query = "SELECT msvalue.string as tag, count(msvalue.id) as total "; + * @param int $ent_ts Optionally specify an end timestamp for tags used to generate cloud. + * @return array|false Array of objects with ->tag and ->total values, or false on failure + */ + + function get_tags($threshold = 1, $limit = 10, $metadata_name = "", $entity_type = "object", $entity_subtype = "", $owner_guid = "", $site_guid = -1, $start_ts = "", $end_ts = "") { + + global $CONFIG; + + $threshold = (int) $threshold; + $limit = (int) $limit; + + if (!empty($metadata_name)) { + $metadata_name = (int) get_metastring_id($metadata_name); + } else { + $metadata_name = 0; + } + $entity_subtype = get_subtype_id($entity_type, $entity_subtype); + $entity_type = sanitise_string($entity_type); + + if ($owner_guid != "") + if (is_array($owner_guid)) { + foreach($owner_guid as $key => $val) + $owner_guid[$key] = (int) $val; + } else { + $owner_guid = (int) $owner_guid; + } + + if ($site_guid < 0) { + $site_guid = $CONFIG->site_id; + } + + //$access = get_access_list(); + + $query = "SELECT msvalue.string as tag, count(msvalue.id) as total "; $query .= "FROM {$CONFIG->dbprefix}entities e join {$CONFIG->dbprefix}metadata md on md.entity_guid = e.guid "; - if ($entity_subtype > 0) - $query .= " join {$CONFIG->dbprefix}entity_subtypes subtype on subtype.id = e.subtype "; - $query .= " join {$CONFIG->dbprefix}metastrings msvalue on msvalue.id = md.value_id "; - - $query .= " where msvalue.string != '' "; - - if ($metadata_name > 0) { - $query .= " and md.name_id = {$metadata_name} "; - } - if ($site_guid > 0) { - $query .= " and e.site_guid = {$site_guid} "; - } - if ($entity_subtype > 0) { - $query .= " and e.subtype = {$entity_subtype} "; - } - if ($entity_type != "") { - $query .= " and e.type = '{$entity_type}' "; - } - if (is_array($owner_guid)) { - $query .= " and e.container_guid in (".implode(",",$owner_guid).")"; - } else if (is_int($owner_guid)) { - $query .= " and e.container_guid = {$owner_guid} "; + if ($entity_subtype > 0) + $query .= " join {$CONFIG->dbprefix}entity_subtypes subtype on subtype.id = e.subtype "; + $query .= " join {$CONFIG->dbprefix}metastrings msvalue on msvalue.id = md.value_id "; + + $query .= " where msvalue.string != '' "; + + if ($metadata_name > 0) { + $query .= " and md.name_id = {$metadata_name} "; + } + if ($site_guid > 0) { + $query .= " and e.site_guid = {$site_guid} "; + } + if ($entity_subtype > 0) { + $query .= " and e.subtype = {$entity_subtype} "; + } + if ($entity_type != "") { + $query .= " and e.type = '{$entity_type}' "; + } + if (is_array($owner_guid)) { + $query .= " and e.container_guid in (".implode(",",$owner_guid).")"; + } else if (is_int($owner_guid)) { + $query .= " and e.container_guid = {$owner_guid} "; } if ($start_ts) { $start_ts = (int)$start_ts; @@ -142,35 +142,35 @@ if ($end_ts) { $end_ts = (int)$end_ts; $query .= " and e.time_created<=$end_ts"; - } - - //$userid = get_loggedin_userid(); - //$query .= " and (e.access_id in {$access} or (e.access_id = " . ACCESS_PRIVATE . " and e.owner_guid = {$userid}))"; - $query .= ' and ' . get_access_sql_suffix("e"); // Add access controls - - $query .= " group by msvalue.string having total > {$threshold} order by total desc limit {$limit} "; - - return get_data($query); - - } - - /** - * Loads and displays a tagcloud given particular criteria. - * - * @param int $threshold Get the threshold of minimum number of each tags to bother with (ie only show tags where there are more than $threshold occurances) - * @param int $limit Number of tags to return - * @param string $metadata_name Optionally, the name of the field you want to grab for - * @param string $entity_type Optionally, the entity type ('object' etc) - * @param string $entity_subtype The entity subtype, optionally - * @param int $owner_guid The GUID of the tags owner, optionally - * @param int $site_guid Optionally, the site to restrict to (default is the current site) - * @return string THe HTML (or other, depending on view type) of the tagcloud. - */ - - function display_tagcloud($threshold = 1, $limit = 10, $metadata_name = "", $entity_type = "object", $entity_subtype = "", $owner_guid = "", $site_guid = -1) { - - return elgg_view("output/tagcloud",array('value' => get_tags($threshold, $limit, $metadata_name, $entity_type, $entity_subtype, $owner_guid, $site_guid),'object' => $entity_type, 'subtype' => $entity_subtype)); - - } - + } + + //$userid = get_loggedin_userid(); + //$query .= " and (e.access_id in {$access} or (e.access_id = " . ACCESS_PRIVATE . " and e.owner_guid = {$userid}))"; + $query .= ' and ' . get_access_sql_suffix("e"); // Add access controls + + $query .= " group by msvalue.string having total > {$threshold} order by total desc limit {$limit} "; + + return get_data($query); + + } + + /** + * Loads and displays a tagcloud given particular criteria. + * + * @param int $threshold Get the threshold of minimum number of each tags to bother with (ie only show tags where there are more than $threshold occurances) + * @param int $limit Number of tags to return + * @param string $metadata_name Optionally, the name of the field you want to grab for + * @param string $entity_type Optionally, the entity type ('object' etc) + * @param string $entity_subtype The entity subtype, optionally + * @param int $owner_guid The GUID of the tags owner, optionally + * @param int $site_guid Optionally, the site to restrict to (default is the current site) + * @return string THe HTML (or other, depending on view type) of the tagcloud. + */ + + function display_tagcloud($threshold = 1, $limit = 10, $metadata_name = "", $entity_type = "object", $entity_subtype = "", $owner_guid = "", $site_guid = -1) { + + return elgg_view("output/tagcloud",array('value' => get_tags($threshold, $limit, $metadata_name, $entity_type, $entity_subtype, $owner_guid, $site_guid),'object' => $entity_type, 'subtype' => $entity_subtype)); + + } + ?> \ No newline at end of file diff --git a/engine/lib/upgrades/2008101303.php b/engine/lib/upgrades/2008101303.php index ac189b956..c98eace74 100644 --- a/engine/lib/upgrades/2008101303.php +++ b/engine/lib/upgrades/2008101303.php @@ -1,11 +1,11 @@ -guid, true, 'email'); - } - } - +guid, true, 'email'); + } + } + ?> \ No newline at end of file diff --git a/engine/lib/users.php b/engine/lib/users.php index b56ecdcf6..e086c8236 100644 --- a/engine/lib/users.php +++ b/engine/lib/users.php @@ -1,148 +1,148 @@ -attributes['type'] = "user"; + $this->attributes['name'] = ""; + $this->attributes['username'] = ""; + $this->attributes['password'] = ""; + $this->attributes['salt'] = ""; + $this->attributes['email'] = ""; + $this->attributes['language'] = ""; + $this->attributes['code'] = ""; + $this->attributes['banned'] = "no"; + $this->attributes['tables_split'] = 2; + } + + /** + * Construct a new user entity, optionally from a given id value. + * + * @param mixed $guid If an int, load that GUID. + * If a db row then will attempt to load the rest of the data. + * @throws Exception if there was a problem creating the user. + */ + function __construct($guid = null) + { + $this->initialise_attributes(); + + if (!empty($guid)) + { + // Is $guid is a DB row - either a entity row, or a user table row. + if ($guid instanceof stdClass) { + // Load the rest + if (!$this->load($guid->guid)) + throw new IOException(sprintf(elgg_echo('IOException:FailedToLoadGUID'), get_class(), $guid->guid)); + } + + // See if this is a username + else if (is_string($guid)) + { + $guid = get_user_by_username($guid); + foreach ($guid->attributes as $key => $value) + $this->attributes[$key] = $value; + + } + + // Is $guid is an ElggUser? Use a copy constructor + else if ($guid instanceof ElggUser) + { + foreach ($guid->attributes as $key => $value) + $this->attributes[$key] = $value; + } + + // Is this is an ElggEntity but not an ElggUser = ERROR! + else if ($guid instanceof ElggEntity) + throw new InvalidParameterException(elgg_echo('InvalidParameterException:NonElggUser')); + + // We assume if we have got this far, $guid is an int + else if (is_numeric($guid)) { + if (!$this->load($guid)) IOException(sprintf(elgg_echo('IOException:FailedToLoadGUID'), get_class(), $guid)); + } + + else + throw new InvalidParameterException(elgg_echo('InvalidParameterException:UnrecognisedValue')); + } + } + + /** + * Override the load function. + * This function will ensure that all data is loaded (were possible), so + * if only part of the ElggUser is loaded, it'll load the rest. + * + * @param int $guid + * @return true|false + */ + protected function load($guid) + { + // Test to see if we have the generic stuff + if (!parent::load($guid)) + return false; - * @link http://elgg.org/ - */ - - /// Map a username to a cached GUID - $USERNAME_TO_GUID_MAP_CACHE = array(); - - /// Map a user code to a cached GUID - $CODE_TO_GUID_MAP_CACHE = array(); - - /** - * ElggUser - * - * Representation of a "user" in the system. - * - * @package Elgg - * @subpackage Core - */ - class ElggUser extends ElggEntity - implements Friendable - { - /** - * Initialise the attributes array. - * This is vital to distinguish between metadata and base parameters. - * - * Place your base parameters here. - */ - protected function initialise_attributes() - { - parent::initialise_attributes(); - - $this->attributes['type'] = "user"; - $this->attributes['name'] = ""; - $this->attributes['username'] = ""; - $this->attributes['password'] = ""; - $this->attributes['salt'] = ""; - $this->attributes['email'] = ""; - $this->attributes['language'] = ""; - $this->attributes['code'] = ""; - $this->attributes['banned'] = "no"; - $this->attributes['tables_split'] = 2; - } - - /** - * Construct a new user entity, optionally from a given id value. - * - * @param mixed $guid If an int, load that GUID. - * If a db row then will attempt to load the rest of the data. - * @throws Exception if there was a problem creating the user. - */ - function __construct($guid = null) - { - $this->initialise_attributes(); - - if (!empty($guid)) - { - // Is $guid is a DB row - either a entity row, or a user table row. - if ($guid instanceof stdClass) { - // Load the rest - if (!$this->load($guid->guid)) - throw new IOException(sprintf(elgg_echo('IOException:FailedToLoadGUID'), get_class(), $guid->guid)); - } - - // See if this is a username - else if (is_string($guid)) - { - $guid = get_user_by_username($guid); - foreach ($guid->attributes as $key => $value) - $this->attributes[$key] = $value; - - } - - // Is $guid is an ElggUser? Use a copy constructor - else if ($guid instanceof ElggUser) - { - foreach ($guid->attributes as $key => $value) - $this->attributes[$key] = $value; - } - - // Is this is an ElggEntity but not an ElggUser = ERROR! - else if ($guid instanceof ElggEntity) - throw new InvalidParameterException(elgg_echo('InvalidParameterException:NonElggUser')); - - // We assume if we have got this far, $guid is an int - else if (is_numeric($guid)) { - if (!$this->load($guid)) IOException(sprintf(elgg_echo('IOException:FailedToLoadGUID'), get_class(), $guid)); - } - - else - throw new InvalidParameterException(elgg_echo('InvalidParameterException:UnrecognisedValue')); - } - } - - /** - * Override the load function. - * This function will ensure that all data is loaded (were possible), so - * if only part of the ElggUser is loaded, it'll load the rest. - * - * @param int $guid - * @return true|false - */ - protected function load($guid) - { - // Test to see if we have the generic stuff - if (!parent::load($guid)) - return false; - - // Check the type - if ($this->attributes['type']!='user') - throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $guid, get_class())); - - // Load missing data - $row = get_user_entity_as_row($guid); - if (($row) && (!$this->isFullyLoaded())) $this->attributes['tables_loaded'] ++; // If $row isn't a cached copy then increment the counter - - // Now put these into the attributes array as core values - $objarray = (array) $row; - foreach($objarray as $key => $value) - $this->attributes[$key] = $value; - - return true; - } - - /** - * Saves this user to the database. - * @return true|false - */ - public function save() - { - // Save generic stuff - if (!parent::save()) - return false; - - // Now save specific stuff - return create_user_entity($this->get('guid'), $this->get('name'), $this->get('username'), $this->get('password'), $this->get('salt'), $this->get('email'), $this->get('language'), $this->get('code')); + // Check the type + if ($this->attributes['type']!='user') + throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $guid, get_class())); + + // Load missing data + $row = get_user_entity_as_row($guid); + if (($row) && (!$this->isFullyLoaded())) $this->attributes['tables_loaded'] ++; // If $row isn't a cached copy then increment the counter + + // Now put these into the attributes array as core values + $objarray = (array) $row; + foreach($objarray as $key => $value) + $this->attributes[$key] = $value; + + return true; + } + + /** + * Saves this user to the database. + * @return true|false + */ + public function save() + { + // Save generic stuff + if (!parent::save()) + return false; + + // Now save specific stuff + return create_user_entity($this->get('guid'), $this->get('name'), $this->get('username'), $this->get('password'), $this->get('salt'), $this->get('email'), $this->get('language'), $this->get('code')); } /** @@ -158,876 +158,876 @@ // Delete entity return parent::delete(); - } - - /** - * Ban this user. - * - * @param string $reason Optional reason - */ - public function ban($reason = "") { return ban_user($this->guid, $reason); } - - /** - * Unban this user. - */ - public function unban() { return unban_user($this->guid); } - - /** - * Is this user banned or not? - * - * @return bool - */ - public function isBanned() { return $this->banned == 'yes'; } - - /** - * Get sites that this user is a member of - * - * @param string $subtype Optionally, the subtype of result we want to limit to - * @param int $limit The number of results to return - * @param int $offset Any indexing offset - */ - function getSites($subtype="", $limit = 10, $offset = 0) { - // return get_site_users($this->getGUID(), $subtype, $limit, $offset); - return get_user_sites($this->getGUID(), $subtype, $limit, $offset); - } - - /** - * Add this user to a particular site - * - * @param int $site_guid The guid of the site to add it to - * @return true|false - */ - function addToSite($site_guid) { - // return add_site_user($this->getGUID(), $site_guid); - return add_site_user($site_guid, $this->getGUID()); - } - - /** - * Remove this user from a particular site - * - * @param int $site_guid The guid of the site to remove it from - * @return true|false - */ - function removeFromSite($site_guid) { - //return remove_site_user($this->getGUID(), $site_guid); - return remove_site_user($site_guid, $this->getGUID()); - } - - /** - * Adds a user to this user's friends list - * - * @param int $friend_guid The GUID of the user to add - * @return true|false Depending on success - */ - function addFriend($friend_guid) { return user_add_friend($this->getGUID(), $friend_guid); } - - /** - * Removes a user from this user's friends list - * - * @param int $friend_guid The GUID of the user to remove - * @return true|false Depending on success - */ - function removeFriend($friend_guid) { return user_remove_friend($this->getGUID(), $friend_guid); } - - /** - * Determines whether or not this user is a friend of the currently logged in user - * - * @return true|false - */ - function isFriend() { return user_is_friend(get_loggedin_userid(), $this->getGUID()); } - - /** - * Determines whether this user is friends with another user - * - * @param int $user_guid The GUID of the user to check is on this user's friends list - * @return true|false - */ - function isFriendsWith($user_guid) { return user_is_friend($this->getGUID(), $user_guid); } - - /** - * Determines whether or not this user is on another user's friends list - * - * @param int $user_guid The GUID of the user to check against - * @return true|false - */ - function isFriendOf($user_guid) { return user_is_friend($user_guid, $this->getGUID()); } - - /** - * Retrieves a list of this user's friends - * - * @param string $subtype Optionally, the subtype of user to filter to (leave blank for all) - * @param int $limit The number of users to retrieve - * @param int $offset Indexing offset, if any - * @return array|false Array of ElggUsers, or false, depending on success - */ - function getFriends($subtype = "", $limit = 10, $offset = 0) { return get_user_friends($this->getGUID(), $subtype, $limit, $offset); } - - /** - * Retrieves a list of people who have made this user a friend - * - * @param string $subtype Optionally, the subtype of user to filter to (leave blank for all) - * @param int $limit The number of users to retrieve - * @param int $offset Indexing offset, if any - * @return array|false Array of ElggUsers, or false, depending on success - */ - function getFriendsOf($subtype = "", $limit = 10, $offset = 0) { return get_user_friends_of($this->getGUID(), $subtype, $limit, $offset); } - - /** - * Get an array of ElggObjects owned by this user. - * - * @param string $subtype The subtype of the objects, if any - * @param int $limit Number of results to return - * @param int $offset Any indexing offset - */ - public function getObjects($subtype="", $limit = 10, $offset = 0) { return get_user_objects($this->getGUID(), $subtype, $limit, $offset); } - - /** - * Get an array of ElggObjects owned by this user's friends. - * - * @param string $subtype The subtype of the objects, if any - * @param int $limit Number of results to return - * @param int $offset Any indexing offset - */ - public function getFriendsObjects($subtype = "", $limit = 10, $offset = 0) { return get_user_friends_objects($this->getGUID(), $subtype, $limit, $offset); } - - /** - * Counts the number of ElggObjects owned by this user - * - * @param string $subtype The subtypes of the objects, if any - * @return int The number of ElggObjects - */ - public function countObjects($subtype = "") { - return count_user_objects($this->getGUID(), $subtype); - } - - /** - * Get the collections associated with a user. - * - * @param string $subtype Optionally, the subtype of result we want to limit to - * @param int $limit The number of results to return - * @param int $offset Any indexing offset - * @return unknown - */ - public function getCollections($subtype="", $limit = 10, $offset = 0) { return get_user_collections($this->getGUID(), $subtype, $limit, $offset); } - - /** - * If a user's owner is blank, return its own GUID as the owner - * - * @return int User GUID - */ - function getOwner() { - if ($this->owner_guid == 0) - return $this->getGUID(); - - return $this->owner_guid; - } - - // EXPORTABLE INTERFACE //////////////////////////////////////////////////////////// - - /** - * Return an array of fields which can be exported. - */ - public function getExportableValues() - { - return array_merge(parent::getExportableValues(), array( - 'name', - 'username', - 'language', - )); - } - } - - /** - * Return the user specific details of a user by a row. - * - * @param int $guid - */ - function get_user_entity_as_row($guid) - { - global $CONFIG; - - /*$row = retrieve_cached_entity_row($guid); - if ($row) - { - // We have already cached this object, so retrieve its value from the cache - if (isset($CONFIG->debug) && $CONFIG->debug == true) - error_log("** Retrieving sub part of GUID:$guid from cache"); - - return $row; - } - else - {*/ - // Object not cached, load it. - if (isset($CONFIG->debug) && $CONFIG->debug == true) - error_log("** Sub part of GUID:$guid loaded from DB"); - - $guid = (int)$guid; - - return get_data_row("SELECT * from {$CONFIG->dbprefix}users_entity where guid=$guid"); - //} - } - - /** - * Create or update the extras table for a given user. - * Call create_entity first. - * - * @param int $guid - * @param string $name - * @param string $description - * @param string $url - */ - function create_user_entity($guid, $name, $username, $password, $salt, $email, $language, $code) - { - global $CONFIG; - - $guid = (int)$guid; - $name = sanitise_string($name); - $username = sanitise_string($username); - $password = sanitise_string($password); - $salt = sanitise_string($salt); - $email = sanitise_string($email); - $language = sanitise_string($language); - $code = sanitise_string($code); - - $row = get_entity_as_row($guid); - if ($row) - { - // Exists and you have access to it - - if ($exists = get_data_row("SELECT guid from {$CONFIG->dbprefix}users_entity where guid = {$guid}")) { - $result = update_data("UPDATE {$CONFIG->dbprefix}users_entity set name='$name', username='$username', password='$password', salt='$salt', email='$email', language='$language', code='$code', last_action = ". time() ." where guid = {$guid}"); - if ($result != false) - { - // Update succeeded, continue - $entity = get_entity($guid); - if (trigger_elgg_event('update',$entity->type,$entity)) { - return $guid; - } else { - $entity->delete(); - } - } - } - else - { - // Update failed, attempt an insert. - $result = insert_data("INSERT into {$CONFIG->dbprefix}users_entity (guid, name, username, password, salt, email, language, code) values ($guid, '$name', '$username', '$password', '$salt', '$email', '$language', '$code')"); - if ($result!==false) { - $entity = get_entity($guid); - if (trigger_elgg_event('create',$entity->type,$entity)) { - return $guid; - } else { - $entity->delete(); //delete_entity($guid); - } - } - } - - } - - return false; - } - - /** - * Disables all of a user's entities - * - * @param int $owner_guid The owner GUID - * @return true|false Depending on success - */ - function disable_user_entities($owner_guid) { - - global $CONFIG; - $owner_guid = (int) $owner_guid; - if ($entity = get_entity($owner_guid)) { - if (trigger_elgg_event('disable',$entity->type,$entity)) { - if ($entity->canEdit()) { - $res = update_data("UPDATE {$CONFIG->dbprefix}entities set enabled='no' where owner_guid={$owner_guid} or container_guid = {$owner_guid}"); - return $res; - } - } - } - return false; - - } - - /** - * Ban a user - * - * @param int $user_guid The user guid - * @param string $reason A reason - */ - function ban_user($user_guid, $reason = "") - { - global $CONFIG; - - $user_guid = (int)$user_guid; - $reason = sanitise_string($reason); - - $user = get_entity($user_guid); - - if (($user) && ($user->canEdit()) && ($user instanceof ElggUser)) + } + + /** + * Ban this user. + * + * @param string $reason Optional reason + */ + public function ban($reason = "") { return ban_user($this->guid, $reason); } + + /** + * Unban this user. + */ + public function unban() { return unban_user($this->guid); } + + /** + * Is this user banned or not? + * + * @return bool + */ + public function isBanned() { return $this->banned == 'yes'; } + + /** + * Get sites that this user is a member of + * + * @param string $subtype Optionally, the subtype of result we want to limit to + * @param int $limit The number of results to return + * @param int $offset Any indexing offset + */ + function getSites($subtype="", $limit = 10, $offset = 0) { + // return get_site_users($this->getGUID(), $subtype, $limit, $offset); + return get_user_sites($this->getGUID(), $subtype, $limit, $offset); + } + + /** + * Add this user to a particular site + * + * @param int $site_guid The guid of the site to add it to + * @return true|false + */ + function addToSite($site_guid) { + // return add_site_user($this->getGUID(), $site_guid); + return add_site_user($site_guid, $this->getGUID()); + } + + /** + * Remove this user from a particular site + * + * @param int $site_guid The guid of the site to remove it from + * @return true|false + */ + function removeFromSite($site_guid) { + //return remove_site_user($this->getGUID(), $site_guid); + return remove_site_user($site_guid, $this->getGUID()); + } + + /** + * Adds a user to this user's friends list + * + * @param int $friend_guid The GUID of the user to add + * @return true|false Depending on success + */ + function addFriend($friend_guid) { return user_add_friend($this->getGUID(), $friend_guid); } + + /** + * Removes a user from this user's friends list + * + * @param int $friend_guid The GUID of the user to remove + * @return true|false Depending on success + */ + function removeFriend($friend_guid) { return user_remove_friend($this->getGUID(), $friend_guid); } + + /** + * Determines whether or not this user is a friend of the currently logged in user + * + * @return true|false + */ + function isFriend() { return user_is_friend(get_loggedin_userid(), $this->getGUID()); } + + /** + * Determines whether this user is friends with another user + * + * @param int $user_guid The GUID of the user to check is on this user's friends list + * @return true|false + */ + function isFriendsWith($user_guid) { return user_is_friend($this->getGUID(), $user_guid); } + + /** + * Determines whether or not this user is on another user's friends list + * + * @param int $user_guid The GUID of the user to check against + * @return true|false + */ + function isFriendOf($user_guid) { return user_is_friend($user_guid, $this->getGUID()); } + + /** + * Retrieves a list of this user's friends + * + * @param string $subtype Optionally, the subtype of user to filter to (leave blank for all) + * @param int $limit The number of users to retrieve + * @param int $offset Indexing offset, if any + * @return array|false Array of ElggUsers, or false, depending on success + */ + function getFriends($subtype = "", $limit = 10, $offset = 0) { return get_user_friends($this->getGUID(), $subtype, $limit, $offset); } + + /** + * Retrieves a list of people who have made this user a friend + * + * @param string $subtype Optionally, the subtype of user to filter to (leave blank for all) + * @param int $limit The number of users to retrieve + * @param int $offset Indexing offset, if any + * @return array|false Array of ElggUsers, or false, depending on success + */ + function getFriendsOf($subtype = "", $limit = 10, $offset = 0) { return get_user_friends_of($this->getGUID(), $subtype, $limit, $offset); } + + /** + * Get an array of ElggObjects owned by this user. + * + * @param string $subtype The subtype of the objects, if any + * @param int $limit Number of results to return + * @param int $offset Any indexing offset + */ + public function getObjects($subtype="", $limit = 10, $offset = 0) { return get_user_objects($this->getGUID(), $subtype, $limit, $offset); } + + /** + * Get an array of ElggObjects owned by this user's friends. + * + * @param string $subtype The subtype of the objects, if any + * @param int $limit Number of results to return + * @param int $offset Any indexing offset + */ + public function getFriendsObjects($subtype = "", $limit = 10, $offset = 0) { return get_user_friends_objects($this->getGUID(), $subtype, $limit, $offset); } + + /** + * Counts the number of ElggObjects owned by this user + * + * @param string $subtype The subtypes of the objects, if any + * @return int The number of ElggObjects + */ + public function countObjects($subtype = "") { + return count_user_objects($this->getGUID(), $subtype); + } + + /** + * Get the collections associated with a user. + * + * @param string $subtype Optionally, the subtype of result we want to limit to + * @param int $limit The number of results to return + * @param int $offset Any indexing offset + * @return unknown + */ + public function getCollections($subtype="", $limit = 10, $offset = 0) { return get_user_collections($this->getGUID(), $subtype, $limit, $offset); } + + /** + * If a user's owner is blank, return its own GUID as the owner + * + * @return int User GUID + */ + function getOwner() { + if ($this->owner_guid == 0) + return $this->getGUID(); + + return $this->owner_guid; + } + + // EXPORTABLE INTERFACE //////////////////////////////////////////////////////////// + + /** + * Return an array of fields which can be exported. + */ + public function getExportableValues() + { + return array_merge(parent::getExportableValues(), array( + 'name', + 'username', + 'language', + )); + } + } + + /** + * Return the user specific details of a user by a row. + * + * @param int $guid + */ + function get_user_entity_as_row($guid) + { + global $CONFIG; + + /*$row = retrieve_cached_entity_row($guid); + if ($row) + { + // We have already cached this object, so retrieve its value from the cache + if (isset($CONFIG->debug) && $CONFIG->debug == true) + error_log("** Retrieving sub part of GUID:$guid from cache"); + + return $row; + } + else + {*/ + // Object not cached, load it. + if (isset($CONFIG->debug) && $CONFIG->debug == true) + error_log("** Sub part of GUID:$guid loaded from DB"); + + $guid = (int)$guid; + + return get_data_row("SELECT * from {$CONFIG->dbprefix}users_entity where guid=$guid"); + //} + } + + /** + * Create or update the extras table for a given user. + * Call create_entity first. + * + * @param int $guid + * @param string $name + * @param string $description + * @param string $url + */ + function create_user_entity($guid, $name, $username, $password, $salt, $email, $language, $code) + { + global $CONFIG; + + $guid = (int)$guid; + $name = sanitise_string($name); + $username = sanitise_string($username); + $password = sanitise_string($password); + $salt = sanitise_string($salt); + $email = sanitise_string($email); + $language = sanitise_string($language); + $code = sanitise_string($code); + + $row = get_entity_as_row($guid); + if ($row) + { + // Exists and you have access to it + + if ($exists = get_data_row("SELECT guid from {$CONFIG->dbprefix}users_entity where guid = {$guid}")) { + $result = update_data("UPDATE {$CONFIG->dbprefix}users_entity set name='$name', username='$username', password='$password', salt='$salt', email='$email', language='$language', code='$code', last_action = ". time() ." where guid = {$guid}"); + if ($result != false) + { + // Update succeeded, continue + $entity = get_entity($guid); + if (trigger_elgg_event('update',$entity->type,$entity)) { + return $guid; + } else { + $entity->delete(); + } + } + } + else + { + // Update failed, attempt an insert. + $result = insert_data("INSERT into {$CONFIG->dbprefix}users_entity (guid, name, username, password, salt, email, language, code) values ($guid, '$name', '$username', '$password', '$salt', '$email', '$language', '$code')"); + if ($result!==false) { + $entity = get_entity($guid); + if (trigger_elgg_event('create',$entity->type,$entity)) { + return $guid; + } else { + $entity->delete(); //delete_entity($guid); + } + } + } + + } + + return false; + } + + /** + * Disables all of a user's entities + * + * @param int $owner_guid The owner GUID + * @return true|false Depending on success + */ + function disable_user_entities($owner_guid) { + + global $CONFIG; + $owner_guid = (int) $owner_guid; + if ($entity = get_entity($owner_guid)) { + if (trigger_elgg_event('disable',$entity->type,$entity)) { + if ($entity->canEdit()) { + $res = update_data("UPDATE {$CONFIG->dbprefix}entities set enabled='no' where owner_guid={$owner_guid} or container_guid = {$owner_guid}"); + return $res; + } + } + } + return false; + + } + + /** + * Ban a user + * + * @param int $user_guid The user guid + * @param string $reason A reason + */ + function ban_user($user_guid, $reason = "") + { + global $CONFIG; + + $user_guid = (int)$user_guid; + $reason = sanitise_string($reason); + + $user = get_entity($user_guid); + + if (($user) && ($user->canEdit()) && ($user instanceof ElggUser)) { - if (trigger_elgg_event('ban', 'user', $user)) { - // Add reason - if ($reason) - create_metadata($user_guid, 'ban_reason', $reason,'', 0, ACCESS_PUBLIC); - - // Set ban flag + if (trigger_elgg_event('ban', 'user', $user)) { + // Add reason + if ($reason) + create_metadata($user_guid, 'ban_reason', $reason,'', 0, ACCESS_PUBLIC); + + // Set ban flag return update_data("UPDATE {$CONFIG->dbprefix}users_entity set banned='yes' where guid=$user_guid"); - } - } - - return false; - } - - /** - * Unban a user. - * - * @param int $user_guid Unban a user. - */ - function unban_user($user_guid) - { - global $CONFIG; - - $user_guid = (int)$user_guid; - - $user = get_entity($user_guid); - - if (($user) && ($user->canEdit()) && ($user instanceof ElggUser)) + } + } + + return false; + } + + /** + * Unban a user. + * + * @param int $user_guid Unban a user. + */ + function unban_user($user_guid) + { + global $CONFIG; + + $user_guid = (int)$user_guid; + + $user = get_entity($user_guid); + + if (($user) && ($user->canEdit()) && ($user instanceof ElggUser)) { - if (trigger_elgg_event('unban', 'user', $user)) { - create_metadata($user_guid, 'ban_reason', '','', 0, ACCESS_PUBLIC); + if (trigger_elgg_event('unban', 'user', $user)) { + create_metadata($user_guid, 'ban_reason', '','', 0, ACCESS_PUBLIC); return update_data("UPDATE {$CONFIG->dbprefix}users_entity set banned='no' where guid=$user_guid"); - } - } - - return false; - } - + } + } + + return false; + } + /** * THIS FUNCTION IS DEPRECATED. - * - * Delete a user's extra data. - * - * @param int $guid - */ - function delete_user_entity($guid) + * + * Delete a user's extra data. + * + * @param int $guid + */ + function delete_user_entity($guid) { system_message(sprintf(elgg_echo('deprecatedfunction'), 'delete_user_entity')); - return 1; // Always return that we have deleted one row in order to not break existing code. - } - - /** - * Get the sites this user is part of - * - * @param int $user_guid The user's GUID - * @param int $limit Number of results to return - * @param int $offset Any indexing offset - * @return false|array On success, an array of ElggSites - */ - function get_user_sites($user_guid, $limit = 10, $offset = 0) { - $user_guid = (int)$user_guid; - $limit = (int)$limit; - $offset = (int)$offset; - - return get_entities_from_relationship("member_of_site", $user_guid, false, "site", "", 0, "time_created desc", $limit, $offset); - } - - /** - * Adds a user to another user's friends list. - * - * @param int $user_guid The GUID of the friending user - * @param int $friend_guid The GUID of the user to friend - * @return true|false Depending on success - */ - function user_add_friend($user_guid, $friend_guid) { - $user_guid = (int) $user_guid; - $friend_guid = (int) $friend_guid; - if ($user_guid == $friend_guid) return false; - if (!$friend = get_entity($friend_guid)) return false; - if (!$user = get_entity($user_guid)) return false; - if ( (!($user instanceof ElggUser)) || (!($friend instanceof ElggUser)) ) return false; - return add_entity_relationship($user_guid, "friend", $friend_guid); - } - - /** - * Removes a user from another user's friends list. - * - * @param int $user_guid The GUID of the friending user - * @param int $friend_guid The GUID of the user on the friends list - * @return true|false Depending on success - */ - function user_remove_friend($user_guid, $friend_guid) { - global $CONFIG; - - $user_guid = (int) $user_guid; - $friend_guid = (int) $friend_guid; - - // perform cleanup for access lists. - $collections = get_user_access_collections($user_guid); - foreach ($collections as $collection) { - remove_user_from_access_collection($friend_guid, $collection->id); - } - - return remove_entity_relationship($user_guid, "friend", $friend_guid); - } - - /** - * Determines whether or not a user is another user's friend. - * - * @param int $user_guid The GUID of the user - * @param int $friend_guid The GUID of the friend - * @return true|false - */ - function user_is_friend($user_guid, $friend_guid) { - return check_entity_relationship($user_guid, "friend", $friend_guid); - } - - /** - * Obtains a given user's friends - * - * @param int $user_guid The user's GUID - * @param string $subtype The subtype of users, if any - * @param int $limit Number of results to return (default 10) - * @param int $offset Indexing offset, if any - * @return false|array Either an array of ElggUsers or false, depending on success - */ - function get_user_friends($user_guid, $subtype = "", $limit = 10, $offset = 0) { - return get_entities_from_relationship("friend",$user_guid,false,"user",$subtype,0,"time_created desc",$limit,$offset); - } - - /** - * Obtains the people who have made a given user a friend - * - * @param int $user_guid The user's GUID - * @param string $subtype The subtype of users, if any - * @param int $limit Number of results to return (default 10) - * @param int $offset Indexing offset, if any - * @return false|array Either an array of ElggUsers or false, depending on success - */ - function get_user_friends_of($user_guid, $subtype = "", $limit = 10, $offset = 0) { - return get_entities_from_relationship("friend",$user_guid,true,"user",$subtype,0,"time_created desc",$limit,$offset); - } - - /** - * Obtains a list of objects owned by a user - * - * @param int $user_guid The GUID of the owning user - * @param string $subtype Optionally, the subtype of objects - * @param int $limit The number of results to return (default 10) - * @param int $offset Indexing offset, if any - * @param int $timelower The earliest time the entity can have been created. Default: all - * @param int $timeupper The latest time the entity can have been created. Default: all - * @return false|array An array of ElggObjects or false, depending on success - */ - function get_user_objects($user_guid, $subtype = "", $limit = 10, $offset = 0, $timelower = 0, $timeupper = 0) { - $ntt = get_entities('object',$subtype, $user_guid, "time_created desc", $limit, $offset,false,0,$user_guid,$timelower, $timeupper); - return $ntt; - } - - /** - * Counts the objects (optionally of a particular subtype) owned by a user - * - * @param int $user_guid The GUID of the owning user - * @param string $subtype Optionally, the subtype of objects - * @param int $timelower The earliest time the entity can have been created. Default: all - * @param int $timeupper The latest time the entity can have been created. Default: all - * @return int The number of objects the user owns (of this subtype) - */ - function count_user_objects($user_guid, $subtype = "", $timelower, $timeupper) { - $total = get_entities('object', $subtype, $user_guid, "time_created desc", null, null, true, 0, $user_guid,$timelower,$timeupper); - return $total; - } - - /** - * Displays a list of user objects of a particular subtype, with navigation. - * - * @see elgg_view_entity_list - * - * @param int $user_guid The GUID of the user - * @param string $subtype The object subtype - * @param int $limit The number of entities to display on a page - * @param true|false $fullview Whether or not to display the full view (default: true) - * @param int $timelower The earliest time the entity can have been created. Default: all - * @param int $timeupper The latest time the entity can have been created. Default: all - * @return string The list in a form suitable to display - */ - function list_user_objects($user_guid, $subtype = "", $limit = 10, $fullview = true, $viewtypetoggle = true, $pagination = true, $timelower = 0, $timeupper = 0) { - - $offset = (int) get_input('offset'); - $limit = (int) $limit; - $count = (int) count_user_objects($user_guid, $subtype,$timelower,$timeupper); - $entities = get_user_objects($user_guid, $subtype, $limit, $offset, $timelower, $timeupper); - - return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); - - } - - /** - * Obtains a list of objects owned by a user's friends - * - * @param int $user_guid The GUID of the user to get the friends of - * @param string $subtype Optionally, the subtype of objects - * @param int $limit The number of results to return (default 10) - * @param int $offset Indexing offset, if any - * @return false|array An array of ElggObjects or false, depending on success - */ - function get_user_friends_objects($user_guid, $subtype = "", $limit = 10, $offset = 0) { - if ($friends = get_user_friends($user_guid, $subtype, 999999, 0)) { - $friendguids = array(); - foreach($friends as $friend) { - $friendguids[] = $friend->getGUID(); - } - return get_entities('object',$subtype,$friendguids, "time_created desc", $limit, $offset, false, 0, $friendguids); - } - return false; - } - - /** - * Counts the number of objects owned by a user's friends - * - * @param int $user_guid The GUID of the user to get the friends of - * @param string $subtype Optionally, the subtype of objects - * @return int The number of objects - */ - function count_user_friends_objects($user_guid, $subtype = "") { - if ($friends = get_user_friends($user_guid, $subtype, 999999, 0)) { - $friendguids = array(); - foreach($friends as $friend) { - $friendguids[] = $friend->getGUID(); - } - return get_entities('object',$subtype,$friendguids, "time_created desc", $limit, $offset, true, 0, $friendguids); - } - return 0; - } - - /** - * Displays a list of a user's friends' objects of a particular subtype, with navigation. - * - * @see elgg_view_entity_list - * - * @param int $user_guid The GUID of the user - * @param string $subtype The object subtype - * @param int $limit The number of entities to display on a page - * @param true|false $fullview Whether or not to display the full view (default: true) - * @param true|false $viewtypetoggle Whether or not to allow you to flip to gallery mode (default: true) - * @return string The list in a form suitable to display - */ - function list_user_friends_objects($user_guid, $subtype = "", $limit = 10, $fullview = true, $viewtypetoggle = true, $pagination = true) { - - $offset = (int) get_input('offset'); - $limit = (int) $limit; - $count = (int) count_user_friends_objects($user_guid, $subtype); - $entities = get_user_friends_objects($user_guid, $subtype, $limit, $offset); - - return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); - - } - - /** - * Get user objects by an array of metadata - * - * @param int $user_guid The GUID of the owning user - * @param string $subtype Optionally, the subtype of objects - * @paran array $metadata An array of metadata - * @param int $limit The number of results to return (default 10) - * @param int $offset Indexing offset, if any - * @return false|array An array of ElggObjects or false, depending on success - * @return unknown - */ - function get_user_objects_by_metadata($user_guid, $subtype = "", $metadata = array(), $limit = 0, $offset = 0) { - - return get_entities_from_metadata_multi($metadata,"object",$subtype,$user_guid,$limit,$offset); - - } - - /** - * Get a user object from a GUID. - * - * This function returns an ElggUser from a given GUID. - * @param int $guid The GUID - * @return ElggUser|false - */ - function get_user($guid) - { - if (!empty($guid)) // Fixes "Exception thrown without stack frame" when db_select fails - $result = get_entity($guid); - - if ((!empty($result)) && (!($result instanceof ElggUser))) - //throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $guid, 'ElggUser')); - return false; - - if (!empty($result)) - return $result; - - return false; - } - - /** - * Get user by username - * - * @param string $username The user's username - * @return ElggUser|false Depending on success - */ - function get_user_by_username($username) - { - global $CONFIG, $USERNAME_TO_GUID_MAP_CACHE; - - $username = sanitise_string($username); - $access = get_access_sql_suffix('e'); - - // Caching - if ( (isset($USERNAME_TO_GUID_MAP_CACHE[$username])) && (retrieve_cached_entity($USERNAME_TO_GUID_MAP_CACHE[$username])) ) - return retrieve_cached_entity($USERNAME_TO_GUID_MAP_CACHE[$username]); - - $row = get_data_row("SELECT e.* from {$CONFIG->dbprefix}users_entity u join {$CONFIG->dbprefix}entities e on e.guid=u.guid where u.username='$username' and $access "); - if ($row) { - $USERNAME_TO_GUID_MAP_CACHE[$username] = $row->guid; - return new ElggUser($row); - } - - return false; - } - - /** - * Get user by session code - * - * @param string $code The session code - * @return ElggUser|false Depending on success - */ - function get_user_by_code($code) - { - global $CONFIG, $CODE_TO_GUID_MAP_CACHE; - - $code = sanitise_string($code); - - $access = get_access_sql_suffix('e'); - - // Caching - if ( (isset($CODE_TO_GUID_MAP_CACHE[$code])) && (retrieve_cached_entity($CODE_TO_GUID_MAP_CACHE[$code])) ) - return retrieve_cached_entity($CODE_TO_GUID_MAP_CACHE[$code]); - - $row = get_data_row("SELECT e.* from {$CONFIG->dbprefix}users_entity u join {$CONFIG->dbprefix}entities e on e.guid=u.guid where u.code='$code' and $access"); - if ($row) { - $CODE_TO_GUID_MAP_CACHE[$code] = $row->guid; - return new ElggUser($row); - } - - return false; - } - - /** - * Get an array of users from their - * - * @param string $email Email address. - * @return Array of users - */ - function get_user_by_email($email) - { - global $CONFIG; - - $email = sanitise_string($email); - - $access = get_access_sql_suffix('e'); - - $query = "SELECT e.* from {$CONFIG->dbprefix}entities e join {$CONFIG->dbprefix}users_entity u on e.guid=u.guid where email='$email' and $access"; - - return get_data($query, 'entity_row_to_elggstar'); - } - - /** - * Searches for a user based on a complete or partial name or username. - * - * @param string $criteria The partial or full name or username. - * @param int $limit Limit of the search. - * @param int $offset Offset. - * @param string $order_by The order. - * @param boolean $count Whether to return the count of results or just the results. - */ - function search_for_user($criteria, $limit = 10, $offset = 0, $order_by = "", $count = false) - { - global $CONFIG; - - $criteria = sanitise_string($criteria); - $limit = (int)$limit; - $offset = (int)$offset; - $order_by = sanitise_string($order_by); - - $access = get_access_sql_suffix("e"); - - if ($order_by == "") $order_by = "e.time_created desc"; - - if ($count) { - $query = "SELECT count(e.guid) as total "; - } else { - $query = "SELECT e.* "; - } - $query .= "from {$CONFIG->dbprefix}entities e join {$CONFIG->dbprefix}users_entity u on e.guid=u.guid where "; - // $query .= " match(u.name,u.username) against ('$criteria') "; - $query .= "(u.name like \"%{$criteria}%\" or u.username like \"%{$criteria}%\")"; - $query .= " and $access"; - - if (!$count) { - $query .= " order by $order_by limit $offset, $limit"; // Add order and limit - return get_data($query, "entity_row_to_elggstar"); - } else { - if ($count = get_data_row($query)) { - return $count->total; - } - } - return false; - } - - /** - * Displays a list of user objects that have been searched for. - * - * @see elgg_view_entity_list - * + return 1; // Always return that we have deleted one row in order to not break existing code. + } + + /** + * Get the sites this user is part of + * + * @param int $user_guid The user's GUID + * @param int $limit Number of results to return + * @param int $offset Any indexing offset + * @return false|array On success, an array of ElggSites + */ + function get_user_sites($user_guid, $limit = 10, $offset = 0) { + $user_guid = (int)$user_guid; + $limit = (int)$limit; + $offset = (int)$offset; + + return get_entities_from_relationship("member_of_site", $user_guid, false, "site", "", 0, "time_created desc", $limit, $offset); + } + + /** + * Adds a user to another user's friends list. + * + * @param int $user_guid The GUID of the friending user + * @param int $friend_guid The GUID of the user to friend + * @return true|false Depending on success + */ + function user_add_friend($user_guid, $friend_guid) { + $user_guid = (int) $user_guid; + $friend_guid = (int) $friend_guid; + if ($user_guid == $friend_guid) return false; + if (!$friend = get_entity($friend_guid)) return false; + if (!$user = get_entity($user_guid)) return false; + if ( (!($user instanceof ElggUser)) || (!($friend instanceof ElggUser)) ) return false; + return add_entity_relationship($user_guid, "friend", $friend_guid); + } + + /** + * Removes a user from another user's friends list. + * + * @param int $user_guid The GUID of the friending user + * @param int $friend_guid The GUID of the user on the friends list + * @return true|false Depending on success + */ + function user_remove_friend($user_guid, $friend_guid) { + global $CONFIG; + + $user_guid = (int) $user_guid; + $friend_guid = (int) $friend_guid; + + // perform cleanup for access lists. + $collections = get_user_access_collections($user_guid); + foreach ($collections as $collection) { + remove_user_from_access_collection($friend_guid, $collection->id); + } + + return remove_entity_relationship($user_guid, "friend", $friend_guid); + } + + /** + * Determines whether or not a user is another user's friend. + * + * @param int $user_guid The GUID of the user + * @param int $friend_guid The GUID of the friend + * @return true|false + */ + function user_is_friend($user_guid, $friend_guid) { + return check_entity_relationship($user_guid, "friend", $friend_guid); + } + + /** + * Obtains a given user's friends + * + * @param int $user_guid The user's GUID + * @param string $subtype The subtype of users, if any + * @param int $limit Number of results to return (default 10) + * @param int $offset Indexing offset, if any + * @return false|array Either an array of ElggUsers or false, depending on success + */ + function get_user_friends($user_guid, $subtype = "", $limit = 10, $offset = 0) { + return get_entities_from_relationship("friend",$user_guid,false,"user",$subtype,0,"time_created desc",$limit,$offset); + } + + /** + * Obtains the people who have made a given user a friend + * + * @param int $user_guid The user's GUID + * @param string $subtype The subtype of users, if any + * @param int $limit Number of results to return (default 10) + * @param int $offset Indexing offset, if any + * @return false|array Either an array of ElggUsers or false, depending on success + */ + function get_user_friends_of($user_guid, $subtype = "", $limit = 10, $offset = 0) { + return get_entities_from_relationship("friend",$user_guid,true,"user",$subtype,0,"time_created desc",$limit,$offset); + } + + /** + * Obtains a list of objects owned by a user + * + * @param int $user_guid The GUID of the owning user + * @param string $subtype Optionally, the subtype of objects + * @param int $limit The number of results to return (default 10) + * @param int $offset Indexing offset, if any + * @param int $timelower The earliest time the entity can have been created. Default: all + * @param int $timeupper The latest time the entity can have been created. Default: all + * @return false|array An array of ElggObjects or false, depending on success + */ + function get_user_objects($user_guid, $subtype = "", $limit = 10, $offset = 0, $timelower = 0, $timeupper = 0) { + $ntt = get_entities('object',$subtype, $user_guid, "time_created desc", $limit, $offset,false,0,$user_guid,$timelower, $timeupper); + return $ntt; + } + + /** + * Counts the objects (optionally of a particular subtype) owned by a user + * + * @param int $user_guid The GUID of the owning user + * @param string $subtype Optionally, the subtype of objects + * @param int $timelower The earliest time the entity can have been created. Default: all + * @param int $timeupper The latest time the entity can have been created. Default: all + * @return int The number of objects the user owns (of this subtype) + */ + function count_user_objects($user_guid, $subtype = "", $timelower, $timeupper) { + $total = get_entities('object', $subtype, $user_guid, "time_created desc", null, null, true, 0, $user_guid,$timelower,$timeupper); + return $total; + } + + /** + * Displays a list of user objects of a particular subtype, with navigation. + * + * @see elgg_view_entity_list + * + * @param int $user_guid The GUID of the user + * @param string $subtype The object subtype + * @param int $limit The number of entities to display on a page + * @param true|false $fullview Whether or not to display the full view (default: true) + * @param int $timelower The earliest time the entity can have been created. Default: all + * @param int $timeupper The latest time the entity can have been created. Default: all + * @return string The list in a form suitable to display + */ + function list_user_objects($user_guid, $subtype = "", $limit = 10, $fullview = true, $viewtypetoggle = true, $pagination = true, $timelower = 0, $timeupper = 0) { + + $offset = (int) get_input('offset'); + $limit = (int) $limit; + $count = (int) count_user_objects($user_guid, $subtype,$timelower,$timeupper); + $entities = get_user_objects($user_guid, $subtype, $limit, $offset, $timelower, $timeupper); + + return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); + + } + + /** + * Obtains a list of objects owned by a user's friends + * + * @param int $user_guid The GUID of the user to get the friends of + * @param string $subtype Optionally, the subtype of objects + * @param int $limit The number of results to return (default 10) + * @param int $offset Indexing offset, if any + * @return false|array An array of ElggObjects or false, depending on success + */ + function get_user_friends_objects($user_guid, $subtype = "", $limit = 10, $offset = 0) { + if ($friends = get_user_friends($user_guid, $subtype, 999999, 0)) { + $friendguids = array(); + foreach($friends as $friend) { + $friendguids[] = $friend->getGUID(); + } + return get_entities('object',$subtype,$friendguids, "time_created desc", $limit, $offset, false, 0, $friendguids); + } + return false; + } + + /** + * Counts the number of objects owned by a user's friends + * + * @param int $user_guid The GUID of the user to get the friends of + * @param string $subtype Optionally, the subtype of objects + * @return int The number of objects + */ + function count_user_friends_objects($user_guid, $subtype = "") { + if ($friends = get_user_friends($user_guid, $subtype, 999999, 0)) { + $friendguids = array(); + foreach($friends as $friend) { + $friendguids[] = $friend->getGUID(); + } + return get_entities('object',$subtype,$friendguids, "time_created desc", $limit, $offset, true, 0, $friendguids); + } + return 0; + } + + /** + * Displays a list of a user's friends' objects of a particular subtype, with navigation. + * + * @see elgg_view_entity_list + * + * @param int $user_guid The GUID of the user + * @param string $subtype The object subtype + * @param int $limit The number of entities to display on a page + * @param true|false $fullview Whether or not to display the full view (default: true) + * @param true|false $viewtypetoggle Whether or not to allow you to flip to gallery mode (default: true) + * @return string The list in a form suitable to display + */ + function list_user_friends_objects($user_guid, $subtype = "", $limit = 10, $fullview = true, $viewtypetoggle = true, $pagination = true) { + + $offset = (int) get_input('offset'); + $limit = (int) $limit; + $count = (int) count_user_friends_objects($user_guid, $subtype); + $entities = get_user_friends_objects($user_guid, $subtype, $limit, $offset); + + return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, $viewtypetoggle, $pagination); + + } + + /** + * Get user objects by an array of metadata + * + * @param int $user_guid The GUID of the owning user + * @param string $subtype Optionally, the subtype of objects + * @paran array $metadata An array of metadata + * @param int $limit The number of results to return (default 10) + * @param int $offset Indexing offset, if any + * @return false|array An array of ElggObjects or false, depending on success + * @return unknown + */ + function get_user_objects_by_metadata($user_guid, $subtype = "", $metadata = array(), $limit = 0, $offset = 0) { + + return get_entities_from_metadata_multi($metadata,"object",$subtype,$user_guid,$limit,$offset); + + } + + /** + * Get a user object from a GUID. + * + * This function returns an ElggUser from a given GUID. + * @param int $guid The GUID + * @return ElggUser|false + */ + function get_user($guid) + { + if (!empty($guid)) // Fixes "Exception thrown without stack frame" when db_select fails + $result = get_entity($guid); + + if ((!empty($result)) && (!($result instanceof ElggUser))) + //throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $guid, 'ElggUser')); + return false; + + if (!empty($result)) + return $result; + + return false; + } + + /** + * Get user by username + * + * @param string $username The user's username + * @return ElggUser|false Depending on success + */ + function get_user_by_username($username) + { + global $CONFIG, $USERNAME_TO_GUID_MAP_CACHE; + + $username = sanitise_string($username); + $access = get_access_sql_suffix('e'); + + // Caching + if ( (isset($USERNAME_TO_GUID_MAP_CACHE[$username])) && (retrieve_cached_entity($USERNAME_TO_GUID_MAP_CACHE[$username])) ) + return retrieve_cached_entity($USERNAME_TO_GUID_MAP_CACHE[$username]); + + $row = get_data_row("SELECT e.* from {$CONFIG->dbprefix}users_entity u join {$CONFIG->dbprefix}entities e on e.guid=u.guid where u.username='$username' and $access "); + if ($row) { + $USERNAME_TO_GUID_MAP_CACHE[$username] = $row->guid; + return new ElggUser($row); + } + + return false; + } + + /** + * Get user by session code + * + * @param string $code The session code + * @return ElggUser|false Depending on success + */ + function get_user_by_code($code) + { + global $CONFIG, $CODE_TO_GUID_MAP_CACHE; + + $code = sanitise_string($code); + + $access = get_access_sql_suffix('e'); + + // Caching + if ( (isset($CODE_TO_GUID_MAP_CACHE[$code])) && (retrieve_cached_entity($CODE_TO_GUID_MAP_CACHE[$code])) ) + return retrieve_cached_entity($CODE_TO_GUID_MAP_CACHE[$code]); + + $row = get_data_row("SELECT e.* from {$CONFIG->dbprefix}users_entity u join {$CONFIG->dbprefix}entities e on e.guid=u.guid where u.code='$code' and $access"); + if ($row) { + $CODE_TO_GUID_MAP_CACHE[$code] = $row->guid; + return new ElggUser($row); + } + + return false; + } + + /** + * Get an array of users from their + * + * @param string $email Email address. + * @return Array of users + */ + function get_user_by_email($email) + { + global $CONFIG; + + $email = sanitise_string($email); + + $access = get_access_sql_suffix('e'); + + $query = "SELECT e.* from {$CONFIG->dbprefix}entities e join {$CONFIG->dbprefix}users_entity u on e.guid=u.guid where email='$email' and $access"; + + return get_data($query, 'entity_row_to_elggstar'); + } + + /** + * Searches for a user based on a complete or partial name or username. + * + * @param string $criteria The partial or full name or username. + * @param int $limit Limit of the search. + * @param int $offset Offset. + * @param string $order_by The order. + * @param boolean $count Whether to return the count of results or just the results. + */ + function search_for_user($criteria, $limit = 10, $offset = 0, $order_by = "", $count = false) + { + global $CONFIG; + + $criteria = sanitise_string($criteria); + $limit = (int)$limit; + $offset = (int)$offset; + $order_by = sanitise_string($order_by); + + $access = get_access_sql_suffix("e"); + + if ($order_by == "") $order_by = "e.time_created desc"; + + if ($count) { + $query = "SELECT count(e.guid) as total "; + } else { + $query = "SELECT e.* "; + } + $query .= "from {$CONFIG->dbprefix}entities e join {$CONFIG->dbprefix}users_entity u on e.guid=u.guid where "; + // $query .= " match(u.name,u.username) against ('$criteria') "; + $query .= "(u.name like \"%{$criteria}%\" or u.username like \"%{$criteria}%\")"; + $query .= " and $access"; + + if (!$count) { + $query .= " order by $order_by limit $offset, $limit"; // Add order and limit + return get_data($query, "entity_row_to_elggstar"); + } else { + if ($count = get_data_row($query)) { + return $count->total; + } + } + return false; + } + + /** + * Displays a list of user objects that have been searched for. + * + * @see elgg_view_entity_list + * * @param string $tag Search criteria * @param int $limit The number of entities to display on a page - * @return string The list in a form suitable to display - */ - function list_user_search($tag, $limit = 10) { - - $offset = (int) get_input('offset'); - $limit = (int) $limit; - $count = (int) search_for_user($tag, 10, 0, '', true); - $entities = search_for_user($tag, $limit, $offset); - - return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, false); - - } - - /** - * A function that returns a maximum of $limit users who have done something within the last - * $seconds seconds. - * - * @param int $seconds Number of seconds (default 600 = 10min) - * @param int $limit Limit, default 10. - * @param int $offset Offset, defualt 0. - */ - function find_active_users($seconds = 600, $limit = 10, $offset = 0) - { - global $CONFIG; - - $seconds = (int)$seconds; - $limit = (int)$limit; - $offset = (int)$offset; - - $time = time() - $seconds; - - $access = get_access_sql_suffix("e"); - - $query = "SELECT distinct e.* from {$CONFIG->dbprefix}entities e join {$CONFIG->dbprefix}users_entity u on e.guid = u.guid where u.last_action >= {$time} and $access order by u.last_action desc limit {$offset},{$limit}"; - - return get_data($query, "entity_row_to_elggstar"); - } - - /** - * Generate and send a password request email to a given user's registered email address. - * - * @param int $user_guid - */ - function send_new_password_request($user_guid) - { - global $CONFIG; - - $user_guid = (int)$user_guid; - - $user = get_entity($user_guid); - if ($user) - { - // generate code - $code = generate_random_cleartext_password(); - //create_metadata($user_guid, 'conf_code', $code,'', 0, ACCESS_PRIVATE); - set_private_setting($user_guid, 'passwd_conf_code', $code); - - // generate link - $link = $CONFIG->site->url . "action/user/passwordreset?u=$user_guid&c=$code"; - - // generate email - $email = sprintf(elgg_echo('email:resetreq:body'), $user->name, $_SERVER['REMOTE_ADDR'], $link); - - return notify_user($user->guid, $CONFIG->site->guid, elgg_echo('email:resetreq:subject'), $email, NULL, 'email'); - - } - - return false; - } - - /** - * Low level function to reset a given user's password. - * - * This can only be called from execute_new_password_request(). - * - * @param int $user_guid The user. - * @param string $password password text (which will then be converted into a hash and stored) - */ - function force_user_password_reset($user_guid, $password) - { - global $CONFIG; - - if (call_gatekeeper('execute_new_password_request', __FILE__)) - { - $user = get_entity($user_guid); - - if ($user) - { + * @return string The list in a form suitable to display + */ + function list_user_search($tag, $limit = 10) { + + $offset = (int) get_input('offset'); + $limit = (int) $limit; + $count = (int) search_for_user($tag, 10, 0, '', true); + $entities = search_for_user($tag, $limit, $offset); + + return elgg_view_entity_list($entities, $count, $offset, $limit, $fullview, false); + + } + + /** + * A function that returns a maximum of $limit users who have done something within the last + * $seconds seconds. + * + * @param int $seconds Number of seconds (default 600 = 10min) + * @param int $limit Limit, default 10. + * @param int $offset Offset, defualt 0. + */ + function find_active_users($seconds = 600, $limit = 10, $offset = 0) + { + global $CONFIG; + + $seconds = (int)$seconds; + $limit = (int)$limit; + $offset = (int)$offset; + + $time = time() - $seconds; + + $access = get_access_sql_suffix("e"); + + $query = "SELECT distinct e.* from {$CONFIG->dbprefix}entities e join {$CONFIG->dbprefix}users_entity u on e.guid = u.guid where u.last_action >= {$time} and $access order by u.last_action desc limit {$offset},{$limit}"; + + return get_data($query, "entity_row_to_elggstar"); + } + + /** + * Generate and send a password request email to a given user's registered email address. + * + * @param int $user_guid + */ + function send_new_password_request($user_guid) + { + global $CONFIG; + + $user_guid = (int)$user_guid; + + $user = get_entity($user_guid); + if ($user) + { + // generate code + $code = generate_random_cleartext_password(); + //create_metadata($user_guid, 'conf_code', $code,'', 0, ACCESS_PRIVATE); + set_private_setting($user_guid, 'passwd_conf_code', $code); + + // generate link + $link = $CONFIG->site->url . "action/user/passwordreset?u=$user_guid&c=$code"; + + // generate email + $email = sprintf(elgg_echo('email:resetreq:body'), $user->name, $_SERVER['REMOTE_ADDR'], $link); + + return notify_user($user->guid, $CONFIG->site->guid, elgg_echo('email:resetreq:subject'), $email, NULL, 'email'); + + } + + return false; + } + + /** + * Low level function to reset a given user's password. + * + * This can only be called from execute_new_password_request(). + * + * @param int $user_guid The user. + * @param string $password password text (which will then be converted into a hash and stored) + */ + function force_user_password_reset($user_guid, $password) + { + global $CONFIG; + + if (call_gatekeeper('execute_new_password_request', __FILE__)) + { + $user = get_entity($user_guid); + + if ($user) + { $salt = generate_random_cleartext_password(); // Reset the salt $user->salt = $salt; - - $hash = generate_user_password($user, $password); - - return update_data("UPDATE {$CONFIG->dbprefix}users_entity set password='$hash', salt='$salt' where guid=$user_guid"); - } - } - - return false; - } - - /** - * Validate and execute a password reset for a user. - * - * @param int $user_guid The user id - * @param string $conf_code Confirmation code as sent in the request email. - */ - function execute_new_password_request($user_guid, $conf_code) - { - global $CONFIG; - - $user_guid = (int)$user_guid; - - $user = get_entity($user_guid); - if (($user) && (get_private_setting($user_guid, 'passwd_conf_code') == $conf_code)) - { - $password = generate_random_cleartext_password(); - - if (force_user_password_reset($user_guid, $password)) - { - //remove_metadata($user_guid, 'conf_code'); - remove_private_setting($user_guid, 'passwd_conf_code'); - - $email = sprintf(elgg_echo('email:resetpassword:body'), $user->name, $password); - - return notify_user($user->guid, $CONFIG->site->guid, elgg_echo('email:resetpassword:subject'), $email, NULL, 'email'); - } - } - - return false; - } - - /** - * Set the validation status for a user. - * - * @param bool $status Validated (true) or false - * @param string $method Optional method to say how a user was validated - * @return bool - */ - function set_user_validation_status($user_guid, $status, $method = '') - { - if (!$status) $method = ''; + + $hash = generate_user_password($user, $password); + + return update_data("UPDATE {$CONFIG->dbprefix}users_entity set password='$hash', salt='$salt' where guid=$user_guid"); + } + } + + return false; + } + + /** + * Validate and execute a password reset for a user. + * + * @param int $user_guid The user id + * @param string $conf_code Confirmation code as sent in the request email. + */ + function execute_new_password_request($user_guid, $conf_code) + { + global $CONFIG; + + $user_guid = (int)$user_guid; + + $user = get_entity($user_guid); + if (($user) && (get_private_setting($user_guid, 'passwd_conf_code') == $conf_code)) + { + $password = generate_random_cleartext_password(); + + if (force_user_password_reset($user_guid, $password)) + { + //remove_metadata($user_guid, 'conf_code'); + remove_private_setting($user_guid, 'passwd_conf_code'); + + $email = sprintf(elgg_echo('email:resetpassword:body'), $user->name, $password); + + return notify_user($user->guid, $CONFIG->site->guid, elgg_echo('email:resetpassword:subject'), $email, NULL, 'email'); + } + } + + return false; + } + + /** + * Set the validation status for a user. + * + * @param bool $status Validated (true) or false + * @param string $method Optional method to say how a user was validated + * @return bool + */ + function set_user_validation_status($user_guid, $status, $method = '') + { + if (!$status) $method = ''; if ($status) - { + { if ( (create_metadata($user_guid, 'validated', $status,'', 0, ACCESS_PUBLIC)) && (create_metadata($user_guid, 'validated_method', $method,'', 0, ACCESS_PUBLIC)) @@ -1046,521 +1046,521 @@ (delete_metadata($validated_method->id)) ) return true; - } - - return false; - } - - /** - * Trigger an event requesting that a user guid be validated somehow - either by email address or some other way. - * - * This event invalidates any existing values and returns - * - * @param unknown_type $user_guid - */ - function request_user_validation($user_guid) - { - $user = get_entity($user_guid); - - if (($user) && ($user instanceof ElggUser)) - { - // invalidate any existing validations - set_user_validation_status($user_guid, false); - - // request validation - trigger_elgg_event('validate', 'user', $user); - - } - } - - /** - * Validates an email address. - * - * @param string $address Email address. - * @return bool - */ - function is_email_address($address) - { - // TODO: Make this better! - - if (strpos($address, '@')=== false) - return false; - - if (strpos($address, '.')=== false) - return false; - - return true; - } - - /** - * Simple function that will generate a random clear text password suitable for feeding into generate_user_password(). - * - * @see generate_user_password - * @return string - */ - function generate_random_cleartext_password() - { - return substr(md5(microtime() . rand()), 0, 8); - } - - /** - * Generate a password for a user, currently uses MD5. - * - * Later may introduce salting etc. - * - * @param ElggUser $user The user this is being generated for. - * @param string $password Password in clear text - */ - function generate_user_password(ElggUser $user, $password) - { - return md5($password . $user->salt); - } - - /** - * Simple function which ensures that a username contains only valid characters. - * - * This should only permit chars that are valid on the file system as well. - * - * @param string $username - * @throws RegistrationException on invalid - */ - function validate_username($username) + } + + return false; + } + + /** + * Trigger an event requesting that a user guid be validated somehow - either by email address or some other way. + * + * This event invalidates any existing values and returns + * + * @param unknown_type $user_guid + */ + function request_user_validation($user_guid) + { + $user = get_entity($user_guid); + + if (($user) && ($user instanceof ElggUser)) + { + // invalidate any existing validations + set_user_validation_status($user_guid, false); + + // request validation + trigger_elgg_event('validate', 'user', $user); + + } + } + + /** + * Validates an email address. + * + * @param string $address Email address. + * @return bool + */ + function is_email_address($address) + { + // TODO: Make this better! + + if (strpos($address, '@')=== false) + return false; + + if (strpos($address, '.')=== false) + return false; + + return true; + } + + /** + * Simple function that will generate a random clear text password suitable for feeding into generate_user_password(). + * + * @see generate_user_password + * @return string + */ + function generate_random_cleartext_password() + { + return substr(md5(microtime() . rand()), 0, 8); + } + + /** + * Generate a password for a user, currently uses MD5. + * + * Later may introduce salting etc. + * + * @param ElggUser $user The user this is being generated for. + * @param string $password Password in clear text + */ + function generate_user_password(ElggUser $user, $password) + { + return md5($password . $user->salt); + } + + /** + * Simple function which ensures that a username contains only valid characters. + * + * This should only permit chars that are valid on the file system as well. + * + * @param string $username + * @throws RegistrationException on invalid + */ + function validate_username($username) { global $CONFIG; - + // Basic, check length if (!isset($CONFIG->minusername)) { $CONFIG->minusername = 4; } - + if (strlen($username) < $CONFIG->minusername) - throw new RegistrationException(elgg_echo('registration:usernametooshort')); - - // Blacklist for bad characters (partially nicked from mediawiki) - - $blacklist = '/[' . - '\x{0080}-\x{009f}' . # iso-8859-1 control chars - '\x{00a0}' . # non-breaking space - '\x{2000}-\x{200f}' . # various whitespace - '\x{2028}-\x{202f}' . # breaks and control chars - '\x{3000}' . # ideographic space - '\x{e000}-\x{f8ff}' . # private use - ']/u'; - - if ( - preg_match($blacklist, $username) - ) + throw new RegistrationException(elgg_echo('registration:usernametooshort')); + + // Blacklist for bad characters (partially nicked from mediawiki) + + $blacklist = '/[' . + '\x{0080}-\x{009f}' . # iso-8859-1 control chars + '\x{00a0}' . # non-breaking space + '\x{2000}-\x{200f}' . # various whitespace + '\x{2028}-\x{202f}' . # breaks and control chars + '\x{3000}' . # ideographic space + '\x{e000}-\x{f8ff}' . # private use + ']/u'; + + if ( + preg_match($blacklist, $username) + ) throw new RegistrationException(elgg_echo('registration:invalidchars')); // Belts and braces TODO: Tidy into main unicode $blacklist2 = '/\\"\'*& ?#%^(){}[]~?<>;|¬`@-+='; for ($n=0; $n < strlen($blacklist2); $n++) if (strpos($username, $blacklist2[$n])!==false) - throw new RegistrationException(elgg_echo('registration:invalidchars')); - - $result = true; - return trigger_plugin_hook('registeruser:validate:username', 'all', array('username' => $username), $result); - } - - /** - * Simple validation of a password. - * - * @param string $password - * @throws RegistrationException on invalid - */ - function validate_password($password) - { - if (strlen($password)<6) throw new RegistrationException(elgg_echo('registration:passwordtooshort')); - - $result = true; - return trigger_plugin_hook('registeruser:validate:password', 'all', array('password' => $password), $result); - } - - /** - * Simple validation of a email. - * - * @param string $address - * @throws RegistrationException on invalid - * @return bool - */ - function validate_email_address($address) - { - if (!is_email_address($address)) throw new RegistrationException(elgg_echo('registration:notemail')); - - // Got here, so lets try a hook (defaulting to ok) - $result = true; - return trigger_plugin_hook('registeruser:validate:email', 'all', array('email' => $address), $result); - } - - /** - * Registers a user, returning false if the username already exists - * - * @param string $username The username of the new user - * @param string $password The password - * @param string $name The user's display name - * @param string $email Their email address - * @param bool $allow_multiple_emails Allow the same email address to be registered multiple times? - * @param int $friend_guid Optionally, GUID of a user this user will friend once fully registered - * @return int|false The new user's GUID; false on failure - */ - function register_user($username, $password, $name, $email, $allow_multiple_emails = false, $friend_guid = 0, $invitecode = '') { - - // Load the configuration - global $CONFIG; - - $username = trim($username); - $password = trim($password); - $name = trim($name); - $email = trim($email); - - // A little sanity checking - if (empty($username) - || empty($password) - || empty($name) - || empty($email)) { - return false; - } - - // See if it exists and is disabled - $access_status = access_get_show_hidden_status(); - access_show_hidden_entities(true); - - // Validate email address - if (!validate_email_address($email)) throw new RegistrationException(elgg_echo('registration:emailnotvalid')); - - // Validate password - if (!validate_password($password)) throw new RegistrationException(elgg_echo('registration:passwordnotvalid')); - - // Validate the username - if (!validate_username($username)) throw new RegistrationException(elgg_echo('registration:usernamenotvalid')); - - // Check to see if $username exists already - if ($user = get_user_by_username($username)) { - //return false; - throw new RegistrationException(elgg_echo('registration:userexists')); - } - - // If we're not allowed multiple emails then see if this address has been used before - if ((!$allow_multiple_emails) && (get_user_by_email($email))) - { - throw new RegistrationException(elgg_echo('registration:dupeemail')); - } - - access_show_hidden_entities($access_status); - - // Check to see if we've registered the first admin yet. - // If not, this is the first admin user! - $admin = datalist_get('admin_registered'); - - // Otherwise ... - $user = new ElggUser(); - $user->username = $username; - $user->email = $email; - $user->name = $name; - $user->access_id = ACCESS_PUBLIC; - $user->salt = generate_random_cleartext_password(); // Note salt generated before password! + throw new RegistrationException(elgg_echo('registration:invalidchars')); + + $result = true; + return trigger_plugin_hook('registeruser:validate:username', 'all', array('username' => $username), $result); + } + + /** + * Simple validation of a password. + * + * @param string $password + * @throws RegistrationException on invalid + */ + function validate_password($password) + { + if (strlen($password)<6) throw new RegistrationException(elgg_echo('registration:passwordtooshort')); + + $result = true; + return trigger_plugin_hook('registeruser:validate:password', 'all', array('password' => $password), $result); + } + + /** + * Simple validation of a email. + * + * @param string $address + * @throws RegistrationException on invalid + * @return bool + */ + function validate_email_address($address) + { + if (!is_email_address($address)) throw new RegistrationException(elgg_echo('registration:notemail')); + + // Got here, so lets try a hook (defaulting to ok) + $result = true; + return trigger_plugin_hook('registeruser:validate:email', 'all', array('email' => $address), $result); + } + + /** + * Registers a user, returning false if the username already exists + * + * @param string $username The username of the new user + * @param string $password The password + * @param string $name The user's display name + * @param string $email Their email address + * @param bool $allow_multiple_emails Allow the same email address to be registered multiple times? + * @param int $friend_guid Optionally, GUID of a user this user will friend once fully registered + * @return int|false The new user's GUID; false on failure + */ + function register_user($username, $password, $name, $email, $allow_multiple_emails = false, $friend_guid = 0, $invitecode = '') { + + // Load the configuration + global $CONFIG; + + $username = trim($username); + $password = trim($password); + $name = trim($name); + $email = trim($email); + + // A little sanity checking + if (empty($username) + || empty($password) + || empty($name) + || empty($email)) { + return false; + } + + // See if it exists and is disabled + $access_status = access_get_show_hidden_status(); + access_show_hidden_entities(true); + + // Validate email address + if (!validate_email_address($email)) throw new RegistrationException(elgg_echo('registration:emailnotvalid')); + + // Validate password + if (!validate_password($password)) throw new RegistrationException(elgg_echo('registration:passwordnotvalid')); + + // Validate the username + if (!validate_username($username)) throw new RegistrationException(elgg_echo('registration:usernamenotvalid')); + + // Check to see if $username exists already + if ($user = get_user_by_username($username)) { + //return false; + throw new RegistrationException(elgg_echo('registration:userexists')); + } + + // If we're not allowed multiple emails then see if this address has been used before + if ((!$allow_multiple_emails) && (get_user_by_email($email))) + { + throw new RegistrationException(elgg_echo('registration:dupeemail')); + } + + access_show_hidden_entities($access_status); + + // Check to see if we've registered the first admin yet. + // If not, this is the first admin user! + $admin = datalist_get('admin_registered'); + + // Otherwise ... + $user = new ElggUser(); + $user->username = $username; + $user->email = $email; + $user->name = $name; + $user->access_id = ACCESS_PUBLIC; + $user->salt = generate_random_cleartext_password(); // Note salt generated before password! $user->password = generate_user_password($user, $password); $user->owner_guid = 0; // Users aren't owned by anyone, even if they are admin created. - $user->container_guid = 0; // Users aren't contained by anyone, even if they are admin created. - $user->save(); - - // If $friend_guid has been set, make mutual friends - if ($friend_guid) { - if ($friend_user = get_user($friend_guid)) { - if ($invitecode == generate_invite_code($friend_user->username)) { - $user->addFriend($friend_guid); - $friend_user->addFriend($user->guid); - } - } - } - - global $registering_admin; - if (!$admin) { - $user->admin = true; - datalist_set('admin_registered',1); - $registering_admin = true; - } else { - $registering_admin = false; - } - - // Turn on email notifications by default - set_user_notification_setting($user->getGUID(), 'email', true); - - return $user->getGUID(); - } - - /** - * Generates a unique invite code for a user - * - * @param string $username The username of the user sending the invitation - * @return string Invite code - */ - function generate_invite_code($username) { - - $secret = datalist_get('__site_secret__'); - return md5($username . $secret); - - } - - /** - * Adds collection submenu items - * - */ - function collections_submenu_items() { - global $CONFIG; - $user = get_loggedin_user(); - add_submenu_item(elgg_echo('friends:collections'), $CONFIG->wwwroot . "pg/collections/" . $user->username); - add_submenu_item(elgg_echo('friends:collections:add'),$CONFIG->wwwroot."pg/collections/add"); - } - - /** - * Page handler for friends - * - */ - function friends_page_handler($page_elements) { - - if (isset($page_elements[0]) && $user = get_user_by_username($page_elements[0])) { - set_page_owner($user->getGUID()); - } - if ($_SESSION['guid'] == page_owner()) { - collections_submenu_items(); - } - require_once(dirname(dirname(dirname(__FILE__))) . "/friends/index.php"); - - } - - /** - * Page handler for friends of - * - */ - function friends_of_page_handler($page_elements) { - - if (isset($page_elements[0]) && $user = get_user_by_username($page_elements[0])) { - set_page_owner($user->getGUID()); - } - if ($_SESSION['guid'] == page_owner()) { - collections_submenu_items(); - } - require_once(dirname(dirname(dirname(__FILE__))) . "/friends/of.php"); - - } - - /** - * Page handler for friends of - * - */ - function collections_page_handler($page_elements) { - - if (isset($page_elements[0])) { - if ($page_elements[0] == "add") { - set_page_owner($_SESSION['guid']); - collections_submenu_items(); - require_once(dirname(dirname(dirname(__FILE__))) . "/friends/add.php"); - } else { - if ($user = get_user_by_username($page_elements[0])) { - set_page_owner($user->getGUID()); - if ($_SESSION['guid'] == page_owner()) { - collections_submenu_items(); - } - require_once(dirname(dirname(dirname(__FILE__))) . "/friends/collections.php"); - } - } - } - - } - - /** - * Page handler for dashboard - */ - function dashboard_page_handler($page_elements) { - @require_once(dirname(dirname(dirname(__FILE__))) . "/dashboard/index.php"); - } - - /** - * Sets the last action time of the given user to right now. - * - * @param int $user_guid The user GUID - */ - function set_last_action($user_guid) { - - $user_guid = (int) $user_guid; - global $CONFIG; - $time = time(); - - execute_delayed_write_query("UPDATE {$CONFIG->dbprefix}users_entity set prev_last_action = last_action, last_action = {$time} where guid = {$user_guid}"); - - } - - /** - * Sets the last logon time of the given user to right now. - * - * @param int $user_guid The user GUID - */ - function set_last_login($user_guid) { - - $user_guid = (int) $user_guid; - global $CONFIG; - $time = time(); - - execute_delayed_write_query("UPDATE {$CONFIG->dbprefix}users_entity set prev_last_login = last_login, last_login = {$time} where guid = {$user_guid}"); - - } - - /** - * A permissions plugin hook that grants access to users if they are newly created - allows - * for email activation. - * - * TODO: Do this in a better way! - * - * @param unknown_type $hook - * @param unknown_type $entity_type - * @param unknown_type $returnvalue - * @param unknown_type $params - */ - function new_user_enable_permissions_check($hook, $entity_type, $returnvalue, $params) - { - $entity = $params['entity']; - $user = $params['user']; - if (($entity) && ($entity instanceof ElggUser)) - { - if ( - (($entity->disable_reason == 'new_user') || ( - // if this isn't set at all they're a "new user" - !$entity->validated - )) - && (!isloggedin())) - return true; - - } - - return $returnvalue; - } - - /** - * Sets up user-related menu items - * - */ - function users_pagesetup() { - - // Load config - global $CONFIG; - - //add submenu options - if (get_context() == "friends" || - get_context() == "friendsof" || - get_context() == "collections") { - add_submenu_item(elgg_echo('friends'),$CONFIG->wwwroot."pg/friends/" . page_owner_entity()->username); - add_submenu_item(elgg_echo('friends:of'),$CONFIG->wwwroot."pg/friendsof/" . page_owner_entity()->username); - } - - } - - /** - * Users initialisation function, which establishes the page handler - * - */ - function users_init() { - - // Load config - global $CONFIG; - - // Set up menu for logged in users - if (isloggedin()) { - $user = get_loggedin_user(); - add_menu(elgg_echo('friends'), $CONFIG->wwwroot . "pg/friends/" . $user->username); - } - - register_page_handler('friends','friends_page_handler'); - register_page_handler('friendsof','friends_of_page_handler'); - register_page_handler('collections','collections_page_handler'); - register_page_handler('dashboard','dashboard_page_handler'); - register_action("register",true); - register_action("useradd",true); - register_action("friends/add"); - register_action("friends/remove"); - register_action('friends/addcollection'); - register_action('friends/deletecollection'); - register_action('friends/editcollection'); - register_action("user/spotlight"); - - register_action("usersettings/save"); - - register_action("user/passwordreset"); - register_action("user/requestnewpassword"); - - // User name change - extend_elgg_settings_page('user/settings/name', 'usersettings/user', 1); - //register_action("user/name"); - - // User password change - extend_elgg_settings_page('user/settings/password', 'usersettings/user', 1); - //register_action("user/password"); - - // Add email settings - extend_elgg_settings_page('user/settings/email', 'usersettings/user', 1); - //register_action("email/save"); - - // Add language settings - extend_elgg_settings_page('user/settings/language', 'usersettings/user', 1); - - // Add default access settings - extend_elgg_settings_page('user/settings/default_access', 'usersettings/user', 1); - - //register_action("user/language"); - - // Register the user type - register_entity_type('user',''); - - register_plugin_hook('usersettings:save','user','users_settings_save'); - register_plugin_hook('search','all','search_list_users_by_name'); - - - // Handle a special case for newly created users when the user is not logged in - // TODO: handle this better! - register_plugin_hook('permissions_check','all','new_user_enable_permissions_check'); - } - - /** - * Returns a formatted list of users suitable for injecting into search. - * - */ - function search_list_users_by_name($hook, $user, $returnvalue, $tag) { - - // Change this to set the number of users that display on the search page - $threshold = 4; - - $object = get_input('object'); - - if (!get_input('offset') && (empty($object) || $object == 'user')) - if ($users = search_for_user($tag,$threshold)) { - - $countusers = search_for_user($tag,0,0,"",true); - - $return = elgg_view('user/search/startblurb',array('count' => $countusers, 'tag' => $tag)); - foreach($users as $user) { - $return .= elgg_view_entity($user); - } - $return .= elgg_view('user/search/finishblurb',array('count' => $countusers, 'threshold' => $threshold, 'tag' => $tag)); - return $return; - - } - - } - - function users_settings_save() { - - global $CONFIG; - @include($CONFIG->path . "actions/user/name.php"); - @include($CONFIG->path . "actions/user/password.php"); - @include($CONFIG->path . "actions/email/save.php"); - @include($CONFIG->path . "actions/user/language.php"); - @include($CONFIG->path . "actions/user/default_access.php"); - - } - - //register actions ************************************************************* - - register_elgg_event_handler('init','system','users_init',0); - register_elgg_event_handler('pagesetup','system','users_pagesetup',0); - + $user->container_guid = 0; // Users aren't contained by anyone, even if they are admin created. + $user->save(); + + // If $friend_guid has been set, make mutual friends + if ($friend_guid) { + if ($friend_user = get_user($friend_guid)) { + if ($invitecode == generate_invite_code($friend_user->username)) { + $user->addFriend($friend_guid); + $friend_user->addFriend($user->guid); + } + } + } + + global $registering_admin; + if (!$admin) { + $user->admin = true; + datalist_set('admin_registered',1); + $registering_admin = true; + } else { + $registering_admin = false; + } + + // Turn on email notifications by default + set_user_notification_setting($user->getGUID(), 'email', true); + + return $user->getGUID(); + } + + /** + * Generates a unique invite code for a user + * + * @param string $username The username of the user sending the invitation + * @return string Invite code + */ + function generate_invite_code($username) { + + $secret = datalist_get('__site_secret__'); + return md5($username . $secret); + + } + + /** + * Adds collection submenu items + * + */ + function collections_submenu_items() { + global $CONFIG; + $user = get_loggedin_user(); + add_submenu_item(elgg_echo('friends:collections'), $CONFIG->wwwroot . "pg/collections/" . $user->username); + add_submenu_item(elgg_echo('friends:collections:add'),$CONFIG->wwwroot."pg/collections/add"); + } + + /** + * Page handler for friends + * + */ + function friends_page_handler($page_elements) { + + if (isset($page_elements[0]) && $user = get_user_by_username($page_elements[0])) { + set_page_owner($user->getGUID()); + } + if ($_SESSION['guid'] == page_owner()) { + collections_submenu_items(); + } + require_once(dirname(dirname(dirname(__FILE__))) . "/friends/index.php"); + + } + + /** + * Page handler for friends of + * + */ + function friends_of_page_handler($page_elements) { + + if (isset($page_elements[0]) && $user = get_user_by_username($page_elements[0])) { + set_page_owner($user->getGUID()); + } + if ($_SESSION['guid'] == page_owner()) { + collections_submenu_items(); + } + require_once(dirname(dirname(dirname(__FILE__))) . "/friends/of.php"); + + } + + /** + * Page handler for friends of + * + */ + function collections_page_handler($page_elements) { + + if (isset($page_elements[0])) { + if ($page_elements[0] == "add") { + set_page_owner($_SESSION['guid']); + collections_submenu_items(); + require_once(dirname(dirname(dirname(__FILE__))) . "/friends/add.php"); + } else { + if ($user = get_user_by_username($page_elements[0])) { + set_page_owner($user->getGUID()); + if ($_SESSION['guid'] == page_owner()) { + collections_submenu_items(); + } + require_once(dirname(dirname(dirname(__FILE__))) . "/friends/collections.php"); + } + } + } + + } + + /** + * Page handler for dashboard + */ + function dashboard_page_handler($page_elements) { + @require_once(dirname(dirname(dirname(__FILE__))) . "/dashboard/index.php"); + } + + /** + * Sets the last action time of the given user to right now. + * + * @param int $user_guid The user GUID + */ + function set_last_action($user_guid) { + + $user_guid = (int) $user_guid; + global $CONFIG; + $time = time(); + + execute_delayed_write_query("UPDATE {$CONFIG->dbprefix}users_entity set prev_last_action = last_action, last_action = {$time} where guid = {$user_guid}"); + + } + + /** + * Sets the last logon time of the given user to right now. + * + * @param int $user_guid The user GUID + */ + function set_last_login($user_guid) { + + $user_guid = (int) $user_guid; + global $CONFIG; + $time = time(); + + execute_delayed_write_query("UPDATE {$CONFIG->dbprefix}users_entity set prev_last_login = last_login, last_login = {$time} where guid = {$user_guid}"); + + } + + /** + * A permissions plugin hook that grants access to users if they are newly created - allows + * for email activation. + * + * TODO: Do this in a better way! + * + * @param unknown_type $hook + * @param unknown_type $entity_type + * @param unknown_type $returnvalue + * @param unknown_type $params + */ + function new_user_enable_permissions_check($hook, $entity_type, $returnvalue, $params) + { + $entity = $params['entity']; + $user = $params['user']; + if (($entity) && ($entity instanceof ElggUser)) + { + if ( + (($entity->disable_reason == 'new_user') || ( + // if this isn't set at all they're a "new user" + !$entity->validated + )) + && (!isloggedin())) + return true; + + } + + return $returnvalue; + } + + /** + * Sets up user-related menu items + * + */ + function users_pagesetup() { + + // Load config + global $CONFIG; + + //add submenu options + if (get_context() == "friends" || + get_context() == "friendsof" || + get_context() == "collections") { + add_submenu_item(elgg_echo('friends'),$CONFIG->wwwroot."pg/friends/" . page_owner_entity()->username); + add_submenu_item(elgg_echo('friends:of'),$CONFIG->wwwroot."pg/friendsof/" . page_owner_entity()->username); + } + + } + + /** + * Users initialisation function, which establishes the page handler + * + */ + function users_init() { + + // Load config + global $CONFIG; + + // Set up menu for logged in users + if (isloggedin()) { + $user = get_loggedin_user(); + add_menu(elgg_echo('friends'), $CONFIG->wwwroot . "pg/friends/" . $user->username); + } + + register_page_handler('friends','friends_page_handler'); + register_page_handler('friendsof','friends_of_page_handler'); + register_page_handler('collections','collections_page_handler'); + register_page_handler('dashboard','dashboard_page_handler'); + register_action("register",true); + register_action("useradd",true); + register_action("friends/add"); + register_action("friends/remove"); + register_action('friends/addcollection'); + register_action('friends/deletecollection'); + register_action('friends/editcollection'); + register_action("user/spotlight"); + + register_action("usersettings/save"); + + register_action("user/passwordreset"); + register_action("user/requestnewpassword"); + + // User name change + extend_elgg_settings_page('user/settings/name', 'usersettings/user', 1); + //register_action("user/name"); + + // User password change + extend_elgg_settings_page('user/settings/password', 'usersettings/user', 1); + //register_action("user/password"); + + // Add email settings + extend_elgg_settings_page('user/settings/email', 'usersettings/user', 1); + //register_action("email/save"); + + // Add language settings + extend_elgg_settings_page('user/settings/language', 'usersettings/user', 1); + + // Add default access settings + extend_elgg_settings_page('user/settings/default_access', 'usersettings/user', 1); + + //register_action("user/language"); + + // Register the user type + register_entity_type('user',''); + + register_plugin_hook('usersettings:save','user','users_settings_save'); + register_plugin_hook('search','all','search_list_users_by_name'); + + + // Handle a special case for newly created users when the user is not logged in + // TODO: handle this better! + register_plugin_hook('permissions_check','all','new_user_enable_permissions_check'); + } + + /** + * Returns a formatted list of users suitable for injecting into search. + * + */ + function search_list_users_by_name($hook, $user, $returnvalue, $tag) { + + // Change this to set the number of users that display on the search page + $threshold = 4; + + $object = get_input('object'); + + if (!get_input('offset') && (empty($object) || $object == 'user')) + if ($users = search_for_user($tag,$threshold)) { + + $countusers = search_for_user($tag,0,0,"",true); + + $return = elgg_view('user/search/startblurb',array('count' => $countusers, 'tag' => $tag)); + foreach($users as $user) { + $return .= elgg_view_entity($user); + } + $return .= elgg_view('user/search/finishblurb',array('count' => $countusers, 'threshold' => $threshold, 'tag' => $tag)); + return $return; + + } + + } + + function users_settings_save() { + + global $CONFIG; + @include($CONFIG->path . "actions/user/name.php"); + @include($CONFIG->path . "actions/user/password.php"); + @include($CONFIG->path . "actions/email/save.php"); + @include($CONFIG->path . "actions/user/language.php"); + @include($CONFIG->path . "actions/user/default_access.php"); + + } + + //register actions ************************************************************* + + register_elgg_event_handler('init','system','users_init',0); + register_elgg_event_handler('pagesetup','system','users_pagesetup',0); + ?> \ No newline at end of file diff --git a/engine/lib/version.php b/engine/lib/version.php index 47bb36972..2476a0b75 100644 --- a/engine/lib/version.php +++ b/engine/lib/version.php @@ -1,14 +1,14 @@ -path . "version.php")) { - if (!$humanreadable) return $version; - return $release; - } - - return false; - - } - - /** - * Determines whether or not the database needs to be upgraded. - * - * @return true|false Depending on whether or not the db version matches the code version - */ - function version_upgrade_check() { - - $dbversion = (int) datalist_get('version'); - $version = get_version(); - - if ($version > $dbversion) { - return true; - } - return false; - - } - - /** - * Upgrades Elgg - * - */ - function version_upgrade() { - - $dbversion = (int) datalist_get('version'); + } + + /** + * Get the current version information + * + * @param true|false $humanreadable Whether to return a human readable version (default: false) + * @return string|false Depending on success + */ + function get_version($humanreadable = false) { + + global $CONFIG; + if (@include($CONFIG->path . "version.php")) { + if (!$humanreadable) return $version; + return $release; + } + + return false; + + } + + /** + * Determines whether or not the database needs to be upgraded. + * + * @return true|false Depending on whether or not the db version matches the code version + */ + function version_upgrade_check() { + + $dbversion = (int) datalist_get('version'); + $version = get_version(); + + if ($version > $dbversion) { + return true; + } + return false; + + } + + /** + * Upgrades Elgg + * + */ + function version_upgrade() { + + $dbversion = (int) datalist_get('version'); // Upgrade database - db_upgrade($dbversion); + db_upgrade($dbversion); system_message(elgg_echo('upgrade:db')); // Upgrade core @@ -121,8 +121,8 @@ trigger_elgg_event('upgrade', 'upgrade', $upgrade_details); // Update the version - datalist_set('version', get_version()); - - } - + datalist_set('version', get_version()); + + } + ?> \ No newline at end of file diff --git a/engine/lib/widgets.php b/engine/lib/widgets.php index 8793370ef..f6f01f660 100644 --- a/engine/lib/widgets.php +++ b/engine/lib/widgets.php @@ -1,528 +1,528 @@ -attributes['subtype'] = "widget"; + } + + public function __construct($guid = null) { parent::__construct($guid); } + + /** + * Override entity get and sets in order to save data to private data store. + */ + public function get($name) + { + // See if its in our base attribute + if (isset($this->attributes[$name])) { + return $this->attributes[$name]; + } + + // No, so see if its in the private data store. + $meta = get_private_setting($this->guid, $name); + if ($meta) + return $meta; + + // Can't find it, so return null + return null; + } + + /** + * Override entity get and sets in order to save data to private data store. + */ + public function set($name, $value) + { + if (array_key_exists($name, $this->attributes)) + { + // Check that we're not trying to change the guid! + if ((array_key_exists('guid', $this->attributes)) && ($name=='guid')) + return false; + + $this->attributes[$name] = $value; + } + else + return set_private_setting($this->guid, $name, $value); + + return true; + } + } + + /** + * Register a particular context for use with widgets. + * + * @param string $context The context we wish to enable context for + */ + function use_widgets($context) { + + global $CONFIG; + if (!isset($CONFIG->widgets)) + $CONFIG->widgets = new stdClass; + if (!isset($CONFIG->widgets->contexts)) { + $CONFIG->widgets->contexts = array(); + } + if (!empty($context)) { + $CONFIG->widgets->contexts[] = $context; + } + + } + + /** + * Determines whether or not the current context is using widgets + * + * @return true|false Depending on widget status + */ + function using_widgets() { + + global $CONFIG; + $context = get_context(); + if (isset($CONFIG->widgets->contexts) && is_array($CONFIG->widgets->contexts)) { + if (in_array($context, $CONFIG->widgets->contexts)) return true; + } + + return false; + + } + + /** + * When given a widget entity and a new requested location, saves the new location + * and also provides a sensible ordering for all widgets in that column + * + * @param ElggObject $widget The widget entity + * @param int $order The order within the column + * @param int $column The column (1, 2 or 3) + * @return true|false Depending on success + */ + function save_widget_location(ElggObject $widget, $order, $column) { + + if ($widget instanceof ElggObject) { + if ($widget->subtype == "widget") { + + // If you can't move the widget, don't save a new location + if (!$widget->draggable) + return false; + + // Sanitise the column value + if ($column != 1 || $column != 2 || $column != 3) + $column = 1; + + $widget->column = (int) $column; + + $ordertmp = array(); + + if ($entities = get_entities_from_metadata_multi(array( + 'context' => $widget->context, + 'column' => $column, + ),'object','widget')) { + foreach($entities as $entity) { + $entityorder = $entity->order; + if ($entityorder < $order) { + $ordertmp[$entityorder] = $entity; + } + if ($entityorder >= $order) { + $ordertmp[$entityorder + 10000] = $entity; + } + } + } + + $ordertmp[$order] = $widget; + ksort($ordertmp); + + $orderticker = 10; + foreach($ordertmp as $orderval => $entity) { + $entity->order = $orderticker; + $orderticker += 10; + } + + return true; + + } else { + register_error($widget->subtype); + } + + } + + return false; + + } + + /** + * Get widgets for a particular context and column, in order of display + * + * @param int $user_guid The owner user GUID + * @param string $context The context (profile, dashboard etc) + * @param int $column The column (1 or 2) + * @return array|false An array of widget ElggObjects, or false + */ + function get_widgets($user_guid, $context, $column) { + + if ($widgets = get_entities_from_private_setting_multi(array( + 'column' => $column, + 'context' => $context), "object", "widget", $user_guid, "", 10000)) + /*if ($widgets = get_user_objects_by_metadata($user_guid, "widget", array( + 'column' => $column, + 'context' => $context, + ), 10000)) { + */ + { + + $widgetorder = array(); + foreach($widgets as $widget) { + $order = $widget->order; + while(isset($widgetorder[$order])) { + $order++; + } + $widgetorder[$order] = $widget; + } + + ksort($widgetorder); + + return $widgetorder; + + } + + return false; + + } + + /** + * Displays a particular widget + * + * @param ElggObject $widget The widget to display + * @return string The HTML for the widget, including JavaScript wrapper + */ + function display_widget(ElggObject $widget) { + + return elgg_view_entity($widget); + + } + + /** + * Add a new widget + * + * @param int $user_guid User GUID to associate this widget with + * @param string $handler The handler for this widget + * @param string $context The page context for this widget + * @param int $order The order to display this widget in + * @param int $column The column to display this widget in (1, 2 or 3) + * @param int $access_id If not specified, it is set to the default access level + * @return true|false Depending on success + */ + function add_widget($user_guid, $handler, $context, $order = 0, $column = 1, $access_id = null) { + + if (empty($user_guid) || empty($context) || empty($handler) || !widget_type_exists($handler)) + return false; + + if ($user = get_user($user_guid)) { + + $widget = new ElggWidget; + $widget->owner_guid = $user_guid; + $widget->container_guid = $user_guid; + if (isset($access_id)) { + $widget->access_id = $access_id; + } else { + $widget->access_id = get_default_access(); + } + + if (!$widget->save()) + return false; + + $widget->handler = $handler; + $widget->context = $context; + $widget->column = $column; + $widget->order = $order; + + // save_widget_location($widget, $order, $column); + return true; + + } + + return false; + + } + + /** + * Define a new widget type + * + * @param string $handler The identifier for the widget handler + * @param string $name The name of the widget type + * @param string $description A description for the widget type + * @param string $context A comma-separated list of contexts where this widget is allowed (default: 'all') + * @param true|false $multiple Whether or not multiple instances of this widget are allowed on a single dashboard (default: false) + * @param string $position A comma-separated list of positions on the page (side or main) where this widget is allowed (default: "side,main") + * @return true|false Depending on success + */ + + function add_widget_type($handler, $name, $description, $context = "all", $multiple = false, $positions = "side,main") { + + if (!empty($handler) && !empty($name)) { + + global $CONFIG; + + if (!isset($CONFIG->widgets)) + $CONFIG->widgets = new stdClass; + + if (!isset($CONFIG->widgets->handlers)) + $CONFIG->widgets->handlers = array(); + + $handlerobj = new stdClass; + $handlerobj->name = $name; + $handlerobj->description = $description; + $handlerobj->context = explode(",",$context); + $handlerobj->multiple = $multiple; + $handlerobj->positions = explode(",",$positions); + + $CONFIG->widgets->handlers[$handler] = $handlerobj; + + return true; + + } + + return false; + + } + + /** + * Determines whether or not widgets with the specified handler have been defined + * + * @param string $handler The widget handler identifying string + * @return true|false Whether or not those widgets exist + */ + function widget_type_exists($handler) { + + global $CONFIG; + if (!empty($CONFIG->widgets) + && !empty($CONFIG->widgets->handlers) + && is_array($CONFIG->widgets->handlers) + && array_key_exists($handler, $CONFIG->widgets->handlers)) + return true; + + return false; + + } + + /** + * Returns an array of stdClass objects representing the defined widget types + * + * @return array A list of types defined (if any) + */ + function get_widget_types() { + + global $CONFIG; + if (!empty($CONFIG->widgets) + && !empty($CONFIG->widgets->handlers) + && is_array($CONFIG->widgets->handlers)) { + + $context = get_context(); + + foreach($CONFIG->widgets->handlers as $key => $handler) { + if (!in_array('all',$handler->context) && + !in_array($context,$handler->context)) { + unset($CONFIG->widgets->handlers[$key]); + } + } + + return $CONFIG->widgets->handlers; + + } + + return array(); + + } + + /** + * Saves a widget's settings (by passing an array of (name => value) pairs to save_{$handler}_widget) + * + * @param int $widget_guid The GUID of the widget we're saving to + * @param array $params An array of name => value parameters + */ + function save_widget_info($widget_guid, $params) { + + if ($widget = get_entity($widget_guid)) { + + $subtype = $widget->getSubtype(); + + if ($subtype != "widget") return false; + $handler = $widget->handler; + if (empty($handler) || !widget_type_exists($handler)) return false; + + if (!$widget->canEdit()) return false; + + // Save the params to the widget + if (is_array($params) && sizeof($params) > 0) { + foreach($params as $name => $value) { + + if (!empty($name) && !in_array($name,array( + 'guid','owner_guid','site_guid' + ))) { + if (is_array($value)) + { + // TODO: Handle arrays securely + $widget->setMetaData($name, $value, "", true); + }else + $widget->$name = $value; + } + } + $widget->save(); + } + + $function = "save_{$handler}_widget"; + if (is_callable($function)) { + return $function($params); + } + + return true; + + } + + return false; + + } + + function reorder_widgets_from_panel($panelstring1, $panelstring2, $panelstring3, $context, $owner) { + + $return = true; + + $mainwidgets = explode('::',$panelstring1); + $sidewidgets = explode('::',$panelstring2); + $rightwidgets = explode('::',$panelstring3); + + $handlers = array(); + $guids = array(); + + if (is_array($mainwidgets) && sizeof($mainwidgets) > 0) { + foreach($mainwidgets as $widget) { + + $guid = (int) $widget; + + if ("{$guid}" == "{$widget}") { + $guids[1][] = $widget; + } else { + $handlers[1][] = $widget; + } + + } + } + if (is_array($sidewidgets) && sizeof($sidewidgets) > 0) { + foreach($sidewidgets as $widget) { + + $guid = (int) $widget; + + if ("{$guid}" == "{$widget}") { + $guids[2][] = $widget; + } else { + $handlers[2][] = $widget; + } + + } + } + if (is_array($rightwidgets) && sizeof($rightwidgets) > 0) { + foreach($rightwidgets as $widget) { + + $guid = (int) $widget; + + if ("{$guid}" == "{$widget}") { + $guids[3][] = $widget; + } else { + $handlers[3][] = $widget; + } + + } + } + + // Reorder existing widgets or delete ones that have vanished + foreach (array(1,2,3) as $column) { + if ($dbwidgets = get_widgets($owner,$context,$column)) { + + foreach($dbwidgets as $dbwidget) { + if (in_array($dbwidget->getGUID(),$guids[1]) || in_array($dbwidget->getGUID(),$guids[2]) || in_array($dbwidget->getGUID(),$guids[3])) { + if (in_array($dbwidget->getGUID(),$guids[1])) { + $pos = array_search($dbwidget->getGUID(),$guids[1]); + $col = 1; + } else if (in_array($dbwidget->getGUID(),$guids[2])) { + $pos = array_search($dbwidget->getGUID(),$guids[2]); + $col = 2; + } else { + $pos = array_search($dbwidget->getGUID(),$guids[3]); + $col = 3; + } + $pos = ($pos + 1) * 10; + $dbwidget->column = $col; + $dbwidget->order = $pos; + } else { + $dbguid = $dbwidget->getGUID(); + if (!$dbwidget->delete()) { + $return = false; + } else { + // Remove state cookie + setcookie('widget' + $dbguid, null); + } + } + } + + } + // Add new ones + if (sizeof($guids[$column]) > 0) { + foreach($guids[$column] as $key => $guid) { + if ($guid == 0) { + $pos = ($key + 1) * 10; + $handler = $handlers[$column][$key]; + if (!add_widget($owner,$handler,$context,$pos,$column)) + $return = false; + } + } + } + } + + return $return; + + } + + /** + * Run some things once. + * + */ + function widget_run_once() + { + // Register a class + add_subtype("object", "widget", "ElggWidget"); + } + + /** + * Function to initialise widgets functionality on Elgg init + * + */ + function widgets_init() { + + register_action('widgets/reorder'); + register_action('widgets/save'); + register_action('widgets/add'); + + // Now run this stuff, but only once + run_function_once("widget_run_once"); + } + + // Register event + register_elgg_event_handler('init','system','widgets_init'); + + // Use widgets on the dashboard + use_widgets('dashboard'); - * @link http://elgg.org/ - */ - - /** - * Override ElggObject in order to store widget data in ultra-private stores. - */ - class ElggWidget extends ElggObject - { - protected function initialise_attributes() - { - parent::initialise_attributes(); - - $this->attributes['subtype'] = "widget"; - } - - public function __construct($guid = null) { parent::__construct($guid); } - - /** - * Override entity get and sets in order to save data to private data store. - */ - public function get($name) - { - // See if its in our base attribute - if (isset($this->attributes[$name])) { - return $this->attributes[$name]; - } - - // No, so see if its in the private data store. - $meta = get_private_setting($this->guid, $name); - if ($meta) - return $meta; - - // Can't find it, so return null - return null; - } - - /** - * Override entity get and sets in order to save data to private data store. - */ - public function set($name, $value) - { - if (array_key_exists($name, $this->attributes)) - { - // Check that we're not trying to change the guid! - if ((array_key_exists('guid', $this->attributes)) && ($name=='guid')) - return false; - - $this->attributes[$name] = $value; - } - else - return set_private_setting($this->guid, $name, $value); - - return true; - } - } - - /** - * Register a particular context for use with widgets. - * - * @param string $context The context we wish to enable context for - */ - function use_widgets($context) { - - global $CONFIG; - if (!isset($CONFIG->widgets)) - $CONFIG->widgets = new stdClass; - if (!isset($CONFIG->widgets->contexts)) { - $CONFIG->widgets->contexts = array(); - } - if (!empty($context)) { - $CONFIG->widgets->contexts[] = $context; - } - - } - - /** - * Determines whether or not the current context is using widgets - * - * @return true|false Depending on widget status - */ - function using_widgets() { - - global $CONFIG; - $context = get_context(); - if (isset($CONFIG->widgets->contexts) && is_array($CONFIG->widgets->contexts)) { - if (in_array($context, $CONFIG->widgets->contexts)) return true; - } - - return false; - - } - - /** - * When given a widget entity and a new requested location, saves the new location - * and also provides a sensible ordering for all widgets in that column - * - * @param ElggObject $widget The widget entity - * @param int $order The order within the column - * @param int $column The column (1, 2 or 3) - * @return true|false Depending on success - */ - function save_widget_location(ElggObject $widget, $order, $column) { - - if ($widget instanceof ElggObject) { - if ($widget->subtype == "widget") { - - // If you can't move the widget, don't save a new location - if (!$widget->draggable) - return false; - - // Sanitise the column value - if ($column != 1 || $column != 2 || $column != 3) - $column = 1; - - $widget->column = (int) $column; - - $ordertmp = array(); - - if ($entities = get_entities_from_metadata_multi(array( - 'context' => $widget->context, - 'column' => $column, - ),'object','widget')) { - foreach($entities as $entity) { - $entityorder = $entity->order; - if ($entityorder < $order) { - $ordertmp[$entityorder] = $entity; - } - if ($entityorder >= $order) { - $ordertmp[$entityorder + 10000] = $entity; - } - } - } - - $ordertmp[$order] = $widget; - ksort($ordertmp); - - $orderticker = 10; - foreach($ordertmp as $orderval => $entity) { - $entity->order = $orderticker; - $orderticker += 10; - } - - return true; - - } else { - register_error($widget->subtype); - } - - } - - return false; - - } - - /** - * Get widgets for a particular context and column, in order of display - * - * @param int $user_guid The owner user GUID - * @param string $context The context (profile, dashboard etc) - * @param int $column The column (1 or 2) - * @return array|false An array of widget ElggObjects, or false - */ - function get_widgets($user_guid, $context, $column) { - - if ($widgets = get_entities_from_private_setting_multi(array( - 'column' => $column, - 'context' => $context), "object", "widget", $user_guid, "", 10000)) - /*if ($widgets = get_user_objects_by_metadata($user_guid, "widget", array( - 'column' => $column, - 'context' => $context, - ), 10000)) { - */ - { - - $widgetorder = array(); - foreach($widgets as $widget) { - $order = $widget->order; - while(isset($widgetorder[$order])) { - $order++; - } - $widgetorder[$order] = $widget; - } - - ksort($widgetorder); - - return $widgetorder; - - } - - return false; - - } - - /** - * Displays a particular widget - * - * @param ElggObject $widget The widget to display - * @return string The HTML for the widget, including JavaScript wrapper - */ - function display_widget(ElggObject $widget) { - - return elgg_view_entity($widget); - - } - - /** - * Add a new widget - * - * @param int $user_guid User GUID to associate this widget with - * @param string $handler The handler for this widget - * @param string $context The page context for this widget - * @param int $order The order to display this widget in - * @param int $column The column to display this widget in (1, 2 or 3) - * @param int $access_id If not specified, it is set to the default access level - * @return true|false Depending on success - */ - function add_widget($user_guid, $handler, $context, $order = 0, $column = 1, $access_id = null) { - - if (empty($user_guid) || empty($context) || empty($handler) || !widget_type_exists($handler)) - return false; - - if ($user = get_user($user_guid)) { - - $widget = new ElggWidget; - $widget->owner_guid = $user_guid; - $widget->container_guid = $user_guid; - if (isset($access_id)) { - $widget->access_id = $access_id; - } else { - $widget->access_id = get_default_access(); - } - - if (!$widget->save()) - return false; - - $widget->handler = $handler; - $widget->context = $context; - $widget->column = $column; - $widget->order = $order; - - // save_widget_location($widget, $order, $column); - return true; - - } - - return false; - - } - - /** - * Define a new widget type - * - * @param string $handler The identifier for the widget handler - * @param string $name The name of the widget type - * @param string $description A description for the widget type - * @param string $context A comma-separated list of contexts where this widget is allowed (default: 'all') - * @param true|false $multiple Whether or not multiple instances of this widget are allowed on a single dashboard (default: false) - * @param string $position A comma-separated list of positions on the page (side or main) where this widget is allowed (default: "side,main") - * @return true|false Depending on success - */ - - function add_widget_type($handler, $name, $description, $context = "all", $multiple = false, $positions = "side,main") { - - if (!empty($handler) && !empty($name)) { - - global $CONFIG; - - if (!isset($CONFIG->widgets)) - $CONFIG->widgets = new stdClass; - - if (!isset($CONFIG->widgets->handlers)) - $CONFIG->widgets->handlers = array(); - - $handlerobj = new stdClass; - $handlerobj->name = $name; - $handlerobj->description = $description; - $handlerobj->context = explode(",",$context); - $handlerobj->multiple = $multiple; - $handlerobj->positions = explode(",",$positions); - - $CONFIG->widgets->handlers[$handler] = $handlerobj; - - return true; - - } - - return false; - - } - - /** - * Determines whether or not widgets with the specified handler have been defined - * - * @param string $handler The widget handler identifying string - * @return true|false Whether or not those widgets exist - */ - function widget_type_exists($handler) { - - global $CONFIG; - if (!empty($CONFIG->widgets) - && !empty($CONFIG->widgets->handlers) - && is_array($CONFIG->widgets->handlers) - && array_key_exists($handler, $CONFIG->widgets->handlers)) - return true; - - return false; - - } - - /** - * Returns an array of stdClass objects representing the defined widget types - * - * @return array A list of types defined (if any) - */ - function get_widget_types() { - - global $CONFIG; - if (!empty($CONFIG->widgets) - && !empty($CONFIG->widgets->handlers) - && is_array($CONFIG->widgets->handlers)) { - - $context = get_context(); - - foreach($CONFIG->widgets->handlers as $key => $handler) { - if (!in_array('all',$handler->context) && - !in_array($context,$handler->context)) { - unset($CONFIG->widgets->handlers[$key]); - } - } - - return $CONFIG->widgets->handlers; - - } - - return array(); - - } - - /** - * Saves a widget's settings (by passing an array of (name => value) pairs to save_{$handler}_widget) - * - * @param int $widget_guid The GUID of the widget we're saving to - * @param array $params An array of name => value parameters - */ - function save_widget_info($widget_guid, $params) { - - if ($widget = get_entity($widget_guid)) { - - $subtype = $widget->getSubtype(); - - if ($subtype != "widget") return false; - $handler = $widget->handler; - if (empty($handler) || !widget_type_exists($handler)) return false; - - if (!$widget->canEdit()) return false; - - // Save the params to the widget - if (is_array($params) && sizeof($params) > 0) { - foreach($params as $name => $value) { - - if (!empty($name) && !in_array($name,array( - 'guid','owner_guid','site_guid' - ))) { - if (is_array($value)) - { - // TODO: Handle arrays securely - $widget->setMetaData($name, $value, "", true); - }else - $widget->$name = $value; - } - } - $widget->save(); - } - - $function = "save_{$handler}_widget"; - if (is_callable($function)) { - return $function($params); - } - - return true; - - } - - return false; - - } - - function reorder_widgets_from_panel($panelstring1, $panelstring2, $panelstring3, $context, $owner) { - - $return = true; - - $mainwidgets = explode('::',$panelstring1); - $sidewidgets = explode('::',$panelstring2); - $rightwidgets = explode('::',$panelstring3); - - $handlers = array(); - $guids = array(); - - if (is_array($mainwidgets) && sizeof($mainwidgets) > 0) { - foreach($mainwidgets as $widget) { - - $guid = (int) $widget; - - if ("{$guid}" == "{$widget}") { - $guids[1][] = $widget; - } else { - $handlers[1][] = $widget; - } - - } - } - if (is_array($sidewidgets) && sizeof($sidewidgets) > 0) { - foreach($sidewidgets as $widget) { - - $guid = (int) $widget; - - if ("{$guid}" == "{$widget}") { - $guids[2][] = $widget; - } else { - $handlers[2][] = $widget; - } - - } - } - if (is_array($rightwidgets) && sizeof($rightwidgets) > 0) { - foreach($rightwidgets as $widget) { - - $guid = (int) $widget; - - if ("{$guid}" == "{$widget}") { - $guids[3][] = $widget; - } else { - $handlers[3][] = $widget; - } - - } - } - - // Reorder existing widgets or delete ones that have vanished - foreach (array(1,2,3) as $column) { - if ($dbwidgets = get_widgets($owner,$context,$column)) { - - foreach($dbwidgets as $dbwidget) { - if (in_array($dbwidget->getGUID(),$guids[1]) || in_array($dbwidget->getGUID(),$guids[2]) || in_array($dbwidget->getGUID(),$guids[3])) { - if (in_array($dbwidget->getGUID(),$guids[1])) { - $pos = array_search($dbwidget->getGUID(),$guids[1]); - $col = 1; - } else if (in_array($dbwidget->getGUID(),$guids[2])) { - $pos = array_search($dbwidget->getGUID(),$guids[2]); - $col = 2; - } else { - $pos = array_search($dbwidget->getGUID(),$guids[3]); - $col = 3; - } - $pos = ($pos + 1) * 10; - $dbwidget->column = $col; - $dbwidget->order = $pos; - } else { - $dbguid = $dbwidget->getGUID(); - if (!$dbwidget->delete()) { - $return = false; - } else { - // Remove state cookie - setcookie('widget' + $dbguid, null); - } - } - } - - } - // Add new ones - if (sizeof($guids[$column]) > 0) { - foreach($guids[$column] as $key => $guid) { - if ($guid == 0) { - $pos = ($key + 1) * 10; - $handler = $handlers[$column][$key]; - if (!add_widget($owner,$handler,$context,$pos,$column)) - $return = false; - } - } - } - } - - return $return; - - } - - /** - * Run some things once. - * - */ - function widget_run_once() - { - // Register a class - add_subtype("object", "widget", "ElggWidget"); - } - - /** - * Function to initialise widgets functionality on Elgg init - * - */ - function widgets_init() { - - register_action('widgets/reorder'); - register_action('widgets/save'); - register_action('widgets/add'); - - // Now run this stuff, but only once - run_function_once("widget_run_once"); - } - - // Register event - register_elgg_event_handler('init','system','widgets_init'); - - // Use widgets on the dashboard - use_widgets('dashboard'); - - ?> \ No newline at end of file diff --git a/engine/settings.example.php b/engine/settings.example.php index 50af236e4..4fbc716a3 100644 --- a/engine/settings.example.php +++ b/engine/settings.example.php @@ -1,98 +1,98 @@ -dbuser = '{{CONFIG_DBUSER}}'; - - // Database password - $CONFIG->dbpass = '{{CONFIG_DBPASS}}'; - - // Database name - $CONFIG->dbname = '{{CONFIG_DBNAME}}'; - - // Database server - // (For most configurations, you can leave this as 'localhost') - $CONFIG->dbhost = '{{CONFIG_DBHOST}}'; - - // Database table prefix - // If you're sharing a database with other applications, you will want to use this - // to differentiate Elgg's tables. - $CONFIG->dbprefix = '{{CONFIG_DBPREFIX}}'; - - /* - * Multiple database connections - * - * Here you can set up multiple connections for reads and writes. To do this, uncomment out - * the lines below. - */ - - /* - - // Yes! We want to split reads and writes - $CONFIG->db->split = true; - - // READS - // Database username - $CONFIG->db['read']->dbuser = ""; - - // Database password - $CONFIG->db['read']->dbpass = ""; - - // Database name - $CONFIG->db['read']->dbname = ""; - - // Database server - // (For most configurations, you can leave this as 'localhost') - $CONFIG->db['read']->dbhost = "localhost"; - - // WRITES - // Database username - $CONFIG->db['write']->dbuser = ""; - - // Database password - $CONFIG->db['write']->dbpass = ""; - - // Database name - $CONFIG->db['write']->dbname = ""; - - // Database server - // (For most configurations, you can leave this as 'localhost') - $CONFIG->db['write']->dbhost = "localhost"; - - - */ - - /* - * For extra connections for both reads and writes, you can turn both - * $CONFIG->db['read'] and $CONFIG->db['write'] into an array, eg: - * - * $CONFIG->db['read'][0]->dbhost = "localhost"; - * - * Note that the array keys must be numeric and consecutive, i.e., they start - * at 0, the next one must be at 1, etc. - */ +dbuser = '{{CONFIG_DBUSER}}'; + + // Database password + $CONFIG->dbpass = '{{CONFIG_DBPASS}}'; + + // Database name + $CONFIG->dbname = '{{CONFIG_DBNAME}}'; + + // Database server + // (For most configurations, you can leave this as 'localhost') + $CONFIG->dbhost = '{{CONFIG_DBHOST}}'; + + // Database table prefix + // If you're sharing a database with other applications, you will want to use this + // to differentiate Elgg's tables. + $CONFIG->dbprefix = '{{CONFIG_DBPREFIX}}'; + + /* + * Multiple database connections + * + * Here you can set up multiple connections for reads and writes. To do this, uncomment out + * the lines below. + */ + + /* + + // Yes! We want to split reads and writes + $CONFIG->db->split = true; + + // READS + // Database username + $CONFIG->db['read']->dbuser = ""; + + // Database password + $CONFIG->db['read']->dbpass = ""; + + // Database name + $CONFIG->db['read']->dbname = ""; + + // Database server + // (For most configurations, you can leave this as 'localhost') + $CONFIG->db['read']->dbhost = "localhost"; + + // WRITES + // Database username + $CONFIG->db['write']->dbuser = ""; + + // Database password + $CONFIG->db['write']->dbpass = ""; + + // Database name + $CONFIG->db['write']->dbname = ""; + + // Database server + // (For most configurations, you can leave this as 'localhost') + $CONFIG->db['write']->dbhost = "localhost"; + + + */ + + /* + * For extra connections for both reads and writes, you can turn both + * $CONFIG->db['read'] and $CONFIG->db['write'] into an array, eg: + * + * $CONFIG->db['read'][0]->dbhost = "localhost"; + * + * Note that the array keys must be numeric and consecutive, i.e., they start + * at 0, the next one must be at 1, etc. + */ /** @@ -110,7 +110,7 @@ //$CONFIG->memcache_servers = array ( // array('server1', 11211), // array('server2', 11211) - //); + //); /** * Some work-around flags. @@ -118,12 +118,12 @@ // Try uncommenting the below if your notification emails are not being sent // $CONFIG->broken_mta = true; - - /** - * Url - I am not sure if this will be here ? - **/ - - // URL - $CONFIG->url = ""; - + + /** + * Url - I am not sure if this will be here ? + **/ + + // URL + $CONFIG->url = ""; + ?> \ No newline at end of file diff --git a/engine/start.php b/engine/start.php index c387e2fce..23a04cb60 100644 --- a/engine/start.php +++ b/engine/start.php @@ -1,219 +1,219 @@ -debug) && $CONFIG->debug) error_log("Loading $file..."); - if (!include_once($file)) - throw new InstallationException("Could not load {$file}"); - } - - } else { // End portion for sanitised installs only - - throw new InstallationException(elgg_echo('installation:error:configuration')); - - } - - // Autodetect some default configuration settings - set_default_config(); - - // Trigger events - trigger_elgg_event('boot', 'system'); - - // Load plugins - - $installed = is_installed(); - $db_installed = is_db_installed(); - - // Determine light mode - $lm = strtolower(get_input('lightmode')); - if ($lm == 'true') $lightmode = true; - - // Load plugins, if we're not in light mode - if (($installed) && ($db_installed) && ($sanitised) && (!$lightmode)) { - load_plugins(); - - trigger_elgg_event('plugins_boot', 'system'); - } - - // Forward if we haven't been installed - if ((!$installed || !$db_installed) && !substr_count($_SERVER["PHP_SELF"],"install.php") && !substr_count($_SERVER["PHP_SELF"],"css.php") && !substr_count($_SERVER["PHP_SELF"],"action_handler.php")) { - header("Location: install.php"); - exit; - } - - // Trigger events - if (!substr_count($_SERVER["PHP_SELF"],"install.php") && - !substr_count($_SERVER["PHP_SELF"],"setup.php") && - !$lightmode - && !(defined('upgrading') && upgrading == 'upgrading')) { - // If default settings haven't been installed, forward to the default settings page - trigger_elgg_event('init', 'system'); - //if (!datalist_get('default_settings')) { - //forward("setup.php"); - //} - } - - // System booted, return to normal view - set_input('view', $oldview); - if (empty($oldview)) { - if (empty($CONFIG->view)) - $oldview = 'default'; - else - $oldview = $CONFIG->view; - } - - if (($installed) && ($db_installed)) - { - $lastupdate = datalist_get('simplecache_lastupdate'); - $lastcached = datalist_get('simplecache_'.$oldview); - if ($lastupdate == 0 || $lastcached < $lastupdate) { - elgg_view_regenerate_simplecache(); - $lastcached = time(); - datalist_set('simplecache_lastupdate',$lastcached); - datalist_set('simplecache_'.$oldview,$lastcached); - } - $CONFIG->lastcache = $lastcached; - } + * @author Curverider Ltd + + * @link http://elgg.org/ + */ + + /* + * Basic profiling + */ + global $START_MICROTIME; + $START_MICROTIME = microtime(true); + + /** + * Load important prerequisites + */ + + if (!include_once(dirname(__FILE__) . "/lib/exceptions.php")) { // Exceptions + echo "Error in installation: could not load the Exceptions library."; + exit; + } + + if (!include_once(dirname(__FILE__) . "/lib/elgglib.php")) { // Main Elgg library + echo "Elgg could not load its main library."; + exit; + } + + if (!include_once(dirname(__FILE__) . "/lib/access.php")) { // Access library + echo "Error in installation: could not load the Access library."; + exit; + } + + if (!include_once(dirname(__FILE__) . "/lib/system_log.php")) { // Logging library + echo "Error in installation: could not load the System Log library."; + exit; + } + + if (!include_once(dirname(__FILE__) . "/lib/export.php")) { // Export library + echo "Error in installation: could not load the Export library."; + exit; + } + + if (!include_once(dirname(__FILE__) . "/lib/sessions.php")) { + echo ("Error in installation: Elgg could not load the Sessions library"); + exit; + } + + if (!include_once(dirname(__FILE__) . "/lib/languages.php")) { // Languages library + echo "Error in installation: could not load the languages library."; + exit; + } + + if (!include_once(dirname(__FILE__) . "/lib/input.php")) { // Input library + echo "Error in installation: could not load the input library."; + exit; + } + + if (!include_once(dirname(__FILE__) . "/lib/install.php")) { // Installation library + echo "Error in installation: could not load the installation library."; + exit; + } + + if (!include_once(dirname(__FILE__) . "/lib/cache.php")) { // Installation library + echo "Error in installation: could not load the cache library."; + exit; + } + + + + // Use fallback view until sanitised + $oldview = get_input('view'); + set_input('view', 'failsafe'); + + /** + * Set light mode default + */ + $lightmode = false; + + /** + * Establish handlers + */ + + // Register the error handler + set_error_handler('__elgg_php_error_handler'); + set_exception_handler('__elgg_php_exception_handler'); + + /** + * If there are basic issues with the way the installation is formed, don't bother trying + * to load any more files + */ + + if ($sanitised = sanitised()) { // Begin portion for sanitised installs only + + /** + * Load the system settings + */ + + if (!include_once(dirname(__FILE__) . "/settings.php")) // Global settings + throw new InstallationException("Elgg could not load the settings file."); + + /** + * Load and initialise the database + */ + + if (!include_once(dirname(__FILE__) . "/lib/database.php")) // Database connection + throw new InstallationException("Elgg could not load the main Elgg database library."); + + /** + * Load the remaining libraries from /lib/ in alphabetical order, + * except for a few exceptions + */ + + if (!include_once(dirname(__FILE__) . "/lib/actions.php")) { + throw new InstallationException("Elgg could not load the Actions library"); + } + + + + // We don't want to load or reload these files + + $file_exceptions = array( + '.','..', + '.DS_Store', + 'Thumbs.db', + '.svn', + 'CVS','cvs', + 'settings.php','settings.example.php','languages.php','exceptions.php','elgglib.php','access.php','database.php','actions.php','sessions.php' + ); + + // Get the list of files to include, and alphabetically sort them + + $files = get_library_files(dirname(__FILE__) . "/lib",$file_exceptions); + asort($files); + + // Get config + global $CONFIG; + + // Include them + foreach($files as $file) { + if (isset($CONFIG->debug) && $CONFIG->debug) error_log("Loading $file..."); + if (!include_once($file)) + throw new InstallationException("Could not load {$file}"); + } + + } else { // End portion for sanitised installs only + + throw new InstallationException(elgg_echo('installation:error:configuration')); + + } + + // Autodetect some default configuration settings + set_default_config(); + + // Trigger events + trigger_elgg_event('boot', 'system'); + + // Load plugins + + $installed = is_installed(); + $db_installed = is_db_installed(); + + // Determine light mode + $lm = strtolower(get_input('lightmode')); + if ($lm == 'true') $lightmode = true; + + // Load plugins, if we're not in light mode + if (($installed) && ($db_installed) && ($sanitised) && (!$lightmode)) { + load_plugins(); + + trigger_elgg_event('plugins_boot', 'system'); + } + + // Forward if we haven't been installed + if ((!$installed || !$db_installed) && !substr_count($_SERVER["PHP_SELF"],"install.php") && !substr_count($_SERVER["PHP_SELF"],"css.php") && !substr_count($_SERVER["PHP_SELF"],"action_handler.php")) { + header("Location: install.php"); + exit; + } + + // Trigger events + if (!substr_count($_SERVER["PHP_SELF"],"install.php") && + !substr_count($_SERVER["PHP_SELF"],"setup.php") && + !$lightmode + && !(defined('upgrading') && upgrading == 'upgrading')) { + // If default settings haven't been installed, forward to the default settings page + trigger_elgg_event('init', 'system'); + //if (!datalist_get('default_settings')) { + //forward("setup.php"); + //} + } + + // System booted, return to normal view + set_input('view', $oldview); + if (empty($oldview)) { + if (empty($CONFIG->view)) + $oldview = 'default'; + else + $oldview = $CONFIG->view; + } + + if (($installed) && ($db_installed)) + { + $lastupdate = datalist_get('simplecache_lastupdate'); + $lastcached = datalist_get('simplecache_'.$oldview); + if ($lastupdate == 0 || $lastcached < $lastupdate) { + elgg_view_regenerate_simplecache(); + $lastcached = time(); + datalist_set('simplecache_lastupdate',$lastcached); + datalist_set('simplecache_'.$oldview,$lastcached); + } + $CONFIG->lastcache = $lastcached; + } ?> \ No newline at end of file -- cgit v1.2.3