This is usually used with elgg_get_entities() and friends, elgg_get_annotations(), and elgg_get_metadata(). If you pass a valid PHP callback, all results will be run through that callback. You can still foreach() through the result set after. Valid PHP callbacks can be a string, an array, or a closure. {@link http://php.net/manual/en/language.pseudo-types.php} The callback function must accept 3 arguments: an entity, the getter used, and the options used. Results from the callback are stored in callbackResult. If the callback returns only booleans, callbackResults will be the combined result of all calls. If the callback returns anything else, callbackresult will be an indexed array of whatever the callback returns. If returning error handling information, you should include enough information to determine which result you're referring to. Don't combine returning bools and returning something else. Note that returning false will not stop the foreach.
Inheritance: implements Iterator
Esempio n. 1
0
function tidypics_batch_delete_images()
{
    // delete
    $log = elgg_get_config('tidypics_log');
    $log_time = elgg_get_config('tidypics_logtime');
    $options = array('type' => 'object', 'subtype' => 'image', 'metadata_name_value_pairs' => array('name' => 'tidypics_delete_check', 'value' => $log_time), 'limit' => false);
    $images = new ElggBatch('elgg_get_entities_from_metadata', $options);
    $images->setIncrementOffset(false);
    $total = elgg_get_entities_from_metadata(array_merge($options, array('count' => true)));
    file_put_contents($log, "Starting deletion of {$total} images" . "\n", FILE_APPEND);
    $i = 0;
    $count = 0;
    foreach ($images as $image) {
        $count++;
        if ($image->delete()) {
            $i++;
        }
        if ($count == 1 || !($count % 25)) {
            $time = date('m/d/Y g:i:s a');
            $j = $count - $i;
            $message = "Deleted {$i}, skipped {$j}, of {$total} images as of {$time}";
            file_put_contents($log, $message . "\n", FILE_APPEND);
        }
    }
    $message = '<div class="done">Completed: Deleted ' . $i . ', skipped ' . $j . ', of ' . $total . '</div>';
    file_put_contents($log, $message . "\n", FILE_APPEND);
}
Esempio n. 2
0
 /**
  * Remove all the files in this folder
  *
  * @param \ElggObject $entity the folder to removed the file from
  *
  * @return void
  */
 protected static function removeFolderContents(\ElggObject $entity)
 {
     $batch = new \ElggBatch('elgg_get_entities_from_relationship', ['type' => 'object', 'subtype' => 'file', 'container_guid' => $entity->getContainerGUID(), 'limit' => false, 'relationship' => FILE_TOOLS_RELATIONSHIP, 'relationship_guid' => $entity->getGUID()]);
     $batch->setIncrementOffset(false);
     foreach ($batch as $file) {
         $file->delete();
     }
 }
function import_to_stormpath()
{
    $dbprefix = elgg_get_config('dbprefix');
    $subject = elgg_get_plugin_setting('import_subject', PLUGIN_ID);
    $message = elgg_get_plugin_setting('import_message', PLUGIN_ID);
    $site = elgg_get_site_entity();
    $site_url = elgg_get_site_url();
    if (!$subject || !$message) {
        error_log('no subject/message');
        return true;
    }
    if (is_elgg18()) {
        $name_id = add_metastring('__stormpath_user');
        $value_id = add_metastring(1);
    } else {
        $name_id = elgg_get_metastring_id('__stormpath_user');
        $value_id = elgg_get_metastring_id(1);
    }
    $options = array('type' => 'user', 'joins' => array("LEFT JOIN {$dbprefix}metadata md ON md.entity_guid = e.guid AND md.name_id = {$name_id}"), 'wheres' => array('md.name_id IS NULL'), 'limit' => false);
    $batch = new \ElggBatch('elgg_get_entities', $options);
    $batch->setIncrementOffset(false);
    foreach ($batch as $user) {
        // search stormpath for a matching account
        $application = get_application();
        $accts = $application->getAccounts(array('email' => $user->email));
        $already_exists = false;
        foreach ($accts as $a) {
            $user->__stormpath_user = $a->href;
            error_log('set user ' . $user->username . ': ' . $a->href);
            $already_exists = true;
            break;
        }
        if ($already_exists) {
            continue;
        }
        // change it locally
        $password = generate_random_cleartext_password();
        $user->salt = _elgg_generate_password_salt();
        $user->password = generate_user_password($user, $password);
        $user->save();
        error_log('adding to stormpath ' . $user->email);
        $result = add_to_stormpath($user, $password);
        if ($result) {
            // notify them of the change
            // replace tokens in the message
            $message_m = str_replace('{{password}}', $password, $message);
            $message_m = str_replace('{{name}}', $user->name, $message_m);
            $message_m = str_replace('{{username}}', $user->username, $message_m);
            $message_m = str_replace('{{email}}', $user->email, $message_m);
            $message_m = str_replace('{{forgot_password}}', $site_url . 'forgotpassword', $message_m);
            $message_m = str_replace('{{site_email}}', $site->email, $message_m);
            $message_m = str_replace('{{site_url}}', $site_url, $message_m);
            notify_user($user->guid, $site->guid, $subject, $message_m, null, 'email');
        }
    }
}
Esempio n. 4
0
 /**
  * Listen to the cache flush event to invalidate cache of widgets content
  *
  * @param string $event  the name of the event
  * @param string $type   the type of the event
  * @param mixed  $object supplied param
  *
  * @return void
  */
 public static function resetWidgetsCache($event, $type, $object)
 {
     $ia = elgg_set_ignore_access(true);
     $batch = new \ElggBatch('elgg_get_entities_from_private_settings', ['type' => 'object', 'subtype' => 'widget', 'limit' => false, 'private_setting_name' => 'widget_manager_cached_data']);
     $batch->setIncrementOffset(false);
     foreach ($batch as $entity) {
         $entity->removePrivateSetting('widget_manager_cached_data');
     }
     elgg_set_ignore_access($ia);
 }
Esempio n. 5
0
/**
 * Migrates notifications to private messages
 */
function inbox_upgrade_20162209()
{
    $setting = elgg_get_plugin_setting('default_message_types', 'hypeInbox');
    if ($setting) {
        $setting = unserialize($setting);
        unset($setting['__notification']);
        elgg_set_plugin_setting('default_message_types', serialize($setting), 'hypeInbox');
    }
    $messages = new ElggBatch('elgg_get_entities_from_metadata', ['types' => 'object', 'subtypes' => 'messages', 'metadata_name_value_pairs' => ['name' => 'msgType', 'value' => '__notification'], 'limit' => 0]);
    $messages->setIncrementOffset(false);
    foreach ($messages as $message) {
        $message->msgType = hypeJunction\Inbox\Message::TYPE_PRIVATE;
    }
}
Esempio n. 6
0
 /**
  * Move the imported abstract fields to description
  *
  * @param string $event  the name of the event
  * @param string $type   the type of the event
  * @param mixed  $object supplied params
  *
  * @return void
  */
 public static function abstractToDescription($event, $type, $object)
 {
     $options = ['type' => 'object', 'subtype' => \Publication::SUBTYPE, 'limit' => false, 'metadata_name' => 'abstract'];
     $entities = new \ElggBatch('elgg_get_entities_from_metadata', $options);
     $entities->setIncrementOffset(false);
     foreach ($entities as $entity) {
         // append abstract to description
         $entity->description .= ' ' . $entity->abstract;
         // remove trailing spaces
         trim($entity->description);
         // unset abstract
         unset($entity->abstract);
         // save new data
         $entity->save();
     }
 }
Esempio n. 7
0
 /**
  * Migrate old tree structure to new structure
  *
  * @param string $event  the name of the event
  * @param string $type   the type of the event
  * @param mixed  $entity supplied entity
  *
  * @return void
  */
 public static function migrateTreeStructure($event, $type, $entity)
 {
     // this process could take a while
     set_time_limit(0);
     // set entity options
     $options = ['type' => 'object', 'subtype' => \StaticPage::SUBTYPE, 'metadata_name' => 'parent_guid', 'site_guids' => false, 'limit' => false];
     // set default metadata options
     $metadata_options = ['metadata_name' => 'parent_guid', 'site_guids' => false, 'limit' => false];
     // make sure we can get all entities
     $ia = elgg_set_ignore_access(true);
     // create a batch for processing
     $batch = new \ElggBatch('elgg_get_entities_from_metadata', $options);
     $batch->setIncrementOffset(false);
     foreach ($batch as $entity) {
         $metadata_options['guid'] = $entity->getGUID();
         $parent_guid = (int) $entity->parent_guid;
         if (empty($parent_guid)) {
             // workaround for multi-site
             elgg_delete_metadata($metadata_options);
             continue;
         }
         $parent = get_entity($parent_guid);
         if (empty($parent)) {
             // workaround for multi-site
             elgg_delete_metadata($metadata_options);
             continue;
         }
         // set correct container
         $entity->container_guid = $parent->getGUID();
         $entity->save();
         // find the root page for the tree
         $root = self::findOldRootPage($entity);
         if (empty($root)) {
             // workaround for multi-site
             elgg_delete_metadata($metadata_options);
             continue;
         }
         // add relationship to the correct tree
         remove_entity_relationships($entity->getGUID(), 'subpage_of');
         $entity->addRelationship($root->getGUID(), 'subpage_of');
         // workaround for multi-site
         elgg_delete_metadata($metadata_options);
     }
     // restore access
     elgg_set_ignore_access($ia);
 }
Esempio n. 8
0
 /**
  * Cleanup the old exports
  *
  * @param string $hook         the name of the hook
  * @param string $type         the type of the hook
  * @param string $return_value current return value
  * @param array  $params       supplied params
  *
  * @return void
  */
 public static function cleanupExports($hook, $type, $return_value, $params)
 {
     $time = (int) elgg_extract('time', $params, time());
     $retention = (int) elgg_get_plugin_setting('retention', 'csv_exporter');
     if ($retention < 1) {
         // no cleanup
         return;
     }
     // prepare options
     $options = ['type' => 'object', 'subtype' => \CSVExport::SUBTYPE, 'limit' => false, 'metadata_name_value_pairs' => ['name' => 'completed', 'value' => strtotime("today -{$retention} days", $time), 'operand' => '<']];
     // ignore access
     $ia = elgg_set_ignore_access(true);
     $batch = new \ElggBatch('elgg_get_entities_from_metadata', $options);
     $batch->setIncrementOffset(false);
     /* @var $entity \CSVExport */
     foreach ($batch as $entity) {
         $entity->delete();
     }
     // restore access
     elgg_set_ignore_access($ia);
 }
Esempio n. 9
0
 public function testElggBatchIncOffset()
 {
     // normal increment
     $options = array('offset' => 0, 'limit' => 11);
     $batch = new \ElggBatch([\ElggBatchTest::class, 'elgg_batch_callback_test'], $options, null, 5);
     $j = 0;
     foreach ($batch as $e) {
         $offset = floor($j / 5) * 5;
         $this->assertEqual($offset, $e['offset']);
         $this->assertEqual($j + 1, $e['index']);
         $j++;
     }
     $this->assertEqual(11, $j);
     // no increment, 0 start
     \ElggBatchTest::elgg_batch_callback_test(array(), true);
     $options = array('offset' => 0, 'limit' => 11);
     $batch = new \ElggBatch([\ElggBatchTest::class, 'elgg_batch_callback_test'], $options, null, 5);
     $batch->setIncrementOffset(false);
     $j = 0;
     foreach ($batch as $e) {
         $this->assertEqual(0, $e['offset']);
         // should always be the same 5
         $this->assertEqual($e['index'], $j + 1 - floor($j / 5) * 5);
         $j++;
     }
     $this->assertEqual(11, $j);
     // no increment, 3 start
     \ElggBatchTest::elgg_batch_callback_test(array(), true);
     $options = array('offset' => 3, 'limit' => 11);
     $batch = new \ElggBatch([\ElggBatchTest::class, 'elgg_batch_callback_test'], $options, null, 5);
     $batch->setIncrementOffset(false);
     $j = 0;
     foreach ($batch as $e) {
         $this->assertEqual(3, $e['offset']);
         // same 5 results
         $this->assertEqual($e['index'], $j + 4 - floor($j / 5) * 5);
         $j++;
     }
     $this->assertEqual(11, $j);
 }
<?php

/**
 * Bulk delete users by email
 */
$domain = get_input('domain');
$banned = get_input('banned');
$include_enqueued = get_input('include_enqueued');
$s = BulkUserAdmin\DeleteService::getService();
$errors = array();
$count = 0;
$batch = new ElggBatch('bulk_user_admin_get_users', array('domain' => $domain, 'limit' => false, 'enqueued' => 'exclude'));
$batch->setIncrementOffset(false);
foreach ($batch as $user) {
    if (!$user instanceof ElggUser) {
        $errors[] = elgg_echo('bulk_user_admin:error:wrongguid', array($user->guid));
        continue;
    }
    if (!$s->enqueue($user)) {
        $errors[] = elgg_echo('bulk_user_admin:error:enqueue_failed', array($user->name, $user->username, $user->guid));
    }
    $count++;
}
if ($errors) {
    foreach ($errors as $error) {
        register_error($error);
    }
} else {
    system_message(elgg_echo('bulk_user_admin:enqueue:delete', array($count)));
}
forward('/admin/users/bulk_user_admin');
Esempio n. 11
0
 /**
  * Deletes the entity.
  *
  * Removes the entity and its metadata, annotations, relationships,
  * river entries, and private data.
  *
  * Optionally can remove entities contained and owned by this entity.
  *
  * @warning If deleting recursively, this bypasses ownership of items contained by
  * the entity.  That means that if the container_guid = $this->guid, the item will
  * be deleted regardless of who owns it.
  *
  * @param bool $recursive If true (default) then all entities which are
  *                        owned or contained by $this will also be deleted.
  *
  * @return bool
  */
 public function delete($recursive = true)
 {
     global $CONFIG;
     $guid = $this->guid;
     if (!$guid) {
         return false;
     }
     if (!elgg_trigger_event('delete', $this->type, $this)) {
         return false;
     }
     if (!$this->canEdit()) {
         return false;
     }
     _elgg_invalidate_cache_for_entity($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) {
         $newentity_cache->delete($guid);
     }
     // Delete contained owned and otherwise releated objects (depth first)
     if ($recursive) {
         // Temporary token overriding access controls
         // @todo Do this better.
         static $__RECURSIVE_DELETE_TOKEN;
         // Make it slightly harder to guess
         $__RECURSIVE_DELETE_TOKEN = md5(elgg_get_logged_in_user_guid());
         $entity_disable_override = access_get_show_hidden_status();
         access_show_hidden_entities(true);
         $ia = elgg_set_ignore_access(true);
         // @todo there was logic in the original code that ignored
         // entities with owner or container guids of themselves.
         // this should probably be prevented in \ElggEntity instead of checked for here
         $options = array('wheres' => array("((container_guid = {$guid} OR owner_guid = {$guid} OR site_guid = {$guid})" . " AND guid != {$guid})"), 'limit' => 0);
         $batch = new \ElggBatch('elgg_get_entities', $options);
         $batch->setIncrementOffset(false);
         foreach ($batch as $e) {
             $e->delete(true);
         }
         access_show_hidden_entities($entity_disable_override);
         $__RECURSIVE_DELETE_TOKEN = null;
         elgg_set_ignore_access($ia);
     }
     $entity_disable_override = access_get_show_hidden_status();
     access_show_hidden_entities(true);
     $ia = elgg_set_ignore_access(true);
     // Now delete the entity itself
     $this->deleteMetadata();
     $this->deleteOwnedMetadata();
     $this->deleteAnnotations();
     $this->deleteOwnedAnnotations();
     $this->deleteRelationships();
     access_show_hidden_entities($entity_disable_override);
     elgg_set_ignore_access($ia);
     elgg_delete_river(array('subject_guid' => $guid));
     elgg_delete_river(array('object_guid' => $guid));
     elgg_delete_river(array('target_guid' => $guid));
     remove_all_private_settings($guid);
     $res = $this->getDatabase()->deleteData("DELETE FROM {$CONFIG->dbprefix}entities WHERE guid = {$guid}");
     if ($res) {
         $sub_table = "";
         // Where appropriate delete the sub table
         switch ($this->type) {
             case 'object':
                 $sub_table = $CONFIG->dbprefix . 'objects_entity';
                 break;
             case 'user':
                 $sub_table = $CONFIG->dbprefix . 'users_entity';
                 break;
             case 'group':
                 $sub_table = $CONFIG->dbprefix . 'groups_entity';
                 break;
             case 'site':
                 $sub_table = $CONFIG->dbprefix . 'sites_entity';
                 break;
         }
         if ($sub_table) {
             $this->getDatabase()->deleteData("DELETE FROM {$sub_table} WHERE guid = {$guid}");
         }
     }
     return (bool) $res;
 }
Esempio n. 12
0
/**
 * Delete an entity.
 *
 * Removes an entity and its metadata, annotations, relationships, river entries,
 * and private data.
 *
 * Optionally can remove entities contained and owned by $guid.
 *
 * @tip Use ElggEntity::delete() instead.
 *
 * @warning If deleting recursively, this bypasses ownership of items contained by
 * the entity.  That means that if the container_guid = $guid, the item will be deleted
 * regardless of who owns it.
 *
 * @param int  $guid      The guid of the entity to delete
 * @param bool $recursive If true (default) then all entities which are
 *                        owned or contained by $guid will also be deleted.
 *
 * @return bool
 * @access private
 */
function delete_entity($guid, $recursive = true)
{
    global $CONFIG, $ENTITY_CACHE;
    $guid = (int) $guid;
    if ($entity = get_entity($guid)) {
        if (elgg_trigger_event('delete', $entity->type, $entity)) {
            if ($entity->canEdit()) {
                // delete cache
                if (isset($ENTITY_CACHE[$guid])) {
                    _elgg_invalidate_cache_for_entity($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) {
                    $newentity_cache->delete($guid);
                }
                // Delete contained owned and otherwise releated objects (depth first)
                if ($recursive) {
                    // Temporary token overriding access controls
                    // @todo Do this better.
                    static $__RECURSIVE_DELETE_TOKEN;
                    // Make it slightly harder to guess
                    $__RECURSIVE_DELETE_TOKEN = md5(elgg_get_logged_in_user_guid());
                    $entity_disable_override = access_get_show_hidden_status();
                    access_show_hidden_entities(true);
                    $ia = elgg_set_ignore_access(true);
                    // @todo there was logic in the original code that ignored
                    // entities with owner or container guids of themselves.
                    // this should probably be prevented in ElggEntity instead of checked for here
                    $options = array("limit" => 0, "order_by" => false, "site_guids" => false);
                    foreach (array("site_guid", "container_guid", "owner_guid") as $column) {
                        $options['wheres'] = array("(({$column} = {$guid}) AND guid != {$guid})");
                        $batch = new ElggBatch('elgg_get_entities', $options);
                        $batch->setIncrementOffset(false);
                        foreach ($batch as $e) {
                            $e->delete(true);
                        }
                    }
                    access_show_hidden_entities($entity_disable_override);
                    $__RECURSIVE_DELETE_TOKEN = null;
                    elgg_set_ignore_access($ia);
                }
                // Now delete the entity itself
                $entity->deleteMetadata();
                $entity->deleteOwnedMetadata();
                $entity->deleteAnnotations();
                $entity->deleteOwnedAnnotations();
                $entity->deleteRelationships();
                elgg_delete_river(array('subject_guid' => $guid));
                elgg_delete_river(array('object_guid' => $guid));
                remove_all_private_settings($guid);
                $res = delete_data("DELETE from {$CONFIG->dbprefix}entities where guid={$guid}");
                if ($res) {
                    $sub_table = "";
                    // Where appropriate delete the sub table
                    switch ($entity->type) {
                        case 'object':
                            $sub_table = $CONFIG->dbprefix . 'objects_entity';
                            break;
                        case 'user':
                            $sub_table = $CONFIG->dbprefix . 'users_entity';
                            break;
                        case 'group':
                            $sub_table = $CONFIG->dbprefix . 'groups_entity';
                            break;
                        case 'site':
                            $sub_table = $CONFIG->dbprefix . 'sites_entity';
                            break;
                    }
                    if ($sub_table) {
                        delete_data("DELETE from {$sub_table} where guid={$guid}");
                    }
                }
                return (bool) $res;
            }
        }
    }
    return false;
}
Esempio n. 13
0
 /**
  * Update the access of todoitems in this list to match the list access
  *
  * @return void
  */
 protected function updateTodoItemAccess()
 {
     $options = array('type' => 'object', 'subtype' => TodoItem::SUBTYPE, 'limit' => false, 'container_guid' => $this->getGUID(), 'wheres' => array('e.access_id <> ' . $this->access_id));
     $ia = elgg_set_ignore_access(true);
     $batch = new ElggBatch('elgg_get_entities', $options);
     $batch->setIncrementOffset(false);
     foreach ($batch as $item) {
         $item->access_id = $this->access_id;
         $item->save();
     }
     elgg_set_ignore_access($ia);
 }
Esempio n. 14
0
<?php

if (subsite_manager_on_subsite()) {
    register_error(elgg_echo("subsite_manager:action:error:on_subsite"));
    forward(REFERER);
}
// this could take a while
set_time_limit(0);
$subsite_options = array("type" => "site", "subtype" => Subsite::SUBTYPE, "limit" => false, "joins" => array("JOIN " . get_config("dbprefix") . "sites_entity se ON se.guid = e.guid"), "order_by" => "se.name ASC");
$batch = new ElggBatch("elgg_get_entities", $subsite_options);
$batch->rewind();
if ($batch->valid()) {
    // create a temp file for storage
    $fh = tmpfile();
    $headers = array("name", "url", "site time created (unix)", "site time created (YYYY-MM-DD HH:MM:SS)", "member count", "last activity (unix)", "last activity (YYYY-MM-DD HH:MM:SS)", "admin name", "admin email", "admin profile");
    fwrite($fh, "\"" . implode("\";\"", $headers) . "\"" . PHP_EOL);
    foreach ($batch as $subsite) {
        $member_count = $subsite->getMembers(array("count" => true));
        $last_activity = subsite_manager_get_subsite_last_activity($subsite->getGUID());
        $last_activity_readable = date("Y-m-d G:i:s", $last_activity);
        $admin_guids = $subsite->getAdminGuids();
        $output = array($subsite->name, $subsite->url, $subsite->time_created, date("Y-m-d G:i:s", $subsite->time_created), $member_count, $last_activity, $last_activity_readable);
        if (!empty($admin_guids)) {
            foreach ($admin_guids as $admin_guid) {
                $admin = get_user($admin_guid);
                if (!empty($admin)) {
                    $admin_output = $output;
                    $admin_output[] = $admin->name;
                    $admin_output[] = $admin->email;
                    $admin_output[] = $admin->getURL();
                    // write to file
Esempio n. 15
0
/**
 * Link a user to a Service Provider (SP), so in the future the user can login using this SP.
 *
 * @param ElggUser $user        the user to link
 * @param string   $saml_source the name of the SP
 * @param string   $saml_uid    the unique ID of the user on the IDentity Provider side
 *
 * @return bool
 */
function simplesaml_link_user(ElggUser $user, $saml_source, $saml_uid)
{
    if (!$user instanceof ElggUser || empty($saml_source) || empty($saml_uid)) {
        return false;
    }
    if (!simplesaml_is_enabled_source($saml_source)) {
        return false;
    }
    // remove links from other users
    $options = ['type' => 'user', 'limit' => false, 'site_guids' => false, 'plugin_id' => 'simplesaml', 'plugin_user_setting_name_value_pairs' => [$saml_source . '_uid' => $saml_uid]];
    $users = new ElggBatch('elgg_get_entities_from_plugin_user_settings', $options);
    $users->setIncrementOffset(false);
    foreach ($users as $other_user) {
        simplesaml_unlink_user($other_user, $saml_source);
    }
    // now save the setting for this user
    return elgg_set_plugin_user_setting("{$saml_source}_uid", $saml_uid, $user->getGUID(), 'simplesaml');
}
Esempio n. 16
0
 /**
  * Delete all the images in this album
  */
 protected function deleteImages()
 {
     $images_count = elgg_get_entities(array("type" => "object", "subtype" => "image", "container_guid" => $this->guid, "count" => true));
     if ($images_count > 0) {
         $images = new ElggBatch('elgg_get_entities', array("type" => "object", "subtype" => "image", "container_guid" => $this->guid, "limit" => ELGG_ENTITIES_NO_VALUE));
         $images->setIncrementOffset(false);
         foreach ($images as $image) {
             if ($image) {
                 $image->delete();
             }
         }
     }
 }
Esempio n. 17
0
        break;
    case 'three_months':
        $upper_limit = $now - 60 * 60 * 24 * 91;
        break;
    case 'four_weeks':
        $upper_limit = $now - 60 * 60 * 24 * 29;
        break;
    case 'two_weeks':
        $upper_limit = $now - 60 * 60 * 24 * 15;
        break;
}
if ($upper_limit && $upper_limit > 0) {
    // Fetching events with start_date < $upper_limit here because repeating events have no meaningful real_end_time metadata value
    // Non-scheduled event poll events are not retrieved here because they don't have any fixed start_date metadata value yet
    $options = array('type' => 'object', 'subtype' => 'event_calendar', 'limit' => false, 'metadata_name_value_pairs' => array(array('name' => 'start_date', 'value' => $upper_limit, 'operand' => '<')));
    $past_events = new ElggBatch('elgg_get_entities_from_metadata', $options);
    $past_events->setIncrementOffset(false);
    $success_count = 0;
    $error_count = 0;
    foreach ($past_events as $past_event) {
        // do we delete also repeating events?
        if ($past_event->repeats == 'yes') {
            if ($delete_repeating_events) {
                if ($past_event->delete()) {
                    $success_count++;
                } else {
                    $error_count++;
                }
            }
        } else {
            if ($past_event->repeats != 'yes') {
Esempio n. 18
0
 /**
  * Deletes the entity.
  *
  * Removes the entity and its metadata, annotations, relationships,
  * river entries, and private data.
  *
  * Optionally can remove entities contained and owned by this entity.
  *
  * @warning If deleting recursively, this bypasses ownership of items contained by
  * the entity.  That means that if the container_guid = $this->guid, the item will
  * be deleted regardless of who owns it.
  *
  * @param bool $recursive If true (default) then all entities which are
  *                        owned or contained by $this will also be deleted.
  *
  * @return bool
  */
 public function delete($recursive = true)
 {
     global $CONFIG;
     $guid = $this->guid;
     if (!$guid) {
         return false;
     }
     // first check if we can delete this entity
     // NOTE: in Elgg <= 1.10.3 this was after the delete event,
     // which could potentially remove some content if the user didn't have access
     if (!$this->canDelete()) {
         return false;
     }
     // now trigger an event to let others know this entity is about to be deleted
     // so they can prevent it or take their own actions
     if (!_elgg_services()->events->trigger('delete', $this->type, $this)) {
         return false;
     }
     _elgg_invalidate_cache_for_entity($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) {
         $newentity_cache->delete($guid);
     }
     // Delete contained owned and otherwise releated objects (depth first)
     if ($recursive) {
         // Temporarily overriding access controls
         $entity_disable_override = access_get_show_hidden_status();
         access_show_hidden_entities(true);
         $ia = elgg_set_ignore_access(true);
         // @todo there was logic in the original code that ignored
         // entities with owner or container guids of themselves.
         // this should probably be prevented in \ElggEntity instead of checked for here
         $options = array('wheres' => array("((container_guid = {$guid} OR owner_guid = {$guid} OR site_guid = {$guid})" . " AND guid != {$guid})"), 'limit' => 0);
         $batch = new \ElggBatch('elgg_get_entities', $options);
         $batch->setIncrementOffset(false);
         foreach ($batch as $e) {
             $e->delete(true);
         }
         access_show_hidden_entities($entity_disable_override);
         elgg_set_ignore_access($ia);
     }
     $entity_disable_override = access_get_show_hidden_status();
     access_show_hidden_entities(true);
     $ia = elgg_set_ignore_access(true);
     // Now delete the entity itself
     $this->deleteMetadata();
     $this->deleteOwnedMetadata();
     $this->deleteAnnotations();
     $this->deleteOwnedAnnotations();
     $this->deleteRelationships();
     $this->deleteAccessCollectionMemberships();
     $this->deleteOwnedAccessCollections();
     access_show_hidden_entities($entity_disable_override);
     elgg_set_ignore_access($ia);
     elgg_delete_river(array('subject_guid' => $guid));
     elgg_delete_river(array('object_guid' => $guid));
     elgg_delete_river(array('target_guid' => $guid));
     remove_all_private_settings($guid);
     $res = $this->getDatabase()->deleteData("DELETE FROM {$CONFIG->dbprefix}entities WHERE guid = {$guid}");
     if ($res) {
         $sub_table = "";
         // Where appropriate delete the sub table
         switch ($this->type) {
             case 'object':
                 $sub_table = $CONFIG->dbprefix . 'objects_entity';
                 break;
             case 'user':
                 $sub_table = $CONFIG->dbprefix . 'users_entity';
                 break;
             case 'group':
                 $sub_table = $CONFIG->dbprefix . 'groups_entity';
                 break;
             case 'site':
                 $sub_table = $CONFIG->dbprefix . 'sites_entity';
                 break;
         }
         if ($sub_table) {
             $this->getDatabase()->deleteData("DELETE FROM {$sub_table} WHERE guid = {$guid}");
         }
     }
     _elgg_clear_entity_files($this);
     return (bool) $res;
 }
Esempio n. 19
0
/**
 * Move an entity to a new site (can anly be call by subsite_manager_move_group_to_site())
 *
 * @param ElggEntity $entity            the entity to move
 * @param ElggSite   $target_site       the target site
 * @param array      $access_conversion array with group and site access levels
 *
 * @access private
 *
 * @return bool
 */
function subsite_manager_move_entity_to_site(ElggEntity $entity, ElggSite $target_site, array $access_conversion)
{
    static $newentity_cache;
    $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
    if (!isset($backtrace[1])) {
        return false;
    }
    $function = elgg_extract("function", $backtrace[1]);
    if (empty($function) || !in_array($function, array("subsite_manager_move_group_to_site", "subsite_manager_move_entity_to_site"))) {
        // because this is a dangerous function only allow it to be called the correct way
        return false;
    }
    if (empty($entity) || !$entity instanceof ElggEntity) {
        return false;
    }
    if (empty($target_site) || !elgg_instanceof($target_site, "site")) {
        return false;
    }
    if ($entity->site_guid == $target_site->getGUID()) {
        return false;
    }
    // check for access conversion rules
    if (empty($access_conversion) || !is_array($access_conversion)) {
        return false;
    }
    $group_acl = (int) elgg_extract("group_acl", $access_conversion);
    if (empty($group_acl)) {
        return false;
    }
    $old_site_acl = (int) elgg_extract("site_acl", $access_conversion);
    $affected_access = array(ACCESS_PUBLIC, ACCESS_LOGGED_IN);
    if (!empty($old_site_acl)) {
        $affected_access[] = $old_site_acl;
    }
    // ignore access and show hidden entities
    $ia = elgg_set_ignore_access(true);
    $hidden = access_get_show_hidden_status();
    access_show_hidden_entities(true);
    // first move sub entities (eg blogs in group, event registrations, etc)
    $options = array("type" => "object", "container_guid" => $entity->getGUID(), "limit" => false);
    $batch = new ElggBatch("elgg_get_entities", $options);
    $batch->setIncrementOffset(false);
    foreach ($batch as $sub_entity) {
        if (!subsite_manager_move_entity_to_site($sub_entity, $target_site, $access_conversion)) {
            elgg_set_ignore_access($ia);
            access_show_hidden_entities($hidden);
            return false;
        }
    }
    // also move owned (sub) entities
    $options = array("type" => "object", "owner_guid" => $entity->getGUID(), "wheres" => array("(e.guid <> {$entity->getGUID()})"), "limit" => false);
    $batch = new ElggBatch("elgg_get_entities", $options);
    $batch->setIncrementOffset(false);
    foreach ($batch as $sub_entity) {
        if (!subsite_manager_move_entity_to_site($sub_entity, $target_site, $access_conversion)) {
            elgg_set_ignore_access($ia);
            access_show_hidden_entities($hidden);
            return false;
        }
    }
    $dbprefix = elgg_get_config("dbprefix");
    // move access collections
    $query = "UPDATE {$dbprefix}access_collections";
    $query .= " SET site_guid = {$target_site->getGUID()}";
    $query .= " WHERE owner_guid = {$entity->getGUID()}";
    try {
        update_data($query);
    } catch (Exception $e) {
        elgg_log("Subsite manager move entity({$entity->getGUID()}) access collections: " . $e->getMessage(), "ERROR");
        elgg_set_ignore_access($ia);
        access_show_hidden_entities($hidden);
        return false;
    }
    // move annotations
    $query = "UPDATE {$dbprefix}annotations";
    $query .= " SET site_guid = {$target_site->getGUID()}";
    $query .= " WHERE entity_guid = {$entity->getGUID()}";
    try {
        update_data($query);
    } catch (Exception $e) {
        elgg_log("Subsite manager move entity({$entity->getGUID()}) annotations: " . $e->getMessage(), "ERROR");
        elgg_set_ignore_access($ia);
        access_show_hidden_entities($hidden);
        return false;
    }
    // change annotation access
    $query = "UPDATE {$dbprefix}annotations";
    $query .= " SET access_id = {$group_acl}";
    $query .= " WHERE entity_guid = {$entity->getGUID()}";
    $query .= " AND access_id IN (" . implode(", ", $affected_access) . ")";
    try {
        update_data($query);
    } catch (Exception $e) {
        elgg_log("Subsite manager change entity({$entity->getGUID()}) annotation access: " . $e->getMessage(), "ERROR");
        elgg_set_ignore_access($ia);
        access_show_hidden_entities($hidden);
        return false;
    }
    // move river
    $query = "UPDATE {$dbprefix}river";
    $query .= " SET site_guid = {$target_site->getGUID()}";
    $query .= " WHERE subject_guid = {$entity->getGUID()}";
    $query .= " OR object_guid = {$entity->getGUID()}";
    try {
        update_data($query);
    } catch (Exception $e) {
        elgg_log("Subsite manager move entity({$entity->getGUID()}) river: " . $e->getMessage(), "ERROR");
        elgg_set_ignore_access($ia);
        access_show_hidden_entities($hidden);
        return false;
    }
    // change river access
    $query = "UPDATE {$dbprefix}river";
    $query .= " SET access_id = {$group_acl}";
    $query .= " WHERE (subject_guid = {$entity->getGUID()}";
    $query .= " OR object_guid = {$entity->getGUID()})";
    $query .= " AND access_id IN (" . implode(", ", $affected_access) . ")";
    try {
        update_data($query);
    } catch (Exception $e) {
        elgg_log("Subsite manager change entity({$entity->getGUID()}) river access: " . $e->getMessage(), "ERROR");
        elgg_set_ignore_access($ia);
        access_show_hidden_entities($hidden);
        return false;
    }
    // move metadata
    $query = "UPDATE {$dbprefix}metadata";
    $query .= " SET site_guid = {$target_site->getGUID()}";
    $query .= " WHERE entity_guid = {$entity->getGUID()}";
    try {
        update_data($query);
    } catch (Exception $e) {
        elgg_log("Subsite manager move entity({$entity->getGUID()}) metadata: " . $e->getMessage(), "ERROR");
        elgg_set_ignore_access($ia);
        access_show_hidden_entities($hidden);
        return false;
    }
    // change metadata access
    $query = "UPDATE {$dbprefix}metadata";
    $query .= " SET access_id = {$group_acl}";
    $query .= " WHERE entity_guid = {$entity->getGUID()}";
    $query .= " AND access_id IN (" . implode(", ", $affected_access) . ")";
    try {
        update_data($query);
    } catch (Exception $e) {
        elgg_log("Subsite manager change entity({$entity->getGUID()}) metadata access: " . $e->getMessage(), "ERROR");
        elgg_set_ignore_access($ia);
        access_show_hidden_entities($hidden);
        return false;
    }
    // move entity
    $query = "UPDATE {$dbprefix}entities";
    $query .= " SET site_guid = {$target_site->getGUID()}";
    $query .= " WHERE guid = {$entity->getGUID()}";
    try {
        update_data($query);
    } catch (Exception $e) {
        elgg_log("Subsite manager move entity({$entity->getGUID()}) entity: " . $e->getMessage(), "ERROR");
        elgg_set_ignore_access($ia);
        access_show_hidden_entities($hidden);
        return false;
    }
    // change entity access
    $query = "UPDATE {$dbprefix}entities";
    $query .= " SET access_id = {$group_acl}";
    $query .= " WHERE guid = {$entity->getGUID()}";
    $query .= " AND access_id IN (" . implode(", ", $affected_access) . ")";
    try {
        update_data($query);
    } catch (Exception $e) {
        elgg_log("Subsite manager change entity({$entity->getGUID()}) entity access: " . $e->getMessage(), "ERROR");
        elgg_set_ignore_access($ia);
        access_show_hidden_entities($hidden);
        return false;
    }
    // cache cleanup
    _elgg_invalidate_cache_for_entity($entity->getGUID());
    if (!$newentity_cache && is_memcache_available()) {
        $newentity_cache = new ElggMemcache('new_entity_cache');
    }
    if ($newentity_cache) {
        $newentity_cache->delete($entity->getGUID());
    }
    elgg_set_ignore_access($ia);
    access_show_hidden_entities($hidden);
    return true;
}
Esempio n. 20
0
 /**
  * Return entities from an SQL query generated by elgg_get_entities.
  *
  * @param string    $sql
  * @param \ElggBatch $batch
  * @return \ElggEntity[]
  *
  * @access private
  * @throws \LogicException
  */
 function fetchFromSql($sql, \ElggBatch $batch = null)
 {
     static $plugin_subtype;
     if (null === $plugin_subtype) {
         $plugin_subtype = get_subtype_id('object', 'plugin');
     }
     // Keys are types, values are columns that, if present, suggest that the secondary
     // table is already JOINed. Note it's OK if guess incorrectly because entity load()
     // will fetch any missing attributes.
     $types_to_optimize = array('object' => 'title', 'user' => 'password', 'group' => 'name', 'site' => 'url');
     $rows = _elgg_services()->db->getData($sql);
     // guids to look up in each type
     $lookup_types = array();
     // maps GUIDs to the $rows key
     $guid_to_key = array();
     if (isset($rows[0]->type, $rows[0]->subtype) && $rows[0]->type === 'object' && $rows[0]->subtype == $plugin_subtype) {
         // Likely the entire resultset is plugins, which have already been optimized
         // to JOIN the secondary table. In this case we allow retrieving from cache,
         // but abandon the extra queries.
         $types_to_optimize = array();
     }
     // First pass: use cache where possible, gather GUIDs that we're optimizing
     foreach ($rows as $i => $row) {
         if (empty($row->guid) || empty($row->type)) {
             throw new \LogicException('Entity row missing guid or type');
         }
         $entity = _elgg_retrieve_cached_entity($row->guid);
         if ($entity) {
             $entity->refresh($row);
             $rows[$i] = $entity;
             continue;
         }
         if (isset($types_to_optimize[$row->type])) {
             // check if row already looks JOINed.
             if (isset($row->{$types_to_optimize[$row->type]})) {
                 // Row probably already contains JOINed secondary table. Don't make another query just
                 // to pull data that's already there
                 continue;
             }
             $lookup_types[$row->type][] = $row->guid;
             $guid_to_key[$row->guid] = $i;
         }
     }
     // Do secondary queries and merge rows
     if ($lookup_types) {
         $dbprefix = _elgg_services()->config->get('dbprefix');
         foreach ($lookup_types as $type => $guids) {
             $set = "(" . implode(',', $guids) . ")";
             $sql = "SELECT * FROM {$dbprefix}{$type}s_entity WHERE guid IN {$set}";
             $secondary_rows = _elgg_services()->db->getData($sql);
             if ($secondary_rows) {
                 foreach ($secondary_rows as $secondary_row) {
                     $key = $guid_to_key[$secondary_row->guid];
                     // cast to arrays to merge then cast back
                     $rows[$key] = (object) array_merge((array) $rows[$key], (array) $secondary_row);
                 }
             }
         }
     }
     // Second pass to finish conversion
     foreach ($rows as $i => $row) {
         if ($row instanceof \ElggEntity) {
             continue;
         } else {
             try {
                 $rows[$i] = entity_row_to_elggstar($row);
             } catch (IncompleteEntityException $e) {
                 // don't let incomplete entities throw fatal errors
                 unset($rows[$i]);
                 // report incompletes to the batch process that spawned this query
                 if ($batch) {
                     $batch->reportIncompleteEntity($row);
                 }
             }
         }
     }
     return $rows;
 }
Esempio n. 21
0
<?php

$user_guid = (int) get_input('user_guid');
// Delete all the userpoint objects for the selected user or for all users if user_guid = 0
if ($user_guid > 0) {
    // get all userpoint objects for the selected user and delete them
    $entities = new ElggBatch('elgg_get_entities', array('type' => 'object', 'subtype' => 'userpoint', 'owner_guid' => $user_guid, 'limit' => false));
    $entities->setIncrementOffset(false);
    foreach ($entities as $entity) {
        $entity->delete();
    }
    // and remove the userpoints_points metadata for the selected user
    $options = array('guid' => $user_guid, 'metadata_name' => 'userpoints_points');
    elgg_delete_metadata($options);
} else {
    // get all userpoint objects of all users and delete them
    $entities = new ElggBatch('elgg_get_entities', array('type' => 'object', 'subtype' => 'userpoint', 'limit' => false));
    $entities->setIncrementOffset(false);
    foreach ($entities as $entity) {
        $entity->delete();
    }
    // and also remove all userpoints_points metadata
    $prefix = elgg_get_config('dbprefix');
    delete_data("DELETE from {$prefix}metadata where name_id=" . elgg_get_metastring_id('userpoints_points', true));
}
system_message(elgg_echo("elggx_userpoints:reset:success", array(elgg_echo('elggx_userpoints:lowerplural'))));
forward(REFERER);
Esempio n. 22
0
 /**
  * Deletes the entity.
  *
  * Removes the entity and its metadata, annotations, relationships,
  * river entries, and private data.
  *
  * Optionally can remove entities contained and owned by this entity.
  *
  * @warning If deleting recursively, this bypasses ownership of items contained by
  * the entity.  That means that if the container_guid = $this->guid, the item will
  * be deleted regardless of who owns it.
  *
  * @param bool $recursive If true (default) then all entities which are
  *                        owned or contained by $this will also be deleted.
  *
  * @return bool
  */
 public function delete($recursive = true)
 {
     $guid = $this->guid;
     if (!$guid) {
         return false;
     }
     // first check if we can delete this entity
     // NOTE: in Elgg <= 1.10.3 this was after the delete event,
     // which could potentially remove some content if the user didn't have access
     if (!$this->canDelete()) {
         return false;
     }
     // now trigger an event to let others know this entity is about to be deleted
     // so they can prevent it or take their own actions
     if (!_elgg_services()->events->trigger('delete', $this->type, $this)) {
         return false;
     }
     if ($this instanceof ElggUser) {
         // ban to prevent using the site during delete
         _elgg_services()->usersTable->markBanned($this->guid, true);
     }
     // Delete contained owned and otherwise releated objects (depth first)
     if ($recursive) {
         // Temporarily overriding access controls
         $entity_disable_override = access_get_show_hidden_status();
         access_show_hidden_entities(true);
         $ia = elgg_set_ignore_access(true);
         // @todo there was logic in the original code that ignored
         // entities with owner or container guids of themselves.
         // this should probably be prevented in \ElggEntity instead of checked for here
         $options = array('wheres' => array("((container_guid = {$guid} OR owner_guid = {$guid})" . " AND guid != {$guid})"), 'limit' => 0);
         $batch = new \ElggBatch('elgg_get_entities', $options);
         $batch->setIncrementOffset(false);
         foreach ($batch as $e) {
             $e->delete(true);
         }
         access_show_hidden_entities($entity_disable_override);
         elgg_set_ignore_access($ia);
     }
     $entity_disable_override = access_get_show_hidden_status();
     access_show_hidden_entities(true);
     $ia = elgg_set_ignore_access(true);
     // Now delete the entity itself
     $this->deleteMetadata();
     $this->deleteOwnedMetadata();
     $this->deleteAnnotations();
     $this->deleteOwnedAnnotations();
     $this->deleteRelationships();
     $this->deleteAccessCollectionMemberships();
     $this->deleteOwnedAccessCollections();
     access_show_hidden_entities($entity_disable_override);
     elgg_set_ignore_access($ia);
     _elgg_delete_river(array('subject_guid' => $guid));
     _elgg_delete_river(array('object_guid' => $guid));
     _elgg_delete_river(array('target_guid' => $guid));
     remove_all_private_settings($guid);
     _elgg_invalidate_cache_for_entity($guid);
     _elgg_invalidate_memcache_for_entity($guid);
     $dbprefix = elgg_get_config('dbprefix');
     $sql = "\n\t\t\tDELETE FROM {$dbprefix}entities\n\t\t\tWHERE guid = :guid\n\t\t";
     $params = [':guid' => $guid];
     $deleted = $this->getDatabase()->deleteData($sql, $params);
     if ($deleted && in_array($this->type, ['object', 'user', 'group', 'site'])) {
         // delete from type-specific subtable
         $sql = "\n\t\t\t\tDELETE FROM {$dbprefix}{$this->type}s_entity\n\t\t\t\tWHERE guid = :guid\n\t\t\t";
         $this->getDatabase()->deleteData($sql, $params);
     }
     _elgg_clear_entity_files($this);
     return (bool) $deleted;
 }
Esempio n. 23
0
<?php

set_time_limit(0);
$hidden = access_get_show_hidden_status();
access_show_hidden_entities(true);
$data = new ElggBatch('elgg_get_entities_from_metadata', array('types' => 'user', 'limit' => 0, 'metadata_names' => '__faker'));
$data->setIncrementOffset(false);
foreach ($data as $d) {
    $d->delete(true);
}
$fake_count = elgg_get_entities_from_metadata(array('metadata_names' => '__faker', 'count' => true));
if (!$fake_count) {
    system_message(elgg_echo('faker:delete:success'));
} else {
    register_error(elgg_echo('faker:delete:error', $fake_count));
}
access_show_hidden_entities($hidden);