protected function setUp() { // required by \ElggEntity when setting the owner/container _elgg_services()->setValue('session', new \ElggSession(new \Elgg\Http\MockSessionStorage())); $this->obj = $this->getMockBuilder('\\ElggUpgrade')->setMethods(null)->getMock(); $this->obj->_callable_egefps = array($this, 'mock_egefps'); }
/** * Return the object specific details of a object by a row. * * @param int $guid The guid to retrieve * * @return bool * @access private */ function get_object_entity_as_row($guid) { $dbprefix = elgg_get_config('dbprefix'); $sql = "SELECT * FROM {$dbprefix}objects_entity\n\t\tWHERE guid = :guid"; $params = [':guid' => (int) $guid]; return _elgg_services()->db->getDataRow($sql, null, $params); }
/** * {@inheritdoc} */ protected function handle() { $uri = '/' . ltrim($this->argument('uri'), '/'); $method = $this->argument('method') ?: 'GET'; $add_csrf_tokens = $this->option('tokens'); $site_url = elgg_get_site_url(); $uri = substr(elgg_normalize_url($uri), strlen($site_url)); $path_key = Application::GET_PATH_KEY; $parameters = []; $query = trim((string) $this->option('query'), '?'); parse_str($query, $parameters); if ($add_csrf_tokens) { $ts = time(); $parameters['__elgg_ts'] = $ts; $parameters['__elgg_token'] = _elgg_services()->actions->generateActionToken($ts); } $request = Request::create("?{$path_key}=" . urlencode($uri), $method, $parameters); $cookie_name = _elgg_services()->config->getCookieConfig()['session']['name']; $session_id = _elgg_services()->session->getId(); $request->cookies->set($cookie_name, $session_id); $request->headers->set('Referer', elgg_normalize_url()); if ($this->option('export')) { elgg_set_viewtype('json'); $request->headers->set('X-Elgg-Ajax-API', '2'); } _elgg_services()->setValue('request', $request); Application::index(); }
/** * Get some input from variables passed submitted through GET or POST. * * If using any data obtained from get_input() in a web page, please be aware that * it is a possible vector for a reflected XSS attack. If you are expecting an * integer, cast it to an int. If it is a string, escape quotes. * * Note: this function does not handle nested arrays (ex: form input of param[m][n]) * because of the filtering done in htmlawed from the filter_tags call. * @todo Is this ^ still true? * * @param string $variable The variable name we want. * @param mixed $default A default value for the variable if it is not found. * @param bool $filter_result If true, then the result is filtered for bad tags. * * @return mixed */ function get($variable, $default = null, $filter_result = true) { $result = $default; elgg_push_context('input'); if (isset($this->CONFIG->input[$variable])) { // a plugin has already set this variable $result = $this->CONFIG->input[$variable]; if ($filter_result) { $result = filter_tags($result); } } else { $request = _elgg_services()->request; $value = $request->get($variable); if ($value !== null) { $result = $value; if (is_string($result)) { // @todo why trim $result = trim($result); } if ($filter_result) { $result = filter_tags($result); } } } elgg_pop_context(); return $result; }
public static function getService() { $db = _elgg_services()->db; $queue = new \Elgg\Queue\DatabaseQueue('bulk_user_admin', $db); $entities = _elgg_services()->entityTable; return new self($queue, $entities); }
/** * Constructor */ public function __construct() { $sp = _elgg_services(); $this->setValue('session', \ElggSession::getMock()); $this->setFactory('db', function (MockServiceProvider $m) use($sp) { $config = $this->getTestingDatabaseConfig(); return new \Elgg\Mocks\Database($config, $sp->logger); }); $this->setFactory('entityTable', function (MockServiceProvider $m) use($sp) { return new \Elgg\Mocks\Database\EntityTable($sp->config, $m->db, $sp->entityCache, $sp->metadataCache, $m->subtypeTable, $sp->events, $sp->session, $sp->translator, $sp->logger); }); $this->setFactory('metadataTable', function (MockServiceProvider $m) use($sp) { return new \Elgg\Mocks\Database\MetadataTable($sp->metadataCache, $m->db, $m->entityTable, $sp->events, $m->session); }); $this->setFactory('annotations', function (MockServiceProvider $m) use($sp) { return new \Elgg\Mocks\Database\Annotations($m->db, $m->session, $sp->events); }); $this->setFactory('relationshipsTable', function (MockServiceProvider $m) use($sp) { return new \Elgg\Mocks\Database\RelationshipsTable($m->db, $m->entityTable, $m->metadataTable, $sp->events); }); $this->setFactory('subtypeTable', function (MockServiceProvider $m) { return new \Elgg\Mocks\Database\SubtypeTable($m->db); }); $this->setFactory('accessCollections', function (MockServiceProvider $m) use($sp) { return new \Elgg\Mocks\Database\AccessCollections($sp->config, $m->db, $m->entityTable, $sp->accessCache, $sp->hooks, $sp->session, $sp->translator); }); $this->setFactory('privateSettings', function (MockServiceProvider $m) use($sp) { return new \Elgg\Mocks\Database\PrivateSettingsTable($m->db, $m->entityTable, $sp->pluginSettingsCache); }); }
function testElggSendEmailBypass() { _elgg_services()->hooks->registerHandler('email', 'system', [$this, 'handleEmailHookTrue']); $this->assertTrue(elgg_send_email("*****@*****.**", "*****@*****.**", "Hello", "World", ['foo' => 1])); _elgg_services()->hooks->unregisterHandler('email', 'system', [$this, 'handleEmailHookTrue']); $this->assertNull($this->mailer->getLastMessage()); }
/** * Check if requested page is a static page * * @param string $hook name of the hook * @param string $type type of the hook * @param array $return_value return value * @param array $params hook parameters * * @return array */ public static function routeAll($hook, $type, $return_value, $params) { if (!is_array($return_value)) { // someone else already routed this page return; } /** * $return_value contains: * $return_value['identifier'] => requested handler * $return_value['segments'] => url parts ($page) */ $identifier = elgg_extract('identifier', $return_value); if (empty($identifier)) { return; } $handlers = _elgg_services()->router->getPageHandlers(); if (elgg_extract($identifier, $handlers)) { return; } $ia = elgg_set_ignore_access(true); $entities = elgg_get_entities_from_metadata(['type' => 'object', 'subtype' => \StaticPage::SUBTYPE, 'limit' => 1, 'metadata_name_value_pairs' => ['friendly_title' => $identifier], 'metadata_case_sensitive' => false]); elgg_set_ignore_access($ia); if (empty($entities)) { return; } $entity = $entities[0]; if (!has_access_to_entity($entity) && !$entity->canEdit()) { return; } $return_value['segments'] = ['view', $entity->getGUID()]; $return_value['identifier'] = 'static'; return $return_value; }
/** * Checks if additional select columns are readable as volatile data even if we hit the cache while fetching entity. * * https://github.com/Elgg/Elgg/issues/5544 */ public function testSqlAdditionalSelectsAsVolatileDataWithCache() { // remove ignore access as it disables entity cache $access = elgg_set_ignore_access(false); // may not have groups in DB - let's create one $group = new \ElggGroup(); $group->name = 'test_group'; $group->access_id = ACCESS_PUBLIC; $this->assertTrue($group->save() !== false); foreach (array('site', 'user', 'group', 'object') as $type) { $entities = elgg_get_entities(array('type' => $type, 'selects' => array('42 as added_col3'), 'limit' => 1)); $this->assertFalse(empty($entities)); if ($entities) { $entity = array_shift($entities); $this->assertTrue($entity instanceof \ElggEntity); $this->assertEqual($entity->added_col3, null, "Additional select columns are leaking to attributes for " . get_class($entity)); $this->assertEqual($entity->getVolatileData('select:added_col3'), 42); // make sure we have cached the entity $this->assertNotEqual(false, _elgg_services()->entityCache->get($entity->guid)); } } // run these again but with different value to make sure cache does not interfere foreach (array('site', 'user', 'group', 'object') as $type) { $entities = elgg_get_entities(array('type' => $type, 'selects' => array('64 as added_col3'), 'limit' => 1)); $this->assertFalse(empty($entities)); if ($entities) { $entity = array_shift($entities); $this->assertTrue($entity instanceof \ElggEntity); $this->assertEqual($entity->added_col3, null, "Additional select columns are leaking to attributes for " . get_class($entity)); $this->assertEqual($entity->getVolatileData('select:added_col3'), 64, "Failed to overwrite volatile data in cached entity"); } } elgg_set_ignore_access($access); $group->delete(); }
/** * Look for entities with an owner that cannot be loaded */ function dbvalidate_get_bad_entities() { global $ENTITY_CACHE; $access_status = access_get_show_hidden_status(); access_show_hidden_entities(true); $db_prefix = elgg_get_config('dbprefix'); _elgg_services()->db->disableQueryCache(); $query = "SELECT COUNT(*) as total from {$db_prefix}entities WHERE type='object' OR type='group'"; $result = get_data_row($query); $num_entities = $result->total; $bad_guids = array(); // handle 1000 at time $count = 0; $step = 1000; while ($count < $num_entities) { // flush caches so that we don't have memory issues $ENTITY_CACHE = array(); $query = "SELECT guid, owner_guid from {$db_prefix}entities WHERE type='object' OR type='group' LIMIT {$count}, {$step}"; $guids = get_data($query); $count = $count += $step; // looking for 0 owner or an owner that cannot be loaded foreach ($guids as $guid) { if ($guid->owner_guid == 0) { $bad_guids[] = $guid->guid; } else { if (!get_entity($guid->owner_guid)) { $bad_guids[] = $guid->guid; } } } } _elgg_services()->db->enableQueryCache(); access_show_hidden_entities($access_status); return $bad_guids; }
/** * Save the wire_tools preferences for the user * * @param string $hook the name of the hook * @param stirng $type the type of the hook * @param array $return_value the current return value * @param array $params supplied values * * @return void */ public static function saveUserNotificationsSettings($hook, $type, $return_value, $params) { $NOTIFICATION_HANDLERS = _elgg_services()->notifications->getMethods(); if (empty($NOTIFICATION_HANDLERS) || !is_array($NOTIFICATION_HANDLERS)) { return; } $user_guid = (int) get_input('guid'); if (empty($user_guid)) { return; } $user = get_user($user_guid); if (empty($user) || !$user->canEdit()) { return; } $methods = []; foreach ($NOTIFICATION_HANDLERS as $method) { $setting = get_input("thewire_tools_{$method}"); if (!empty($setting)) { $methods[] = $method; } } if (!empty($methods)) { elgg_set_plugin_user_setting('notification_settings', implode(',', $methods), $user->getGUID(), 'thewire_tools'); } else { elgg_unset_plugin_user_setting('notification_settings', $user->getGUID(), 'thewire_tools'); } // set flag for correct fallback behaviour elgg_set_plugin_user_setting('notification_settings_saved', '1', $user->getGUID(), 'thewire_tools'); }
/** * Sleep for a while to slow things down. * * @param int $multiplier A time multipler to tarpit repeat offending IPs */ function registration_randomizer_tarpit($wait = 5) { $ip = filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_VALIDATE_IP); $setting_name = "{$ip}_tarpit_count"; $count = (int) elgg_get_plugin_setting($setting_name, 'registration_randomizer'); if ($count > 4) { $wait = pow(4, 4); } else { $wait = pow($count, 4); } // now limit it to something reasonable, like 90% of max execution time $max_execution_time = ini_get('max_execution_time'); if ($max_execution_time === false) { $max_execution_time = 30; } $max_execution_time = floor(0.9 * $max_execution_time); if ($max_execution_time && $wait > $max_execution_time) { $wait = $max_execution_time; } elgg_set_plugin_setting($setting_name, $count + 1, 'registration_randomizer'); registration_randomizer_log("Tarpitting {$ip} for {$wait} seconds after {$count} failures.", false); if ($wait > 0) { // close mysql connections for the time of a sleep mysql_close(_elgg_services()->db->getLink('read')); mysql_close(_elgg_services()->db->getLink('write')); sleep($wait); //restore connections _elgg_services()->db->setupConnections(); } }
/** * Set ignore access. * * @param bool $ignore Ignore access * * @return bool Previous setting */ public function setIgnoreAccess($ignore = true) { _elgg_services()->accessCache->clear(); $prev = $this->ignore_access; $this->ignore_access = $ignore; return $prev; }
/** * {@inheritdoc} */ public function registerHandler($name, $type, $callback, $priority = 500) { if (($name == 'view' || $name == 'view_vars') && $type !== 'all') { $type = _elgg_services()->views->canonicalizeViewName($type); } return parent::registerHandler($name, $type, $callback, $priority); }
protected function getLoggerInstance() { $mock = $this->getMock('\\Elgg\\PluginHooksService', array('trigger')); $mock->expects($this->never())->method('trigger'); $sp = _elgg_services(); return new \Elgg\Logger($mock, $sp->config, $sp->context); }
/** * Get notification preferences of users who have answered the poll * * The poll contents have changed so we must notify the people * who had answered before the changes took place. * * @param string $hook 'get' * @param string $type 'subscriptions' * @param array $subscriptions Array containing subscriptions in the form * <user guid> => array('email', 'site', etc.) * @param array $params Hook parameters * @return array */ public static function subscribers($hook, $type, $subscriptions, $params) { $poll = $params['event']->getObject(); if (!$poll instanceof \ElggSchedulingPoll) { return $subscriptions; } $subscriptions = array(); $voters = array_keys($poll->getVotesByUser()); if (empty($voters)) { // There's no one to notify return $subscriptions; } // Get all available notification methods $methods = _elgg_services()->notifications->getMethods(); // Get all users who have voted $users = elgg_get_entities(array('type' => 'user', 'guids' => $voters, 'limit' => 0)); // Personal notification settings are saved into a metadata // called notification:method:{$method}. Go through the users // and check which methods have been enabled for each user. foreach ($users as $user) { foreach ($methods as $method) { $meta_name = "notification:method:{$method}"; if ((bool) $user->{$meta_name}) { $subscriptions[$user->guid][] = $method; } } } return $subscriptions; }
/** * Test that legacy bootstrap has been autoloaded and * stay BC with older test cases */ public function testIsBoostrapped() { $this->assertInstanceOf(Di\ServiceProvider::class, _elgg_services()); $this->assertInstanceOf(Application::class, _elgg_testing_application()); $this->assertInstanceof(Config::class, _elgg_testing_config()); $this->assertInstanceOf(Http\Request::class, _elgg_testing_request()); }
/** * Initialise the site secret (32 bytes: "z" to indicate format + 186-bit key in Base64 URL). * * Used during installation and saves as a config. * * Note: Old secrets were hex encoded. * * @return mixed The site secret hash or false * @access private */ function init() { $secret = 'z' . _elgg_services()->crypto->getRandomString(31); if ($this->configTable->set('__site_secret__', $secret)) { return $secret; } return false; }
public function testCanNotGetFooterOutsideFormView() { _elgg_services()->logger->disable(); $this->assertFalse(_elgg_services()->forms->getFooter()); $expected = [['message' => 'Form footer can only be set and retrieved during form rendering, anywhere in elgg_view_form() call stack (e.g. form view, extending views, or view hooks)', 'level' => Logger::ERROR]]; $logs = _elgg_services()->logger->enable(); $this->assertEquals($expected, $logs); }
public function testSetLanguageFromGetParameter() { $translator = new Translator(); $input_lang = 'nl'; _elgg_services()->input->set('hl', $input_lang); $lang = $translator->getLanguage(); $this->assertEquals($lang, $input_lang); }
public function testCanValidateAcrossMultipleSession() { $signed_url = $this->service->sign($this->url, '+1 day'); $this->assertTrue($this->service->isValid($signed_url)); _elgg_services()->session->invalidate(); _elgg_services()->session->start(); $this->assertTrue($this->service->isValid($signed_url)); }
/** * Returns the site secret. * * Used to generate difficult to guess hashes for sessions and action tokens. * * @return string Site secret. * @access private */ function get() { $secret = _elgg_services()->datalist->get('__site_secret__'); if (!$secret) { $secret = init_site_secret(); } return $secret; }
public function setup() { $this->obj = new EntityPreloader(\_elgg_services()->entityCache, \_elgg_services()->entityTable); $dependency = new PreloaderMock_20140623(); $this->obj->_callable_cache_checker = array($dependency, 'isCached'); $this->obj->_callable_entity_loader = array($dependency, 'load'); $this->mock = $this->getMock('Elgg\\PreloaderMock_20140623'); }
public function testOthersTypedAsTextWithWarning() { _elgg_services()->logger->disable(); $this->assertSame('text', detect_extender_valuetype(null)); $this->assertSame('text', detect_extender_valuetype(true)); $this->assertSame('text', detect_extender_valuetype((object) [])); $expected = [['message' => 'Metadata and annotations store only integers and strings. NULL given.', 'level' => 300], ['message' => 'Metadata and annotations store only integers and strings. boolean given.', 'level' => 300], ['message' => 'Metadata and annotations store only integers and strings. object given.', 'level' => 300]]; $this->assertSame($expected, _elgg_services()->logger->enable()); }
function testServices() { $services = _elgg_services(); $app = new Application($services); $names = []; foreach ($names as $name) { $this->assertSame($services->{$name}, $app->{$name}); } }
/** * Parse a manifest object from 1.8 and later * * @return bool * * @throws PluginException */ public function parse() { $parsed = array(); foreach ($this->manifestObject->children as $element) { switch ($element->name) { // single elements case 'blurb': case 'description': case 'name': case 'author': case 'version': case 'id': case 'website': case 'copyright': case 'license': case 'repository': case 'bugtracker': case 'donations': case 'activate_on_install': $parsed[$element->name] = $element->content; break; // arrays // arrays case 'category': $parsed[$element->name][] = $element->content; break; // 3d arrays // 3d arrays case 'screenshot': case 'contributor': case 'provides': case 'conflicts': case 'requires': case 'suggests': if (!isset($element->children)) { return false; } $info = array(); foreach ($element->children as $child_element) { $info[$child_element->name] = $child_element->content; } $parsed[$element->name][] = $info; break; } } // check we have all the required fields foreach ($this->requiredAttributes as $attr) { if (!array_key_exists($attr, $parsed)) { throw new \PluginException(_elgg_services()->translator->translate('PluginException:ParserErrorMissingRequiredAttribute', array($attr, $this->caller->getPluginID()))); } } $this->manifest = $parsed; if (!$this->manifest) { return false; } return true; }
/** * Constructor * * @param ElggData $object The object of the event (ElggEntity) * @param string $action The name of the action (default: create) * @param ElggEntity $actor The entity that caused the event (default: logged in user) */ public function __construct(ElggData $object = null, $action = null, ElggEntity $actor = null) { $this->object = $object; $this->actor = $actor; if (!isset($actor)) { $this->actor = _elgg_services()->session->getLoggedInUser(); } $this->action = $action ?: self::DEFAULT_ACTION_NAME; }
/** * Initialize the plugin * @return void */ function notifications_html_handler_init() { _elgg_services()->hooks->clearHandlers('send', 'notification:email'); elgg_register_plugin_hook_handler('send', 'notification:email', 'notifications_html_handler_send_email_notification'); elgg_register_plugin_hook_handler('email', 'system', 'notifications_html_handler_send_system_email', 1); elgg_register_plugin_hook_handler('format', 'notification', 'notifications_html_handler_format', 9999); elgg_register_action('notifications/html/test', __DIR__ . '/actions/notifications/html/test.php', 'admin'); elgg_extend_view('page/notification.css', 'elements/components.css'); }
/** * Handle a request for a file * * @param array $path URL path * @return void */ public function handleRequest($path) { if (!preg_match('~e(\\d+)/l(\\d+)/d([ia])/c([01])/([a-zA-Z0-9\\-_]+)/(.*)$~', $path, $m)) { header("HTTP/1.1 400 Bad Request"); exit; } list(, $expires, $last_updated, $disposition, $use_cookie, $mac, $path_from_dataroot) = $m; if ($expires && $expires < time()) { $this->send403('URL has expired'); } $etag = '"' . $last_updated . '"'; $this->handle304($etag); $hmac_data = array('expires' => (int) $expires, 'last_updated' => (int) $last_updated, 'disposition' => $disposition, 'path' => $path_from_dataroot, 'use_cookie' => (int) $use_cookie); if ((bool) $use_cookie) { $hmac_data['cookie'] = _elgg_services()->session->getId(); } ksort($hmac_data); $hmac = elgg_build_hmac($hmac_data); if (!$hmac->matchesToken($mac)) { $this->send403(); } $dataroot = _elgg_services()->config->get('dataroot'); if (empty($dataroot)) { $this->send404(); } $filenameonfilestore = "{$dataroot}{$path_from_dataroot}"; if (!is_readable($filenameonfilestore)) { $this->send404(); } $actual_last_updated = filemtime($filenameonfilestore); if ($actual_last_updated != $last_updated) { $this->send403('URL has expired'); } $mime = $this->getContentType($filenameonfilestore); header("Content-type: {$mime}", true); $filesize = filesize($filenameonfilestore); header("Content-Length: {$filesize}", true); if ($disposition == 'i') { header("Content-disposition: inline"); } else { $basename = basename($filenameonfilestore); header("Content-disposition: attachment; filename='{$basename}'"); } if ($expires) { $expires_str = gmdate('D, d M Y H:i:s \\G\\M\\T', $expires); } else { $expires_str = gmdate('D, d M Y H:i:s \\G\\M\\T', strtotime("+3 years")); } header('Expires: ' . $expires_str, true); $cache_control = $use_cookie ? 'no-cache' : 'public'; header("Pragma: {$cache_control}", true); header("Cache-Control: {$cache_control}", true); header("ETag: {$etag}"); readfile($filenameonfilestore); exit; }
/** * When a user joins a group * * @param string $event join * @param string $type group * @param array $params array with the user and the user * * @return void */ function group_tools_join_group_event($event, $type, $params) { $NOTIFICATION_HANDLERS = _elgg_services()->notifications->getMethods(); static $auto_notification; // only load plugin setting once if (!isset($auto_notification)) { $auto_notification = array(); if (isset($NOTIFICATION_HANDLERS) && is_array($NOTIFICATION_HANDLERS)) { if (elgg_get_plugin_setting("auto_notification", "group_tools") == "yes") { // Backwards compatibility $auto_notification = array("email", "site"); } foreach ($NOTIFICATION_HANDLERS as $method => $foo) { if (elgg_get_plugin_setting("auto_notification_" . $method, "group_tools") == "1") { $auto_notification[] = $method; } } } } if (!empty($params) && is_array($params)) { $group = elgg_extract("group", $params); $user = elgg_extract("user", $params); if ($user instanceof ElggUser && $group instanceof ElggGroup) { // check for the auto notification settings if (!empty($NOTIFICATION_HANDLERS) && is_array($NOTIFICATION_HANDLERS)) { foreach ($NOTIFICATION_HANDLERS as $method => $dummy) { if (in_array($method, $auto_notification)) { add_entity_relationship($user->getGUID(), "notify" . $method, $group->getGUID()); } } } // cleanup invites remove_entity_relationship($group->getGUID(), "invited", $user->getGUID()); // and requests remove_entity_relationship($user->getGUID(), "membership_request", $group->getGUID()); // cleanup email invitations $options = array("annotation_name" => "email_invitation", "annotation_value" => group_tools_generate_email_invite_code($group->getGUID(), $user->email), "limit" => false); if (elgg_is_logged_in()) { elgg_delete_annotations($options); } elseif ($annotations = elgg_get_annotations($options)) { group_tools_delete_annotations($annotations); } // welcome message $welcome_message = $group->getPrivateSetting("group_tools:welcome_message"); $check_message = trim(strip_tags($welcome_message)); if (!empty($check_message)) { // replace the place holders $welcome_message = str_ireplace("[name]", $user->name, $welcome_message); $welcome_message = str_ireplace("[group_name]", $group->name, $welcome_message); $welcome_message = str_ireplace("[group_url]", $group->getURL(), $welcome_message); // notify the user notify_user($user->getGUID(), $group->getGUID(), elgg_echo("group_tools:welcome_message:subject", array($group->name)), $welcome_message); } } } }