/** * Recursively loop through all menu items and children to get correct options. * * @param array $menu_items the current level of menu items * @param int $entity_guid the current entity being edited (optional) * @param int $depth recursive depth for layout * * @return array the selection options */ function menu_builder_get_menu_select_option($menu_items, $entity_guid = 0, $depth = 0) { $result = array(); $entity_guid = sanitise_int($entity_guid, false); $depth = sanitise_int($depth, false); if (!empty($menu_items) && $depth < 4) { foreach ($menu_items as $menu_item) { $name = $menu_item->getName(); if (!is_numeric($name)) { // skip extra menu items continue; } if (!empty($entity_guid) && $name == $entity_guid) { // skip yourself and all your children continue; } $result[$name] = trim(str_repeat("-", $depth) . " " . $menu_item->getText()); $children = $menu_item->getChildren(); if (!empty($children)) { $child_items = menu_builder_get_menu_select_option($children, $entity_guid, $depth + 1); if (!empty($child_items)) { $result += $child_items; } } } } return $result; }
function DoTask() { global $Administrator, $GAME; if (!$Administrator) { $mypage = page::standard(); $mypage->title_body('Not authorised'); $mypage->leaf('p', 'You are not authorised to make use of this page. Please click <a href="board.php?GameID=' . $GAME['GameID'] . '">here</a> to go to the board page, or <a href="index.php">here</a> to return to the Main Page.'); $mypage->finish(); } $thenumber = sanitise_int(@$_POST['thenumber']); if ($thenumber < -9 or $thenumber > 99 or $thenumber == 0) { $mypage = page::standard(); $mypage->title_body('Invalid input'); $mypage->leaf('p', 'Expected a nonzero integer between -9 and 99 inclusive, but received ' . $thenumber . '. Please click <a href="board.php?GameID=' . $GAME['GameID'] . '">here</a> to go to the board page, or <a href="index.php">here</a> to return to the Main Page.'); $mypage->finish(); } $interval = sanitise_enum(@$_POST['theinterval'], array('MINUTE', 'HOUR', 'DAY')); if (@$_POST['whattime'] == 'now') { $whattime = 'UTC_TIMESTAMP()'; } else { $whattime = '"LastMove"'; } $time_expr = 'TIMESTAMPADD(' . $interval . ', :thenumber:, ' . $whattime . ')'; dbquery(DBQUERY_WRITE, 'UPDATE "Game" JOIN "GameInProgress" ON "Game"."GameID" = "GameInProgress"."Game" SET "Game"."LastMove" = ' . $time_expr . ', "GameInProgress"."GIPLastMove" = ' . $time_expr . ' "Game"."GameTicker" = CONCAT("Game"."GameTicker", :tickerconcat:), "Game"."GameTickerNames" = CONCAT("Game"."GameTickerNames", :namesconcat:) WHERE "GameID" = :game:', 'thenumber', $thenumber, 'tickerconcat', '3A' . callmovetimediff() . letter_end_number($_SESSION['MyUserID']) . letter_end_number($_SESSION['MyGenderCode']), 'namesconcat', '|' . $_SESSION['MyUserName'], 'game', $GAME['GameID']); dbquery(DBQUERY_COMMIT); page::redirect(3, 'board.php?GameID=' . $GAME['GameID'], 'Successfully altered clock.'); }
/** * returns an array to be used in elgg_get_* functions * * @param int $assignee the guid of the assigned user * @param int $group_filter optional group filter * * @return array */ function todos_get_open_assigned_item_options($assignee = 0, $group_filter = 0) { $assignee = sanitise_int($assignee, false); $group_filter = sanitise_int($group_filter, false); $options = array('type' => 'object', 'subtype' => TodoItem::SUBTYPE, 'limit' => false, 'metadata_name_value_pairs' => array(array('name' => 'order', 'value' => 0, 'operand' => '>')), 'full_view' => false, 'item_class' => 'todos-list-item', 'list_class' => 'todos-list mtl', 'pagination' => false); if (!empty($assignee)) { // assiged to specific person $options['metadata_name_value_pairs'][] = array('name' => 'assignee', 'value' => $assignee); $options['show_assignee'] = false; } else { // just assigned $options['metadata_name_value_pairs'][] = array('name' => 'assignee', 'value' => 0, 'operand' => '>'); } if (!empty($group_filter) && $assignee !== $group_filter) { $group_lists = elgg_get_entities_from_metadata(array('type' => 'object', 'subtype' => TodoList::SUBTYPE, 'container_guid' => $group_filter, 'limit' => false, 'callback' => false, 'metadata_name_value_pairs' => array('active' => true))); if (!empty($group_lists)) { $guids = array(); foreach ($group_lists as $row) { $guids[] = (int) $row->guid; } $options['wheres'] = array('e.container_guid IN (' . implode(',', $guids) . ')'); } } return $options; }
function DoTask() { global $GAME; if ($GAME['MyColour'] == 50) { $mypage = page::standard(); $mypage->title_body('Not playing in this game'); $mypage->leaf('p', 'You are not currently playing in this game. Please click <a href="board.php?GameID=' . $GAME['GameID'] . '">here</a> to go to the board page, or <a href="index.php">here</a> to return to the Main Page.'); $mypage->finish(); } if (@$_POST['FirstCardNotMyTurn'] == 'NoCardSelected' or @$_POST['SecondCardNotMyTurn'] == 'NoCardSelected') { $mypage = page::standard(); $mypage->title_body('Cards not selected'); $mypage->leaf('p', 'You omitted to select a card in one or both of the selection lists. Please select a card in each list and then try again. Click <a href="board.php?GameID=' . $GAME['GameID'] . '">here</a> to go to the board page, or <a href="index.php">here</a> to return to the Main Page.'); $mypage->finish(); } $FC = sanitise_int(@$_POST['FirstCardNotMyTurn'], SANITISE_NO_FLAGS, 0, $GAME['HandSize'][$GAME['MyColour']] - 1); $SC = sanitise_int(@$_POST['SecondCardNotMyTurn'], SANITISE_NO_FLAGS, 0, $GAME['HandSize'][$GAME['MyColour']] - 1); if ($FC == $SC) { $mypage = page::standard(); $mypage->title_body('Same cards selected'); $mypage->leaf('p', 'You selected the same card in each selection list. Please select a different card in each list and then try again. Click <a href="board.php?GameID=' . $GAME['GameID'] . '">here</a> to go to the board page, or <a href="index.php">here</a> to return to the Main Page.'); $mypage->finish(); } $CardSwitch = $GAME['Cards'][$GAME['MyColour']][$FC]; $GAME['Cards'][$GAME['MyColour']][$FC] = $GAME['Cards'][$GAME['MyColour']][$SC]; $GAME['Cards'][$GAME['MyColour']][$SC] = $CardSwitch; dbformatgamedata(); page::redirect(3, 'board.php?GameID=' . $GAME['GameID'], 'Successfully swapped cards.'); }
/** * Batch sync data to ElasticSearch * * This function is timed at a max runtime of 30sec * * @param array $options the options for elgg_get_entities() * @param int $crontime the starttime of the cron in order to limit max runtime * @param string $getter the getter function to use for \ElggBatch * * @return bool|void */ protected static function batchSync($options, $crontime, $getter = '') { if (empty($options) || !is_array($options)) { return; } if (empty($getter)) { $getter = 'elgg_get_entities_from_private_settings'; } if (!is_callable($getter)) { return false; } $client = elasticsearch_get_client(); if (empty($client)) { return; } $crontime = sanitise_int($crontime, false); if (empty($crontime)) { $crontime = time(); } if (time() - $crontime >= 30) { return false; } set_time_limit(40); $ia = elgg_set_ignore_access(true); $time_left = true; $batch_size = 100; $options['callback'] = false; $options['limit'] = $batch_size; while ($time_left && ($rows = call_user_func($getter, $options))) { $guids = array(); foreach ($rows as $row) { $guids[] = (int) $row->guid; } $result = $client->bulkIndexDocuments($guids); if (empty($result)) { break; } $items = elgg_extract('items', $result); foreach ($items as $item) { $guid = (int) elgg_extract('_id', elgg_extract('index', $item)); $status = elgg_extract('status', elgg_extract('index', $item)); if ($status !== 200) { continue; } if (empty($guid)) { continue; } set_private_setting($guid, ELASTICSEARCH_INDEXED_NAME, time()); } if (time() - $crontime >= 30) { $time_left = false; break; } } // restore access elgg_set_ignore_access($ia); return $time_left; }
function setIframeHeight($height) { $result = false; $height = sanitise_int($height); if (!empty($height)) { $result = $this->set("iframe_height", $height); } return $result; }
/** * Convert a byte size into something readable * * @param int $size the size to convert * * @return string */ function dataroot_browser_format_size($size) { $size = sanitise_int($size, false); if (empty($size)) { return 'n/a'; } $sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; return round($size / pow(1024, $i = floor(log($size, 1024))), 2) . ' ' . $sizes[$i]; }
/** * Handles voting on an entity * * @param integer $guid The entity guid being voted on * @param integer $vote The vote * @return string A status message to be returned to the client */ function elggx_fivestar_vote($guid, $vote) { $result = false; // do we have an entity if (!empty($guid) && ($entity = get_entity($guid))) { // do we have a logged in user if ($user_guid = elgg_get_logged_in_user_guid()) { $vote = sanitise_int($vote, false); $annotation_options = array("guid" => $entity->getGUID(), "type" => $entity->getType(), "annotation_name" => "fivestar", "annotation_owner_guid" => $user_guid, "limit" => 1); // already voted? if ($annotations = elgg_get_annotations($annotation_options)) { // yes // are we allowed the change/cancel our vote // 1 = yes // 0 = no $change_cancel = (int) elgg_get_plugin_setting("change_cancel", "elggx_fivestar"); // check if we want to cancel (vote = 0) if ($vote == 0 && $change_cancel) { // fire a hook to allow other plugins to halt the action $params = array("entity" => $entity, "vote" => $vote, "user_guid" => $user_guid); if (!elgg_trigger_plugin_hook("elggx_fivestar:cancel", "all", $params, false)) { // nobody stopped us, so remove the annotation $annotations[0]->delete(); // let the user know $result = elgg_echo("elggx_fivestar:deleted"); } } else { if ($change_cancel) { // we want to update update_annotation($annotations[0]->id, "fivestar", $vote, "integer", $user_guid, ACCESS_PUBLIC); $result = elgg_echo("elggx_fivestar:updated"); } else { // not allowed to update/cancel $result = elgg_echo("elggx_fivestar:nodups"); } } } elseif ($vote > 0) { // no, and wish to vote // fire a hook to allow other plugins to halt the action $params = array("entity" => $entity, "vote" => $vote, "user_guid" => $user_guid); if (!elgg_trigger_plugin_hook("elggx_fivestar:vote", "all", $params, false)) { // nobody stopped us, so save the vote $entity->annotate("fivestar", $vote, ACCESS_PUBLIC, $user_guid); } } else { // incorrect vote $result = elgg_echo("elggx_fivestar:novote"); } // update the avarage vote on the entity elggx_fivestar_set_rating($entity); } } return $result; }
/** * listen to the livesearch in order to provide the objects picker * * @param string $hook the name of the hook * @param string $type the type of the hook * @param array $return_value current return value * @param array $params supplied params * * @return void */ public static function livesearch($hook, $type, $return_value, $params) { // only return results to logged in users. $user = elgg_get_logged_in_user_entity(); if (empty($user)) { return; } $q = get_input('term', get_input('q')); if (empty($q)) { return; } $input_name = get_input('name', 'objects'); $q = sanitise_string($q); // replace mysql vars with escaped strings $q = str_replace(['_', '%'], ['\\_', '\\%'], $q); $match_on = get_input('match_on', 'all'); if (!is_array($match_on)) { $match_on = [$match_on]; } // only take over groups search if (count($match_on) > 1 || !in_array('objects', $match_on)) { return; } $owner_guid = ELGG_ENTITIES_ANY_VALUE; if (get_input('match_owner', false)) { $owner_guid = $user->getGUID(); } $subtype = get_input('subtype', ELGG_ENTITIES_ANY_VALUE); $limit = sanitise_int(get_input('limit', 10), false); $container_guid = sanitise_int(get_input('container_guid'), false); if (empty($container_guid)) { $container_guid = ELGG_ENTITIES_ANY_VALUE; } if ($subtype === 'static' && $container_guid) { $owner_guid = $container_guid; $container_guid = ELGG_ENTITIES_ANY_VALUE; } // grab a list of entities and send them in json. $results = []; $options = ['type' => 'object', 'subtype' => $subtype, 'limit' => $limit, 'owner_guid' => $owner_guid, 'container_guid' => $container_guid, 'joins' => ['JOIN ' . elgg_get_config('dbprefix') . 'objects_entity oe ON e.guid = oe.guid'], 'wheres' => ["(oe.title LIKE '%{$q}%' OR oe.description LIKE '%{$q}%')"]]; $entities = elgg_get_entities($options); if (!empty($entities)) { foreach ($entities as $entity) { $output = elgg_view('input/objectpicker/item', ['entity' => $entity, 'input_name' => $input_name, 'owner_guid' => $owner_guid, 'container_guid' => $container_guid]); $result = ['type' => 'object', 'name' => $entity->title, 'desc' => $entity->description, 'guid' => $entity->getGUID(), 'label' => $output, 'value' => $entity->getGUID(), 'url' => $entity->getURL(), 'html' => $output]; $results[] = $result; } } header('Content-Type: application/json'); echo json_encode($results); exit; }
function DoTask() { global $Administrator, $GAME, $unexpectederrormessage; $AdminKickList = sanitise_int(@$_POST['AdminKickList']); $PostFailureTitle = false; do { if (!$Administrator) { $PostFailureTitle = 'Not authorised'; $PostFailureMessage = 'You are not authorised to make use of this page. Please click <a href="board.php?GameID=' . $GAME['GameID'] . '">here</a> to return to the board page, or <a href="index.php">here</a> to return to the Main Page.'; break; } if (!@$_POST['CheckC']) { $PostFailureTitle = 'Tick box left unticked'; $PostFailureMessage = 'The tick box was left unticked. You need to make sure the box is ticked - this is to prevent accidental use of the administrator controls. Please click <a href="board.php?GameID=' . $GAME['GameID'] . '">here</a> to go to the board page, or <a href="index.php">here</a> to return to the Main Page.'; break; } if ($GAME['GameStatus'] != 'In Progress' and $GAME['GameStatus'] != 'Recruiting Replacement') { $PostFailureTitle = 'Cannot kick player'; $PostFailureMessage = 'Players cannot be kicked right now, perhaps because the game has finished. Please click <a href="board.php?GameID=' . $GAME['GameID'] . '">here</a> to go to the board page, or <a href="index.php">here</a> to return to the Main Page.'; break; } if ($AdminKickList < 0 or $AdminKickList >= MAX_PLAYERS) { $PostFailureTitle = 'Invalid input'; $PostFailureMessage = 'Expected an integer between 0 and ' . (MAX_PLAYERS - 1) . ' inclusive, but received ' . $AdminKickList . '. Please click <a href="board.php?GameID=' . $GAME['GameID'] . '">here</a> to go to the board page, or <a href="index.php">here</a> to return to the Main Page.'; break; } if (!$GAME['PlayerExists'][$AdminKickList] or $GAME['PlayerMissing'][$AdminKickList]) { $PostFailureTitle = 'Seat is empty'; $PostFailureMessage = 'The chosen seat is empty, or the chosen colour does not exist in this game. Perhaps the player was kicked in the meantime. Please click <a href="board.php?GameID=' . $GAME['GameID'] . '">here</a> to go to the board page, or <a href="index.php">here</a> to return to the Main Page.'; break; } if ($GAME['PlayersMissing'] + 1 == $GAME['CurrentPlayers']) { $PostFailureTitle = 'Only one player is not missing'; $PostFailureMessage = 'This is the only player who is not missing. If you do not want the game to continue, please select to abort it instead. Click <a href="board.php?GameID=' . $GAME['GameID'] . '">here</a> to go to the board page, or <a href="index.php">here</a> to return to the Main Page.'; break; } } while (false); if ($PostFailureTitle !== false) { $mypage = page::standard(); $mypage->title_body($PostFailureTitle); $mypage->leaf('p', $PostFailureMessage); $mypage->finish(); } KickPlayer($AdminKickList, 1); dbformatgamedata(); page::redirect(3, 'board.php?GameID=' . $GAME['GameID'], 'Successfully kicked player.'); }
/** * Create river events when a friend is added * * @param int $user_guid the user who is accepting * @param int $friend_guid the friend who he accepted * * @return bool */ function friend_request_create_river_events($user_guid, $friend_guid) { $user_guid = sanitise_int($user_guid, false); $friend_guid = sanitise_int($friend_guid, false); if (empty($user_guid) || empty($friend_guid)) { return false; } // check plugin setting if (elgg_get_plugin_setting('add_river', 'friend_request') === 'no') { // no event are to be created return true; } // add to river elgg_create_river_item(['view' => 'river/relationship/friend/create', 'action_type' => 'friend', 'subject_guid' => $user_guid, 'object_guid' => $friend_guid]); elgg_create_river_item(['view' => 'river/relationship/friend/create', 'action_type' => 'friend', 'subject_guid' => $friend_guid, 'object_guid' => $user_guid]); return true; }
function setUrl($url = '') { if (preg_match('/(https?:\\/\\/)?((youtu\\.be\\/)|((www\\.)?(youtube\\.com\\/)))(.*)/', $url, $matches)) { $this->type = 'youtube'; } elseif (preg_match('/(https?:\\/\\/)?(www\\.)?(vimeo\\.com\\/)(.*)/', $url, $matches)) { $this->type = 'vimeo'; } elseif (preg_match('/(https?:\\/\\/)?(www\\.)?(dailymotion\\.com\\/)(.*)/', $url, $matches)) { $this->type = 'dailymotion'; } switch ($this->type) { case 'youtube': $youtube_api_key = elgg_get_plugin_setting('youtube_api_key', 'izap_videos'); if (preg_match('/(https?:\\/\\/)?(youtu\\.be\\/)(.*)/', $url, $matches)) { $explode_char = '/'; $url_pram = explode($explode_char, $url); $this->video_id = sanitise_string(end($url_pram)); } else { $url_pram = explode("?", $url); $url_pram = explode("&", $url_pram[1]); $url_pram = explode("=", $url_pram[0]); $this->video_id = $url_pram[1]; } $this->feed = array('url' => $this->youtube_api_capture['api_location'] . $this->video_id . '&key=' . $youtube_api_key, 'type' => 'youtube'); break; case 'vimeo': $explode_char = '/'; if (preg_match('/staffpicks#/', $url)) { $explode_char = '#'; } $url_pram = explode($explode_char, $url); $this->video_id = sanitise_int(end($url_pram)); $this->feed = array('url' => $this->vimeo_api_capture['api_location'] . $this->video_id . '.php', 'type' => 'vimeo'); break; case 'dailymotion': $explode_char = '/'; $url_pram = explode($explode_char, $url); $this->video_id = sanitise_string(end($url_pram)); $this->feed = array('url' => $this->dailymotion_api_capture['api_location'] . $this->video_id . '?fields=title,description,thumbnail_url,id,tags', 'type' => 'dailymotion'); break; default: return 103; break; } return $this->capture(); }
/** * Get related blogs to this blog * * @param ElggBlog $entity the blog to relate to * @param int $limit number of blogs to return * * @return bool|ElggBlog[] */ function blog_tools_get_related_blogs(ElggBlog $entity, $limit = 4) { $result = false; $limit = sanitise_int($limit, false); if (!empty($entity) && elgg_instanceof($entity, "object", "blog")) { // transform to values $tag_values = $entity->tags; if (!empty($tag_values)) { if (!is_array($tag_values)) { $tag_values = array($tag_values); } // find blogs with these metadatavalues $options = array("type" => "object", "subtype" => "blog", "metadata_name" => "tags", "metadata_values" => $tag_values, "wheres" => array("(e.guid <> " . $entity->getGUID() . ")"), "group_by" => "e.guid", "order_by" => "count(msn.id) DESC", "limit" => $limit); $result = elgg_get_entities_from_metadata($options); } } return $result; }
/** * Get related blogs to this blog * * @param ElggBlog $entity the blog to relate to * @param int $limit number of blogs to return * * @return false|ElggBlog[] */ function blog_tools_get_related_blogs(ElggBlog $entity, $limit = 4) { $limit = sanitise_int($limit, false); if (!$entity instanceof ElggBlog) { return false; } // transform to values $tag_values = $entity->tags; if (empty($tag_values)) { return false; } if (!is_array($tag_values)) { $tag_values = [$tag_values]; } // find blogs with these metadatavalues $options = ['type' => 'object', 'subtype' => 'blog', 'metadata_name' => 'tags', 'metadata_values' => $tag_values, 'wheres' => ["(e.guid <> {$entity->getGUID()})"], 'group_by' => 'e.guid', 'order_by' => 'count(msn.id) DESC', 'limit' => $limit]; return elgg_get_entities_from_metadata($options); }
/** * Check if the user has already linked this entity * * @param int $entity_guid the guid of the entity to check * @param int $user_guid the user to check for (default: current user) * * @return bool */ function quicklinks_check_relationship($entity_guid, $user_guid = 0) { static $cache; $entity_guid = sanitise_int($entity_guid, false); if (empty($entity_guid)) { return false; } $user_guid = sanitise_int($user_guid, false); if (empty($user_guid)) { $user_guid = elgg_get_logged_in_user_guid(); } if (empty($user_guid)) { return false; } if (!is_array($cache)) { $cache = []; } if (!isset($cache[$user_guid])) { $options = ['relationship' => QUICKLINKS_RELATIONSHIP, 'relationship_guid' => $user_guid, 'limit' => false, 'callback' => 'quicklinks_row_to_guid']; $cache[$user_guid] = elgg_get_entities_from_relationship($options); } return in_array($entity_guid, $cache[$user_guid]); }
/** * Return the write access for the current group if the user has write access to it. */ function groups_write_acl_plugin_hook($hook, $entity_type, $returnvalue, $params) { $user_guid = sanitise_int(elgg_extract('user_id', $params), false); $user = get_user($user_guid); if (empty($user)) { return $returnvalue; } $page_owner = elgg_get_page_owner_entity(); if (!$page_owner instanceof ElggGroup) { return $returnvalue; } if (!$page_owner->canWriteToContainer($user_guid)) { return $returnvalue; } // check group content access rules $allowed_access = array(ACCESS_PRIVATE); if ($page_owner->getContentAccessMode() !== ElggGroup::CONTENT_ACCESS_MODE_MEMBERS_ONLY) { $allowed_access[] = ACCESS_LOGGED_IN; $allowed_access[] = ACCESS_PUBLIC; } foreach ($returnvalue as $access_id => $access_string) { if (!in_array($access_id, $allowed_access)) { unset($returnvalue[$access_id]); } } // add write access to the group $returnvalue[$page_owner->group_acl] = elgg_echo('groups:acl', array($page_owner->name)); return $returnvalue; }
/** * Sanitises an integer for database use. * Wrapper function for alternate English spelling (@see sanitise_int) * * @param int $int Integer * @param bool[optional] $signed Whether negative values should be allowed (true) * @return int Sanitised integer */ function sanitize_int($int, $signed = true) { return sanitise_int($int, $signed); }
/** * Process the newsletter for a given guid * * @param int $entity_guid guid of the newsletter * * @return void */ function newsletter_process($entity_guid) { $entity_guid = sanitise_int($entity_guid, false); if (!empty($entity_guid)) { // ignore access $ia = elgg_set_ignore_access(true); $entity = get_entity($entity_guid); // is this a Newsletter if (!empty($entity) && elgg_instanceof($entity, "object", Newsletter::SUBTYPE)) { $logging = array("start_time" => time()); $site = elgg_get_site_entity(); $container = $entity->getContainerEntity(); $dbprefix = elgg_get_config("dbprefix"); // ================================ // set newsletter status to sending // ================================ $entity->status = "sending"; $entity->start_time = $logging["start_time"]; // ================== // get the recipients // ================== // basic set of user selection options $basic_user_options = array("type" => "user", "limit" => false, "selects" => array("ue.email"), "joins" => array("JOIN " . $dbprefix . "users_entity ue ON e.guid = ue.guid"), "callback" => "newsletter_user_row_to_subscriber_info"); // include users without settings if (newsletter_include_existing_users()) { // yes, so exclude blocked $basic_user_options["wheres"] = array("(e.guid NOT IN (SELECT guid_one\n\t\t\t\t\t\tFROM " . $dbprefix . "entity_relationships\n\t\t\t\t\t\tWHERE relationship = '" . NewsletterSubscription::GENERAL_BLACKLIST . "'\n\t\t\t\t\t\tAND guid_two = " . $site->getGUID() . ")\n\t\t\t\t\t)", "(e.guid NOT IN (SELECT guid_one\n\t\t\t\t\t\tFROM " . $dbprefix . "entity_relationships\n\t\t\t\t\t\tWHERE relationship = '" . NewsletterSubscription::BLACKLIST . "'\n\t\t\t\t\t\tAND guid_two = " . $container->getGUID() . ")\n\t\t\t\t\t)"); } else { // no, so subscription is required $basic_user_options["wheres"] = array("(e.guid IN (SELECT guid_one\n\t\t\t\t\t\tFROM " . $dbprefix . "entity_relationships\n\t\t\t\t\t\tWHERE relationship = '" . NewsletterSubscription::SUBSCRIPTION . "'\n\t\t\t\t\t\tAND guid_two = " . $container->getGUID() . ")\n\t\t\t\t\t)"); } $filtered_recipients = array("users" => array(), "emails" => array()); $recipients = $entity->getRecipients(); if (empty($recipients)) { // no recipients so report error $entity->status = "sent"; return false; } // recipients is an array consisting of: // - user_guids: individual users // - group_guids: groups to send the content to // - emails: individual email addresses // - subscribers: (int) whether or not to add the subscribers of the container // - members: (int) whether or not to aad the member of the container $user_guids = elgg_extract("user_guids", $recipients); if (!empty($user_guids)) { if (!is_array($user_guids)) { $user_guids = array($user_guids); } // convert to a format we can use $options = $basic_user_options; $options["wheres"][] = "(e.guid IN (" . implode(",", $user_guids) . "))"; $users = elgg_get_entities($options); if (!empty($users)) { $new_users = array(); foreach ($users as $user) { $new_users[$user["guid"]] = $user["email"]; } $filtered_recipients["users"] += $new_users; } } $group_guids = elgg_extract("group_guids", $recipients); if (!empty($group_guids)) { if (!is_array($group_guids)) { $group_guids = array($group_guids); } $options = $basic_user_options; $options["joins"][] = "JOIN " . $dbprefix . "entity_relationships r ON e.guid = r.guid_one"; $options["wheres"][] = "(r.guid_two IN (" . implode(",", $group_guids) . ") AND r.relationship = 'member')"; $users = elgg_get_entities($options); if (!empty($users)) { $new_users = array(); foreach ($users as $user) { $new_users[$user["guid"]] = $user["email"]; } $filtered_recipients["users"] += $new_users; } } $subscribers = elgg_extract("subscribers", $recipients); if (!empty($subscribers)) { $subscribers = newsletter_get_subscribers($container); $filtered_recipients["users"] += $subscribers["users"]; $filtered_recipients["emails"] = array_merge($filtered_recipients["emails"], $subscribers["emails"]); } $members = elgg_extract("members", $recipients); if (!empty($members)) { $relationship = "member"; if (elgg_instanceof($container, "site")) { $relationship = "member_of_site"; } $options = $basic_user_options; $options["relationship"] = $relationship; $options["relationship_guid"] = $container->getGUID(); $options["inverse_relationship"] = true; $users = elgg_get_entities_from_relationship($options); if (!empty($users)) { $new_users = array(); foreach ($users as $user) { $new_users[$user["guid"]] = $user["email"]; } $filtered_recipients["users"] += $new_users; } } $emails = elgg_extract("emails", $recipients); if (!empty($emails)) { if (!is_array($emails)) { $emails = array($emails); } // get blocked users $options = array("type" => "user", "limit" => false, "selects" => array("ue.email"), "joins" => array("JOIN " . $dbprefix . "users_entity ue ON e.guid = ue.guid"), "wheres" => array("(ue.email IN ('" . implode("','", $emails) . "'))", "(e.guid IN (SELECT guid_one\n\t\t\t\t\t\t\tFROM " . $dbprefix . "entity_relationships\n\t\t\t\t\t\t\tWHERE relationship = '" . NewsletterSubscription::GENERAL_BLACKLIST . "'\n\t\t\t\t\t\t\tAND guid_two = " . $site->getGUID() . ")\n\t\t\t\t\t\tOR\n\t\t\t\t\t\te.guid IN (SELECT guid_one\n\t\t\t\t\t\t\tFROM " . $dbprefix . "entity_relationships\n\t\t\t\t\t\t\tWHERE relationship = '" . NewsletterSubscription::BLACKLIST . "'\n\t\t\t\t\t\t\tAND guid_two = " . $container->getGUID() . ")\n\t\t\t\t\t\t)"), "callback" => "newsletter_user_row_to_subscriber_info"); $users = elgg_get_entities($options); if (!empty($users)) { $blocked_emails = array(); foreach ($users as $user) { $blocked_emails[] = $user["email"]; } $emails = array_diff($emails, $blocked_emails); } if (!empty($emails)) { // get blocked emails $options = array("type" => "object", "subtype" => NewsletterSubscription::SUBTYPE, "limit" => false, "selects" => array("oe.title AS email"), "joins" => array("JOIN " . $dbprefix . "objects_entity oe ON e.guid = oe.guid"), "wheres" => array("(oe.title IN ('" . implode("','", $emails) . "'))", "(e.guid IN (SELECT guid_one\n\t\t\t\t\t\t\t\tFROM " . $dbprefix . "entity_relationships\n\t\t\t\t\t\t\t\tWHERE relationship = '" . NewsletterSubscription::GENERAL_BLACKLIST . "'\n\t\t\t\t\t\t\t\tAND guid_two = " . $site->getGUID() . ")\n\t\t\t\t\t\t\tOR\n\t\t\t\t\t\t\te.guid IN (SELECT guid_one\n\t\t\t\t\t\t\t\tFROM " . $dbprefix . "entity_relationships\n\t\t\t\t\t\t\t\tWHERE relationship = '" . NewsletterSubscription::BLACKLIST . "'\n\t\t\t\t\t\t\t\tAND guid_two = " . $container->getGUID() . ")\n\t\t\t\t\t\t\t)"), "callback" => "newsletter_user_row_to_subscriber_info"); $subscriptions = elgg_get_entities($options); if (!empty($subscriptions)) { $blocked_emails = array(); foreach ($subscriptions as $subscription) { $blocked_emails[] = $subscription["email"]; } $emails = array_diff($emails, $blocked_emails); } if (!empty($emails)) { $filtered_recipients["emails"] = array_merge($filtered_recipients["emails"], $emails); } } } // ====================== // get newsletter content // ====================== if ($entity->subject) { $message_subject = $entity->subject; } else { $message_subject = elgg_echo("newsletter:subject", array($container->name, $entity->title)); } $message_plaintext_content = elgg_echo("newsletter:plain_message", array(elgg_normalize_url($entity->getURL()))); $message_html_content = elgg_view_layout("newsletter", array("entity" => $entity)); // convert to inline CSS for email clients $message_html_content = html_email_handler_css_inliner($message_html_content); // ======================= // proccess all recipients // ======================= $send_options = array("from" => html_email_handler_make_rfc822_address($container), "subject" => $message_subject, "plaintext_message" => $message_plaintext_content); foreach ($filtered_recipients as $type => $recipients) { if (!empty($recipients)) { foreach ($recipients as $id => $recipient) { $recipient_log = array("type" => $type, "email" => $recipient, "time" => date(DATE_RFC1123), "timestamp" => time(), "status" => false); // ============================================= // create individual footer for unsubscribe link // ============================================= if ($type == "users") { $recipient_log["guid"] = $id; $unsubscribe_link = newsletter_generate_unsubscribe_link($container, $id); } else { $unsubscribe_link = newsletter_generate_unsubscribe_link($container, $recipient); } // place the unsubscribe link in the message $unsubscribe_link = elgg_normalize_url($unsubscribe_link); $message_html_content_user = str_ireplace(urlencode("{unsublink}"), $unsubscribe_link, $message_html_content); // replace the online link for logged out users to add an emailadres if ($type !== "users") { $online_link = $entity->getURL(); $new_online_link = $online_link . "?e=" . $recipient; $message_html_content_user = str_ireplace($online_link, $new_online_link, $message_html_content_user); } // add URL postfix to all internal links $message_html_content_user = newsletter_apply_url_postfix($message_html_content_user); // ========= // send mail // ========= $send_options["to"] = $recipient; $send_options["html_message"] = $message_html_content_user; $recipient_log["status"] = html_email_handler_send_email($send_options); if ($recipient_log["status"] && !empty($recipient_log["guid"])) { $entity->addRelationship($recipient_log["guid"], Newsletter::SEND_TO); } // ============== // add to logging // ============== $logging["recipients"][] = $recipient_log; $entity->saveLogging($logging); } } } $logging["end_time"] = time(); $entity->saveLogging($logging); // ============================= // set newsletter status to done // ============================= $entity->status = "sent"; // ======================== // send status notification // ======================== if (!empty($entity->status_notification) && newsletter_is_email_address($entity->status_notification)) { $from = html_email_handler_make_rfc822_address($site); $subject = elgg_echo("newsletter:status_notification:subject"); $message = elgg_echo("newsletter:status_notification:message", array($entity->title, $entity->getURL())); elgg_send_email($from, $entity->status_notification, $subject, $message); } } // restore access elgg_set_ignore_access($ia); } }
<?php global $CONFIG; $offset = sanitise_int(get_input("offset", 0)); $limit = sanitise_int(get_input("limit", 10)); $sorting = sanitise_string(get_input("sorting", "newest")); $user_data_partial_search_criteria = get_input("user_data_partial_search_criteria", false); $meta_data_array_search_criteria = get_input("meta_data_array_search_criteria", false, false); // no filtering because get_input does not support filtering of nested arrays $meta_data_partial_search_criteria = get_input("meta_data_partial_search_criteria", false); $meta_data_exact_search_criteria = get_input("meta_data_exact_search_criteria", false); $meta_data_between_search_criteria = get_input("meta_data_between_search_criteria", false, false); // no filtering because get_input does not support filtering of nested arrays $where = array(); $meta_array = array(); // meta_data_array contains all stuff that requires a complete (multi)hit on a metadata value if (!empty($meta_data_array_search_criteria)) { foreach ($meta_data_array_search_criteria as $field_name => $field_value) { if (!empty($field_value)) { foreach ($field_value as $key => $value) { $field_value[$key] = "'" . sanitise_string($value) . "'"; } $meta_name_id = get_metastring_id($field_name); $filter = implode(",", $field_value); $meta_array[$meta_name_id] = "IN (" . $filter . ")"; } } } // user partial hit if (!empty($user_data_partial_search_criteria)) { foreach ($user_data_partial_search_criteria as $field_name => $field_value) {
/** * Get comments that match the search parameters. * * @param string $hook Hook name * @param string $type Hook type * @param array $value Empty array * @param array $params Search parameters * @return array */ function search_comments_hook($hook, $type, $value, $params) { $db_prefix = elgg_get_config('dbprefix'); $query = sanitise_string($params['query']); $limit = sanitise_int($params['limit']); $offset = sanitise_int($params['offset']); $params['annotation_names'] = array('generic_comment', 'group_topic_post'); $params['joins'] = array("JOIN {$db_prefix}annotations a on e.guid = a.entity_guid", "JOIN {$db_prefix}metastrings msn on a.name_id = msn.id", "JOIN {$db_prefix}metastrings msv on a.value_id = msv.id"); $fields = array('string'); // force IN BOOLEAN MODE since fulltext isn't // available on metastrings (and boolean mode doesn't need it) $search_where = search_get_where_sql('msv', $fields, $params, FALSE); $container_and = ''; if ($params['container_guid'] && $params['container_guid'] !== ELGG_ENTITIES_ANY_VALUE) { $container_and = 'AND e.container_guid = ' . sanitise_int($params['container_guid']); } $e_access = get_access_sql_suffix('e'); $a_access = get_access_sql_suffix('a'); // @todo this can probably be done through the api.. $q = "SELECT count(DISTINCT a.id) as total FROM {$db_prefix}annotations a\n\t\tJOIN {$db_prefix}metastrings msn ON a.name_id = msn.id\n\t\tJOIN {$db_prefix}metastrings msv ON a.value_id = msv.id\n\t\tJOIN {$db_prefix}entities e ON a.entity_guid = e.guid\n\t\tWHERE msn.string IN ('generic_comment', 'group_topic_post')\n\t\t\tAND ({$search_where})\n\t\t\tAND {$e_access}\n\t\t\tAND {$a_access}\n\t\t\t{$container_and}\n\t\t"; if (!($result = get_data($q))) { return FALSE; } $count = $result[0]->total; // don't continue if nothing there... if (!$count) { return array('entities' => array(), 'count' => 0); } // no full text index on metastrings table if ($params['sort'] == 'relevance') { $params['sort'] = 'created'; } $order_by = search_get_order_by_sql('a', null, $params['sort'], $params['order']); if ($order_by) { $order_by = "ORDER BY {$order_by}"; } $q = "SELECT DISTINCT a.*, msv.string as comment FROM {$db_prefix}annotations a\n\t\tJOIN {$db_prefix}metastrings msn ON a.name_id = msn.id\n\t\tJOIN {$db_prefix}metastrings msv ON a.value_id = msv.id\n\t\tJOIN {$db_prefix}entities e ON a.entity_guid = e.guid\n\t\tWHERE msn.string IN ('generic_comment', 'group_topic_post')\n\t\t\tAND ({$search_where})\n\t\t\tAND {$e_access}\n\t\t\tAND {$a_access}\n\t\t\t{$container_and}\n\t\t\n\t\t{$order_by}\n\t\tLIMIT {$offset}, {$limit}\n\t\t"; $comments = get_data($q); // @todo if plugins are disabled causing subtypes // to be invalid and there are comments on entities of those subtypes, // the counts will be wrong here and results might not show up correctly, // especially on the search landing page, which only pulls out two results. // probably better to check against valid subtypes than to do what I'm doing. // need to return actual entities // add the volatile data for why these entities have been returned. $entities = array(); foreach ($comments as $comment) { $entity = get_entity($comment->entity_guid); // hic sunt dracones if (!$entity) { //continue; $entity = new ElggObject(); $entity->setVolatileData('search_unavailable_entity', TRUE); } $comment_str = search_get_highlighted_relevant_substrings($comment->comment, $query); $comments_data = $entity->getVolatileData('search_comments_data'); if (!$comments_data) { $comments_data = array(); } $comments_data[] = array('annotation_id' => $comment->id, 'text' => $comment_str, 'owner_guid' => $comment->owner_guid, 'time_created' => $comment->time_created); $entity->setVolatileData('search_comments_data', $comments_data); $entities[] = $entity; } return array('entities' => $entities, 'count' => $count); }
<?php /** * Elggx Userpoints Plugin * * Index page Toppoints widget for Widget Manager plugin * */ $count = sanitise_int($vars["entity"]->toppoints_count, false); if (empty($count)) { $count = 10; } ?> <div> <?php echo elgg_echo("elggx_groupuserpoints:settings:toppoints:num"); ?> <br /> <?php echo elgg_view("input/text", array("name" => "params[toppoints_count]", "value" => $count, "size" => "4", "maxlength" => "4")); ?> </div>
/** * Get popular tags and their frequencies * * Supports similar arguments as elgg_get_entities() * * @param array $options Array in format: * * threshold => INT minimum tag count * * tag_names => array() metadata tag names - must be registered tags * * limit => INT number of tags to return * * types => null|STR entity type (SQL: type = '$type') * * subtypes => null|STR entity subtype (SQL: subtype = '$subtype') * * type_subtype_pairs => null|ARR (array('type' => 'subtype')) * (SQL: type = '$type' AND subtype = '$subtype') pairs * * owner_guids => null|INT entity guid * * container_guids => null|INT container_guid * * site_guids => null (current_site)|INT site_guid * * created_time_lower => null|INT Created time lower boundary in epoch time * * created_time_upper => null|INT Created time upper boundary in epoch time * * modified_time_lower => null|INT Modified time lower boundary in epoch time * * modified_time_upper => null|INT Modified time upper boundary in epoch time * * wheres => array() Additional where clauses to AND together * * joins => array() Additional joins * * @return object[]|false If no tags or error, false * otherwise, array of objects with ->tag and ->total values * @since 1.7.1 */ function elgg_get_tags(array $options = array()) { global $CONFIG; $defaults = array('threshold' => 1, 'tag_names' => array(), 'limit' => 10, 'types' => ELGG_ENTITIES_ANY_VALUE, 'subtypes' => ELGG_ENTITIES_ANY_VALUE, 'type_subtype_pairs' => ELGG_ENTITIES_ANY_VALUE, 'owner_guids' => ELGG_ENTITIES_ANY_VALUE, 'container_guids' => ELGG_ENTITIES_ANY_VALUE, 'site_guids' => $CONFIG->site_guid, 'modified_time_lower' => ELGG_ENTITIES_ANY_VALUE, 'modified_time_upper' => ELGG_ENTITIES_ANY_VALUE, 'created_time_lower' => ELGG_ENTITIES_ANY_VALUE, 'created_time_upper' => ELGG_ENTITIES_ANY_VALUE, 'joins' => array(), 'wheres' => array()); $options = array_merge($defaults, $options); $singulars = array('type', 'subtype', 'owner_guid', 'container_guid', 'site_guid', 'tag_name'); $options = _elgg_normalize_plural_options_array($options, $singulars); $registered_tags = elgg_get_registered_tag_metadata_names(); if (!is_array($options['tag_names'])) { return false; } // empty array so use all registered tag names if (count($options['tag_names']) == 0) { $options['tag_names'] = $registered_tags; } $diff = array_diff($options['tag_names'], $registered_tags); if (count($diff) > 0) { elgg_deprecated_notice('Tag metadata names must be registered by elgg_register_tag_metadata_name()', 1.7); // return false; } $wheres = $options['wheres']; // catch for tags that were spaces $wheres[] = "msv.string != ''"; $sanitised_tags = array(); foreach ($options['tag_names'] as $tag) { $sanitised_tags[] = '"' . sanitise_string($tag) . '"'; } $tags_in = implode(',', $sanitised_tags); $wheres[] = "(msn.string IN ({$tags_in}))"; $wheres[] = _elgg_get_entity_type_subtype_where_sql('e', $options['types'], $options['subtypes'], $options['type_subtype_pairs']); $wheres[] = _elgg_get_guid_based_where_sql('e.site_guid', $options['site_guids']); $wheres[] = _elgg_get_guid_based_where_sql('e.owner_guid', $options['owner_guids']); $wheres[] = _elgg_get_guid_based_where_sql('e.container_guid', $options['container_guids']); $wheres[] = _elgg_get_entity_time_where_sql('e', $options['created_time_upper'], $options['created_time_lower'], $options['modified_time_upper'], $options['modified_time_lower']); // 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); $joins = $options['joins']; $joins[] = "JOIN {$CONFIG->dbprefix}metadata md on md.entity_guid = e.guid"; $joins[] = "JOIN {$CONFIG->dbprefix}metastrings msv on msv.id = md.value_id"; $joins[] = "JOIN {$CONFIG->dbprefix}metastrings msn on md.name_id = msn.id"; // remove identical join clauses $joins = array_unique($joins); foreach ($joins as $i => $join) { if ($join === false) { return false; } elseif (empty($join)) { unset($joins[$i]); } } $query = "SELECT msv.string as tag, count(msv.id) as total "; $query .= "FROM {$CONFIG->dbprefix}entities e "; // add joins foreach ($joins as $j) { $query .= " {$j} "; } // add wheres $query .= ' WHERE '; foreach ($wheres as $w) { $query .= " {$w} AND "; } // Add access controls $query .= _elgg_get_access_where_sql(); $threshold = sanitise_int($options['threshold']); $query .= " GROUP BY msv.string HAVING total >= {$threshold} "; $query .= " ORDER BY total DESC "; $limit = sanitise_int($options['limit']); $query .= " LIMIT {$limit} "; return get_data($query); }
/** * Backdate an entity, since this can't be done by Elgg core functions * * @param int $entity_guid the entity to update * @param int $time_created the new time_created * * @access private * * @return bool */ function questions_backdate_entity($entity_guid, $time_created) { $entity_guid = sanitise_int($entity_guid, false); $time_created = sanitise_int($time_created); if (empty($entity_guid)) { return false; } $dbprefix = elgg_get_config('dbprefix'); $query = "UPDATE {$dbprefix}entities\n\t\tSET time_created = {$time_created}\n\t\tWHERE guid = {$entity_guid}"; return (bool) update_data($query); }
/** * Returns metadata name and value SQL where for entities. * NB: $names and $values are not paired. Use $pairs for this. * Pairs default to '=' operand. * * This function is reused for annotations because the tables are * exactly the same. * * @param string $e_table Entities table name * @param string $n_table Normalized metastrings table name (Where entities, * values, and names are joined. annotations / metadata) * @param array|null $names Array of names * @param array|null $values Array of values * @param array|null $pairs Array of names / values / operands * @param string $pair_operator ("AND" or "OR") Operator to use to join the where clauses for pairs * @param bool $case_sensitive Case sensitive metadata names? * @param array|null $order_by_metadata Array of names / direction * @param array|null $owner_guids Array of owner GUIDs * * @return false|array False on fail, array('joins', 'wheres') * @since 1.7.0 * @access private */ function _elgg_get_entity_metadata_where_sql($e_table, $n_table, $names = null, $values = null, $pairs = null, $pair_operator = 'AND', $case_sensitive = true, $order_by_metadata = null, $owner_guids = null) { global $CONFIG; // short circuit if nothing requested // 0 is a valid (if not ill-conceived) metadata name. // 0 is also a valid metadata value for false, null, or 0 // 0 is also a valid(ish) owner_guid if (!$names && $names !== 0 && (!$values && $values !== 0) && (!$pairs && $pairs !== 0) && (!$owner_guids && $owner_guids !== 0) && !$order_by_metadata) { return ''; } // join counter for incremental joins. $i = 1; // binary forces byte-to-byte comparision of strings, making // it case- and diacritical-mark- sensitive. // only supported on values. $binary = $case_sensitive ? ' BINARY ' : ''; $access = _elgg_get_access_where_sql(array('table_alias' => 'n_table')); $return = array('joins' => array(), 'wheres' => array(), 'orders' => array()); // will always want to join these tables if pulling metastrings. $return['joins'][] = "JOIN {$CONFIG->dbprefix}{$n_table} n_table on\n\t\t{$e_table}.guid = n_table.entity_guid"; $wheres = array(); // get names wheres and joins $names_where = ''; if ($names !== null) { if (!is_array($names)) { $names = array($names); } $sanitised_names = array(); foreach ($names as $name) { // normalise to 0. if (!$name) { $name = '0'; } $sanitised_names[] = '\'' . sanitise_string($name) . '\''; } if ($names_str = implode(',', $sanitised_names)) { $return['joins'][] = "JOIN {$CONFIG->dbprefix}metastrings msn on n_table.name_id = msn.id"; $names_where = "(msn.string IN ({$names_str}))"; } } // get values wheres and joins $values_where = ''; if ($values !== null) { if (!is_array($values)) { $values = array($values); } $sanitised_values = array(); foreach ($values as $value) { // normalize to 0 if (!$value) { $value = 0; } $sanitised_values[] = '\'' . sanitise_string($value) . '\''; } if ($values_str = implode(',', $sanitised_values)) { $return['joins'][] = "JOIN {$CONFIG->dbprefix}metastrings msv on n_table.value_id = msv.id"; $values_where = "({$binary}msv.string IN ({$values_str}))"; } } if ($names_where && $values_where) { $wheres[] = "({$names_where} AND {$values_where} AND {$access})"; } elseif ($names_where) { $wheres[] = "({$names_where} AND {$access})"; } elseif ($values_where) { $wheres[] = "({$values_where} AND {$access})"; } // add pairs // pairs must be in arrays. if (is_array($pairs)) { // check if this is an array of pairs or just a single pair. if (isset($pairs['name']) || isset($pairs['value'])) { $pairs = array($pairs); } $pair_wheres = array(); // @todo when the pairs are > 3 should probably split the query up to // denormalize the strings table. foreach ($pairs as $index => $pair) { // @todo move this elsewhere? // support shortcut 'n' => 'v' method. if (!is_array($pair)) { $pair = array('name' => $index, 'value' => $pair); } // must have at least a name and value if (!isset($pair['name']) || !isset($pair['value'])) { // @todo should probably return false. continue; } // case sensitivity can be specified per pair. // default to higher level setting. if (isset($pair['case_sensitive'])) { $pair_binary = $pair['case_sensitive'] ? ' BINARY ' : ''; } else { $pair_binary = $binary; } if (isset($pair['operand'])) { $operand = sanitise_string($pair['operand']); } else { $operand = ' = '; } // for comparing $trimmed_operand = trim(strtolower($operand)); $access = _elgg_get_access_where_sql(array('table_alias' => "n_table{$i}")); // if the value is an int, don't quote it because str '15' < str '5' // if the operand is IN don't quote it because quoting should be done already. if (is_numeric($pair['value'])) { $value = sanitise_string($pair['value']); } else { if (is_bool($pair['value'])) { $value = (int) $pair['value']; } else { if (is_array($pair['value'])) { $values_array = array(); foreach ($pair['value'] as $pair_value) { if (is_numeric($pair_value)) { $values_array[] = sanitise_string($pair_value); } else { $values_array[] = "'" . sanitise_string($pair_value) . "'"; } } if ($values_array) { $value = '(' . implode(', ', $values_array) . ')'; } // @todo allow support for non IN operands with array of values. // will have to do more silly joins. $operand = 'IN'; } else { if ($trimmed_operand == 'in') { $value = "({$pair['value']})"; } else { $value = "'" . sanitise_string($pair['value']) . "'"; } } } } $name = sanitise_string($pair['name']); // @todo The multiple joins are only needed when the operator is AND $return['joins'][] = "JOIN {$CONFIG->dbprefix}{$n_table} n_table{$i}\n\t\t\t\ton {$e_table}.guid = n_table{$i}.entity_guid"; $return['joins'][] = "JOIN {$CONFIG->dbprefix}metastrings msn{$i}\n\t\t\t\ton n_table{$i}.name_id = msn{$i}.id"; $return['joins'][] = "JOIN {$CONFIG->dbprefix}metastrings msv{$i}\n\t\t\t\ton n_table{$i}.value_id = msv{$i}.id"; $pair_wheres[] = "(msn{$i}.string = '{$name}' AND {$pair_binary}msv{$i}.string\n\t\t\t\t{$operand} {$value} AND {$access})"; $i++; } if ($where = implode(" {$pair_operator} ", $pair_wheres)) { $wheres[] = "({$where})"; } } // add owner_guids if ($owner_guids) { if (is_array($owner_guids)) { $sanitised = array_map('sanitise_int', $owner_guids); $owner_str = implode(',', $sanitised); } else { $owner_str = sanitise_int($owner_guids); } $wheres[] = "(n_table.owner_guid IN ({$owner_str}))"; } if ($where = implode(' AND ', $wheres)) { $return['wheres'][] = "({$where})"; } if (is_array($order_by_metadata)) { if (count($order_by_metadata) > 0 && !isset($order_by_metadata[0])) { // singleton, so fix $order_by_metadata = array($order_by_metadata); } foreach ($order_by_metadata as $order_by) { if (is_array($order_by) && isset($order_by['name'])) { $name = sanitise_string($order_by['name']); if (isset($order_by['direction'])) { $direction = sanitise_string($order_by['direction']); } else { $direction = 'ASC'; } $return['joins'][] = "JOIN {$CONFIG->dbprefix}{$n_table} n_table{$i}\n\t\t\t\t\ton {$e_table}.guid = n_table{$i}.entity_guid"; $return['joins'][] = "JOIN {$CONFIG->dbprefix}metastrings msn{$i}\n\t\t\t\t\ton n_table{$i}.name_id = msn{$i}.id"; $return['joins'][] = "JOIN {$CONFIG->dbprefix}metastrings msv{$i}\n\t\t\t\t\ton n_table{$i}.value_id = msv{$i}.id"; $access = _elgg_get_access_where_sql(array('table_alias' => "n_table{$i}")); $return['wheres'][] = "(msn{$i}.string = '{$name}' AND {$access})"; if (isset($order_by['as']) && $order_by['as'] == 'integer') { $return['orders'][] = "CAST(msv{$i}.string AS SIGNED) {$direction}"; } else { $return['orders'][] = "msv{$i}.string {$direction}"; } $i++; } } } return $return; }
/** * Page handler for autocomplete endpoint. * * @todo split this into functions/objects, this is way too big * * /livesearch?q=<query> * * Other options include: * match_on string all or array(groups|users|friends) * match_owner int 0/1 * limit int default is 10 * * @param array $page * @return string JSON string is returned and then exit * @access private */ function input_livesearch_page_handler($page) { global $CONFIG; // only return results to logged in users. if (!($user = elgg_get_logged_in_user_entity())) { exit; } if (!($q = get_input('term', get_input('q')))) { exit; } $q = sanitise_string($q); // replace mysql vars with escaped strings $q = str_replace(array('_', '%'), array('\\_', '\\%'), $q); $match_on = get_input('match_on', 'all'); if (!is_array($match_on)) { $match_on = array($match_on); } // all = users and groups if (in_array('all', $match_on)) { $match_on = array('users', 'groups'); } if (get_input('match_owner', false)) { $owner_where = 'AND e.owner_guid = ' . $user->getGUID(); } else { $owner_where = ''; } $limit = sanitise_int(get_input('limit', 10)); // grab a list of entities and send them in json. $results = array(); foreach ($match_on as $match_type) { switch ($match_type) { case 'users': $query = "SELECT * FROM {$CONFIG->dbprefix}users_entity as ue, {$CONFIG->dbprefix}entities as e\n\t\t\t\t\tWHERE e.guid = ue.guid\n\t\t\t\t\t\tAND e.enabled = 'yes'\n\t\t\t\t\t\tAND ue.banned = 'no'\n\t\t\t\t\t\tAND (ue.name LIKE '{$q}%' OR ue.name LIKE '% {$q}%' OR ue.username LIKE '{$q}%')\n\t\t\t\t\tLIMIT {$limit}\n\t\t\t\t"; if ($entities = get_data($query)) { foreach ($entities as $entity) { // @todo use elgg_get_entities (don't query in a loop!) $entity = get_entity($entity->guid); /* @var ElggUser $entity */ if (!$entity) { continue; } if (in_array('groups', $match_on)) { $value = $entity->guid; } else { $value = $entity->username; } $output = elgg_view_list_item($entity, array('use_hover' => false, 'class' => 'elgg-autocomplete-item')); $icon = elgg_view_entity_icon($entity, 'tiny', array('use_hover' => false)); $result = array('type' => 'user', 'name' => $entity->name, 'desc' => $entity->username, 'guid' => $entity->guid, 'label' => $output, 'value' => $value, 'icon' => $icon, 'url' => $entity->getURL()); $results[$entity->name . rand(1, 100)] = $result; } } break; case 'groups': // don't return results if groups aren't enabled. if (!elgg_is_active_plugin('groups')) { continue; } $query = "SELECT * FROM {$CONFIG->dbprefix}groups_entity as ge, {$CONFIG->dbprefix}entities as e\n\t\t\t\t\tWHERE e.guid = ge.guid\n\t\t\t\t\t\tAND e.enabled = 'yes'\n\t\t\t\t\t\t{$owner_where}\n\t\t\t\t\t\tAND (ge.name LIKE '{$q}%' OR ge.name LIKE '% {$q}%' OR ge.description LIKE '% {$q}%')\n\t\t\t\t\tLIMIT {$limit}\n\t\t\t\t"; if ($entities = get_data($query)) { foreach ($entities as $entity) { // @todo use elgg_get_entities (don't query in a loop!) $entity = get_entity($entity->guid); /* @var ElggGroup $entity */ if (!$entity) { continue; } $output = elgg_view_list_item($entity, array('use_hover' => false, 'class' => 'elgg-autocomplete-item')); $icon = elgg_view_entity_icon($entity, 'tiny', array('use_hover' => false)); $result = array('type' => 'group', 'name' => $entity->name, 'desc' => strip_tags($entity->description), 'guid' => $entity->guid, 'label' => $output, 'value' => $entity->guid, 'icon' => $icon, 'url' => $entity->getURL()); $results[$entity->name . rand(1, 100)] = $result; } } break; case 'friends': $query = "SELECT * FROM\n\t\t\t\t\t\t{$CONFIG->dbprefix}users_entity as ue,\n\t\t\t\t\t\t{$CONFIG->dbprefix}entity_relationships as er,\n\t\t\t\t\t\t{$CONFIG->dbprefix}entities as e\n\t\t\t\t\tWHERE er.relationship = 'friend'\n\t\t\t\t\t\tAND er.guid_one = {$user->getGUID()}\n\t\t\t\t\t\tAND er.guid_two = ue.guid\n\t\t\t\t\t\tAND e.guid = ue.guid\n\t\t\t\t\t\tAND e.enabled = 'yes'\n\t\t\t\t\t\tAND ue.banned = 'no'\n\t\t\t\t\t\tAND (ue.name LIKE '{$q}%' OR ue.name LIKE '% {$q}%' OR ue.username LIKE '{$q}%')\n\t\t\t\t\tLIMIT {$limit}\n\t\t\t\t"; if ($entities = get_data($query)) { foreach ($entities as $entity) { // @todo use elgg_get_entities (don't query in a loop!) $entity = get_entity($entity->guid); /* @var ElggUser $entity */ if (!$entity) { continue; } $output = elgg_view_list_item($entity, array('use_hover' => false, 'class' => 'elgg-autocomplete-item')); $icon = elgg_view_entity_icon($entity, 'tiny', array('use_hover' => false)); $result = array('type' => 'user', 'name' => $entity->name, 'desc' => $entity->username, 'guid' => $entity->guid, 'label' => $output, 'value' => $entity->username, 'icon' => $icon, 'url' => $entity->getURL()); $results[$entity->name . rand(1, 100)] = $result; } } break; default: header("HTTP/1.0 400 Bad Request", true); echo "livesearch: unknown match_on of {$match_type}"; exit; break; } } ksort($results); header("Content-Type: application/json"); echo json_encode(array_values($results)); exit; }
function elgg_solr_get_entity_guids(array $options = array()) { global $CONFIG; $defaults = array('types' => ELGG_ENTITIES_ANY_VALUE, 'subtypes' => ELGG_ENTITIES_ANY_VALUE, 'type_subtype_pairs' => ELGG_ENTITIES_ANY_VALUE, 'guids' => ELGG_ENTITIES_ANY_VALUE, 'owner_guids' => ELGG_ENTITIES_ANY_VALUE, 'container_guids' => ELGG_ENTITIES_ANY_VALUE, 'site_guids' => $CONFIG->site_guid, 'modified_time_lower' => ELGG_ENTITIES_ANY_VALUE, 'modified_time_upper' => ELGG_ENTITIES_ANY_VALUE, 'created_time_lower' => ELGG_ENTITIES_ANY_VALUE, 'created_time_upper' => ELGG_ENTITIES_ANY_VALUE, 'reverse_order_by' => false, 'order_by' => 'e.time_created desc', 'group_by' => ELGG_ENTITIES_ANY_VALUE, 'limit' => 10, 'offset' => 0, 'count' => false, 'selects' => array(), 'wheres' => array(), 'joins' => array(), 'callback' => false, '__ElggBatch' => null); $options = array_merge($defaults, $options); // can't use helper function with type_subtype_pair because // it's already an array...just need to merge it if (isset($options['type_subtype_pair'])) { if (isset($options['type_subtype_pairs'])) { $options['type_subtype_pairs'] = array_merge($options['type_subtype_pairs'], $options['type_subtype_pair']); } else { $options['type_subtype_pairs'] = $options['type_subtype_pair']; } } $singulars = array('type', 'subtype', 'guid', 'owner_guid', 'container_guid', 'site_guid'); $options = _elgg_normalize_plural_options_array($options, $singulars); // evaluate where clauses if (!is_array($options['wheres'])) { $options['wheres'] = array($options['wheres']); } $wheres = $options['wheres']; $wheres[] = _elgg_get_entity_type_subtype_where_sql('e', $options['types'], $options['subtypes'], $options['type_subtype_pairs']); $wheres[] = _elgg_get_guid_based_where_sql('e.guid', $options['guids']); $wheres[] = _elgg_get_guid_based_where_sql('e.owner_guid', $options['owner_guids']); $wheres[] = _elgg_get_guid_based_where_sql('e.container_guid', $options['container_guids']); $wheres[] = _elgg_get_guid_based_where_sql('e.site_guid', $options['site_guids']); $wheres[] = _elgg_get_entity_time_where_sql('e', $options['created_time_upper'], $options['created_time_lower'], $options['modified_time_upper'], $options['modified_time_lower']); // 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); // evaluate join clauses if (!is_array($options['joins'])) { $options['joins'] = array($options['joins']); } // remove identical join clauses $joins = array_unique($options['joins']); foreach ($joins as $i => $join) { if ($join === false) { return false; } elseif (empty($join)) { unset($joins[$i]); } } // evalutate selects if ($options['selects']) { $selects = ''; foreach ($options['selects'] as $select) { $selects .= ", {$select}"; } } else { $selects = ''; } if (!$options['count']) { $distinct = ''; if ($options['require_distinct']) { $distinct = ' DISTINCT'; } $query = "SELECT{$distinct} e.guid{$selects} FROM {$CONFIG->dbprefix}entities e "; } else { $query = "SELECT count(DISTINCT e.guid) as total FROM {$CONFIG->dbprefix}entities e "; } // add joins foreach ($joins as $j) { $query .= " {$j} "; } // add wheres $query .= ' WHERE '; foreach ($wheres as $w) { $query .= " {$w} AND "; } // Add access controls $query .= _elgg_get_access_where_sql(); // reverse order by if ($options['reverse_order_by']) { $options['order_by'] = _elgg_sql_reverse_order_by_clause($options['order_by']); } if (!$options['count']) { if ($options['group_by']) { $query .= " GROUP BY {$options['group_by']}"; } if ($options['order_by']) { $query .= " ORDER BY {$options['order_by']}"; } if ($options['limit']) { $limit = sanitise_int($options['limit'], false); $offset = sanitise_int($options['offset'], false); $query .= " LIMIT {$offset}, {$limit}"; } if ($options['callback'] === 'entity_row_to_elggstar') { $dt = _elgg_fetch_entities_from_sql($query, $options['__ElggBatch']); } else { $dt = get_data($query, $options['callback']); } if ($dt) { // populate entity and metadata caches $guids = array(); foreach ($dt as $item) { // A custom callback could result in items that aren't ElggEntity's, so check for them if ($item instanceof ElggEntity) { _elgg_cache_entity($item); // plugins usually have only settings if (!$item instanceof ElggPlugin) { $guids[] = $item->guid; } } } // @todo Without this, recursive delete fails. See #4568 reset($dt); if ($guids) { _elgg_get_metadata_cache()->populateFromEntities($guids); } } return $dt; } else { $total = get_data_row($query); return (int) $total->total; } }
* Author: Rosana Montes Soldado * Universidad de Granada * Licence: CC-ByNCSA * Reference: Microproyecto CEI BioTIC Ref. 11-2015 * Project coordinator: @rosanamontes * Website: http://lsi.ugr.es/rosana * Project colaborator: Antonio Moles * * Project Derivative: * TFG: Desarrollo de un sistema de gestión de paquetería para Teranga Go * Advisor: Rosana Montes * Student: Ricardo Luzón Fernández * */ set_time_limit(0); $last_login = sanitise_int(get_input("last_login"), false); if (!empty($last_login)) { $dbprefix = elgg_get_config("dbprefix"); $options = array("type" => "user", "limit" => false, "relationship" => "member_of_site", "relationship_guid" => elgg_get_site_entity()->getGUID(), "inverse_relationship" => true, "site_guids" => false, "joins" => array("JOIN " . $dbprefix . "users_entity ue ON e.guid = ue.guid"), "wheres" => array("ue.last_login <= " . $last_login), "order_by" => "ue.last_login"); $users = elgg_get_entities_from_relationship($options); if ($users) { $fields = array("username", "name", "email", "last_login", "banned"); // We'll be outputting a CSV // It will be called export_inactive.csv header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); header("Content-Disposition: attachment;filename=export_inactive.csv");
/** * Check if the group allows multiple admins * * @param ElggGroup $group the group to check * @param int $user_guid the user to check with * * @return bool */ function group_tools_group_multiple_admin_enabled(ElggGroup $group, $user_guid = 0) { $result = false; if (empty($group) || !elgg_instanceof($group, "group")) { return $result; } $user_guid = sanitise_int($user_guid, false); if (empty($user_guid)) { $user_guid = elgg_get_logged_in_user_guid(); } if (empty($user_guid)) { return $result; } if (!group_tools_multiple_admin_enabled()) { return $result; } if ($group->getOwnerGUID() == $user_guid || elgg_is_admin_logged_in()) { $result = true; } elseif ($group->group_multiple_admin_allow_enable == "yes" && $group->canEdit($user_guid)) { $result = true; } return $result; }
<?php $widget = elgg_extract("entity", $vars); $result = ""; $dbprefix = elgg_get_config("dbprefix"); // get widget settings $count = sanitise_int($widget->content_count, false); if (empty($count)) { $count = 8; } $content_type = $widget->content_type; if (empty($content_type)) { // set default content type filter if (elgg_is_active_plugin("blog")) { $content_type = "blog"; } elseif (elgg_is_active_plugin("file")) { $content_type = "file"; } elseif (elgg_is_active_plugin("pages")) { $content_type = "page"; } elseif (elgg_is_active_plugin("bookmarks")) { $content_type = "bookmarks"; } elseif (elgg_is_active_plugin("thewire")) { $content_type = "thewire"; } elseif (elgg_is_active_plugin("videolist")) { $content_type = "videolist_item"; } elseif (elgg_is_active_plugin("event_manager")) { $content_type = "event"; } elseif (elgg_is_active_plugin("tasks")) { $content_type = "task_top"; } elseif (elgg_is_active_plugin("groups")) { $content_type = "groupforumtopic";
/** * Make sure all the children are in the correct tree * * @param ElggObject $entity the entity to check the children from * @param int $tree_guid the correct tree guid (will default to the given entity) * * @return bool */ function static_check_children_tree(ElggObject $entity, $tree_guid = 0) { if (!elgg_instanceof($entity, 'object', 'static')) { return false; } $tree_guid = sanitise_int($tree_guid, false); if (empty($tree_guid)) { $tree_guid = $entity->getGUID(); } // ignore access for this part $ia = elgg_set_ignore_access(true); $batch = new ElggBatch('elgg_get_entities', ['type' => 'object', 'subtype' => StaticPage::SUBTYPE, 'owner_guid' => $entity->getOwnerGUID(), 'container_guid' => $entity->getGUID(), 'limit' => false]); foreach ($batch as $static) { // remove old tree remove_entity_relationships($static->getGUID(), 'subpage_of'); // add new tree add_entity_relationship($static->getGUID(), 'subpage_of', $tree_guid); // check children static_check_children_tree($static, $tree_guid); } // restore access elgg_set_ignore_access($ia); return true; }