/** * Returns prototyped fields * * @param string $hook "prototype" * @param string $type "groups/edit" * @param array $return Fields * @param array $params Hook params * @return array */ function prototyper_group_get_prototype_fields($hook, $type, $return, $params) { $entity = elgg_extract('entity', $params); $subtype = $entity->getSubtype() ?: 'default'; $prototype = elgg_get_plugin_setting("prototype:{$subtype}", 'prototyper_group'); if (!$prototype && $subtype != 'default') { $prototype = elgg_get_plugin_setting('prototype:default', 'prototyper_group'); } if ($prototype) { $prototype_fields = unserialize($prototype); $return = array_merge($return, $prototype_fields); } else { $fields = elgg_get_config('group'); $return['icon'] = ['type' => 'icon', 'data_type' => 'file', 'label' => [get_current_language() => elgg_echo('groups:icon')], 'help' => false]; $return['description'] = ['type' => 'description', 'data_type' => 'attribute', 'label' => [get_current_language() => elgg_echo('groups:description')], 'help' => false]; foreach ($fields as $shortname => $input_type) { $return[$shortname] = ['type' => $input_type, 'data_type' => 'metadata', 'label' => [get_current_language() => elgg_echo("groups:{$shortname}")], 'help' => false]; } } // Not adding these above, as we want them to persist, even if they are deleted from the UI $return['name'] = ['type' => 'name', 'data_type' => 'attribute', 'class_name' => \hypeJunction\Prototyper\Groups\NameField::class, 'label' => [get_current_language() => elgg_echo('groups:name')], 'help' => false, 'priority' => 1]; $return['membership'] = ['type' => 'membership', 'data_type' => 'metadata', 'id' => 'groups-membership', 'input_view' => 'input/groups/membership', 'output_view' => false, 'class_name' => hypeJunction\Prototyper\Groups\MembershipField::class, 'label' => [get_current_language() => elgg_echo("groups:membership")], 'help' => false, 'priority' => 900]; // treating this as metadata so that it gets handled after the entity has been saved once and group_acl has been created $return['vis'] = ['type' => 'access', 'data_type' => 'metadata', 'id' => 'groups-vis', 'input_view' => 'input/groups/visibility', 'output_view' => false, 'class_name' => hypeJunction\Prototyper\Groups\VisibilityField::class, 'label' => [get_current_language() => elgg_echo("groups:visibility")], 'help' => false, 'priority' => 900]; $return['content_access_mode'] = ['type' => 'content_access_mode', 'data_type' => 'metadata', 'id' => 'groups-content-access-mode', 'input_view' => 'input/groups/content_access_mode', 'output_view' => false, 'class_name' => hypeJunction\Prototyper\Groups\ContentAccessModeField::class, 'label' => [get_current_language() => elgg_echo("groups:content_access_mode")], 'help' => false, 'priority' => 900]; $return['owner_guid'] = ['type' => 'select', 'data_type' => 'attribute', 'input_view' => 'input/groups/owner', 'output_view' => false, 'class_name' => hypeJunction\Prototyper\Groups\OwnerField::class, 'label' => [get_current_language() => elgg_echo("groups:owner")], 'help' => false, 'priority' => 900]; $return['tools'] = ['type' => 'checkboxes', 'data_type' => 'metadata', 'input_view' => 'input/groups/tools', 'output_view' => false, 'class_name' => hypeJunction\Prototyper\Groups\ToolsField::class, 'label' => false, 'help' => false, 'priority' => 900]; return $return; }
/** * Clean unvalidated users cron hook */ function clean_unvalidate($vars) { $days_till_first_reminder = elgg_get_plugin_setting("validation_reminder_first_message") * 1; $days_till_second_reminder = elgg_get_plugin_setting("validation_reminder_second_message") * 1; $days_till_removal = elgg_get_plugin_setting("validation_reminder_remove") * 1; $proviousAccessShowHiddenEntities = access_show_hidden_entities(true); $proviousIgnoreAccess = elgg_set_ignore_access(true); $dbprefix = elgg_get_config('dbprefix'); // @var $users ElggUser[] $users = elgg_get_entities_from_metadata(['type' => 'user', 'limit' => false, 'metadata_name_value_pair' => array(array('name' => 'validated', 'value' => false))]); foreach ($users as $user) { $validate_reminder_start_date = $user->time_created; if (time() - $validate_reminder_start_date >= $days_till_removal * 24 * 60 * 60) { $user->delete(); echo 'Account deleted'; } else { if (time() - $validate_reminder_start_date >= $days_till_second_reminder * 24 * 60 * 60 && time() - $validate_reminder_start_date <= ($days_till_second_reminder + 1) * 24 * 60 * 60) { send_validation_reminder_mail($user, $days_till_removal, $days_till_second_reminder); echo 'Send second reminder send'; } else { if (time() - $validate_reminder_start_date >= $days_till_first_reminder * 24 * 60 * 60 && time() - $validate_reminder_start_date <= ($days_till_first_reminder + 1) * 24 * 60 * 60) { send_validation_reminder_mail($user, $days_till_removal, $days_till_first_reminder); echo 'Send first reminder send'; } else { echo 'Waiting for validation'; } } } echo ' for user: '******'<br>'; } elgg_set_ignore_access($proviousIgnoreAccess); access_show_hidden_entities($proviousAccessShowHiddenEntities); }
/** * * Returns array of people containing entity, mutuals (friends), groups (shared) and priority * @param Int $guid * @param Int $friends_limit * @param Int $groups_limit * @return Array */ function get_suggestions($guid, $friends_of_friends_limit = 10, $groups_members_limit = 10) { $dbprefix = elgg_get_config('dbprefix'); $guid = sanitize_int($guid); $suggestions = array(); if ($friends_of_friends_limit) { // get some friends of friends $options = array('selects' => array('COUNT(fof.guid_two) as priority'), 'type' => 'user', 'joins' => array("JOIN {$dbprefix}users_entity ue ON ue.guid = e.guid", "JOIN {$dbprefix}entity_relationships fr ON fr.guid_one = {$guid} AND fr.relationship = 'friend'", "JOIN {$dbprefix}entity_relationships fof ON fof.guid_one = fr.guid_two AND fof.relationship = 'friend'"), "wheres" => array("ue.banned = 'no'", "e.guid NOT IN (SELECT f.guid_two FROM {$dbprefix}entity_relationships f WHERE f.guid_one = {$guid} AND f.relationship = 'friend')", "fof.guid_two = e.guid", "e.guid != {$guid}"), 'group_by' => 'e.guid', 'order_by' => 'priority desc, ue.last_action desc', 'limit' => abs((int) $friends_of_friends_limit)); $fof = elgg_get_entities($options); foreach ($fof as $f) { $priority = (int) $f->getVolatileData('select:priority'); $suggestions[$f->guid] = array('entity' => $f, 'mutuals' => $priority, 'groups' => 0, 'priority' => $priority); } } if ($groups_members_limit) { // get some mutual group members $options = array('selects' => array('COUNT(mog.guid_two) as priority'), 'type' => 'user', 'joins' => array("JOIN {$dbprefix}users_entity ue ON ue.guid = e.guid", "JOIN {$dbprefix}entity_relationships g ON g.guid_one = {$guid} AND g.relationship = 'member'", "JOIN {$dbprefix}groups_entity ge ON ge.guid = g.guid_two", "JOIN {$dbprefix}entity_relationships mog ON mog.guid_two = g.guid_two AND mog.relationship = 'member'"), "wheres" => array("ue.banned = 'no'", "e.guid NOT IN (SELECT f.guid_two FROM {$dbprefix}entity_relationships f WHERE f.guid_one = {$guid} AND f.relationship = 'friend')", "mog.guid_one = e.guid", "e.guid != {$guid}"), 'group_by' => 'e.guid', 'order_by' => 'priority desc, ue.last_action desc', 'limit' => 3); // get members of groups $mog = elgg_get_entities($options); foreach ($mog as $m) { if (!isset($suggestions[$m->guid])) { $priority = (int) $m->getVolatileData('select:priority'); $suggestions[$m->guid] = array('entity' => $m, 'mutuals' => 0, 'groups' => $priority, 'priority' => $priority); } else { $priority = (int) $m->getVolatileData('select:priority'); $suggestions[$m->guid]['groups'] = $priority; $suggestions[$m->guid]['priority'] += $priority; } } } // sort by priority usort($suggestions, __NAMESPACE__ . '\\suggested_friends_sorter'); return $suggestions; }
/** * hook called on route, all * check if $returnvalue['handler'] to see if we need to replace it * if the handler is an original handler, we want to foward it to the new url * * @param type $hook * @param type $type * @param type $returnvalue * @param type $params * @return array */ function router($hook, $type, $returnvalue, $params) { if (elgg_get_config('pagehandler_hijack')) { return $returnvalue; } $handlers = get_replacement_handlers(); if (in_array($returnvalue['handler'], array_keys($handlers))) { // we have been given an old handler -> we should forward to the replacement // probably from an old link or something $currenturl = current_page_url(); //get everything after the pagehandler $afterhandler = str_replace(elgg_get_site_url() . $returnvalue['handler'], "", $currenturl); $newurl = elgg_get_site_url() . $handlers[$returnvalue['handler']] . $afterhandler; // forward to the new url forward($newurl); } if (in_array($returnvalue['handler'], $handlers)) { // we need to do something about it // get the original handler $original = array_search($returnvalue['handler'], $handlers); if (!empty($original)) { // reset the context for non-hijack aware code elgg_set_context($original); // let the system load content for the original handler $returnvalue['handler'] = $original; $returnvalue['identifier'] = $original; // set a flag so we don't infinite loop ourselves in route hooks elgg_set_config('pagehandler_hijack', true); return elgg_trigger_plugin_hook('route', $original, null, $returnvalue); } } }
/** * Clean up operations on calendar delete * * @param string $event "delete" * @param string $type "object" * @param ElggEntity $entity Entity being deleted */ function delete_event_handler($event, $type, $entity) { if ($entity instanceof Calendar) { // Do not allow users to delete publi calendars if ($entity->isPublicCalendar() && !elgg_is_admin_logged_in()) { register_error(elgg_echo('events:error:public_calendar_delete')); return false; } // Move all orphaned events to the public calendar $owner = $entity->getContainerEntity(); $public_calendar = Calendar::getPublicCalendar($owner); if (!$public_calendar) { register_error(elgg_echo('events:error:no_public_for_orphans')); return false; } $dbprefix = elgg_get_config('dbprefix'); $relationship_name = sanitize_string(Calendar::EVENT_CALENDAR_RELATIONSHIP); $calendar_subtype_id = (int) get_subtype_id('object', Calendar::SUBTYPE); // Get all events that do not appear on container's other calendars $events = new ElggBatch('elgg_get_entities_from_relationship', array('types' => 'object', 'subtypes' => Event::SUBTYPE, 'relationship' => Calendar::EVENT_CALENDAR_RELATIONSHIP, 'relationship_guid' => $entity->guid, 'inverse_relationship' => true, 'limit' => 0, 'wheres' => array("NOT EXISTS(SELECT * FROM {$dbprefix}entity_relationships er2\n\t\t\t\t\tJOIN {$dbprefix}entities e2 ON er2.guid_two = e2.guid\n\t\t\t\t\tWHERE er2.relationship = '{$relationship_name}'\n\t\t\t\t\t\tAND er2.guid_one = e.guid\n\t\t\t\t\t\tAND er2.guid_two != {$entity->guid}\n\t\t\t\t\t\tAND e2.container_guid = {$entity->container_guid}\n\t\t\t\t\t\tAND e2.type = 'object' AND e2.subtype = {$calendar_subtype_id})"))); foreach ($events as $event) { /* @var Event $event */ $public_calendar->addEvent($event); } } return true; }
function DeleteConsumerTool($consumer_tool) { // Delete Tool from the DB $sql = "DELETE FROM " . elgg_get_config('dbprefix') . "lti_consumer "; $sql .= "WHERE consumer_guid = '" . $consumer_tool->guid . "'"; return mysql_query($sql); }
/** * Filter profile fields by blacklist */ function community_spam_profile_blacklist() { $blacklist = elgg_get_plugin_setting('profile_blacklist', 'community_spam_tools'); $blacklist = explode(",", $blacklist); $blacklist = array_map('trim', $blacklist); foreach ($_REQUEST as $key => $value) { if (is_string($value)) { foreach ($blacklist as $word) { if (stripos($value, $word) !== false) { ban_user(elgg_get_logged_in_user_guid(), "used '{$word}' on profile"); $user->automated_ban = true; return false; } } } } // if the email address is a phrase, block $profile_fields = elgg_get_config('profile_fields'); foreach ($profile_fields as $name => $type) { if ($type == 'email') { $value = get_input($name); if ($value && substr_count($value, ' ') > 1) { ban_user(elgg_get_logged_in_user_guid(), "Used multiple spaces in email field."); $user->automated_ban = true; return false; } } } }
/** * Add query specs for a relationship data row * * @param stdClass $row Data row * @return void */ public function addQuerySpecs(stdClass $row) { $this->clearQuerySpecs($row->id); $dbprefix = elgg_get_config('dbprefix'); // Insert a new relationship $sql = "\n\t\t\tINSERT INTO {$dbprefix}entity_relationships\n\t\t\t (guid_one, relationship, guid_two, time_created)\n\t\t\tVALUES (:guid1, :relationship, :guid2, :time)\n\t\t\t\tON DUPLICATE KEY UPDATE time_created = :time\n\t\t"; $this->query_specs[$row->id][] = $this->db->addQuerySpec(['sql' => $sql, 'params' => [':guid1' => $row->guid_one, ':guid2' => $row->guid_two, ':relationship' => $row->relationship, ':time' => $row->time_created], 'insert_id' => $row->id]); // Get relationship by its ID $sql = "\n\t\t\tSELECT * FROM {$dbprefix}entity_relationships\n\t\t\tWHERE id = :id\n\t\t"; $this->query_specs[$row->id][] = $this->db->addQuerySpec(['sql' => $sql, 'params' => [':id' => (int) $row->id], 'results' => function () use($row) { if (isset($this->rows[$row->id])) { return [$this->rows[$row->id]]; } return []; }]); // Delete relationship by its ID $sql = "\n\t\t\tDELETE FROM {$dbprefix}entity_relationships\n\t\t\tWHERE id = :id\n\t\t"; $this->query_specs[$row->id][] = $this->db->addQuerySpec(['sql' => $sql, 'params' => [':id' => (int) $row->id], 'results' => function () use($row) { if (isset($this->rows[$row->id])) { $this->clearQuerySpecs($row->id); unset($this->rows[$row->id]); return [$row->id]; } return []; }, 'times' => 1]); // Check relationship between two GUIDs $sql = "\n\t\t\tSELECT * FROM {$dbprefix}entity_relationships\n\t\t\tWHERE guid_one = :guid1\n\t\t\t AND relationship = :relationship\n\t\t\t AND guid_two = :guid2\n\t\t\tLIMIT 1\n\t\t"; $this->query_specs[$row->id][] = $this->db->addQuerySpec(['sql' => $sql, 'params' => [':guid1' => (int) $row->guid_one, ':guid2' => (int) $row->guid_two, ':relationship' => $row->relationship], 'results' => function () use($row) { if (isset($this->rows[$row->id])) { return [$this->rows[$row->id]]; } return []; }]); }
/** * @TODO - is there a way we can target them directly instead of iterating through all? * * @param type $h * @param type $t * @param type $r * @param type $p * @return type */ function weekly_cron($h, $t, $r, $p) { $ia = elgg_set_ignore_access(true); // check for abandoned acls $dbprefix = elgg_get_config('dbprefix'); // try to make this as light as possible $options = array('type' => 'object', 'subtype' => 'granular_access', 'limit' => false); $batch = new ElggBatch('elgg_get_entities', $options); foreach ($batch as $b) { $sql = "SELECT COUNT(guid) as total FROM {$dbprefix}entities WHERE access_id = {$b->acl_id}"; $result = get_data($sql); if ($result[0]->total) { continue; } $sql = "SELECT COUNT(id) as total FROM {$dbprefix}metadata WHERE access_id = {$b->acl_id}"; $result = get_data($sql); if ($result[0]->total) { continue; } $sql = "SELECT COUNT(id) as total FROM {$dbprefix}annotations WHERE access_id = {$b->acl_id}"; $result = get_data($sql); if ($result[0]->total) { continue; } // this appears to be orphaned delete_access_collection($b->acl_id); $b->delete(); } elgg_set_ignore_access($ia); return $r; }
/** * External pages page handler * * @param array $page URL segements * @param string $handler Handler identifier * @return bool */ function expages_page_handler($page, $handler) { if ($handler == 'expages') { expages_url_forwarder($page[1]); } $type = strtolower($handler); $title = elgg_echo("expages:{$type}"); $header = elgg_view_title($title); $object = elgg_get_entities(array('type' => 'object', 'subtype' => $type, 'limit' => 1)); if ($object) { $content .= elgg_view('output/longtext', array('value' => $object[0]->description)); } else { $content .= elgg_echo("expages:notset"); } $content = elgg_view('expages/wrapper', array('content' => $content)); if (elgg_is_admin_logged_in()) { elgg_register_menu_item('title', array('name' => 'edit', 'text' => elgg_echo('edit'), 'href' => "admin/appearance/expages?type={$type}", 'link_class' => 'elgg-button elgg-button-action')); } if (elgg_is_logged_in() || !elgg_get_config('walled_garden')) { $body = elgg_view_layout('one_column', array('title' => $title, 'content' => $content)); echo elgg_view_page($title, $body); } else { elgg_load_css('elgg.walled_garden'); $body = elgg_view_layout('walled_garden', array('content' => $header . $content)); echo elgg_view_page($title, $body, 'walled_garden'); } return true; }
function search_by_proximity_hook($hook, $type, $return, $params) { $query = $params['query']; $coords = elgg_geocode_location($query); if (!$coords) { return $return; } $registered_entities = elgg_get_config('registered_entities'); $options = array('types' => array('object', 'user', 'group'), 'subtypes' => array_merge($registered_entities['object'], $registered_entities['user'], $registered_entities['group']), 'limit' => get_input('limit', 20), 'offset' => get_input('proximity_offset', 0), 'offset_key' => 'proximity_offset', 'count' => true); $options = add_order_by_proximity_clauses($options, $coords['lat'], $coords['long']); $options = add_distance_constraint_clauses($options, $coords['lat'], $coords['long'], SEARCH_RADIUS); $count = elgg_get_entities($options); if ($count) { $options['count'] = false; $entities = elgg_get_entities($options); } if ($entities) { foreach ($entities as $entity) { $name = search_get_highlighted_relevant_substrings(isset($entity->name) ? $entity->name : $entity->title, $query); $entity->setVolatileData('search_matched_title', $name); $location = search_get_highlighted_relevant_substrings($entity->getLocation(), $query); $entity->setVolatileData('search_matched_location', $location); $distance = get_distance($entity->getLatitude(), $entity->getLongitude(), $coords['lat'], $coords['long']); // distance in metres $distance = round($distance / 1000, 2); // distance in km $distance_str = elgg_echo('geo:search:proximity', array($query, $distance)); $entity->setVolatileData('search_proximity', $distance_str); } } return array('entities' => $entities, 'count' => $count); }
/** * Custom clauses for forum keyword search */ function hj_forum_filter_forum_list($hook, $type, $options, $params) { if (!is_array($options['subtypes'])) { if (isset($options['subtype'])) { $options['subtypes'] = array($options['subtype']); unset($options['subtype']); } elseif (isset($options['subtypes'])) { $options['subtypes'] = array($options['subtypes']); } else { return $options; } } if (!in_array('hjforum', $options['subtypes']) && !in_array('hjforumtopic', $options['subtypes'])) { return $options; } $query = get_input("__q", false); if (!$query || empty($query)) { return $options; } $query = sanitise_string(urldecode($query)); $dbprefix = elgg_get_config('dbprefix'); $options['joins'][] = "JOIN {$dbprefix}objects_entity oe_q ON e.guid = oe_q.guid"; $options['wheres'][] = "MATCH(oe_q.title, oe_q.description) AGAINST ('{$query}')"; return $options; }
/** * Checks if cached menu html is available and returns the html if it is available * * @return boolean|string */ public function getCachedData() { if (!elgg_get_config('system_cache_enabled')) { return false; } return elgg_load_system_cache($this->getCacheName()) ?: false; }
/** * Get users with a few more options * * domain => Match the last part of the email address * only_banned => Only return banned users * enqueued => include|exclude|only users enqueued to be deleted (default = exclude, other values = doesn't matter) * * @param array $sent Options */ function bulk_user_admin_get_users(array $sent) { $db_prefix = elgg_get_config('dbprefix'); $defaults = ['type' => 'user', 'domain' => false, 'only_banned' => false, 'enqueued' => 'exclude']; $options = array_merge($defaults, $sent); if (!is_array($options['wheres'])) { $options['wheres'] = []; } if (!is_array($options['joins'])) { $options['joins'] = []; } // sometimes ue is joined, sometimes it's not... // use our own join to make sure. $options['joins'][] = "JOIN {$db_prefix}users_entity bua_ue on e.guid = bua_ue.guid"; if ($options['domain']) { $options['wheres'][] = "bua_ue.email LIKE '%@%{$options['domain']}'"; } if ($options['only_banned']) { $options['wheres'][] = "bua_ue.banned = 'yes'"; } switch ($options['enqueued']) { case 'include': // no-op break; case 'only': $options['metadata_name'] = \BulkUserAdmin\DeleteService::PENDING_DELETE_MD; break; case 'exclude': default: $options['wheres'][] = bulk_user_admin_get_sql_where_not_enqueued(); break; } return elgg_get_entities_from_metadata($options); }
public function testCanGetEntitiesByAnnotationCreationTime() { $prefix = elgg_get_config('dbprefix'); $users = elgg_get_entities(array('type' => 'user', 'limit' => 1)); // create some test annotations $subtypes = $this->getRandomValidSubtypes(array('object'), 1); $subtype = $subtypes[0]; $annotation_name = 'test_annotation_name_' . rand(); // our targets $valid1 = new \ElggObject(); $valid1->subtype = $subtype; $valid1->save(); $id1 = $valid1->annotate($annotation_name, 1, ACCESS_PUBLIC, $users[0]->guid); // this one earlier $yesterday = time() - 86400; update_data("\n\t\t\tUPDATE {$prefix}annotations\n\t\t\tSET time_created = {$yesterday}\n\t\t\tWHERE id = {$id1}\n\t\t"); $valid2 = new \ElggObject(); $valid2->subtype = $subtype; $valid2->save(); $valid2->annotate($annotation_name, 1, ACCESS_PUBLIC, $users[0]->guid); $options = array('annotation_owner_guid' => $users[0]->guid, 'annotation_created_time_lower' => time() - 3600, 'annotation_name' => $annotation_name); $entities = elgg_get_entities_from_annotations($options); $this->assertEqual(1, count($entities)); $this->assertEqual($valid2->guid, $entities[0]->guid); $options = array('annotation_owner_guid' => $users[0]->guid, 'annotation_created_time_upper' => time() - 3600, 'annotation_name' => $annotation_name); $entities = elgg_get_entities_from_annotations($options); $this->assertEqual(1, count($entities)); $this->assertEqual($valid1->guid, $entities[0]->guid); $valid1->delete(); $valid2->delete(); }
/** * Cleanup the cached inline images * * @param string $hook the name of the hook * @param string $type the type of the hook * @param mixed $return current return value * @param array $params supplied params * * @return mixed */ function html_email_handler_daily_cron_hook($hook, $type, $return, $params) { if (empty($params) || !is_array($params)) { return $return; } $cache_dir = elgg_get_config("dataroot") . "html_email_handler/image_cache/"; if (!is_dir($cache_dir)) { return $return; } $dh = opendir($cache_dir); if (empty($dh)) { return $return; } $max_lifetime = elgg_extract("time", $params, time()) - 24 * 60 * 60; while (($filename = readdir($dh)) !== false) { // make sure we have a file if (!is_file($cache_dir . $filename)) { continue; } $modified_time = filemtime($cache_dir . $filename); if ($modified_time > $max_lifetime) { continue; } // file is past lifetime, so cleanup unlink($cache_dir . $filename); } closedir($dh); return $return; }
/** * Logs the notification sent * * @param string $hook "send" * @param string $type "all" * @param mixed $return Result * @param array $params Hook params * @return mixed */ function notifications_log_sent_message($hook, $type, $return, $params) { list($hook_type, $method) = explode(':', $type); if ($hook_type != 'notification') { return; } $notification = elgg_extract('notification', $params); $recipient = $notification->getRecipient(); $sender = $notification->getSender(); $content = array('status' => $return === false ? 'failed' : 'sent', 'subject' => $notification->subject, 'summary' => $notification->summary, 'body' => $notification->body); $description = 'instant'; $event = elgg_extract('event', $params); if ($event) { $action = $event->getAction(); $actor = $event->getActor(); $object = $event->getObject(); $event_data = array('action' => $action, 'object' => is_callable(array($object, 'toObject')) ? $object->toObject() : array('guid' => $object->guid, 'id' => $object->id), 'actor' => is_callable(array($actor, 'toObject')) ? $actor->toObject() : array('guid' => $event->getActorGUID())); $content = array_merge($content, $event_data); $description = str_replace(':', '_', $event->getDescription()); } $name = implode('_', array($method, "TO-{$recipient->guid}", "FROM-{$sender->guid}", $description, time())); $dirname = elgg_get_config('dataroot') . '/notifications_log/'; if (!is_dir($dirname)) { mkdir($dirname, 0700, true); } $filename = "{$dirname}{$name}.json"; file_put_contents($filename, json_encode($content)); }
/** * Returns a list of upgrade files relative to the $upgrade_path dir. * * @param string $upgrade_path The directory that has upgrade scripts * @return array|false * @access private * * @todo the wire and groups plugins and the installer are using this */ function elgg_get_upgrade_files($upgrade_path = null) { if (!$upgrade_path) { $upgrade_path = elgg_get_config('path') . 'engine/lib/upgrades/'; } $upgrade_path = sanitise_filepath($upgrade_path); $handle = opendir($upgrade_path); if (!$handle) { return false; } $upgrade_files = array(); while ($upgrade_file = readdir($handle)) { // make sure this is a well formed upgrade. if (is_dir($upgrade_path . '$upgrade_file')) { continue; } $upgrade_version = elgg_get_upgrade_file_version($upgrade_file); if (!$upgrade_version) { continue; } $upgrade_files[] = $upgrade_file; } sort($upgrade_files); return $upgrade_files; }
function fix_orientation($source, $name) { $imginfo = getimagesize($source); $requiredMemory1 = ceil($imginfo[0] * $imginfo[1] * 5.35); $requiredMemory2 = ceil($imginfo[0] * $imginfo[1] * ($imginfo['bits'] / 8) * $imginfo['channels'] * 2.5); $requiredMemory = (int) max($requiredMemory1, $requiredMemory2); $mem_avail = elgg_get_ini_setting_in_bytes('memory_limit'); $mem_used = memory_get_usage(); $mem_avail = $mem_avail - $mem_used - 2097152; // 2 MB buffer if ($requiredMemory > $mem_avail) { // we don't have enough memory for any manipulation // @TODO - we should only throw an error if the image needs rotating... //register_error(elgg_echo('image_orientation:toolarge')); return false; } elgg_load_library('imagine'); $name = uniqid() . $name; $tmp_location = elgg_get_config('dataroot') . 'image_orientation/' . $name; //@note - need to copy to a tmp_location as // imagine doesn't like images with no file extension copy($source, $tmp_location); try { $imagine = new Imagine(); $imagine->setMetadataReader(new ExifMetadataReader()); $autorotate = new Autorotate(); $autorotate->apply($imagine->open($tmp_location))->save($tmp_location); copy($tmp_location, $source); unlink($tmp_location); return true; } catch (Imagine\Exception\Exception $exc) { // fail silently, we don't need to rotate it bad enough to kill the script return false; } }
function entity_view_counter_get_configured_entity_types() { static $result; if (!isset($result)) { $result = false; // get registered entity types and plugin setting if (($registered_types = elgg_get_config("registered_entities")) && ($setting = elgg_get_plugin_setting("entity_types", "entity_view_counter"))) { $setting = json_decode($setting, true); $temp_result = array(); foreach ($registered_types as $type => $subtypes) { if (elgg_extract($type, $setting)) { $temp_result[$type] = array(); if (!empty($subtypes) && is_array($subtypes)) { foreach ($subtypes as $subtype) { if (elgg_extract($subtype, $setting[$type])) { $temp_result[$type][] = $subtype; } } } } } if (!empty($temp_result)) { $result = $temp_result; } } } return $result; }
function upgrade_20141130() { $upgrade_version = get_upgrade_version(); if ($upgrade_version >= UPGRADE_VERSION) { return true; } $site = elgg_get_site_entity(); $dbprefix = elgg_get_config('dbprefix'); // move ip tracking from heavy object entities to lighter-weight annotations $options = array("type" => "object", "subtype" => "spam_login_filter_ip", 'limit' => false); $batch = new ElggBatch('elgg_get_entities', $options, null, 50, false); $week_ago = time() - 604800; // just delete anything over a week old foreach ($batch as $e) { // create a new record as an annotation and delete the entity if ($e->time_created > $week_ago) { $id = $site->annotate('spam_login_filter_ip', $e->ip_address, ACCESS_PUBLIC); if ($id) { $sql = "UPDATE {$dbprefix}annotations SET time_created = {$e->time_created} WHERE id = {$id}"; update_data($sql); } } $e->delete(); } set_upgrade_version(20141130); }
/** * External pages page handler * * @param array $page URL segements * @param string $handler Handler identifier * @return bool */ function expages_page_handler($page, $handler) { if ($handler == 'expages') { expages_url_forwarder($page[1]); } $type = strtolower($handler); $title = elgg_echo("expages:{$type}"); $header = elgg_view_title($title); $object = elgg_get_entities(array('type' => 'object', 'subtype' => $type, 'limit' => 1)); if ($object) { $content .= elgg_view('output/longtext', array('value' => $object[0]->description)); } else { $content .= elgg_echo("expages:notset"); } $content = elgg_view('expages/wrapper', array('content' => $content)); if (elgg_is_logged_in() || !elgg_get_config('walled_garden')) { $body = elgg_view_layout('one_column', array('title' => $title, 'content' => $content)); echo elgg_view_page($title, $body); } else { elgg_load_css('elgg.walled_garden'); $body = elgg_view_layout('walled_garden', array('content' => $header . $content)); echo elgg_view_page($title, $body, 'walled_garden'); } return true; }
function zhgroups_find_groups($options = array(), $tag = null) { $defaults = array('count' => false, 'offset' => 0, 'limit' => ZHAOHU_MANAGER_SEARCH_LIST_LIMIT, 'count_only' => false, 'by_title' => false, 'by_tag' => false); $options = array_merge($defaults, $options); $entities_options = array('type' => 'group', 'offset' => $options['offset'], 'limit' => $options['limit'], 'joins' => array(), 'wheres' => array()); if ($tag != null) { if ($options["by_title"]) { $db_prefix = elgg_get_config('dbprefix'); $entities_options['joins'][] = "JOIN {$db_prefix}groups_entity ge ON e.guid = ge.guid"; $entities_options['wheres'][] = "ge.name LIKE '%{$tag}%'"; } if ($options["by_tag"] && $tag != 'All' && $tag != elgg_echo('AllInterests')) { $entities_options['metadata_name'] = 'interests'; $entities_options['metadata_value'] = $tag; } } if ($options["state"] && !empty($options["state"]) && $options["state"] != elgg_echo("All")) { $entities_options['metadata_name_value_pairs'][] = array('name' => 'state', 'value' => $options["state"]); } $entities_options['count'] = true; $count = elgg_get_entities_from_metadata($entities_options); $entities = null; if (!$options['count_only'] && $count) { $entities_options['count'] = false; $entities_options['order_by_metadata'] = array("name" => 'score', "direction" => 'DESC', "as" => "integer"); $entities = elgg_get_entities_from_metadata($entities_options); } $result = array("entities" => $entities, "count" => $count); return $result; }
function birthdays_get_upcoming_user_guids() { $site = elgg_get_site_entity(); $today = (int) date("z"); $field = birthdays_get_configured_birthday_field(); if (!$field) { return false; } if (date("w") == 1) { // Mondays $today -= 2; } elseif (date("w") == 2) { // Tuesdays $today -= 1; } $dbprefix = elgg_get_config('dbprefix'); $field_id = (int) get_metastring_id($field); $sql = "SELECT\n\t\te.guid,\n\t\tDAYOFYEAR(DATE(msv.string)) AS birthday\n\t\tFROM {$dbprefix}entities e\n\t\tJOIN {$dbprefix}entity_relationships r ON r.guid_one = e.guid\n\t\tJOIN {$dbprefix}metadata m ON e.guid = m.entity_guid\n\t\tJOIN {$dbprefix}metastrings msv ON m.value_id = msv.id\n\t\tWHERE\n\t\te.type = 'user' AND\n\t\tr.relationship = 'member_of_site' AND\n\t\tr.guid_two = {$site->guid} AND\n\t\tm.name_id = {$field_id}\n\t\tHAVING birthday >= {$today}\n\t\tORDER BY birthday\n\t\tLIMIT 25"; $users = get_data($sql); $return = array(); foreach ($users as $user) { $return[] = $user->guid; } return $return; }
function zhsocial_apply_icon($zh_user, $icon_url) { // if($zh_user->icontime) // return; $icon_sizes = elgg_get_config('icon_sizes'); $prefix = "profile/{$zh_user->guid}"; $filehandler = new ElggFile(); $filehandler->owner_guid = $zh_user->guid; $filehandler->setFilename($prefix . ".jpg"); $filehandler->open("write"); $filehandler->write(file_get_contents($icon_url)); $filehandler->close(); $filename = $filehandler->getFilenameOnFilestore(); $sizes = array('topbar', 'tiny', 'small', 'medium', 'large', 'master'); $thumbs = array(); foreach ($sizes as $size) { $thumbs[$size] = get_resized_image_from_existing_file($filename, $icon_sizes[$size]['w'], $icon_sizes[$size]['h'], $icon_sizes[$size]['square']); } if ($thumbs['tiny']) { // just checking if resize successful $thumb = new ElggFile(); $thumb->owner_guid = $zh_user->guid; $thumb->setMimeType('image/jpeg'); foreach ($sizes as $size) { $thumb->setFilename("{$prefix}{$size}.jpg"); $thumb->open("write"); $thumb->write($thumbs[$size]); $thumb->close(); } $zh_user->icontime = time(); } }
function widget_manager_widget_url_handler($widget) { $result = false; if ($widget instanceof ElggWidget) { /* plugins should use the following hook for setting the correct widget title */ $result = elgg_trigger_plugin_hook("widget_url", "widget_manager", array("entity" => $widget), false); if (empty($result)) { $handler = $widget->handler; $widgettypes = elgg_get_config("widgets"); if (isset($widgettypes->handlers[$handler]->link)) { $link = $widgettypes->handlers[$handler]->link; } if (!empty($link)) { /* this substitution loop will be deprecated in a future version */ $owner = $widget->getOwnerEntity(); if ($owner instanceof ElggSite) { if (elgg_is_logged_in()) { // index widgets sometimes use usernames in widget titles $owner = elgg_get_logged_in_user_entity(); } } /* Let's do some basic substitutions to the link */ /* [USERNAME] */ $link = preg_replace('#\\[USERNAME\\]#', $owner->username, $link); /* [GUID] */ $link = preg_replace('#\\[GUID\\]#', $owner->getGUID(), $link); /* [BASEURL] */ $link = preg_replace('#\\[BASEURL\\]#', elgg_get_site_url(), $link); $result = $link; } } } return $result; }
function theme_ffd_category_filter_menu_hook_handler($hook, $type, $return_value, $params) { if (elgg_in_context("questions")) { $return_value[] = ElggMenuItem::factory(array("name" => "most_viewed", "text" => elgg_echo("theme_ffd:questions:filter:most_viewed"), "href" => "questions/most_viewed", "priority" => 600)); $return_value[] = ElggMenuItem::factory(array("name" => "filter-category", "text" => elgg_echo("theme_ffd:questions:filter:category") . elgg_view_icon("caret-down"), "href" => "#", "priority" => 1000, "item_class" => "float-alt")); $options = array("type" => "group", "limit" => false, "metadata_name_value_pairs" => array("name" => "questions_enable", "value" => "yes"), "joins" => "JOIN " . elgg_get_config("dbprefix") . "groups_entity ge ON e.guid = ge.guid", "order_by" => "ge.name"); $group_batch = new ElggBatch("elgg_get_entities_from_metadata", $options); foreach ($group_batch as $group) { if (elgg_in_context("workflow")) { if (questions_workflow_enabled($group)) { $context = "workflow"; } else { $context = false; } } else { $context = "all"; } if ($context) { $return_value[] = ElggMenuItem::factory(array("name" => "filter-category_" . $group->getGUID(), "text" => elgg_view_icon("share-square", "mrs") . $group->name, "href" => "questions/group/" . $group->getGUID() . "/" . $context, "parent_name" => "filter-category")); } } } elseif (elgg_in_context('cafe')) { $return_value[] = ElggMenuItem::factory(array("name" => "filter-category", "text" => elgg_echo("theme_ffd:questions:filter:category") . elgg_view_icon("caret-down"), "href" => "#", "priority" => 1000, "item_class" => "float-alt")); $options = array('search', 'share', 'experience'); foreach ($options as $option) { $return_value[] = ElggMenuItem::factory(array("name" => "filter-category_" . $option, "text" => elgg_view_icon("share-square", "mrs") . elgg_echo('theme_ffd:cafe:purpose:' . $option), "href" => "cafe/purpose/" . $option, "parent_name" => "filter-category")); } } return $return_value; }
/** * Initialize base attributes * * @see ElggObject::initializeAttributes() * * @return void */ protected function initializeAttributes() { parent::initializeAttributes(); $this->attributes["subtype"] = self::SUBTYPE; $this->attributes["owner_guid"] = elgg_get_config("site_guid"); $this->attributes["container_guid"] = elgg_get_config("site_guid"); }
function batch_find_images() { $log = elgg_get_config('mfp_log'); $logtime = elgg_get_config('mfp_logtime'); // only search $options = array('type' => 'object', 'subtype' => 'image', 'limit' => 0); $images = new ElggBatch('elgg_get_entities', $options); $count = 0; $bad_images = 0; $total = elgg_get_entities(array_merge($options, array('count' => true))); file_put_contents($log, "Starting scan of {$total} images" . "\n", FILE_APPEND); foreach ($images as $image) { $count++; // don't use ->exists() because of #5207. if (!is_file($image->getFilenameOnFilestore())) { $bad_images++; $image->mfp_delete_check = $logtime; } if ($count == 1 || !($count % 25)) { $time = date('Y-m-d g:ia'); $message = "Checked {$count} of {$total} images as of {$time}"; file_put_contents($log, $message . "\n", FILE_APPEND); } } $message = '<div class="done"><a href="#" id="elgg-tidypics-broken-images-delete" data-time="' . $logtime . '">Delete ' . $bad_images . ' broken images</a></div>'; file_put_contents($log, $message . "\n", FILE_APPEND); }
/** * Take over the groupicon page handler for fallback * * @param array $page the url elements * * @return void */ function group_tools_groupicon_page_handler($page) { // group guid if (!isset($page[0])) { header("HTTP/1.1 400 Bad Request"); exit; } $group_guid = $page[0]; $group = get_entity($group_guid); if (empty($group) || !elgg_instanceof($group, "group")) { header("HTTP/1.1 400 Bad Request"); exit; } $owner_guid = $group->getOwnerGUID(); $icontime = (int) $group->icontime; if (empty($icontime)) { header("HTTP/1.1 404 Not Found"); exit; } // size $size = "medium"; if (isset($page[1])) { $icon_sizes = elgg_get_config("icon_sizes"); if (!empty($icon_sizes) && array_key_exists($page[1], $icon_sizes)) { $size = $page[1]; } } $params = array("group_guid" => $group_guid, "guid" => $owner_guid, "size" => $size, "icontime" => $icontime); $url = elgg_http_add_url_query_elements("mod/group_tools/pages/groups/thumbnail.php", $params); forward($url); }