From a8d7ea23f8868aa70dd6fe87482e3b860e0b615f Mon Sep 17 00:00:00 2001 From: ben Date: Wed, 4 Feb 2009 13:05:44 +0000 Subject: Moves access permissions references over to using the ACCESS_* constants defined in access.php. Refs #687 git-svn-id: https://code.elgg.org/elgg/trunk@2639 36083f99-b078-4883-b0ff-0f9b5a30f544 --- engine/lib/admin.php | 214 +- engine/lib/annotations.php | 280 +-- engine/lib/entities.php | 5200 ++++++++++++++++++++++---------------------- engine/lib/group.php | 1364 ++++++------ engine/lib/metadata.php | 1102 +++++----- engine/lib/plugins.php | 914 ++++---- engine/lib/system_log.php | 504 ++--- engine/lib/tags.php | 136 +- engine/lib/users.php | 192 +- engine/lib/widgets.php | 162 +- 10 files changed, 5034 insertions(+), 5034 deletions(-) (limited to 'engine/lib') diff --git a/engine/lib/admin.php b/engine/lib/admin.php index 9c54bc588..ad40926c0 100644 --- a/engine/lib/admin.php +++ b/engine/lib/admin.php @@ -1,64 +1,64 @@ -subtype = 'admin_message'; - $admin_message->access_id = 2; - $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 + + /** + * 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/annotations.php b/engine/lib/annotations.php index 8c177ffff..bfac0d557 100644 --- a/engine/lib/annotations.php +++ b/engine/lib/annotations.php @@ -98,13 +98,13 @@ function delete() { return delete_annotation($this->id); - } - - /** - * Get a url for this annotation. - * - * @return string - */ + } + + /** + * Get a url for this annotation. + * + * @return string + */ public function getURL() { return get_annotation_url($this->guid); } // SYSTEM LOG INTERFACE //////////////////////////////////////////////////////////// @@ -156,7 +156,7 @@ * @param int $owner_guid * @param int $access_id */ - function create_annotation($entity_guid, $name, $value, $value_type, $owner_guid, $access_id = 0) + function create_annotation($entity_guid, $name, $value, $value_type, $owner_guid, $access_id = ACCESS_PRIVATE) { global $CONFIG; @@ -183,16 +183,16 @@ system_log($entity, 'annotate'); // If ok then add it - $result = insert_data("INSERT into {$CONFIG->dbprefix}annotations (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 ($result!==false) { - $obj = get_annotation($result); - if (trigger_elgg_event('create', 'annotation', $obj)) { - return true; - } else { - delete_annotation($result); - } - } - + $result = insert_data("INSERT into {$CONFIG->dbprefix}annotations (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 ($result!==false) { + $obj = get_annotation($result); + if (trigger_elgg_event('create', 'annotation', $obj)) { + return true; + } else { + delete_annotation($result); + } + } + return $result; } @@ -230,16 +230,16 @@ if (!$name) return false; // If ok then add it - $result = update_data("UPDATE {$CONFIG->dbprefix}annotations set value_id='$value', value_type='$value_type', access_id=$access_id, owner_guid=$owner_guid where id=$annotation_id and name_id='$name' and $access"); - if ($result!==false) { - $obj = get_annotation($annotation_id); - if (trigger_elgg_event('update', 'annotation', $obj)) { - return true; - } else { - delete_annotation($annotation_id); - } - } - + $result = update_data("UPDATE {$CONFIG->dbprefix}annotations set value_id='$value', value_type='$value_type', access_id=$access_id, owner_guid=$owner_guid where id=$annotation_id and name_id='$name' and $access"); + if ($result!==false) { + $obj = get_annotation($annotation_id); + if (trigger_elgg_event('update', 'annotation', $obj)) { + return true; + } else { + delete_annotation($annotation_id); + } + } + return $result; } @@ -334,98 +334,98 @@ $query .= " order by $order_by limit $offset,$limit"; // Add order and limit return get_data($query, "row_to_elggannotation"); - } - - /** - * Return a list of entities which are annotated with a specific annotation. - * These can be ordered by when the annotation was created/updated. - * - * @param string $entity_type Type of entity. - * @param string $entity_subtype Subtype of entity. - * @param string $name Name of annotation. - * @param string $value Value of annotation. - * @param int $owner_guid Owner. - * @param int $group_guid Group container. Currently this is only supported if $entity_type == 'object' - * @param int $limit Maximum number of results to return. - * @param int $offset Place to start. + } + + /** + * Return a list of entities which are annotated with a specific annotation. + * These can be ordered by when the annotation was created/updated. + * + * @param string $entity_type Type of entity. + * @param string $entity_subtype Subtype of entity. + * @param string $name Name of annotation. + * @param string $value Value of annotation. + * @param int $owner_guid Owner. + * @param int $group_guid Group container. Currently this is only supported if $entity_type == 'object' + * @param int $limit Maximum number of results to return. + * @param int $offset Place to start. * @param string $order_by How to order results. - * @param boolean $count Whether to count entities rather than return them - */ - function get_entities_from_annotations($entity_type = "", $entity_subtype = "", $name = "", $value = "", $owner_guid = 0, $group_guid = 0, $limit = 10, $offset = 0, $order_by = "asc", $count = false) - { - global $CONFIG; - - $entity_type = sanitise_string($entity_type); - $entity_subtype = get_subtype_id($entity_type, $entity_subtype); - if ($name) - { - $name = get_metastring_id($name); - - if ($name === false) - $name = 0; - } - if ($value != "") $value = get_metastring_id($value); - if (is_array($owner_guid)) { - if (sizeof($owner_guid) > 0) { - foreach($owner_guid as $key => $val) { - $owner_guid[$key] = (int) $val; - } - } else { - $owner_guid = 0; - } - } else { - $owner_guid = (int)$owner_guid; - } - $group_guid = (int)$group_guid; - - $limit = (int)$limit; - $offset = (int)$offset; - if($order_by == 'asc') - $order_by = "maxtime asc"; - - if($order_by == 'desc') - $order_by = "maxtime desc"; - - $where = array(); - - if ($entity_type != "") - $where[] = "e.type='$entity_type'"; - - if ($entity_subtype != "") - $where[] = "e.subtype='$entity_subtype'"; - - if ($owner_guid != 0 && !is_array($owner_guid)) { - $where[] = "a.owner_guid=$owner_guid"; - } else { - if (is_array($owner_guid)) - $where[] = "a.owner_guid in (" . implode(",",$owner_guid) . ")"; - } - - if (($group_guid != 0) && ($entity_type=='object')) - $where[] = "e.container_guid = $group_guid"; - - if ($name !== "") - $where[] = "a.name_id='$name'"; - - if ($value != "") - $where[] = "a.value_id='$value'"; - + * @param boolean $count Whether to count entities rather than return them + */ + function get_entities_from_annotations($entity_type = "", $entity_subtype = "", $name = "", $value = "", $owner_guid = 0, $group_guid = 0, $limit = 10, $offset = 0, $order_by = "asc", $count = false) + { + global $CONFIG; + + $entity_type = sanitise_string($entity_type); + $entity_subtype = get_subtype_id($entity_type, $entity_subtype); + if ($name) + { + $name = get_metastring_id($name); + + if ($name === false) + $name = 0; + } + if ($value != "") $value = get_metastring_id($value); + if (is_array($owner_guid)) { + if (sizeof($owner_guid) > 0) { + foreach($owner_guid as $key => $val) { + $owner_guid[$key] = (int) $val; + } + } else { + $owner_guid = 0; + } + } else { + $owner_guid = (int)$owner_guid; + } + $group_guid = (int)$group_guid; + + $limit = (int)$limit; + $offset = (int)$offset; + if($order_by == 'asc') + $order_by = "maxtime asc"; + + if($order_by == 'desc') + $order_by = "maxtime desc"; + + $where = array(); + + if ($entity_type != "") + $where[] = "e.type='$entity_type'"; + + if ($entity_subtype != "") + $where[] = "e.subtype='$entity_subtype'"; + + if ($owner_guid != 0 && !is_array($owner_guid)) { + $where[] = "a.owner_guid=$owner_guid"; + } else { + if (is_array($owner_guid)) + $where[] = "a.owner_guid in (" . implode(",",$owner_guid) . ")"; + } + + if (($group_guid != 0) && ($entity_type=='object')) + $where[] = "e.container_guid = $group_guid"; + + if ($name !== "") + $where[] = "a.name_id='$name'"; + + if ($value != "") + $where[] = "a.value_id='$value'"; + if ($count) { $query = "SELECT count(distinct e.guid) as total "; } else { $query = "SELECT e.*, max(a.time_created) as maxtime "; - } + } $query .= "from {$CONFIG->dbprefix}annotations a JOIN {$CONFIG->dbprefix}entities e on e.guid = a.entity_guid "; if ($value != "") - $query .= " JOIN {$CONFIG->dbprefix}metastrings v on a.value_id=v.id"; - - if (($group_guid != 0) && ($entity_type=='object')) $query .= "JOIN {$CONFIG->dbprefix}objects_entity o on o.guid = e.guid"; - $query .= " where"; - - foreach ($where as $w) - $query .= " $w and "; - $query .= get_access_sql_suffix("a"); // Add access controls + $query .= " JOIN {$CONFIG->dbprefix}metastrings v on a.value_id=v.id"; + + if (($group_guid != 0) && ($entity_type=='object')) $query .= "JOIN {$CONFIG->dbprefix}objects_entity o on o.guid = e.guid"; + $query .= " where"; + + foreach ($where as $w) + $query .= " $w and "; + $query .= get_access_sql_suffix("a"); // Add access controls $query .= ' and ' . get_access_sql_suffix("e"); // Add access controls if ($count) { @@ -434,7 +434,7 @@ } else { $query .= " group by a.entity_guid order by $order_by limit $offset,$limit"; // Add order and limit return get_data($query, "entity_row_to_elggstar"); - } + } } /** @@ -596,7 +596,7 @@ $query = "SELECT $sum(ms.string) as sum from {$CONFIG->dbprefix}annotations a JOIN {$CONFIG->dbprefix}entities e on a.entity_guid = e.guid JOIN {$CONFIG->dbprefix}metastrings ms on a.value_id=ms.id WHERE "; foreach ($where as $w) $query .= " $w and "; - $query .= get_access_sql_suffix("a"); // now add access + $query .= get_access_sql_suffix("a"); // now add access $query .= ' and ' . get_access_sql_suffix("e"); // now add access $row = get_data_row($query); @@ -841,32 +841,32 @@ } return $returnvalue; - } - - /** - * 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_annotation_url($id) - { - $id = (int)$id; - - if ($extender = get_annotation($id)) { - return get_extender_url($extender); - } - return false; - } - - - /** - * Register an annotation url handler. - * - * @param string $function_name The function. - * @param string $extender_name The name, default 'all'. - */ - function register_annotation_url_handler($function_name, $extender_name = "all") { - return register_extender_url_handler($function_name, 'annotation', $extender_name); + } + + /** + * 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_annotation_url($id) + { + $id = (int)$id; + + if ($extender = get_annotation($id)) { + return get_extender_url($extender); + } + return false; + } + + + /** + * Register an annotation url handler. + * + * @param string $function_name The function. + * @param string $extender_name The name, default 'all'. + */ + function register_annotation_url_handler($function_name, $extender_name = "all") { + return register_extender_url_handler($function_name, 'annotation', $extender_name); } /** Register the hook */ diff --git a/engine/lib/entities.php b/engine/lib/entities.php index 4d4b3edca..426102e38 100644 --- a/engine/lib/entities.php +++ b/engine/lib/entities.php @@ -1,2600 +1,2600 @@ - - * @copyright Curverider Ltd 2008-2009 - * @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'] = 0; - $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 = 0, $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 - */ - public function disable($reason = "") - { - return disable_entity($this->get('guid'), $reason); - } - - /** - * 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() - { - $res = delete_entity($this->get('guid')); - return $res; - } - - // 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; - - 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 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) && ($user)) - { - - // 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 ($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; - - if (!can_write_to_container($owner_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; - - $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 $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($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 = "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($subtype)) { - $tempwhere = ""; - if (sizeof($subtype)) - foreach($subtype as $typekey => $subtypearray) { - foreach($subtypearray as $subtypeval) { - $typekey = sanitise_string($typekey); - if (!empty($subtypeval)) { - $subtypeval = (int) get_subtype_id($typekey, $subtypeval); - } else { - $subtypeval = 0; - } - if (!empty($tempwhere)) $tempwhere .= " or "; - $tempwhere .= "(type = '{$typekey}' and subtype = {$subtypeval})"; - } - } - if (!empty($tempwhere)) $where[] = "({$tempwhere})"; - - } else { - - $type = sanitise_string($type); - $subtype = get_subtype_id($type, $subtype); - - 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 (!$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); - } - - /** - * Disable an entity but not delete it. - * - * @param int $guid The guid - * @param string $reason Optional reason - */ - function disable_entity($guid, $reason = "") - { - 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, 2); - //$entity->disable_reason = $reason; - - $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 - */ - function delete_entity($guid) - { - global $CONFIG; - - // TODO Make sure this deletes all metadata/annotations/relationships/etc!! - - $guid = (int)$guid; - if ($entity = get_entity($guid)) { - if (trigger_elgg_event('delete',$entity->type,$entity)) { - if ($entity->canEdit()) { - $entity->clearMetadata(); - $entity->clearAnnotations(); - $entity->clearRelationships(); - $res = delete_data("DELETE from {$CONFIG->dbprefix}entities 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)) - { - case 'master': - 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)) { - $subtypeval = (int) get_subtype_id($typekey, $subtypeval); - } 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); - $subtype = get_subtype_id($type, $subtype); - - 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 $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_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)) { - $subtypeval = (int) get_subtype_id($typekey, $subtypeval); - } 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); - $subtype = get_subtype_id($type, $subtype); - - 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); - - return insert_data("INSERT into {$CONFIG->dbprefix}private_settings (entity_guid, name, value) VALUES ($entity_guid, '{$name}', '{$value}') ON DUPLICATE KEY UPDATE value='$value'"); - - } - - /** - * 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}"); - } - - /** - * Entities init function; establishes the page handler - * - */ - function entities_init() { - register_page_handler('view','entities_page_handler'); - } - - /** 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'); - -?> + + * @copyright Curverider Ltd 2008-2009 + * @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 + */ + public function disable($reason = "") + { + return disable_entity($this->get('guid'), $reason); + } + + /** + * 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() + { + $res = delete_entity($this->get('guid')); + return $res; + } + + // 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; + + 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 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) && ($user)) + { + + // 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 ($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; + + if (!can_write_to_container($owner_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; + + $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 $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($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 = "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($subtype)) { + $tempwhere = ""; + if (sizeof($subtype)) + foreach($subtype as $typekey => $subtypearray) { + foreach($subtypearray as $subtypeval) { + $typekey = sanitise_string($typekey); + if (!empty($subtypeval)) { + $subtypeval = (int) get_subtype_id($typekey, $subtypeval); + } else { + $subtypeval = 0; + } + if (!empty($tempwhere)) $tempwhere .= " or "; + $tempwhere .= "(type = '{$typekey}' and subtype = {$subtypeval})"; + } + } + if (!empty($tempwhere)) $where[] = "({$tempwhere})"; + + } else { + + $type = sanitise_string($type); + $subtype = get_subtype_id($type, $subtype); + + 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 (!$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); + } + + /** + * Disable an entity but not delete it. + * + * @param int $guid The guid + * @param string $reason Optional reason + */ + function disable_entity($guid, $reason = "") + { + 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); + //$entity->disable_reason = $reason; + + $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 + */ + function delete_entity($guid) + { + global $CONFIG; + + // TODO Make sure this deletes all metadata/annotations/relationships/etc!! + + $guid = (int)$guid; + if ($entity = get_entity($guid)) { + if (trigger_elgg_event('delete',$entity->type,$entity)) { + if ($entity->canEdit()) { + $entity->clearMetadata(); + $entity->clearAnnotations(); + $entity->clearRelationships(); + $res = delete_data("DELETE from {$CONFIG->dbprefix}entities 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)) + { + case 'master': + 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)) { + $subtypeval = (int) get_subtype_id($typekey, $subtypeval); + } 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); + $subtype = get_subtype_id($type, $subtype); + + 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 $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_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)) { + $subtypeval = (int) get_subtype_id($typekey, $subtypeval); + } 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); + $subtype = get_subtype_id($type, $subtype); + + 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); + + return insert_data("INSERT into {$CONFIG->dbprefix}private_settings (entity_guid, name, value) VALUES ($entity_guid, '{$name}', '{$value}') ON DUPLICATE KEY UPDATE value='$value'"); + + } + + /** + * 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}"); + } + + /** + * Entities init function; establishes the page handler + * + */ + function entities_init() { + register_page_handler('view','entities_page_handler'); + } + + /** 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/group.php b/engine/lib/group.php index f3f8f2ac9..588a60aac 100644 --- a/engine/lib/group.php +++ b/engine/lib/group.php @@ -1,96 +1,96 @@ -attributes['type'] = "group"; - $this->attributes['name'] = ""; - $this->attributes['description'] = ""; - $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)); - } - - // Is $guid is an ElggGroup? Use a copy constructor - else if ($guid instanceof ElggGroup) - { - foreach ($guid->attributes as $key => $value) - $this->attributes[$key] = $value; - } - - // Is this is an ElggEntity but not an ElggGroup = ERROR! - else if ($guid instanceof ElggEntity) - throw new InvalidParameterException(elgg_echo('InvalidParameterException:NonElggGroup')); - - // 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')); - } - } - - /** - * Add an ElggObject to this group. - * - * @param ElggObject $object The object. - * @return bool - */ - public function addObjectToGroup(ElggObject $object) - { - return add_object_to_group($this->getGUID(), $object->getGUID()); - } - - /** - * Remove an object from the containing group. - * - * @param int $guid The guid of the object. - * @return bool - */ - public function removeObjectFromGroup($guid) - { - return remove_object_from_group($this->getGUID(), $guid); - } + implements Friendable + { + protected function initialise_attributes() + { + parent::initialise_attributes(); + + $this->attributes['type'] = "group"; + $this->attributes['name'] = ""; + $this->attributes['description'] = ""; + $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)); + } + + // Is $guid is an ElggGroup? Use a copy constructor + else if ($guid instanceof ElggGroup) + { + foreach ($guid->attributes as $key => $value) + $this->attributes[$key] = $value; + } + + // Is this is an ElggEntity but not an ElggGroup = ERROR! + else if ($guid instanceof ElggEntity) + throw new InvalidParameterException(elgg_echo('InvalidParameterException:NonElggGroup')); + + // 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')); + } + } + + /** + * Add an ElggObject to this group. + * + * @param ElggObject $object The object. + * @return bool + */ + public function addObjectToGroup(ElggObject $object) + { + return add_object_to_group($this->getGUID(), $object->getGUID()); + } + + /** + * Remove an object from the containing group. + * + * @param int $guid The guid of the object. + * @return bool + */ + public function removeObjectFromGroup($guid) + { + return remove_object_from_group($this->getGUID(), $guid); + } public function get($name) { @@ -195,602 +195,602 @@ /** * End friendable compatibility block */ - - /** - * Get a list of group members. - * - * @param int $limit - * @param int $offset - * @return mixed - */ - public function getMembers($limit = 10, $offset = 0, $count = false) - { - return get_group_members($this->getGUID(), $limit, $offset, 0 , $count); + + /** + * Get a list of group members. + * + * @param int $limit + * @param int $offset + * @return mixed + */ + public function getMembers($limit = 10, $offset = 0, $count = false) + { + return get_group_members($this->getGUID(), $limit, $offset, 0 , $count); } - - /** - * Returns whether the current group is public membership or not. - * @return bool - */ - public function isPublicMembership() - { - if ($this->membership == 2) - return true; - - return false; - } - - /** - * Return whether a given user is a member of this group or not. - * - * @param ElggUser $user The user - * @return bool - */ - public function isMember($user = 0) + + /** + * Returns whether the current group is public membership or not. + * @return bool + */ + public function isPublicMembership() + { + if ($this->membership == ACCESS_PUBLIC) + return true; + + return false; + } + + /** + * Return whether a given user is a member of this group or not. + * + * @param ElggUser $user The user + * @return bool + */ + public function isMember($user = 0) { if (!($user instanceof ElggUser)) $user = get_loggedin_user(); - if (!($user instanceof ElggUser)) return false; - return is_group_member($this->getGUID(), $user->getGUID()); - } - - /** - * Join an elgg user to this group. - * - * @param ElggUser $user - * @return bool - */ - public function join(ElggUser $user) - { - return join_group($this->getGUID(), $user->getGUID()); - } - - /** - * Remove a user from the group. - * - * @param ElggUser $user - */ - public function leave(ElggUser $user) - { - return leave_group($this->getGUID(), $user->getGUID()); - } - - /** - * Delete this group. - */ - public function delete() - { - - if (!delete_group_entity($this->get('guid'))) - return false; - - return parent::delete(); - - } - - - /** - * Override the load function. - * This function will ensure that all data is loaded (were possible), so - * if only part of the ElggGroup is loaded, it'll load the rest. - * - * @param int $guid - */ - 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']!='group') - throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $guid, get_class())); - - // Load missing data - $row = get_group_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. - */ - public function save() - { - // Save generic stuff - if (!parent::save()) - return false; - - // Now save specific stuff - return create_group_entity($this->get('guid'), $this->get('name'), $this->get('description')); - } - - // EXPORTABLE INTERFACE //////////////////////////////////////////////////////////// - - /** - * Return an array of fields which can be exported. - */ - public function getExportableValues() - { - return array_merge(parent::getExportableValues(), array( - 'name', - 'description', - )); - } - } - - /** - * Get the group entity. - * - * @param int $guid - */ - function get_group_entity_as_row($guid) - { - global $CONFIG; - - $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 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"); - - return get_data_row("SELECT * from {$CONFIG->dbprefix}groups_entity where guid=$guid"); - } - } - - /** - * Create or update the extras table for a given group. - * Call create_entity first. - * - * @param int $guid - * @param string $name - * @param string $description - */ - function create_group_entity($guid, $name, $description) - { - global $CONFIG; - - $guid = (int)$guid; - $name = sanitise_string($name); - $description = sanitise_string($description); - - $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}groups_entity WHERE guid = {$guid}")) { - $result = update_data("UPDATE {$CONFIG->dbprefix}groups_entity set name='$name', description='$description' 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(); - //delete_entity($guid); - } - } - } - else - { - // Update failed, attempt an insert. - $result = insert_data("INSERT into {$CONFIG->dbprefix}groups_entity (guid, name, description) values ($guid, '$name','$description')"); - 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; - } + if (!($user instanceof ElggUser)) return false; + return is_group_member($this->getGUID(), $user->getGUID()); + } + + /** + * Join an elgg user to this group. + * + * @param ElggUser $user + * @return bool + */ + public function join(ElggUser $user) + { + return join_group($this->getGUID(), $user->getGUID()); + } + + /** + * Remove a user from the group. + * + * @param ElggUser $user + */ + public function leave(ElggUser $user) + { + return leave_group($this->getGUID(), $user->getGUID()); + } + + /** + * Delete this group. + */ + public function delete() + { + + if (!delete_group_entity($this->get('guid'))) + return false; + + return parent::delete(); + + } + + + /** + * Override the load function. + * This function will ensure that all data is loaded (were possible), so + * if only part of the ElggGroup is loaded, it'll load the rest. + * + * @param int $guid + */ + 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']!='group') + throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $guid, get_class())); + + // Load missing data + $row = get_group_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. + */ + public function save() + { + // Save generic stuff + if (!parent::save()) + return false; + + // Now save specific stuff + return create_group_entity($this->get('guid'), $this->get('name'), $this->get('description')); + } + + // EXPORTABLE INTERFACE //////////////////////////////////////////////////////////// + + /** + * Return an array of fields which can be exported. + */ + public function getExportableValues() + { + return array_merge(parent::getExportableValues(), array( + 'name', + 'description', + )); + } + } + + /** + * Get the group entity. + * + * @param int $guid + */ + function get_group_entity_as_row($guid) + { + global $CONFIG; + + $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 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"); + + return get_data_row("SELECT * from {$CONFIG->dbprefix}groups_entity where guid=$guid"); + } + } + + /** + * Create or update the extras table for a given group. + * Call create_entity first. + * + * @param int $guid + * @param string $name + * @param string $description + */ + function create_group_entity($guid, $name, $description) + { + global $CONFIG; + + $guid = (int)$guid; + $name = sanitise_string($name); + $description = sanitise_string($description); + + $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}groups_entity WHERE guid = {$guid}")) { + $result = update_data("UPDATE {$CONFIG->dbprefix}groups_entity set name='$name', description='$description' 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(); + //delete_entity($guid); + } + } + } + else + { + // Update failed, attempt an insert. + $result = insert_data("INSERT into {$CONFIG->dbprefix}groups_entity (guid, name, description) values ($guid, '$name','$description')"); + 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; + } + - - /** - * Delete a group's extra data. - * - * @param int $guid The guid of the group - * @return bool - */ - function delete_group_entity($guid) - { - global $CONFIG; - - $guid = (int)$guid; - - $row = get_entity_as_row($guid); - - // Check to see if we have access and it exists - if ($row) - { - // Delete any existing stuff - return delete_data("DELETE from {$CONFIG->dbprefix}groups_entity where guid=$guid"); - } - - return false; - } - - /** - * Add an object to the given group. - * - * @param int $group_guid The group to add the object to. - * @param int $object_guid The guid of the elgg object (must be ElggObject or a child thereof) - * @return bool - */ - function add_object_to_group($group_guid, $object_guid) - { - $group_guid = (int)$group_guid; - $object_guid = (int)$object_guid; - - $group = get_entity($group_guid); - $object = get_entity($object_guid); - - if ((!$group) || (!$object)) return false; - - if (!($group instanceof ElggGroup)) - throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $group_guid, 'ElggGroup')); - - if (!($object instanceof ElggObject)) - throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $object_guid, 'ElggObject')); - - $object->container_guid = $group_guid; - return $object->save(); - } - - /** - * Remove an object from the given group. - * - * @param int $group_guid The group to remove the object from - * @param int $object_guid The object to remove - */ - function remove_object_from_group($group_guid, $object_guid) - { - $group_guid = (int)$group_guid; - $object_guid = (int)$object_guid; - - $group = get_entity($group_guid); - $object = get_entity($object_guid); - - if ((!$group) || (!$object)) return false; - - if (!($group instanceof ElggGroup)) - throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $group_guid, 'ElggGroup')); - - if (!($object instanceof ElggObject)) - throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $object_guid, 'ElggObject')); - - $object->container_guid = $object->owner_guid; - return $object->save(); - } - - /** - * Return an array of objects in a given container. - * @see get_entities() - * - * @param int $group_guid The container (defaults to current page owner) - * @param string $subtype The subtype - * @param int $owner_guid Owner - * @param int $site_guid The site - * @param string $order_by Order - * @param unknown_type $limit Limit on number of elements to return, by default 10. - * @param unknown_type $offset Where to start, by default 0. - * @param unknown_type $count Whether to return the entities or a count of them. - */ - function get_objects_in_group($group_guid, $subtype = "", $owner_guid = 0, $site_guid = 0, $order_by = "", $limit = 10, $offset = 0, $count = false) - { - global $CONFIG; - - if ($subtype === false || $subtype === null || $subtype === 0) - return false; - - $subtype = get_subtype_id('object', $subtype); - - 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; - - $container_guid = (int)$group_guid; - if ($container_guid == 0) - $container_guid = page_owner(); - - $where = array(); - - $where[] = "e.type='object'"; - if ($subtype!=="") - $where[] = "e.subtype=$subtype"; - if ($owner_guid != "") { - if (!is_array($owner_guid)) { - $owner_guid = (int) $owner_guid; - $where[] = "e.container_guid = '$owner_guid'"; - } else if (sizeof($owner_guid) > 0) { - // Cast every element to the owner_guid array to int - $owner_guid = array_map("sanitise_int", $owner_guid); - $owner_guid = implode(",",$owner_guid); - $where[] = "e.container_guid in ({$owner_guid})"; - } - } - if ($site_guid > 0) - $where[] = "e.site_guid = {$site_guid}"; - - if ($container_guid > 0) - $where[] = "e.container_guid = {$container_guid}"; - - if (!$count) { - $query = "SELECT * from {$CONFIG->dbprefix}entities e join {$CONFIG->dbprefix}objects_entity o on e.guid=o.guid where "; - } else { - $query = "SELECT count(e.guid) as total from {$CONFIG->dbprefix}entities e join {$CONFIG->dbprefix}objects_entity o on e.guid=o.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 all the entities from metadata from a group. - * - * @param int $group_guid The ID of the group. - * @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) - */ - function get_entities_from_metadata_groups($group_guid, $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"; - $order_by = sanitise_string($order_by); - $site_guid = (int) $site_guid; - if (is_array($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; - - $container_guid = (int)$group_guid; - if ($container_guid == 0) - $container_guid = page_owner(); - - //$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 ($container_guid > 0) - $where[] = "e.container_guid = {$container_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(e.guid) as total "; - } - - $query .= "from {$CONFIG->dbprefix}entities e JOIN {$CONFIG->dbprefix}metadata m on e.guid = m.entity_guid join {$CONFIG->dbprefix}objects_entity o on e.guid = o.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 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; - } - - /** - * As get_entities_from_metadata_groups() but with multiple entities. - * - * @param int $group_guid The ID of the group. - * @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) - * @return int|array List of ElggEntities, or the total number if count is set to false - */ - function get_entities_from_metadata_groups_multi($group_guid, $meta_array, $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $offset = 0, $order_by = "", $site_guid = 0, $count = false) - { - global $CONFIG; - - if (!is_array($meta_array) || sizeof($meta_array) == 0) { - return false; - } - - $where = array(); - - $mindex = 1; - $join = ""; - 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 join {$CONFIG->dbprefix}objects_entity o on e.guid = o.guid "; - if ($meta_name!="") - $where[] = "m{$mindex}.name_id='$meta_n'"; - if ($meta_value!="") - $where[] = "m{$mindex}.value_id='$meta_v'"; - $mindex++; - } - - $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); - $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 ($owner_guid > 0) - $where[] = "e.owner_guid = {$owner_guid}"; - if ($container_guid > 0) - $where[] = "e.container_guid = {$container_guid}"; - - if ($count) { - $query = "SELECT count(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 - - 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; - } - - /** - * Return a list of this group's members. - * - * @param int $group_guid The ID of the container/group. - * @param int $limit The limit - * @param int $offset The offset - * @param int $site_guid The site - * @param bool $count Return the users (false) or the count of them (true) - * @return mixed - */ - function get_group_members($group_guid, $limit = 10, $offset = 0, $site_guid = 0, $count = false) - { - return get_entities_from_relationship('member', $group_guid, true, 'user', '', 0, "", $limit, $offset, $count, $site_guid); - } - - /** - * Return whether a given user is a member of the group or not. - * - * @param int $group_guid The group ID - * @param int $user_guid The user guid - * @return bool - */ - function is_group_member($group_guid, $user_guid) - { - return check_entity_relationship($user_guid, 'member', $group_guid); - } - - /** - * Join a user to a group. - * - * @param int $group_guid The group. - * @param int $user_guid The user. - */ - function join_group($group_guid, $user_guid) + /** + * Delete a group's extra data. + * + * @param int $guid The guid of the group + * @return bool + */ + function delete_group_entity($guid) { - trigger_elgg_event('join','group',array('group' => get_entity($group_guid), 'user' => get_entity($user_guid))); - return add_entity_relationship($user_guid, 'member', $group_guid); - } - - /** - * Remove a user from a group. - * - * @param int $group_guid The group. - * @param int $user_guid The user. - */ - function leave_group($group_guid, $user_guid) + global $CONFIG; + + $guid = (int)$guid; + + $row = get_entity_as_row($guid); + + // Check to see if we have access and it exists + if ($row) + { + // Delete any existing stuff + return delete_data("DELETE from {$CONFIG->dbprefix}groups_entity where guid=$guid"); + } + + return false; + } + + /** + * Add an object to the given group. + * + * @param int $group_guid The group to add the object to. + * @param int $object_guid The guid of the elgg object (must be ElggObject or a child thereof) + * @return bool + */ + function add_object_to_group($group_guid, $object_guid) + { + $group_guid = (int)$group_guid; + $object_guid = (int)$object_guid; + + $group = get_entity($group_guid); + $object = get_entity($object_guid); + + if ((!$group) || (!$object)) return false; + + if (!($group instanceof ElggGroup)) + throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $group_guid, 'ElggGroup')); + + if (!($object instanceof ElggObject)) + throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $object_guid, 'ElggObject')); + + $object->container_guid = $group_guid; + return $object->save(); + } + + /** + * Remove an object from the given group. + * + * @param int $group_guid The group to remove the object from + * @param int $object_guid The object to remove + */ + function remove_object_from_group($group_guid, $object_guid) + { + $group_guid = (int)$group_guid; + $object_guid = (int)$object_guid; + + $group = get_entity($group_guid); + $object = get_entity($object_guid); + + if ((!$group) || (!$object)) return false; + + if (!($group instanceof ElggGroup)) + throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $group_guid, 'ElggGroup')); + + if (!($object instanceof ElggObject)) + throw new InvalidClassException(sprintf(elgg_echo('InvalidClassException:NotValidElggStar'), $object_guid, 'ElggObject')); + + $object->container_guid = $object->owner_guid; + return $object->save(); + } + + /** + * Return an array of objects in a given container. + * @see get_entities() + * + * @param int $group_guid The container (defaults to current page owner) + * @param string $subtype The subtype + * @param int $owner_guid Owner + * @param int $site_guid The site + * @param string $order_by Order + * @param unknown_type $limit Limit on number of elements to return, by default 10. + * @param unknown_type $offset Where to start, by default 0. + * @param unknown_type $count Whether to return the entities or a count of them. + */ + function get_objects_in_group($group_guid, $subtype = "", $owner_guid = 0, $site_guid = 0, $order_by = "", $limit = 10, $offset = 0, $count = false) + { + global $CONFIG; + + if ($subtype === false || $subtype === null || $subtype === 0) + return false; + + $subtype = get_subtype_id('object', $subtype); + + 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; + + $container_guid = (int)$group_guid; + if ($container_guid == 0) + $container_guid = page_owner(); + + $where = array(); + + $where[] = "e.type='object'"; + if ($subtype!=="") + $where[] = "e.subtype=$subtype"; + if ($owner_guid != "") { + if (!is_array($owner_guid)) { + $owner_guid = (int) $owner_guid; + $where[] = "e.container_guid = '$owner_guid'"; + } else if (sizeof($owner_guid) > 0) { + // Cast every element to the owner_guid array to int + $owner_guid = array_map("sanitise_int", $owner_guid); + $owner_guid = implode(",",$owner_guid); + $where[] = "e.container_guid in ({$owner_guid})"; + } + } + if ($site_guid > 0) + $where[] = "e.site_guid = {$site_guid}"; + + if ($container_guid > 0) + $where[] = "e.container_guid = {$container_guid}"; + + if (!$count) { + $query = "SELECT * from {$CONFIG->dbprefix}entities e join {$CONFIG->dbprefix}objects_entity o on e.guid=o.guid where "; + } else { + $query = "SELECT count(e.guid) as total from {$CONFIG->dbprefix}entities e join {$CONFIG->dbprefix}objects_entity o on e.guid=o.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 all the entities from metadata from a group. + * + * @param int $group_guid The ID of the group. + * @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) + */ + function get_entities_from_metadata_groups($group_guid, $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"; + $order_by = sanitise_string($order_by); + $site_guid = (int) $site_guid; + if (is_array($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; + + $container_guid = (int)$group_guid; + if ($container_guid == 0) + $container_guid = page_owner(); + + //$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 ($container_guid > 0) + $where[] = "e.container_guid = {$container_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(e.guid) as total "; + } + + $query .= "from {$CONFIG->dbprefix}entities e JOIN {$CONFIG->dbprefix}metadata m on e.guid = m.entity_guid join {$CONFIG->dbprefix}objects_entity o on e.guid = o.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 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; + } + + /** + * As get_entities_from_metadata_groups() but with multiple entities. + * + * @param int $group_guid The ID of the group. + * @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) + * @return int|array List of ElggEntities, or the total number if count is set to false + */ + function get_entities_from_metadata_groups_multi($group_guid, $meta_array, $entity_type = "", $entity_subtype = "", $owner_guid = 0, $limit = 10, $offset = 0, $order_by = "", $site_guid = 0, $count = false) + { + global $CONFIG; + + if (!is_array($meta_array) || sizeof($meta_array) == 0) { + return false; + } + + $where = array(); + + $mindex = 1; + $join = ""; + 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 join {$CONFIG->dbprefix}objects_entity o on e.guid = o.guid "; + if ($meta_name!="") + $where[] = "m{$mindex}.name_id='$meta_n'"; + if ($meta_value!="") + $where[] = "m{$mindex}.value_id='$meta_v'"; + $mindex++; + } + + $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); + $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 ($owner_guid > 0) + $where[] = "e.owner_guid = {$owner_guid}"; + if ($container_guid > 0) + $where[] = "e.container_guid = {$container_guid}"; + + if ($count) { + $query = "SELECT count(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 + + 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; + } + + /** + * Return a list of this group's members. + * + * @param int $group_guid The ID of the container/group. + * @param int $limit The limit + * @param int $offset The offset + * @param int $site_guid The site + * @param bool $count Return the users (false) or the count of them (true) + * @return mixed + */ + function get_group_members($group_guid, $limit = 10, $offset = 0, $site_guid = 0, $count = false) { - trigger_elgg_event('leave','group',array('group' => get_entity($group_guid), 'user' => get_entity($user_guid))); - return remove_entity_relationship($user_guid, 'member', $group_guid); - } - - /** - * Return all groups a user is a member of. - * - * @param unknown_type $user_guid - */ - function get_users_membership($user_guid) - { - return get_entities_from_relationship('member', $user_guid, false); + return get_entities_from_relationship('member', $group_guid, true, 'user', '', 0, "", $limit, $offset, $count, $site_guid); + } + + /** + * Return whether a given user is a member of the group or not. + * + * @param int $group_guid The group ID + * @param int $user_guid The user guid + * @return bool + */ + function is_group_member($group_guid, $user_guid) + { + return check_entity_relationship($user_guid, 'member', $group_guid); + } + + /** + * Join a user to a group. + * + * @param int $group_guid The group. + * @param int $user_guid The user. + */ + function join_group($group_guid, $user_guid) + { + trigger_elgg_event('join','group',array('group' => get_entity($group_guid), 'user' => get_entity($user_guid))); + return add_entity_relationship($user_guid, 'member', $group_guid); + } + + /** + * Remove a user from a group. + * + * @param int $group_guid The group. + * @param int $user_guid The user. + */ + function leave_group($group_guid, $user_guid) + { + trigger_elgg_event('leave','group',array('group' => get_entity($group_guid), 'user' => get_entity($user_guid))); + return remove_entity_relationship($user_guid, 'member', $group_guid); + } + + /** + * Return all groups a user is a member of. + * + * @param unknown_type $user_guid + */ + function get_users_membership($user_guid) + { + return get_entities_from_relationship('member', $user_guid, false); } /** @@ -801,6 +801,6 @@ register_entity_type('group',''); } - register_elgg_event_handler('init','system','group_init'); - + register_elgg_event_handler('init','system','group_init'); + ?> \ No newline at end of file diff --git a/engine/lib/metadata.php b/engine/lib/metadata.php index 8a77b69fb..fae3e292b 100644 --- a/engine/lib/metadata.php +++ b/engine/lib/metadata.php @@ -1,72 +1,72 @@ - - * @copyright Curverider Ltd 2008-2009 - * @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; + + * @copyright Curverider Ltd 2008-2009 + * @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); + $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); } /** @@ -81,87 +81,87 @@ } 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); } + } + + /** + * 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); } - - /** - * 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; + + + /** + * 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")); - } + $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 $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 */ @@ -169,12 +169,12 @@ 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); + $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) @@ -184,333 +184,333 @@ 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 = 0, $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); - } - } - + + /** + * 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; - + } + + 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 (!$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); + + //$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 = 0, $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; - + + // 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); - - // 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()) - return delete_data("DELETE from {$CONFIG->dbprefix}metadata where id=$id"); - - } - - /** - * 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; + $metadata = get_metadata($id); + + // 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()) + return delete_data("DELETE from {$CONFIG->dbprefix}metadata where id=$id"); + + } + + /** + * 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}"); + $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; + $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); + $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; + + $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 "; + 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 + $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; + * @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"; + if ($order_by == "") $order_by = "e.time_created desc"; $order_by = sanitise_string($order_by); $site_guid = (int) $site_guid; if ((is_array($owner_guid) && (count($owner_guid)))) { @@ -521,47 +521,47 @@ $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!="") + $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}"; + $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 .= "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 + 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 false; } /** @@ -659,12 +659,12 @@ $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++; + $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) { @@ -703,50 +703,50 @@ 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; + } + + /** + * 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()) + if ($entity->canEdit()) return delete_data("DELETE from {$CONFIG->dbprefix}metadata where entity_guid={$entity_guid}"); } - return false; - } - - /** - * 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; - } + return false; + } + + /** + * 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 @@ -757,9 +757,9 @@ function string_to_tag_array($string) { if (is_string($string)) { - $ar = explode(",",$string); - $ar = array_map('trim', $ar); // trim blank spaces - $ar = array_map('strtolower', $ar); // make lower case + $ar = explode(",",$string); + $ar = array_map('trim', $ar); // trim blank spaces + $ar = array_map('strtolower', $ar); // make lower case $ar = array_filter($ar, 'is_not_null'); // Remove null values return $ar; } @@ -785,21 +785,21 @@ 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; + } + + /** + * 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; } /** @@ -848,21 +848,21 @@ } } 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") { + } + + /** + * 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 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'); - + ?> \ No newline at end of file diff --git a/engine/lib/plugins.php b/engine/lib/plugins.php index 3ba31b521..a38f159cc 100644 --- a/engine/lib/plugins.php +++ b/engine/lib/plugins.php @@ -11,77 +11,77 @@ * @copyright Curverider Ltd 2008-2009 * @link http://elgg.org/ */ - - - /// Cache enabled plugins per page + + + /// 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; - } + + /** + * 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; + } } /** @@ -201,22 +201,22 @@ 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 + * @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)) { - - // temporary disable all plugins if there is a file called 'disabled' in the plugin dir - if (file_exists($CONFIG->pluginspath . "disabled")) + if (!empty($CONFIG->pluginspath)) { + + // 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(); @@ -281,255 +281,255 @@ } } 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; - } - - /** - * 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'); - $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 = 2; - $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)) { + } + + /** + * 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; + } + + /** + * 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'); + $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(); @@ -538,140 +538,140 @@ $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) - * - * @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; - - $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); - - return $return; - } - - /** - * Disable a plugin for a site (default current site) - * - * @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; - - $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); - - 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; - } + + } + + return $installed_plugins; + } - /** - * 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 + /** + * Enable a plugin for a site (default current site) + * + * @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; + + $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); + + return $return; + } + + /** + * Disable a plugin for a site (default current site) + * + * @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; + + $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); + + 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/reorder', false, "", true); // Disable - - } - - // Register a startup event + + } + + // Register a startup event register_elgg_event_handler('init','system','plugin_init'); ?> \ No newline at end of file diff --git a/engine/lib/system_log.php b/engine/lib/system_log.php index fa4117dbd..b500c573b 100644 --- a/engine/lib/system_log.php +++ b/engine/lib/system_log.php @@ -1,115 +1,115 @@ - 0) { foreach($by_user as $key => $val) { $by_user[$key] = (int) $val; } - } else { + } else { $by_user = (int)$by_user; - } - $event = sanitise_string($event); - $class = sanitise_string($class); - $type = sanitise_string($type); - $subtype = sanitise_string($subtype); - $limit = (int)$limit; - $offset = (int)$offset; - - $where = array(); - - if ($by_user_orig!=="") - { - if (is_int($by_user)) { + } + $event = sanitise_string($event); + $class = sanitise_string($class); + $type = sanitise_string($type); + $subtype = sanitise_string($subtype); + $limit = (int)$limit; + $offset = (int)$offset; + + $where = array(); + + if ($by_user_orig!=="") + { + if (is_int($by_user)) { $where[] = "performed_by_guid=$by_user"; } else if (is_array($by_user)) { $where [] = "performed_by_guid in (". implode(",",$by_user) .")"; - } - } - if ($event != "") - $where[] = "event='$event'"; - if ($class!=="") - $where[] = "object_class='$class'"; - if ($type != "") - $where[] = "object_type='$type'"; - if ($subtype!=="") - $where[] = "object_subtype='$subtype'"; + } + } + if ($event != "") + $where[] = "event='$event'"; + if ($class!=="") + $where[] = "object_class='$class'"; + if ($type != "") + $where[] = "object_type='$type'"; + if ($subtype!=="") + $where[] = "object_subtype='$subtype'"; if ($timebefore) $where[] = "time_created < " . ((int) $timebefore); @@ -117,164 +117,164 @@ $where[] = "time_created > " . ((int) $timeafter); if ($object_id) $where[] = "object_id = " . ((int) $object_id); - - $select = "*"; - if ($count) $select = "count(*) as count"; - $query = "SELECT $select from {$CONFIG->dbprefix}system_log where 1 "; - foreach ($where as $w) - $query .= " and $w"; - - if (!$count) - { - $query .= " order by time_created desc"; - $query .= " limit $offset, $limit"; // Add order and limit - } - - if ($count) - { - if ($numrows = get_data_row($query)) - return $numrows->count; - } - else - return get_data($query); - - return false; - } - - /** - * Return a specific log entry. - * - * @param int $entry_id The log entry - */ - function get_log_entry($entry_id) - { - global $CONFIG; - - $entry_id = (int)$entry_id; - - return get_data_row("SELECT * from {$CONFIG->dbprefix}system_log where id=$entry_id"); - } - - /** - * Return the object referred to by a given log entry - * - * @param int $entry_id The log entry - */ - function get_object_from_log_entry($entry_id) - { - $entry = get_log_entry($entry_id); - - if ($entry) - { - $class = $entry->object_class; - $tmp = new $class(); - $object = $tmp->getObjectFromID($entry->object_id); - - if ($object) - return $object; - } - - return false; - } - - /** - * Log a system event related to a specific object. - * - * This is called by the event system and should not be called directly. - * - * @param $object The object you're talking about. - * @param $event String The event being logged - */ - function system_log($object, $event) - { + + $select = "*"; + if ($count) $select = "count(*) as count"; + $query = "SELECT $select from {$CONFIG->dbprefix}system_log where 1 "; + foreach ($where as $w) + $query .= " and $w"; + + if (!$count) + { + $query .= " order by time_created desc"; + $query .= " limit $offset, $limit"; // Add order and limit + } + + if ($count) + { + if ($numrows = get_data_row($query)) + return $numrows->count; + } + else + return get_data($query); + + return false; + } + + /** + * Return a specific log entry. + * + * @param int $entry_id The log entry + */ + function get_log_entry($entry_id) + { + global $CONFIG; + + $entry_id = (int)$entry_id; + + return get_data_row("SELECT * from {$CONFIG->dbprefix}system_log where id=$entry_id"); + } + + /** + * Return the object referred to by a given log entry + * + * @param int $entry_id The log entry + */ + function get_object_from_log_entry($entry_id) + { + $entry = get_log_entry($entry_id); + + if ($entry) + { + $class = $entry->object_class; + $tmp = new $class(); + $object = $tmp->getObjectFromID($entry->object_id); + + if ($object) + return $object; + } + + return false; + } + + /** + * Log a system event related to a specific object. + * + * This is called by the event system and should not be called directly. + * + * @param $object The object you're talking about. + * @param $event String The event being logged + */ + function system_log($object, $event) + { global $CONFIG; - static $logcache; - - if ($object instanceof Loggable) + static $logcache; + + if ($object instanceof Loggable) { if (!is_array($logcache)) $logcache = array(); - - // Has loggable interface, extract the necessary information and store - $object_id = (int)$object->getSystemLogID(); - $object_class = $object->getClassName(); - $object_type = $object->getType(); - $object_subtype = $object->getSubtype(); - $event = sanitise_string($event); - $time = time(); - $performed_by = (int)$_SESSION['guid']; - - if (isset($object->access_id)) - $access_id = $object->access_id; - else - $access_id = 2; - if (isset($object->enabled)) - $enabled = $object->enabled; - else - $enabled = 'yes'; - - if (isset($object->owner_guid)) - $owner_guid = $object->owner_guid; - else - $owner_guid = 0; - + + // Has loggable interface, extract the necessary information and store + $object_id = (int)$object->getSystemLogID(); + $object_class = $object->getClassName(); + $object_type = $object->getType(); + $object_subtype = $object->getSubtype(); + $event = sanitise_string($event); + $time = time(); + $performed_by = (int)$_SESSION['guid']; + + if (isset($object->access_id)) + $access_id = $object->access_id; + else + $access_id = ACCESS_PUBLIC; + if (isset($object->enabled)) + $enabled = $object->enabled; + else + $enabled = 'yes'; + + if (isset($object->owner_guid)) + $owner_guid = $object->owner_guid; + else + $owner_guid = 0; + // Create log if we haven't already created it - if (!isset($logcache[$time][$object_id][$event])) { + if (!isset($logcache[$time][$object_id][$event])) { insert_data("INSERT DELAYED into {$CONFIG->dbprefix}system_log (object_id, object_class, object_type, object_subtype, event, performed_by_guid, owner_guid, access_id, enabled, time_created) VALUES ('$object_id','$object_class','$object_type', '$object_subtype', '$event',$performed_by, $owner_guid, $access_id, '$enabled', '$time')"); - + $logcache[$time][$object_id][$event] = true; } return true; - - } - } - - /** - * This function creates an archive copy of the system log. - * - * @param int $offset An offset in seconds from now to archive (useful for log rotation) - */ - function archive_log($offset = 0) - { - global $CONFIG; - - $offset = (int)$offset; - $now = time(); // Take a snapshot of now - - $ts = $now - $offset; - - // create table - if (!update_data("CREATE TABLE {$CONFIG->dbprefix}system_log_$now as SELECT * from {$CONFIG->dbprefix}system_log WHERE time_created<=$ts")) - return false; - - // alter table to engine - if (!update_data("ALTER TABLE {$CONFIG->dbprefix}system_log_$now engine=archive")) - return false; - - // delete - if (delete_data("DELETE from {$CONFIG->dbprefix}system_log WHERE id in (select id from {$CONFIG->dbprefix}system_log_$now)")===false) // Don't delete on time since we are running in a concurrent environment - return false; - - return true; - } - - /** - * System log listener. - * This function listens to all events in the system and logs anything appropriate. - * - * @param String $event - * @param String $object_type - * @param mixed $object - */ - function system_log_listener($event, $object_type, $object) - { - system_log($object, $event); - - return true; - } - - /** Register event to listen to all events **/ + + } + } + + /** + * This function creates an archive copy of the system log. + * + * @param int $offset An offset in seconds from now to archive (useful for log rotation) + */ + function archive_log($offset = 0) + { + global $CONFIG; + + $offset = (int)$offset; + $now = time(); // Take a snapshot of now + + $ts = $now - $offset; + + // create table + if (!update_data("CREATE TABLE {$CONFIG->dbprefix}system_log_$now as SELECT * from {$CONFIG->dbprefix}system_log WHERE time_created<=$ts")) + return false; + + // alter table to engine + if (!update_data("ALTER TABLE {$CONFIG->dbprefix}system_log_$now engine=archive")) + return false; + + // delete + if (delete_data("DELETE from {$CONFIG->dbprefix}system_log WHERE id in (select id from {$CONFIG->dbprefix}system_log_$now)")===false) // Don't delete on time since we are running in a concurrent environment + return false; + + return true; + } + + /** + * System log listener. + * This function listens to all events in the system and logs anything appropriate. + * + * @param String $event + * @param String $object_type + * @param mixed $object + */ + function system_log_listener($event, $object_type, $object) + { + system_log($object, $event); + + return true; + } + + /** Register event to listen to all events **/ register_elgg_event_handler('all','all','system_log_listener', 400); - + ?> \ No newline at end of file diff --git a/engine/lib/tags.php b/engine/lib/tags.php index 9d87d8b15..ed04f579c 100644 --- a/engine/lib/tags.php +++ b/engine/lib/tags.php @@ -1,68 +1,68 @@ - - * @copyright Curverider Ltd 2008-2009 - * @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; + + * @copyright Curverider Ltd 2008-2009 + * @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; } /** @@ -131,9 +131,9 @@ } else if (is_int($owner_guid)) { $query .= " and e.container_guid = {$owner_guid} "; } - + $userid = get_loggedin_userid(); - $query .= " and (e.access_id in {$access} or (e.access_id = 0 and e.owner_guid = {$userid}))"; + $query .= " and (e.access_id in {$access} or (e.access_id = " . ACCESS_PRIVATE . " and e.owner_guid = {$userid}))"; $query .= " group by msvalue.string having total > {$threshold} order by total desc limit {$limit} "; @@ -159,5 +159,5 @@ 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/users.php b/engine/lib/users.php index baf3b5950..adbea4ede 100644 --- a/engine/lib/users.php +++ b/engine/lib/users.php @@ -46,7 +46,7 @@ $this->attributes['salt'] = ""; $this->attributes['email'] = ""; $this->attributes['language'] = ""; - $this->attributes['code'] = ""; + $this->attributes['code'] = ""; $this->attributes['banned'] = "no"; $this->attributes['tables_split'] = 2; } @@ -156,25 +156,25 @@ 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 - */ + } + + /** + * 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'; } /** @@ -419,78 +419,78 @@ } 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)) - { - // Add reason - if ($reason) - create_metadata($user_guid, 'ban_reason', $reason,'', 0, 2); - - // 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)) - { - create_metadata($user_guid, 'ban_reason', '','', 0, 2); - return update_data("UPDATE {$CONFIG->dbprefix}users_entity set banned='no' where guid=$user_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)) + { + // 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)) + { + 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; } /** @@ -930,7 +930,7 @@ { // generate code $code = generate_random_cleartext_password(); - //create_metadata($user_guid, 'conf_code', $code,'', 0, 0); + //create_metadata($user_guid, 'conf_code', $code,'', 0, ACCESS_PRIVATE); set_private_setting($user_guid, 'passwd_conf_code', $code); // generate link @@ -1016,8 +1016,8 @@ { if (!$status) $method = ''; - create_metadata($user_guid, 'validated', $status,'', 0, 2); - create_metadata($user_guid, 'validated_method', $method,'', 0, 2); + create_metadata($user_guid, 'validated', $status,'', 0, ACCESS_PUBLIC); + create_metadata($user_guid, 'validated_method', $method,'', 0, ACCESS_PUBLIC); return true; } @@ -1225,7 +1225,7 @@ $user->username = $username; $user->email = $email; $user->name = $name; - $user->access_id = 2; + $user->access_id = ACCESS_PUBLIC; $user->salt = generate_random_cleartext_password(); // Note salt generated before password! $user->password = generate_user_password($user, $password); $user->save(); diff --git a/engine/lib/widgets.php b/engine/lib/widgets.php index 5f9d8969f..2660cc240 100644 --- a/engine/lib/widgets.php +++ b/engine/lib/widgets.php @@ -9,59 +9,59 @@ * @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU Public License version 2 * @copyright Curverider Ltd 2008-2009 * @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; - } + */ + + /** + * 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; + } } /** @@ -171,15 +171,15 @@ * @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, + + 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(); @@ -230,11 +230,11 @@ if ($user = get_user($user_guid)) { - $widget = new ElggWidget; - $widget->owner_guid = $user_guid; - $widget->access_id = 1; - if (!$widget->save()) - return false; + $widget = new ElggWidget; + $widget->owner_guid = $user_guid; + $widget->access_id = ACCESS_LOGGED_IN; + if (!$widget->save()) + return false; $widget->handler = $handler; $widget->context = $context; @@ -355,19 +355,19 @@ $handler = $widget->handler; if (empty($handler) || !widget_type_exists($handler)) return false; - if (!$widget->canEdit()) 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) { + 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); + ))) { + if (is_array($value)) + { + // TODO: Handle arrays securely + $widget->setMetaData($name, $value, "", true); }else $widget->$name = $value; } @@ -486,16 +486,16 @@ return $return; } - - /** - * Run some things once. - * - */ - function widget_run_once() - { - // Register a class - add_subtype("object", "widget", "ElggWidget"); - } + + /** + * Run some things once. + * + */ + function widget_run_once() + { + // Register a class + add_subtype("object", "widget", "ElggWidget"); + } /** * Function to initialise widgets functionality on Elgg init @@ -506,8 +506,8 @@ register_action('widgets/reorder'); register_action('widgets/save'); register_action('widgets/add'); - - // Now run this stuff, but only once + + // Now run this stuff, but only once run_function_once("widget_run_once"); } -- cgit v1.2.3