/**
 * Called on successful user login
 * If they are not in stormpath lets add them
 * 
 * @param type $event
 * @param type $type
 * @param type $user
 */
function event_user_login($event, $type, $user)
{
    $access_status = access_get_show_hidden_status();
    access_show_hidden_entities(TRUE);
    if ($user instanceof ElggUser && !$user->isEnabled() && !$user->validated) {
        // send new validation email
        uservalidationbyemail_request_validation($user->getGUID());
        // restore hidden entities settings
        access_show_hidden_entities($access_status);
        // throw error so we get a nice error message
        throw new LoginException(elgg_echo('uservalidationbyemail:login:fail'));
    }
    access_show_hidden_entities($access_status);
    if ($user->__stormpath_user) {
        return true;
    }
    // search stormpath for a matching account
    // may be in stormpath by manual addition, or from another application
    // with shared login
    $application = get_application();
    if ($application) {
        $accts = $application->getAccounts(array('email' => $user->email));
        foreach ($accts as $a) {
            $user->__stormpath_user = $a->href;
            return true;
        }
        $password = get_input('password');
        if ($password) {
            add_to_stormpath($user, $password);
        }
    }
    return true;
}
/**
 * Listen to the registration of a new user
 *
 * @param string $hook         the name of the hook
 * @param string $type         the type of the hook
 * @param bool   $return_value the current return value
 * @param array  $params       supplied params
 *
 * @return bool
 */
function uservalidationbyadmin_register_user_hook($hook, $type, $return_value, $params)
{
    if (empty($params) || !is_array($params)) {
        return $return_value;
    }
    $user = elgg_extract("user", $params);
    if (empty($user) || !elgg_instanceof($user, "user")) {
        return $return_value;
    }
    // make sure we can see everything
    $hidden = access_get_show_hidden_status();
    access_show_hidden_entities(true);
    // make sure we can save metadata
    elgg_push_context("uservalidationbyadmin_new_user");
    // this user needs validation
    $user->admin_validated = false;
    // check who to notify
    $notify_admins = uservalidationbyadmin_get_admin_notification_setting();
    if ($notify_admins == "direct") {
        uservalidationbyadmin_notify_admins();
    }
    // check if we need to disable the user
    if ($user->isEnabled()) {
        $user->disable();
    }
    // restore context
    elgg_pop_context();
    // restore access settings
    access_show_hidden_entities($hidden);
    return $return_value;
}
Exemple #3
0
/**
 * Get security token, forward to action.
 *
 * @param unknown_type $page
 * @return unknown_type
 */
function uservalidationbyemail_page_handler($page)
{
    global $CONFIG;
    if (isset($page[0]) && $page[0] == 'confirm') {
        $code = sanitise_string(get_input('c', FALSE));
        $user_guid = get_input('u', FALSE);
        // new users are not enabled by default.
        $access_status = access_get_show_hidden_status();
        access_show_hidden_entities(true);
        $user = get_entity($user_guid);
        if ($code && $user) {
            if (uservalidationbyemail_validate_email($user_guid, $code)) {
                system_message(elgg_echo('email:confirm:success'));
                $user = get_entity($user_guid);
                $user->enable();
                notify_user($user_guid, $CONFIG->site->guid, sprintf(elgg_echo('email:validate:success:subject'), $user->username), sprintf(elgg_echo('email:validate:success:body'), $user->name), NULL, 'email');
            } else {
                register_error(elgg_echo('email:confirm:fail'));
            }
        } else {
            register_error(elgg_echo('email:confirm:fail'));
        }
        access_show_hidden_entities($access_status);
    } else {
        register_error(elgg_echo('email:confirm:fail'));
    }
    forward();
}
/**
 * Listen to the login event to make sure the user is validated
 *
 * @param string   $event the name of the event
 * @param string   $type  the type of the event
 * @param ElggUser $user  supplied user
 *
 * @return bool
 */
function uservalidationbyadmin_login_event($event, $type, $user)
{
    $result = false;
    // make sure we can see all users
    $hidden = access_get_show_hidden_status();
    access_show_hidden_entities(true);
    // do we actualy have a user
    if (!empty($user) && elgg_instanceof($user, "user")) {
        // is the user enabled
        if ($user->isEnabled()) {
            if ($user->isAdmin()) {
                // admins are always allowed
                $result = true;
            } elseif (isset($user->admin_validated)) {
                // check if the user is validated
                if ($user->admin_validated) {
                    // user is validated and can login
                    $result = true;
                }
            } else {
                // user has register before this plugin was activated
                $result = true;
            }
        }
    }
    // check if the user can login
    if (empty($result)) {
        // register error
        register_error(elgg_echo("uservalidationbyadmin:login:error"));
    }
    // restore access setting
    access_show_hidden_entities($hidden);
    return $result;
}
/**
 * Can we allow the user with the credentials to log in?
 * Check stormpath, create the user if they can log in and don't exist
 * Enable the user if they can log in but were waiting for email verification
 * 
 * @param type $credentials
 * @return boolean
 */
function pam_handler($credentials)
{
    // try to authenticate first
    $application = get_application();
    $authResult = $application->authenticate($credentials['username'], $credentials['password']);
    $account = $authResult->account;
    if (!$account || strtolower($account->status) != 'enabled') {
        return false;
    }
    // we need to search hidden users too
    // in case of email confirmation disabling
    $show_hidden = access_get_show_hidden_status();
    access_show_hidden_entities(true);
    // we have an account and it's enabled
    // see if we have a matching account here
    // check if logging in with email address
    if (strpos($credentials['username'], '@') !== false) {
        $users = get_user_by_email($credentials['username']);
        $user = $users[0];
    } else {
        $user = get_user_by_username($credentials['username']);
    }
    // custom context gives us permission to do this
    elgg_push_context('stormpath_validate_user');
    // if we don't have a user we need to create one
    if (!$user) {
        $user = new \ElggUser();
        $user->username = preg_replace("/[^a-zA-Z0-9]/", "", $account->username);
        $user->email = $account->email;
        $user->name = $account->fullName;
        $user->access_id = ACCESS_PUBLIC;
        $user->salt = _elgg_generate_password_salt();
        $user->password = generate_user_password($user, $credentials['password']);
        $user->owner_guid = 0;
        // Users aren't owned by anyone, even if they are admin created.
        $user->container_guid = 0;
        // Users aren't contained by anyone, even if they are admin created.
        $user->language = get_current_language();
        $user->save();
        $user->__stormpath_user = $account->href;
        elgg_set_user_validation_status($user->guid, TRUE, 'stormpath');
        // Turn on email notifications by default
        set_user_notification_setting($user->getGUID(), 'email', true);
    }
    // see if we need to enable/verify the user
    if (!$user->isEnabled() && in_array($user->disable_reason, array('stormpath_new_user', 'uservalidationbyemail_new_user'))) {
        $user->enable();
        $user->__stormpath_user = $account->href;
        elgg_set_user_validation_status($user->guid, TRUE, 'stormpath');
    }
    elgg_pop_context();
    access_show_hidden_entities($show_hidden);
    if ($user && $user->isEnabled()) {
        return true;
    }
    return false;
}
Exemple #6
0
 public static function isAvailableUsername(\PropertyInterface $prop, $value = null, array $params = array())
 {
     $access_status = access_get_show_hidden_status();
     access_show_hidden_entities(true);
     $available = true;
     if (get_user_by_username($value)) {
         $available = false;
     }
     access_show_hidden_entities($access_status);
     return $available;
 }
/**
 * Delete messages from a user who is being deleted
 *
 * @param string   $event
 * @param string   $type
 * @param ElggUser $user
 */
function customizations_purge_messages($event, $type, $user)
{
    // make sure we delete them all
    $entity_disable_override = access_get_show_hidden_status();
    access_show_hidden_entities(true);
    $messages = elgg_get_entities_from_metadata(array('type' => 'object', 'subtype' => 'messages', 'metadata_name' => 'fromId', 'metadata_value' => $user->getGUID(), 'limit' => 0));
    if ($messages) {
        foreach ($messages as $e) {
            $e->delete();
        }
    }
    access_show_hidden_entities($entity_disable_override);
}
/**
 * Generates a unique available and valid username
 *
 * @param string $username Username prefix
 * @return string
 */
function forms_register_generate_username($username = '')
{
    $available = false;
    $username = iconv('UTF-8', 'ASCII//TRANSLIT', $username);
    $blacklist = '/[\\x{0080}-\\x{009f}\\x{00a0}\\x{2000}-\\x{200f}\\x{2028}-\\x{202f}\\x{3000}\\x{e000}-\\x{f8ff}]/u';
    $blacklist2 = array(' ', '\'', '/', '\\', '"', '*', '&', '?', '#', '%', '^', '(', ')', '{', '}', '[', ']', '~', '?', '<', '>', ';', '|', '¬', '`', '@', '-', '+', '=');
    $username = preg_replace($blacklist, '', $username);
    $username = str_replace($blacklist2, '.', $username);
    $ia = elgg_set_ignore_access(true);
    $ha = access_get_show_hidden_status();
    access_show_hidden_entities(true);
    $minlength = elgg_get_config('minusername') ?: 4;
    if ($username) {
        $fill = $minlength - strlen($username);
    } else {
        $fill = 8;
    }
    $algo = elgg_get_plugin_setting('autogen_username_algo', 'forms_register', 'first_name_only');
    if ($algo == 'full_name' && $fill <= 0) {
        $separator = '.';
    } else {
        $separator = '';
    }
    if ($fill > 0) {
        $suffix = (new ElggCrypto())->getRandomString($fill);
        $username = "******";
    }
    $iterator = 0;
    while (!$available) {
        if ($iterator > 0) {
            $username = "******";
        }
        $user = get_user_by_username($username);
        $available = !$user;
        try {
            if ($available) {
                validate_username($username);
            }
        } catch (Exception $e) {
            if ($iterator >= 100) {
                // too many failed attempts
                $username = (new ElggCrypto())->getRandomString(8);
            }
        }
        $iterator++;
    }
    access_show_hidden_entities($ha);
    elgg_set_ignore_access($ia);
    return strtolower($username);
}
Exemple #9
0
/**
 * Return application for a given application id
 * 
 * @param string $application_id id of the applications
 * 
 * @return ElggEntity|boolean
 */
function ws_pack_get_application_from_id($application_id)
{
    $result = false;
    if (!empty($application_id)) {
        $hidden = access_get_show_hidden_status();
        access_show_hidden_entities(true);
        $options = array("type" => "object", "subtype" => APIApplication::SUBTYPE, "limit" => 1, "metadata_name_value_pairs" => array("application_id" => $application_id));
        if ($entities = elgg_get_entities_from_metadata($options)) {
            $result = $entities[0];
        }
        access_show_hidden_entities($hidden);
    }
    return $result;
}
 /**
  * Generates random unique username
  * @return string
  */
 public static function generateUsername()
 {
     $username = false;
     $ia = elgg_set_ignore_access(true);
     $ha = access_get_show_hidden_status();
     access_show_hidden_entities(true);
     while (!$username) {
         $temp = "u" . rand(100000000, 999999999);
         if (!get_user_by_username($temp)) {
             $username = $temp;
         }
     }
     access_show_hidden_entities($ha);
     elgg_set_ignore_access($ia);
     return $username;
 }
Exemple #11
0
/**
 * Looks for entities without a corresponding entry in the correct type table.
 */
function dbvalidate_get_incomplete_entities()
{
    $access_status = access_get_show_hidden_status();
    access_show_hidden_entities(true);
    $db_prefix = elgg_get_config('dbprefix');
    $types = array('user', 'site', 'group', 'object');
    $bad_guids = array();
    foreach ($types as $type) {
        // thank you for consistent table naming
        $query = "SELECT guid, type, subtype FROM {$db_prefix}entities WHERE type='{$type}'\n\t\t\tAND guid NOT IN (SELECT guid FROM {$db_prefix}{$type}s_entity)";
        if ($result = get_data($query)) {
            $bad_guids = array_merge($bad_guids, $result);
        }
    }
    access_show_hidden_entities($access_status);
    return $bad_guids;
}
Exemple #12
0
/**
 * Handle Stripe webhooks
 */
function stripe_webhook_handler($environment)
{
    $body = get_post_data();
    $event_json = json_decode($body);
    $event_id = $event_json->id;
    $gateway = new StripeClient($environment);
    $event = $gateway->getEvent($event_id);
    if (!$event) {
        return array('success' => false, 'message' => 'Stripe Event for this webhook was not found');
    }
    $ia = elgg_set_ignore_access(true);
    $ha = access_get_show_hidden_status();
    access_show_hidden_entities(true);
    $result = elgg_trigger_plugin_hook_handler($event->type, 'stripe.events', array('environment' => $environment, 'event' => $event), array('success' => true));
    access_show_hidden_entities($ha);
    elgg_set_ignore_access($ia);
    return $result;
}
Exemple #13
0
 static function generateUsername($email)
 {
     list($username, $dummy) = explode("@", $email);
     $username = preg_replace("/[^a-zA-Z0-9]+/", "", $username);
     $hidden = access_get_show_hidden_status();
     access_show_hidden_entities(true);
     if (get_user_by_username($username)) {
         $i = 1;
         while (get_user_by_username($username . $i)) {
             $i++;
         }
         $result = $username . $i;
     } else {
         $result = $username . $i;
     }
     access_show_hidden_entities($hidden);
     return $result;
 }
Exemple #14
0
/**
 * Deletes expired entities.
 * @return boolean
 */
function expirationdate_expire_entities($verbose = true)
{
    $now = time();
    $access = elgg_set_ignore_access(true);
    $access_status = access_get_show_hidden_status();
    access_show_hidden_entities(true);
    if (!($entities = elgg_get_entities_from_metadata(array('metadata_names' => 'expirationdate', 'limit' => false)))) {
        // no entities that need to expire.
        return true;
    }
    foreach ($entities as $entity) {
        if ($entity->expirationdate < $now) {
            $guid = $entity->guid;
            if (!elgg_trigger_plugin_hook('expirationdate:expire_entity', $entity->type, array('entity' => $entity), true)) {
                continue;
            }
            // call the standard delete to allow for triggers, etc.
            if ($entity->expirationdate_disable_only == 1) {
                if ($entity->disable()) {
                    $return = expirationdate_unset($entity->getGUID());
                    $msg = "Disabled {$guid}<br>\n";
                } else {
                    $msg = "Couldn't disable {$guid}<br>\n";
                }
            } else {
                if ($entity->delete()) {
                    $msg = "Deleted {$guid}<br>\n";
                } else {
                    $msg = "Couldn't delete {$guid}<br>\n";
                }
            }
        } else {
            if (!elgg_trigger_plugin_hook('expirationdate:will_expire_entity', $entity->type, array('expirationdate' => $entity->expirationdate, 'entity' => $entity), true)) {
                continue;
            }
        }
        if ($verbose) {
            print $msg;
        }
    }
    access_show_hidden_entities($access_status);
    elgg_set_ignore_access($access);
    return true;
}
Exemple #15
0
/**
 * Listen to the upgrade event to make sure upgrades can be run
 *
 * @param string $event  the name of the event
 * @param string $type   the type of the event
 * @param null   $object nothing
 *
 * @return void
 */
function thewire_tools_upgrade_system_event_handler($event, $type, $object)
{
    // Upgrade also possible hidden entities. This feature get run
    // by an administrator so there's no need to ignore access.
    $access_status = access_get_show_hidden_status();
    access_show_hidden_entities(true);
    // register an upgrade script
    $options = array("type" => "user", "plugin_id" => "thewire_tools", "plugin_user_setting_name" => "notify_mention", "count" => true);
    $count = elgg_get_entities_from_plugin_user_settings($options);
    if ($count) {
        $path = "admin/upgrades/thewire_tools_mentions";
        $upgrade = new ElggUpgrade();
        if (!$upgrade->getUpgradeFromPath($path)) {
            $upgrade->setPath($path);
            $upgrade->title = "TheWire Tools mentions upgrade";
            $upgrade->description = "The way mention notifications are handled has changed. Run this script to make sure all settings are migrated.";
            $upgrade->save();
        }
    }
    access_show_hidden_entities($access_status);
}
Exemple #16
0
/**
 * Handle requests to /welcome/
 *
 * @param array $page Page segments
 *
 * @return boolean
 */
function welcome_page_handler($page)
{
    // User validation by email has disabled the user so we need to
    // explicitly include hidden entities in the database query
    $hidden_status = access_get_show_hidden_status();
    access_show_hidden_entities(true);
    $user = get_user($page[0]);
    // Set hidden entity status back to normal
    access_show_hidden_entities($hidden_status);
    if (!$user) {
        forward();
    }
    set_input('guid', $user->guid);
    $base = elgg_get_plugins_path() . 'welcome/pages/';
    switch ($page[0]) {
        default:
            include $base . '/welcome.php';
            break;
    }
    return true;
}
Exemple #17
0
/**
 * Listen to the upgrade event
 *
 * @param string $event  name of the event
 * @param string $type   type of the event
 * @param null   $object supplied object
 *
 * @return void
 */
function content_subscriptions_upgrade_system_handler($event, $type, $object)
{
    // Upgrade also possible hidden entities. This feature get run
    // by an administrator so there's no need to ignore access.
    $access_status = access_get_show_hidden_status();
    access_show_hidden_entities(true);
    // register an upgrade script
    $options = array("type" => "user", "relationship" => CONTENT_SUBSCRIPTIONS_SUBSCRIPTION, "inverse_relationship" => true, "count" => true);
    $count = elgg_get_entities_from_relationship($options);
    if ($count) {
        $path = "admin/upgrades/content_subscriptions";
        $upgrade = new ElggUpgrade();
        if (!$upgrade->getUpgradeFromPath($path)) {
            $upgrade->setPath($path);
            $upgrade->title = "Content Subscription upgrade";
            $upgrade->description = "The way content subscriptions are handled has changed. Run this script to make sure all content subscriptions are migrated.";
            $upgrade->save();
        }
    }
    access_show_hidden_entities($access_status);
}
Exemple #18
0
    /**
     * Listen to the upgrade event, to register a script
     *
     * @param string $event  name of the event
     * @param string $type   type of the event
     * @param null   $object supplied object
     *
     * @return void
     */
    public static function registerScript($event, $type, $object)
    {
        // Upgrade also possible hidden entities. This feature get run
        // by an administrator so there's no need to ignore access.
        $access_status = access_get_show_hidden_status();
        access_show_hidden_entities(true);
        // register an upgrade script
        $options = array('type' => 'user', 'relationship' => CONTENT_SUBSCRIPTIONS_SUBSCRIPTION, 'inverse_relationship' => true, 'count' => true);
        $count = elgg_get_entities_from_relationship($options);
        if ($count) {
            $path = 'admin/upgrades/content_subscriptions';
            $upgrade = new \ElggUpgrade();
            if (!$upgrade->getUpgradeFromPath($path)) {
                $upgrade->setPath($path);
                $upgrade->title = 'Content Subscription upgrade';
                $upgrade->description = 'The way content subscriptions are handled has changed.
					Run this script to make sure all content subscriptions are migrated.';
                $upgrade->save();
            }
        }
        access_show_hidden_entities($access_status);
    }
/**
 * 
 * Disable a new user pending email verification
 * 
 * @param type $hook
 * @param type $type
 * @param type $return
 * @param type $params
 * @return type
 */
function disable_new_user($hook, $type, $value, $params)
{
    $user = elgg_extract('user', $params);
    if (!elgg_get_plugin_setting('email_validate', PLUGIN_ID)) {
        return;
    }
    // no clue what's going on, so don't react.
    if (!$user instanceof \ElggUser) {
        return;
    }
    // another plugin is requesting that registration be terminated
    // no need for uservalidationbyemail
    if (!$value) {
        return $value;
    }
    // has the user already been validated?
    if (elgg_get_user_validation_status($user->guid) == true) {
        return $value;
    }
    // disable user to prevent showing up on the site
    // set context so our canEdit() override works
    elgg_push_context('stormpath_new_user');
    $hidden_entities = access_get_show_hidden_status();
    access_show_hidden_entities(TRUE);
    // Don't do a recursive disable.  Any entities owned by the user at this point
    // are products of plugins that hook into create user and might need
    // access to the entities.
    // @todo That ^ sounds like a specific case...would be nice to track it down...
    $user->disable('stormpath_new_user', FALSE);
    // set user as unvalidated and send out validation email
    elgg_set_user_validation_status($user->guid, FALSE);
    // trigger the stormpath email validation
    elgg_pop_context();
    access_show_hidden_entities($hidden_entities);
    return $value;
}
Exemple #20
0
$text = get_input("comment");
$emails = get_input("user_guid_email");
if (!empty($emails) && !is_array($emails)) {
    $emails = array($emails);
}
$csv = get_uploaded_file("csv");
if (get_input("resend") == "yes") {
    $resend = true;
} else {
    $resend = false;
}
$group = get_entity($group_guid);
if ((!empty($user_guids) || !empty($emails) || !empty($csv)) && !empty($group)) {
    if ($group instanceof ElggGroup && ($group->canEdit() || group_tools_allow_members_invite($group))) {
        // show hidden (unvalidated) users
        $hidden = access_get_show_hidden_status();
        access_show_hidden_entities(true);
        // counters
        $already_invited = 0;
        $invited = 0;
        $member = 0;
        $join = 0;
        // invite existing users
        if (!empty($user_guids)) {
            if (!$adding) {
                // invite users
                foreach ($user_guids as $u_id) {
                    $user = get_user($u_id);
                    if (!empty($user)) {
                        if (!$group->isMember($user)) {
                            if (!check_entity_relationship($group->getGUID(), "invited", $user->getGUID()) || $resend) {
 /**
  * Ensure that \ElggBatch doesn't go into infinite loop when disabling annotations recursively when show hidden is enabled.
  *
  * https://github.com/Elgg/Elgg/issues/5952
  */
 public function test_disabling_annotations_infinite_loop()
 {
     //let's have some entity
     $group = new \ElggGroup();
     $group->name = 'test_group';
     $group->access_id = ACCESS_PUBLIC;
     $this->assertTrue($group->save() !== false);
     $total = 51;
     //add some annotations
     for ($cnt = 0; $cnt < $total; $cnt++) {
         $group->annotate('test_annotation', 'value_' . $total);
     }
     //disable them
     $show_hidden = access_get_show_hidden_status();
     access_show_hidden_entities(true);
     $options = array('guid' => $group->guid, 'limit' => $total);
     elgg_disable_annotations($options);
     access_show_hidden_entities($show_hidden);
     //confirm all being disabled
     $annotations = $group->getAnnotations(array('limit' => $total));
     foreach ($annotations as $annotation) {
         $this->assertTrue($annotation->enabled == 'no');
     }
     //delete group and annotations
     $group->delete();
 }
Exemple #22
0
<?php

/**
 * Admin area to view, validate, resend validation email, or delete unvalidated users.
 *
 * @package Elgg.Core.Plugin
 * @subpackage UserValidationByEmail.Administration
 */
$limit = get_input('limit', 10);
$offset = get_input('offset', 0);
// can't use elgg_list_entities() and friends because we don't use the default view for users.
$ia = elgg_set_ignore_access(TRUE);
$hidden_entities = access_get_show_hidden_status();
access_show_hidden_entities(TRUE);
$options = array('type' => 'user', 'wheres' => uservalidationbyemail_get_unvalidated_users_sql_where(), 'limit' => $limit, 'offset' => $offset, 'count' => TRUE);
$count = elgg_get_entities($options);
if (!$count) {
    access_show_hidden_entities($hidden_entities);
    elgg_set_ignore_access($ia);
    echo elgg_autop(elgg_echo('uservalidationbyemail:admin:no_unvalidated_users'));
    return TRUE;
}
$options['count'] = FALSE;
$users = elgg_get_entities($options);
access_show_hidden_entities($hidden_entities);
elgg_set_ignore_access($ia);
// setup pagination
$pagination = elgg_view('navigation/pagination', array('base_url' => 'admin/users/unvalidated', 'offset' => $offset, 'count' => $count, 'limit' => $limit));
$bulk_actions_checkbox = '<label><input type="checkbox" id="uservalidationbyemail-checkall" />' . elgg_echo('uservalidationbyemail:check_all') . '</label>';
$validate = elgg_view('output/url', array('href' => 'action/uservalidationbyemail/validate/', 'text' => elgg_echo('uservalidationbyemail:admin:validate'), 'title' => elgg_echo('uservalidationbyemail:confirm_validate_checked'), 'class' => 'uservalidationbyemail-submit', 'is_action' => true, 'is_trusted' => true));
$resend_email = elgg_view('output/url', array('href' => 'action/uservalidationbyemail/resend_validation/', 'text' => elgg_echo('uservalidationbyemail:admin:resend_validation'), 'title' => elgg_echo('uservalidationbyemail:confirm_resend_validation_checked'), 'class' => 'uservalidationbyemail-submit', 'is_action' => true, 'is_trusted' => true));
Exemple #23
0
function elgg_solr_get_system_count($options, $starttime, $endtime)
{
    $options['wheres'] = array("e.time_created >= {$starttime}", "e.time_created <= {$endtime}");
    $options['count'] = true;
    $access = access_get_show_hidden_status();
    access_show_hidden_entities(true);
    $count = elgg_get_entities($options);
    access_show_hidden_entities($access);
    return $count;
}
Exemple #24
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;
 }
Exemple #25
0
 elgg_require_js('hljs-init');
 // filter new friendships and new bookmarks from river
 elgg_register_plugin_hook_handler('creating', 'river', function ($hook, $type, $item) {
     $view = $item['view'];
     switch ($view) {
         case 'river/relationship/friend/create':
         case 'river/object/bookmarks/create':
             return false;
             break;
     }
 });
 // Delete messages from a user who is being deleted
 // TODO(ewinslow): Move to Elgg core??
 elgg_register_event_handler('delete', 'user', function ($event, $type, $user) {
     // make sure we delete them all
     $entity_disable_override = access_get_show_hidden_status();
     access_show_hidden_entities(true);
     $messages = elgg_get_entities_from_metadata(array('type' => 'object', 'subtype' => 'messages', 'metadata_name' => 'fromId', 'metadata_value' => $user->getGUID(), 'limit' => 0));
     if ($messages) {
         foreach ($messages as $e) {
             $e->delete();
         }
     }
     access_show_hidden_entities($entity_disable_override);
 });
 // convert messageboard to private message interface
 elgg_register_widget_type('messageboard', elgg_echo("customizations:widget:pm"), elgg_echo("customizations:widget:pm:desc"), array("profile"));
 // Forward to referrer if posting PM from a widget
 elgg_register_plugin_hook_handler('forward', 'system', function () {
     if (get_input('pm_widget') == true) {
         return $_SERVER['HTTP_REFERER'];
/**
 * Disables metadata based on $options.
 *
 * @warning Unlike elgg_get_metadata() this will not accept an empty options array!
 *
 * @param array $options An options array. {@link elgg_get_metadata()}
 * @return bool|null true on success, false on failure, null if no metadata disabled.
 * @since 1.8.0
 */
function elgg_disable_metadata(array $options)
{
    if (!_elgg_is_valid_options_for_batch_operation($options, 'metadata')) {
        return false;
    }
    _elgg_get_metadata_cache()->invalidateByOptions('disable', $options);
    // if we can see hidden (disabled) we need to use the offset
    // otherwise we risk an infinite loop if there are more than 50
    $inc_offset = access_get_show_hidden_status();
    $options['metastring_type'] = 'metadata';
    return _elgg_batch_metastring_based_objects($options, 'elgg_batch_disable_callback', $inc_offset);
}
Exemple #27
0
/**
 * Prevent a manual code login with login().
 *
 * @param string   $event
 * @param string   $type
 * @param ElggUser $user
 * @return bool
 *
 * @throws LoginException
 */
function uservalidationbyemail_check_manual_login($event, $type, $user)
{
    $access_status = access_get_show_hidden_status();
    access_show_hidden_entities(TRUE);
    if ($user instanceof ElggUser && !$user->isEnabled() && !$user->validated) {
        // send new validation email
        uservalidationbyemail_request_validation($user->getGUID());
        // restore hidden entities settings
        access_show_hidden_entities($access_status);
        // throw error so we get a nice error message
        throw new LoginException(elgg_echo('uservalidationbyemail:login:fail'));
    }
    access_show_hidden_entities($access_status);
}
Exemple #28
0
/**
 * Get river items
 *
 * @note If using types and subtypes in a query, they are joined with an AND.
 *
 * @param array $options Parameters:
 *   ids                  => INT|ARR River item id(s)
 *   subject_guids        => INT|ARR Subject guid(s)
 *   object_guids         => INT|ARR Object guid(s)
 *   target_guids         => INT|ARR Target guid(s)
 *   annotation_ids       => INT|ARR The identifier of the annotation(s)
 *   action_types         => STR|ARR The river action type(s) identifier
 *   posted_time_lower    => INT     The lower bound on the time posted
 *   posted_time_upper    => INT     The upper bound on the time posted
 *
 *   types                => STR|ARR Entity type string(s)
 *   subtypes             => STR|ARR Entity subtype string(s)
 *   type_subtype_pairs   => ARR     Array of type => subtype pairs where subtype
 *                                   can be an array of subtype strings
 *
 *   relationship         => STR     Relationship identifier
 *   relationship_guid    => INT|ARR Entity guid(s)
 *   inverse_relationship => BOOL    Subject or object of the relationship (false)
 *
 * 	 limit                => INT     Number to show per page (20)
 *   offset               => INT     Offset in list (0)
 *   count                => BOOL    Count the river items? (false)
 *   order_by             => STR     Order by clause (rv.posted desc)
 *   group_by             => STR     Group by clause
 *
 *   distinct             => BOOL    If set to false, Elgg will drop the DISTINCT
 *                                   clause from the MySQL query, which will improve
 *                                   performance in some situations. Avoid setting this
 *                                   option without a full understanding of the
 *                                   underlying SQL query Elgg creates. (true)
 *
 * @return array|int
 * @since 1.8.0
 */
function elgg_get_river(array $options = array())
{
    global $CONFIG;
    $defaults = array('ids' => ELGG_ENTITIES_ANY_VALUE, 'subject_guids' => ELGG_ENTITIES_ANY_VALUE, 'object_guids' => ELGG_ENTITIES_ANY_VALUE, 'target_guids' => ELGG_ENTITIES_ANY_VALUE, 'annotation_ids' => ELGG_ENTITIES_ANY_VALUE, 'action_types' => ELGG_ENTITIES_ANY_VALUE, 'relationship' => null, 'relationship_guid' => null, 'inverse_relationship' => false, 'types' => ELGG_ENTITIES_ANY_VALUE, 'subtypes' => ELGG_ENTITIES_ANY_VALUE, 'type_subtype_pairs' => ELGG_ENTITIES_ANY_VALUE, 'posted_time_lower' => ELGG_ENTITIES_ANY_VALUE, 'posted_time_upper' => ELGG_ENTITIES_ANY_VALUE, 'limit' => 20, 'offset' => 0, 'count' => false, 'distinct' => true, 'order_by' => 'rv.posted desc', 'group_by' => ELGG_ENTITIES_ANY_VALUE, 'wheres' => array(), 'joins' => array());
    $options = array_merge($defaults, $options);
    $singulars = array('id', 'subject_guid', 'object_guid', 'target_guid', 'annotation_id', 'action_type', 'type', 'subtype');
    $options = _elgg_normalize_plural_options_array($options, $singulars);
    $wheres = $options['wheres'];
    $wheres[] = _elgg_get_guid_based_where_sql('rv.id', $options['ids']);
    $wheres[] = _elgg_get_guid_based_where_sql('rv.subject_guid', $options['subject_guids']);
    $wheres[] = _elgg_get_guid_based_where_sql('rv.object_guid', $options['object_guids']);
    $wheres[] = _elgg_get_guid_based_where_sql('rv.target_guid', $options['target_guids']);
    $wheres[] = _elgg_get_guid_based_where_sql('rv.annotation_id', $options['annotation_ids']);
    $wheres[] = _elgg_river_get_action_where_sql($options['action_types']);
    $wheres[] = _elgg_get_river_type_subtype_where_sql('rv', $options['types'], $options['subtypes'], $options['type_subtype_pairs']);
    if ($options['posted_time_lower'] && is_int($options['posted_time_lower'])) {
        $wheres[] = "rv.posted >= {$options['posted_time_lower']}";
    }
    if ($options['posted_time_upper'] && is_int($options['posted_time_upper'])) {
        $wheres[] = "rv.posted <= {$options['posted_time_upper']}";
    }
    if (!access_get_show_hidden_status()) {
        $wheres[] = "rv.enabled = 'yes'";
    }
    $joins = $options['joins'];
    $dbprefix = elgg_get_config('dbprefix');
    $joins[] = "JOIN {$dbprefix}entities oe ON rv.object_guid = oe.guid";
    // LEFT JOIN is used because all river items do not necessarily have target
    $joins[] = "LEFT JOIN {$dbprefix}entities te ON rv.target_guid = te.guid";
    if ($options['relationship_guid']) {
        $clauses = elgg_get_entity_relationship_where_sql('rv.subject_guid', $options['relationship'], $options['relationship_guid'], $options['inverse_relationship']);
        if ($clauses) {
            $wheres = array_merge($wheres, $clauses['wheres']);
            $joins = array_merge($joins, $clauses['joins']);
        }
    }
    // see if any functions failed
    // remove empty strings on successful functions
    foreach ($wheres as $i => $where) {
        if ($where === false) {
            return false;
        } elseif (empty($where)) {
            unset($wheres[$i]);
        }
    }
    // remove identical where clauses
    $wheres = array_unique($wheres);
    if (!$options['count']) {
        $distinct = $options['distinct'] ? "DISTINCT" : "";
        $query = "SELECT {$distinct} rv.* FROM {$CONFIG->dbprefix}river rv ";
    } else {
        // note: when DISTINCT unneeded, it's slightly faster to compute COUNT(*) than IDs
        $count_expr = $options['distinct'] ? "DISTINCT rv.id" : "*";
        $query = "SELECT COUNT({$count_expr}) as total FROM {$CONFIG->dbprefix}river rv ";
    }
    // add joins
    foreach ($joins as $j) {
        $query .= " {$j} ";
    }
    // add wheres
    $query .= ' WHERE ';
    foreach ($wheres as $w) {
        $query .= " {$w} AND ";
    }
    // Make sure that user has access to all the entities referenced by each river item
    $object_access_where = _elgg_get_access_where_sql(array('table_alias' => 'oe'));
    $target_access_where = _elgg_get_access_where_sql(array('table_alias' => 'te'));
    // We use LEFT JOIN with entities table but the WHERE clauses are used
    // regardless if a JOIN is successfully made. The "te.guid IS NULL" is
    // needed because of this.
    $query .= "{$object_access_where} AND ({$target_access_where} OR te.guid IS NULL) ";
    if (!$options['count']) {
        $options['group_by'] = sanitise_string($options['group_by']);
        if ($options['group_by']) {
            $query .= " GROUP BY {$options['group_by']}";
        }
        $options['order_by'] = sanitise_string($options['order_by']);
        $query .= " ORDER BY {$options['order_by']}";
        if ($options['limit']) {
            $limit = sanitise_int($options['limit']);
            $offset = sanitise_int($options['offset'], false);
            $query .= " LIMIT {$offset}, {$limit}";
        }
        $river_items = get_data($query, '_elgg_row_to_elgg_river_item');
        _elgg_prefetch_river_entities($river_items);
        return $river_items;
    } else {
        $total = get_data_row($query);
        return (int) $total->total;
    }
}
Exemple #29
0
 /**
  * Disables annotations based on $options.
  *
  * @warning Unlike elgg_get_annotations() this will not accept an empty options array!
  *
  * @param array $options An options array. {@link elgg_get_annotations()}
  * @return bool|null true on success, false on failure, null if no annotations disabled.
  */
 function disableAll(array $options)
 {
     if (!_elgg_is_valid_options_for_batch_operation($options, 'annotation')) {
         return false;
     }
     // if we can see hidden (disabled) we need to use the offset
     // otherwise we risk an infinite loop if there are more than 50
     $inc_offset = access_get_show_hidden_status();
     $options['metastring_type'] = 'annotations';
     return _elgg_batch_metastring_based_objects($options, 'elgg_batch_disable_callback', $inc_offset);
 }
Exemple #30
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])) {
                    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);
                    $sub_entities = get_data("SELECT * from {$CONFIG->dbprefix}entities\n\t\t\t\t\t\tWHERE container_guid={$guid}\n\t\t\t\t\t\t\tor owner_guid={$guid}\n\t\t\t\t\t\t\tor site_guid={$guid}", 'entity_row_to_elggstar');
                    if ($sub_entities) {
                        foreach ($sub_entities as $e) {
                            // check for equality so that an entity that is its own
                            // owner or container does not cause infinite loop
                            if ($e->guid != $guid) {
                                $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 $res;
            }
        }
    }
    return false;
}