diff options
Diffstat (limited to 'engine')
87 files changed, 1939 insertions, 508 deletions
diff --git a/engine/classes/ElggAccess.php b/engine/classes/ElggAccess.php index 6f8d9bb4b..0aed477fc 100644 --- a/engine/classes/ElggAccess.php +++ b/engine/classes/ElggAccess.php @@ -16,6 +16,7 @@ class ElggAccess {  	 */  	private $ignore_access; +	// @codingStandardsIgnoreStart  	/**  	 * Get current ignore access setting.  	 * @@ -26,6 +27,7 @@ class ElggAccess {  		elgg_deprecated_notice('ElggAccess::get_ignore_access() is deprecated by ElggAccess::getIgnoreAccess()', 1.8);  		return $this->getIgnoreAccess();  	} +	// @codingStandardsIgnoreEnd  	/**  	 * Get current ignore access setting. @@ -36,6 +38,7 @@ class ElggAccess {  		return $this->ignore_access;  	} +	// @codingStandardsIgnoreStart  	/**  	 * Set ignore access.  	 * @@ -49,6 +52,7 @@ class ElggAccess {  		elgg_deprecated_notice('ElggAccess::set_ignore_access() is deprecated by ElggAccess::setIgnoreAccess()', 1.8);  		return $this->setIgnoreAccess($ignore);  	} +	// @codingStandardsIgnoreEnd  	/**  	 * Set ignore access. diff --git a/engine/classes/ElggAttributeLoader.php b/engine/classes/ElggAttributeLoader.php index 2d1c1abde..ffc80b02d 100644 --- a/engine/classes/ElggAttributeLoader.php +++ b/engine/classes/ElggAttributeLoader.php @@ -4,6 +4,9 @@   * Loads ElggEntity attributes from DB or validates those passed in via constructor   *   * @access private + * + * @package    Elgg.Core + * @subpackage DataModel   */  class ElggAttributeLoader { @@ -21,7 +24,7 @@ class ElggAttributeLoader {  		'time_created',  		'time_updated',  		'last_action', -		'enabled' +		'enabled',  	);  	/** @@ -65,9 +68,11 @@ class ElggAttributeLoader {  	public $full_loader = '';  	/** -	 * @param string $class class of object being loaded -	 * @param string $required_type entity type this is being used to populate -	 * @param array $initialized_attrs attributes after initializeAttributes() has been run +	 * Constructor +	 * +	 * @param string $class             class of object being loaded +	 * @param string $required_type     entity type this is being used to populate +	 * @param array  $initialized_attrs attributes after initializeAttributes() has been run  	 * @throws InvalidArgumentException  	 */  	public function __construct($class, $required_type, array $initialized_attrs) { @@ -87,14 +92,33 @@ class ElggAttributeLoader {  		$this->secondary_attr_names = array_diff($all_attr_names, self::$primary_attr_names);  	} +	/** +	 * Get primary attributes missing that are missing +	 * +	 * @param stdClass $row Database row +	 * @return array +	 */  	protected function isMissingPrimaries($row) {  		return array_diff(self::$primary_attr_names, array_keys($row)) !== array();  	} +	/** +	 * Get secondary attributes that are missing +	 * +	 * @param stdClass $row Database row +	 * @return array +	 */  	protected function isMissingSecondaries($row) {  		return array_diff($this->secondary_attr_names, array_keys($row)) !== array();  	} +	/** +	 * Check that the type is correct +	 * +	 * @param stdClass $row Database row +	 * @return void +	 * @throws InvalidClassException +	 */  	protected function checkType($row) {  		if ($row['type'] !== $this->required_type) {  			$msg = elgg_echo('InvalidClassException:NotValidElggStar', array($row['guid'], $this->class)); @@ -176,6 +200,8 @@ class ElggAttributeLoader {  						// saved, these are stored w/ type "site", but with no sites_entity row. These  						// are probably only created in the unit tests.  						// @todo Don't save vanilla ElggEntities with type "site" + +						$row = $this->filterAddedColumns($row);  						$row['guid'] = (int) $row['guid'];  						return $row;  					} @@ -185,15 +211,38 @@ class ElggAttributeLoader {  			}  		} -		// loading complete: re-check missing and check type -		if (($was_missing_primaries && $this->isMissingPrimaries($row)) -				|| ($was_missing_secondaries && $this->isMissingSecondaries($row))) { -			throw new LogicException('Attribute loaders failed to return proper attributes'); -		} +		$row = $this->filterAddedColumns($row); + +		// Note: If there are still missing attributes, we're running on a 1.7 or earlier schema. We let +		// this pass so the upgrades can run. -		// guid needs to be an int  http://trac.elgg.org/ticket/4111 +		// guid needs to be an int  https://github.com/elgg/elgg/issues/4111  		$row['guid'] = (int) $row['guid'];  		return $row;  	} + +	/** +	 * Filter out keys returned by the query which should not appear in the entity's attributes +	 * +	 * @param array $row All columns from the query +	 * @return array Columns acceptable for the entity's attributes +	 */ +	protected function filterAddedColumns($row) { +		// make an array with keys as acceptable attribute names +		$acceptable_attrs = self::$primary_attr_names; +		array_splice($acceptable_attrs, count($acceptable_attrs), 0, $this->secondary_attr_names); +		$acceptable_attrs = array_combine($acceptable_attrs, $acceptable_attrs); + +		// @todo remove these when #4584 is in place +		$acceptable_attrs['tables_split'] = true; +		$acceptable_attrs['tables_loaded'] = true; + +		foreach ($row as $key => $val) { +			if (!isset($acceptable_attrs[$key])) { +				unset($row[$key]); +			} +		} +		return $row; +	}  } diff --git a/engine/classes/ElggAutoP.php b/engine/classes/ElggAutoP.php index f3c7cc972..05842d1b2 100644 --- a/engine/classes/ElggAutoP.php +++ b/engine/classes/ElggAutoP.php @@ -7,6 +7,9 @@   *   * In DIV elements, Ps are only added when there would be at   * least two of them. + *  + * @package    Elgg.Core + * @subpackage Output   */  class ElggAutoP { @@ -51,8 +54,12 @@ class ElggAutoP {  	protected $_alterList = 'article aside blockquote body details div footer header  		section'; +	/** @var string */  	protected $_unique = ''; +	/** +	 * Constructor +	 */  	public function __construct() {  		$this->_blocks = preg_split('@\\s+@', $this->_blocks);  		$this->_descendList = preg_split('@\\s+@', $this->_descendList); @@ -98,21 +105,28 @@ class ElggAutoP {  		$html = str_replace('&', $this->_unique . 'AMP', $html);  		$this->_doc = new DOMDocument(); -	    +  		// parse to DOM, suppressing loadHTML warnings  		// http://www.php.net/manual/en/domdocument.loadhtml.php#95463  		libxml_use_internal_errors(true); +		// Do not load entities. May be unnecessary, better safe than sorry +		$disable_load_entities = libxml_disable_entity_loader(true); +  		if (!$this->_doc->loadHTML("<html><meta http-equiv='content-type' "   				. "content='text/html; charset={$this->encoding}'><body>{$html}</body>"  				. "</html>")) { + +			libxml_disable_entity_loader($disable_load_entities);  			return false;  		} +		libxml_disable_entity_loader($disable_load_entities); +  		$this->_xpath = new DOMXPath($this->_doc);  		// start processing recursively at the BODY element  		$nodeList = $this->_xpath->query('//body[1]'); -		$this->_addParagraphs($nodeList->item(0)); +		$this->addParagraphs($nodeList->item(0));  		// serialize back to HTML  		$html = $this->_doc->saveHTML(); @@ -128,9 +142,16 @@ class ElggAutoP {  		// re-parse so we can handle new AUTOP elements +		// Do not load entities. May be unnecessary, better safe than sorry +		$disable_load_entities = libxml_disable_entity_loader(true); +  		if (!$this->_doc->loadHTML($html)) { +			libxml_disable_entity_loader($disable_load_entities);  			return false;  		} + +		libxml_disable_entity_loader($disable_load_entities); +  		// must re-create XPath object after DOM load  		$this->_xpath = new DOMXPath($this->_doc); @@ -187,15 +208,16 @@ class ElggAutoP {  	/**  	 * Add P and BR elements as necessary  	 * -	 * @param DOMElement $el +	 * @param DOMElement $el DOM element +	 * @return void  	 */ -	protected function _addParagraphs(DOMElement $el) { +	protected function addParagraphs(DOMElement $el) {  		// no need to call recursively, just queue up  		$elsToProcess = array($el);  		$inlinesToProcess = array();  		while ($el = array_shift($elsToProcess)) {  			// if true, we can alter all child nodes, if not, we'll just call -			// _addParagraphs on each element in the descendInto list +			// addParagraphs on each element in the descendInto list  			$alterInline = in_array($el->nodeName, $this->_alterList);  			// inside affected elements, we want to trim leading whitespace from @@ -229,8 +251,8 @@ class ElggAutoP {  				if ($alterInline) {  					$isText = ($node->nodeType === XML_TEXT_NODE);  					$isLastInline = (! $node->nextSibling -								   || ($node->nextSibling->nodeType === XML_ELEMENT_NODE -									   && in_array($node->nextSibling->nodeName, $this->_blocks))); +							|| ($node->nextSibling->nodeType === XML_ELEMENT_NODE +								&& in_array($node->nextSibling->nodeName, $this->_blocks)));  					if ($isElement) {  						$isFollowingBr = ($node->nodeName === 'br');  					} @@ -263,7 +285,7 @@ class ElggAutoP {  					if ($isBlock) {  						if (in_array($node->nodeName, $this->_descendList)) {  							$elsToProcess[] = $node; -							//$this->_addParagraphs($node); +							//$this->addParagraphs($node);  						}  					}  					$openP = true; diff --git a/engine/classes/ElggBatch.php b/engine/classes/ElggBatch.php index 5d59425d0..d810ea066 100644 --- a/engine/classes/ElggBatch.php +++ b/engine/classes/ElggBatch.php @@ -150,6 +150,20 @@ class ElggBatch  	private $incrementOffset = true;  	/** +	 * Entities that could not be instantiated during a fetch +	 * +	 * @var stdClass[] +	 */ +	private $incompleteEntities = array(); + +	/** +	 * Total number of incomplete entities fetched +	 * +	 * @var int +	 */ +	private $totalIncompletes = 0; + +	/**  	 * Batches operations on any elgg_get_*() or compatible function that supports  	 * an options array.  	 * @@ -222,16 +236,22 @@ class ElggBatch  	}  	/** +	 * Tell the process that an entity was incomplete during a fetch +	 * +	 * @param stdClass $row +	 * +	 * @access private +	 */ +	public function reportIncompleteEntity(stdClass $row) { +		$this->incompleteEntities[] = $row; +	} + +	/**  	 * Fetches the next chunk of results  	 *  	 * @return bool  	 */  	private function getNextResultsChunk() { -		// reset memory caches after first chunk load -		if ($this->chunkIndex > 0) { -			global $DB_QUERY_CACHE, $ENTITY_CACHE; -			$DB_QUERY_CACHE = $ENTITY_CACHE = array(); -		}  		// always reset results.  		$this->results = array(); @@ -265,27 +285,47 @@ class ElggBatch  		if ($this->incrementOffset) {  			$offset = $this->offset + $this->retrievedResults;  		} else { -			$offset = $this->offset; +			$offset = $this->offset + $this->totalIncompletes;  		}  		$current_options = array(  			'limit' => $limit, -			'offset' => $offset +			'offset' => $offset, +			'__ElggBatch' => $this,  		);  		$options = array_merge($this->options, $current_options); -		$getter = $this->getter; -		if (is_string($getter)) { -			$this->results = $getter($options); -		} else { -			$this->results = call_user_func_array($getter, array($options)); +		$this->incompleteEntities = array(); +		$this->results = call_user_func_array($this->getter, array($options)); + +		$num_results = count($this->results); +		$num_incomplete = count($this->incompleteEntities); + +		$this->totalIncompletes += $num_incomplete; + +		if ($this->incompleteEntities) { +			// pad the front of the results with nulls representing the incompletes +			array_splice($this->results, 0, 0, array_pad(array(), $num_incomplete, null)); +			// ...and skip past them +			reset($this->results); +			for ($i = 0; $i < $num_incomplete; $i++) { +				next($this->results); +			}  		}  		if ($this->results) {  			$this->chunkIndex++; -			$this->resultIndex = 0; -			$this->retrievedResults += count($this->results); + +			// let the system know we've jumped past the nulls +			$this->resultIndex = $num_incomplete; + +			$this->retrievedResults += ($num_results + $num_incomplete); +			if ($num_results == 0) { +				// This fetch was *all* incompletes! We need to fetch until we can either +				// offer at least one row to iterate over, or give up. +				return $this->getNextResultsChunk(); +			}  			return true;  		} else {  			return false; diff --git a/engine/classes/ElggCache.php b/engine/classes/ElggCache.php index 4317f4be9..909eab39b 100644 --- a/engine/classes/ElggCache.php +++ b/engine/classes/ElggCache.php @@ -21,6 +21,7 @@ abstract class ElggCache implements ArrayAccess {  		$this->variables = array();  	} +	// @codingStandardsIgnoreStart  	/**  	 * Set a cache variable.  	 * @@ -35,6 +36,7 @@ abstract class ElggCache implements ArrayAccess {  		elgg_deprecated_notice('ElggCache::set_variable() is deprecated by ElggCache::setVariable()', 1.8);  		$this->setVariable($variable, $value);  	} +	// @codingStandardsIgnoreEnd  	/**  	 * Set a cache variable. @@ -52,6 +54,7 @@ abstract class ElggCache implements ArrayAccess {  		$this->variables[$variable] = $value;  	} +	// @codingStandardsIgnoreStart  	/**  	 * Get variables for this cache.  	 * @@ -65,6 +68,7 @@ abstract class ElggCache implements ArrayAccess {  		elgg_deprecated_notice('ElggCache::get_variable() is deprecated by ElggCache::getVariable()', 1.8);  		return $this->getVariable($variable);  	} +	// @codingStandardsIgnoreEnd  	/**  	 * Get variables for this cache. diff --git a/engine/classes/ElggCrypto.php b/engine/classes/ElggCrypto.php new file mode 100644 index 000000000..317d371e4 --- /dev/null +++ b/engine/classes/ElggCrypto.php @@ -0,0 +1,208 @@ +<?php +/** + * ElggCrypto + * + * @package    Elgg.Core + * @subpackage Crypto + * + * @access private + */ +class ElggCrypto { + +	/** +	 * Character set for temp passwords (no risk of embedded profanity/glyphs that look similar) +	 */ +	const CHARS_PASSWORD = 'bcdfghjklmnpqrstvwxyz2346789'; + +	/** +	 * Generate a string of highly randomized bytes (over the full 8-bit range). +	 * +	 * @param int $length Number of bytes needed +	 * @return string Random bytes +	 * +	 * @author George Argyros <argyros.george@gmail.com> +	 * @copyright 2012, George Argyros. All rights reserved. +	 * @license Modified BSD +	 * @link https://github.com/GeorgeArgyros/Secure-random-bytes-in-PHP/blob/master/srand.php Original +	 * +	 * Redistribution and use in source and binary forms, with or without +	 * modification, are permitted provided that the following conditions are met: +	 *    * Redistributions of source code must retain the above copyright +	 *      notice, this list of conditions and the following disclaimer. +	 *    * Redistributions in binary form must reproduce the above copyright +	 *      notice, this list of conditions and the following disclaimer in the +	 *      documentation and/or other materials provided with the distribution. +	 *    * Neither the name of the <organization> nor the +	 *      names of its contributors may be used to endorse or promote products +	 *      derived from this software without specific prior written permission. +	 * +	 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +	 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +	 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +	 * DISCLAIMED. IN NO EVENT SHALL GEORGE ARGYROS BE LIABLE FOR ANY +	 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +	 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +	 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +	 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +	 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +	 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +	 */ +	public function getRandomBytes($length) { +		/** +		 * Our primary choice for a cryptographic strong randomness function is +		 * openssl_random_pseudo_bytes. +		 */ +		$SSLstr = '4'; // http://xkcd.com/221/ +		if (function_exists('openssl_random_pseudo_bytes') +				&& (version_compare(PHP_VERSION, '5.3.4') >= 0 || substr(PHP_OS, 0, 3) !== 'WIN')) { +			$SSLstr = openssl_random_pseudo_bytes($length, $strong); +			if ($strong) { +				return $SSLstr; +			} +		} + +		/** +		 * If mcrypt extension is available then we use it to gather entropy from +		 * the operating system's PRNG. This is better than reading /dev/urandom +		 * directly since it avoids reading larger blocks of data than needed. +		 * Older versions of mcrypt_create_iv may be broken or take too much time +		 * to finish so we only use this function with PHP 5.3.7 and above. +		 * @see https://bugs.php.net/bug.php?id=55169 +		 */ +		if (function_exists('mcrypt_create_iv') +				&& (version_compare(PHP_VERSION, '5.3.7') >= 0 || substr(PHP_OS, 0, 3) !== 'WIN')) { +			$str = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM); +			if ($str !== false) { +				return $str; +			} +		} + +		/** +		 * No build-in crypto randomness function found. We collect any entropy +		 * available in the PHP core PRNGs along with some filesystem info and memory +		 * stats. To make this data cryptographically strong we add data either from +		 * /dev/urandom or if its unavailable, we gather entropy by measuring the +		 * time needed to compute a number of SHA-1 hashes. +		 */ +		$str = ''; +		$bits_per_round = 2; // bits of entropy collected in each clock drift round +		$msec_per_round = 400; // expected running time of each round in microseconds +		$hash_len = 20; // SHA-1 Hash length +		$total = $length; // total bytes of entropy to collect + +		$handle = @fopen('/dev/urandom', 'rb'); +		if ($handle && function_exists('stream_set_read_buffer')) { +			@stream_set_read_buffer($handle, 0); +		} + +		do { +			$bytes = ($total > $hash_len) ? $hash_len : $total; +			$total -= $bytes; + +			//collect any entropy available from the PHP system and filesystem +			$entropy = rand() . uniqid(mt_rand(), true) . $SSLstr; +			$entropy .= implode('', @fstat(@fopen(__FILE__, 'r'))); +			$entropy .= memory_get_usage() . getmypid(); +			$entropy .= serialize($_ENV) . serialize($_SERVER); +			if (function_exists('posix_times')) { +				$entropy .= serialize(posix_times()); +			} +			if (function_exists('zend_thread_id')) { +				$entropy .= zend_thread_id(); +			} + +			if ($handle) { +				$entropy .= @fread($handle, $bytes); +			} else { +				// Measure the time that the operations will take on average +				for ($i = 0; $i < 3; $i++) { +					$c1 = microtime(true); +					$var = sha1(mt_rand()); +					for ($j = 0; $j < 50; $j++) { +						$var = sha1($var); +					} +					$c2 = microtime(true); +					$entropy .= $c1 . $c2; +				} + +				// Based on the above measurement determine the total rounds +				// in order to bound the total running time. +				$rounds = (int) ($msec_per_round * 50 / (int) (($c2 - $c1) * 1000000)); + +				// Take the additional measurements. On average we can expect +				// at least $bits_per_round bits of entropy from each measurement. +				$iter = $bytes * (int) (ceil(8 / $bits_per_round)); + +				for ($i = 0; $i < $iter; $i++) { +					$c1 = microtime(); +					$var = sha1(mt_rand()); +					for ($j = 0; $j < $rounds; $j++) { +						$var = sha1($var); +					} +					$c2 = microtime(); +					$entropy .= $c1 . $c2; +				} +			} + +			// We assume sha1 is a deterministic extractor for the $entropy variable. +			$str .= sha1($entropy, true); + +		} while ($length > strlen($str)); + +		if ($handle) { +			@fclose($handle); +		} + +		return substr($str, 0, $length); +	} + +	/** +	 * Generate a random string of specified length. +	 * +	 * Uses supplied character list for generating the new string. +	 * If no character list provided - uses Base64 URL character set. +	 * +	 * @param int         $length Desired length of the string +	 * @param string|null $chars  Characters to be chosen from randomly. If not given, the Base64 URL +	 *                            charset will be used. +	 * +	 * @return string The random string +	 * +	 * @throws InvalidArgumentException +	 * +	 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com) +	 * @license   http://framework.zend.com/license/new-bsd New BSD License +	 * +	 * @see https://github.com/zendframework/zf2/blob/master/library/Zend/Math/Rand.php#L179 +	 */ +	public static function getRandomString($length, $chars = null) { +		if ($length < 1) { +			throw new InvalidArgumentException('Length should be >= 1'); +		} + +		if (empty($chars)) { +			$numBytes = ceil($length * 0.75); +			$bytes    = self::getRandomBytes($numBytes); +			$string = substr(rtrim(base64_encode($bytes), '='), 0, $length); + +			// Base64 URL +			return strtr($string, '+/', '-_'); +		} + +		$listLen = strlen($chars); + +		if ($listLen == 1) { +			return str_repeat($chars, $length); +		} + +		$bytes  = self::getRandomBytes($length); +		$pos    = 0; +		$result = ''; +		for ($i = 0; $i < $length; $i++) { +			$pos     = ($pos + ord($bytes[$i])) % $listLen; +			$result .= $chars[$pos]; +		} + +		return $result; +	} +} diff --git a/engine/classes/ElggData.php b/engine/classes/ElggData.php index 426248ca3..4f843cde4 100644 --- a/engine/classes/ElggData.php +++ b/engine/classes/ElggData.php @@ -26,6 +26,7 @@ abstract class ElggData implements  	 */  	protected $attributes = array(); +	// @codingStandardsIgnoreStart  	/**  	 * Initialise the attributes array.  	 * @@ -44,6 +45,7 @@ abstract class ElggData implements  			elgg_deprecated_notice('initialise_attributes() is deprecated by initializeAttributes()', 1.8);  		}  	} +	// @codingStandardsIgnoreEnd  	/**  	 * Initialize the attributes array. diff --git a/engine/classes/ElggDiskFilestore.php b/engine/classes/ElggDiskFilestore.php index 7374aad35..6e2354012 100644 --- a/engine/classes/ElggDiskFilestore.php +++ b/engine/classes/ElggDiskFilestore.php @@ -194,7 +194,9 @@ class ElggDiskFilestore extends ElggFilestore {  	}  	/** -	 * Returns the filename as saved on disk for an ElggFile object +	 * Get the filename as saved on disk for an ElggFile object +	 * +	 * Returns an empty string if no filename set  	 *  	 * @param ElggFile $file File object  	 * @@ -213,7 +215,12 @@ class ElggDiskFilestore extends ElggFilestore {  			throw new InvalidParameterException($msg);  		} -		return $this->dir_root . $this->makefileMatrix($owner_guid) . $file->getFilename(); +		$filename = $file->getFilename(); +		if (!$filename) { +			return ''; +		} + +		return $this->dir_root . $this->makeFileMatrix($owner_guid) . $filename;  	}  	/** @@ -221,7 +228,7 @@ class ElggDiskFilestore extends ElggFilestore {  	 *  	 * @param ElggFile $file File object  	 * -	 * @return mixed +	 * @return string  	 */  	public function grabFile(ElggFile $file) {  		return file_get_contents($file->getFilenameOnFilestore()); @@ -235,6 +242,9 @@ class ElggDiskFilestore extends ElggFilestore {  	 * @return bool  	 */  	public function exists(ElggFile $file) { +		if (!$file->getFilename()) { +			return false; +		}  		return file_exists($this->getFilenameOnFilestore($file));  	} @@ -248,12 +258,13 @@ class ElggDiskFilestore extends ElggFilestore {  	 */  	public function getSize($prefix = '', $container_guid) {  		if ($container_guid) { -			return get_dir_size($this->dir_root . $this->makefileMatrix($container_guid) . $prefix); +			return get_dir_size($this->dir_root . $this->makeFileMatrix($container_guid) . $prefix);  		} else {  			return false;  		}  	} +	// @codingStandardsIgnoreStart  	/**  	 * Create a directory $dirroot  	 * @@ -268,6 +279,7 @@ class ElggDiskFilestore extends ElggFilestore {  		return $this->makeDirectoryRoot($dirroot);  	} +	// @codingStandardsIgnoreEnd  	/**  	 * Create a directory $dirroot @@ -287,6 +299,7 @@ class ElggDiskFilestore extends ElggFilestore {  		return true;  	} +	// @codingStandardsIgnoreStart  	/**  	 * Multibyte string tokeniser.  	 * @@ -318,7 +331,9 @@ class ElggDiskFilestore extends ElggFilestore {  			return str_split($string);  		}  	} +	// @codingStandardsIgnoreEnd +	// @codingStandardsIgnoreStart  	/**  	 * Construct a file path matrix for an entity.  	 * @@ -330,8 +345,9 @@ class ElggDiskFilestore extends ElggFilestore {  	protected function make_file_matrix($identifier) {  		elgg_deprecated_notice('ElggDiskFilestore::make_file_matrix() is deprecated by ::makeFileMatrix()', 1.8); -		return $this->makefileMatrix($identifier); +		return $this->makeFileMatrix($identifier);  	} +	// @codingStandardsIgnoreEnd  	/**  	 * Construct a file path matrix for an entity. @@ -352,6 +368,7 @@ class ElggDiskFilestore extends ElggFilestore {  		return "$time_created/$entity->guid/";  	} +	// @codingStandardsIgnoreStart  	/**  	 * Construct a filename matrix.  	 * @@ -370,6 +387,7 @@ class ElggDiskFilestore extends ElggFilestore {  		return $this->makeFileMatrix($guid);  	} +	// @codingStandardsIgnoreEnd  	/**  	 * Returns a list of attributes to save to the database when saving diff --git a/engine/classes/ElggEntity.php b/engine/classes/ElggEntity.php index f44e73023..a563f6fad 100644 --- a/engine/classes/ElggEntity.php +++ b/engine/classes/ElggEntity.php @@ -24,7 +24,7 @@   *   * @package    Elgg.Core   * @subpackage DataModel.Entities - *  + *   * @property string $type           object, user, group, or site (read-only after save)   * @property string $subtype        Further clarifies the nature of the entity (read-only after save)   * @property int    $guid           The unique identifier for this entity (read only) @@ -352,8 +352,8 @@ abstract class ElggEntity extends ElggData implements  					'limit' => 0  				);  				// @todo in 1.9 make this return false if can't add metadata -				// http://trac.elgg.org/ticket/4520 -				//  +				// https://github.com/elgg/elgg/issues/4520 +				//  				// need to remove access restrictions right now to delete  				// because this is the expected behavior  				$ia = elgg_set_ignore_access(true); @@ -375,12 +375,11 @@ abstract class ElggEntity extends ElggData implements  			}  			return $result; -		} - -		// unsaved entity. store in temp array -		// returning single entries instead of an array of 1 element is decided in -		// getMetaData(), just like pulling from the db. -		else { +		} else { +			// unsaved entity. store in temp array +			// returning single entries instead of an array of 1 element is decided in +			// getMetaData(), just like pulling from the db. +			//  			// if overwrite, delete first  			if (!$multiple || !isset($this->temp_metadata[$name])) {  				$this->temp_metadata[$name] = array(); @@ -965,7 +964,7 @@ abstract class ElggEntity extends ElggData implements  	 *  	 * @tip Can be overridden by registering for the permissions_check:comment,  	 * <entity type> plugin hook. -	 *  +	 *  	 * @param int $user_guid User guid (default is logged in user)  	 *  	 * @return bool @@ -1271,15 +1270,23 @@ abstract class ElggEntity extends ElggData implements  	public function save() {  		$guid = $this->getGUID();  		if ($guid > 0) { -			cache_entity($this); -			return update_entity( +			// See #5600. This ensures the lower level can_edit_entity() check will use a +			// fresh entity from the DB so it sees the persisted owner_guid +			_elgg_disable_caching_for_entity($guid); + +			$ret = update_entity(  				$guid,  				$this->get('owner_guid'),  				$this->get('access_id'),  				$this->get('container_guid'),  				$this->get('time_created')  			); + +			_elgg_enable_caching_for_entity($guid); +			_elgg_cache_entity($this); + +			return $ret;  		} else {  			// Create a new entity (nb: using attribute array directly  			// 'cos set function does something special!) @@ -1321,7 +1328,7 @@ abstract class ElggEntity extends ElggData implements  			$this->attributes['subtype'] = get_subtype_id($this->attributes['type'],  				$this->attributes['subtype']); -			cache_entity($this); +			_elgg_cache_entity($this);  			return $this->attributes['guid'];  		} @@ -1358,12 +1365,12 @@ abstract class ElggEntity extends ElggData implements  				$this->attributes['tables_loaded']++;  			} -			// guid needs to be an int  http://trac.elgg.org/ticket/4111 +			// guid needs to be an int  https://github.com/elgg/elgg/issues/4111  			$this->attributes['guid'] = (int)$this->attributes['guid'];  			// Cache object handle  			if ($this->attributes['guid']) { -				cache_entity($this); +				_elgg_cache_entity($this);  			}  			return true; diff --git a/engine/classes/ElggFile.php b/engine/classes/ElggFile.php index 3e9c24c17..23080834b 100644 --- a/engine/classes/ElggFile.php +++ b/engine/classes/ElggFile.php @@ -275,9 +275,14 @@ class ElggFile extends ElggObject {  	 */  	public function delete() {  		$fs = $this->getFilestore(); -		if ($fs->delete($this)) { -			return parent::delete(); +		 +		$result = $fs->delete($this); +		 +		if ($this->getGUID() && $result) { +			$result = parent::delete();  		} +		 +		return $result;  	}  	/** diff --git a/engine/classes/ElggFileCache.php b/engine/classes/ElggFileCache.php index e654f1db2..94143f777 100644 --- a/engine/classes/ElggFileCache.php +++ b/engine/classes/ElggFileCache.php @@ -26,6 +26,7 @@ class ElggFileCache extends ElggCache {  		}  	} +	// @codingStandardsIgnoreStart  	/**  	 * Create and return a handle to a file.  	 * @@ -41,6 +42,7 @@ class ElggFileCache extends ElggCache {  		return $this->createFile($filename, $rw);  	} +	// @codingStandardsIgnoreEnd  	/**  	 * Create and return a handle to a file. @@ -72,6 +74,7 @@ class ElggFileCache extends ElggCache {  		return fopen($path . $filename, $rw);  	} +	// @codingStandardsIgnoreStart  	/**  	 * Create a sanitised filename for the file.  	 * @@ -86,6 +89,7 @@ class ElggFileCache extends ElggCache {  		return $filename;  	} +	// @codingStandardsIgnoreEnd  	/**  	 * Create a sanitised filename for the file. diff --git a/engine/classes/ElggGroup.php b/engine/classes/ElggGroup.php index 61f699f1a..7e69b7a84 100644 --- a/engine/classes/ElggGroup.php +++ b/engine/classes/ElggGroup.php @@ -48,21 +48,18 @@ class ElggGroup extends ElggEntity  					$msg = elgg_echo('IOException:FailedToLoadGUID', array(get_class(), $guid->guid));  					throw new IOException($msg);  				} - -			// Is $guid is an ElggGroup? Use a copy constructor  			} else if ($guid instanceof ElggGroup) { +				// $guid is an ElggGroup so this is a copy constructor  				elgg_deprecated_notice('This type of usage of the ElggGroup constructor was deprecated. Please use the clone method.', 1.7);  				foreach ($guid->attributes as $key => $value) {  					$this->attributes[$key] = $value;  				} - -			// Is this is an ElggEntity but not an ElggGroup = ERROR!  			} else if ($guid instanceof ElggEntity) { +				// @todo why separate from else  				throw new InvalidParameterException(elgg_echo('InvalidParameterException:NonElggGroup')); - -			// Is it a GUID  			} else if (is_numeric($guid)) { +				// $guid is a GUID so load entity  				if (!$this->load($guid)) {  					throw new IOException(elgg_echo('IOException:FailedToLoadGUID', array(get_class(), $guid)));  				} @@ -338,7 +335,7 @@ class ElggGroup extends ElggEntity  		$this->attributes = $attrs;  		$this->attributes['tables_loaded'] = 2; -		cache_entity($this); +		_elgg_cache_entity($this);  		return true;  	} @@ -355,7 +352,12 @@ class ElggGroup extends ElggEntity  		}  		// Now save specific stuff -		return create_group_entity($this->get('guid'), $this->get('name'), $this->get('description')); + +		_elgg_disable_caching_for_entity($this->guid); +		$ret = create_group_entity($this->get('guid'), $this->get('name'), $this->get('description')); +		_elgg_enable_caching_for_entity($this->guid); + +		return $ret;  	}  	// EXPORTABLE INTERFACE //////////////////////////////////////////////////////////// diff --git a/engine/classes/ElggLRUCache.php b/engine/classes/ElggLRUCache.php new file mode 100644 index 000000000..f51af2ed7 --- /dev/null +++ b/engine/classes/ElggLRUCache.php @@ -0,0 +1,181 @@ +<?php + +/** + * Least Recently Used Cache + * + * A fixed sized cache that removes the element used last when it reaches its + * size limit. + *  + * Based on https://github.com/cash/LRUCache + *  + * @access private + *  + * @package    Elgg.Core + * @subpackage Cache + */ +class ElggLRUCache implements ArrayAccess { +	/** @var int */ +	protected $maximumSize; + +	/** +	 * The front of the array contains the LRU element +	 * +	 * @var array +	 */ +	protected $data = array(); + +	/** +	 * Create a LRU Cache +	 * +	 * @param int $size The size of the cache +	 * @throws InvalidArgumentException +	 */ +	public function __construct($size) { +		if (!is_int($size) || $size <= 0) { +			throw new InvalidArgumentException(); +		} +		$this->maximumSize = $size; +	} + +	/** +	 * Get the value cached with this key +	 * +	 * @param int|string $key     The key. Strings that are ints are cast to ints. +	 * @param mixed      $default The value to be returned if key not found. (Optional) +	 * @return mixed +	 */ +	public function get($key, $default = null) { +		if (isset($this->data[$key])) { +			$this->recordAccess($key); +			return $this->data[$key]; +		} else { +			return $default; +		} +	} + +	/** +	 * Add something to the cache +	 * +	 * @param int|string $key   The key. Strings that are ints are cast to ints. +	 * @param mixed      $value The value to cache +	 * @return void +	 */ +	public function set($key, $value) { +		if (isset($this->data[$key])) { +			$this->data[$key] = $value; +			$this->recordAccess($key); +		} else { +			$this->data[$key] = $value; +			if ($this->size() > $this->maximumSize) { +				// remove least recently used element (front of array) +				reset($this->data); +				unset($this->data[key($this->data)]); +			} +		} +	} + +	/** +	 * Get the number of elements in the cache +	 * +	 * @return int +	 */ +	public function size() { +		return count($this->data); +	} + +	/** +	 * Does the cache contain an element with this key +	 * +	 * @param int|string $key The key +	 * @return boolean +	 */ +	public function containsKey($key) { +		return isset($this->data[$key]); +	} + +	/** +	 * Remove the element with this key. +	 * +	 * @param int|string $key The key +	 * @return mixed Value or null if not set +	 */ +	public function remove($key) { +		if (isset($this->data[$key])) { +			$value = $this->data[$key]; +			unset($this->data[$key]); +			return $value; +		} else { +			return null; +		} +	} + +	/** +	 * Clear the cache +	 *  +	 * @return void +	 */ +	public function clear() { +		$this->data = array(); +	} + +	/** +	 * Moves the element from current position to end of array +	 *  +	 * @param int|string $key The key +	 * @return void +	 */ +	protected function recordAccess($key) { +		$value = $this->data[$key]; +		unset($this->data[$key]); +		$this->data[$key] = $value; +	} + +	/** +	 * Assigns a value for the specified key +	 * +	 * @see ArrayAccess::offsetSet() +	 * +	 * @param int|string $key   The key to assign the value to. +	 * @param mixed      $value The value to set. +	 * @return void +	 */ +	public function offsetSet($key, $value) { +		$this->set($key, $value); +	} + +	/** +	 * Get the value for specified key +	 * +	 * @see ArrayAccess::offsetGet() +	 * +	 * @param int|string $key The key to retrieve. +	 * @return mixed +	 */ +	public function offsetGet($key) { +		return $this->get($key); +	} + +	/** +	 * Unsets a key. +	 * +	 * @see ArrayAccess::offsetUnset() +	 * +	 * @param int|string $key The key to unset. +	 * @return void +	 */ +	public function offsetUnset($key) { +		$this->remove($key); +	} + +	/** +	 * Does key exist? +	 * +	 * @see ArrayAccess::offsetExists() +	 * +	 * @param int|string $key A key to check for. +	 * @return boolean +	 */ +	public function offsetExists($key) { +		return $this->containsKey($key); +	} +} diff --git a/engine/classes/ElggMenuBuilder.php b/engine/classes/ElggMenuBuilder.php index f6ec9dcd3..b463143d8 100644 --- a/engine/classes/ElggMenuBuilder.php +++ b/engine/classes/ElggMenuBuilder.php @@ -128,8 +128,10 @@ class ElggMenuBuilder {  					$parent_name = $menu_item->getParentName();  					if (array_key_exists($parent_name, $current_gen)) {  						$next_gen[$menu_item->getName()] = $menu_item; -						$current_gen[$parent_name]->addChild($menu_item); -						$menu_item->setParent($current_gen[$parent_name]); +						if (!in_array($menu_item, $current_gen[$parent_name]->getData('children'))) { +							$current_gen[$parent_name]->addChild($menu_item); +							$menu_item->setParent($current_gen[$parent_name]); +						}  						unset($children[$index]);  					}  				} @@ -235,8 +237,8 @@ class ElggMenuBuilder {  	/**  	 * Compare two menu items by their display text  	 * -	 * @param ElggMenuItem $a -	 * @param ElggMenuItem $b +	 * @param ElggMenuItem $a Menu item +	 * @param ElggMenuItem $b Menu item  	 * @return bool  	 */  	public static function compareByText($a, $b) { @@ -253,8 +255,8 @@ class ElggMenuBuilder {  	/**  	 * Compare two menu items by their identifiers  	 * -	 * @param ElggMenuItem $a -	 * @param ElggMenuItem $b +	 * @param ElggMenuItem $a Menu item +	 * @param ElggMenuItem $b Menu item  	 * @return bool  	 */  	public static function compareByName($a, $b) { @@ -271,8 +273,8 @@ class ElggMenuBuilder {  	/**  	 * Compare two menu items by their priority  	 * -	 * @param ElggMenuItem $a -	 * @param ElggMenuItem $b +	 * @param ElggMenuItem $a Menu item +	 * @param ElggMenuItem $b Menu item  	 * @return bool  	 *  	 * @todo change name to compareByPriority diff --git a/engine/classes/ElggObject.php b/engine/classes/ElggObject.php index 6263f84f6..aeaa3ba5c 100644 --- a/engine/classes/ElggObject.php +++ b/engine/classes/ElggObject.php @@ -66,21 +66,18 @@ class ElggObject extends ElggEntity {  					$msg = elgg_echo('IOException:FailedToLoadGUID', array(get_class(), $guid->guid));  					throw new IOException($msg);  				} - -			// Is $guid is an ElggObject? Use a copy constructor  			} else if ($guid instanceof ElggObject) { +				// $guid is an ElggObject so this is a copy constructor  				elgg_deprecated_notice('This type of usage of the ElggObject constructor was deprecated. Please use the clone method.', 1.7);  				foreach ($guid->attributes as $key => $value) {  					$this->attributes[$key] = $value;  				} - -			// Is this is an ElggEntity but not an ElggObject = ERROR!  			} else if ($guid instanceof ElggEntity) { +				// @todo remove - do not need separate exception  				throw new InvalidParameterException(elgg_echo('InvalidParameterException:NonElggObject')); - -			// Is it a GUID  			} else if (is_numeric($guid)) { +				// $guid is a GUID so load  				if (!$this->load($guid)) {  					throw new IOException(elgg_echo('IOException:FailedToLoadGUID', array(get_class(), $guid)));  				} @@ -110,7 +107,7 @@ class ElggObject extends ElggEntity {  		$this->attributes = $attrs;  		$this->attributes['tables_loaded'] = 2; -		cache_entity($this); +		_elgg_cache_entity($this);  		return true;  	} @@ -129,8 +126,12 @@ class ElggObject extends ElggEntity {  		}  		// Save ElggObject-specific attributes -		return create_object_entity($this->get('guid'), $this->get('title'), -			$this->get('description')); + +		_elgg_disable_caching_for_entity($this->guid); +		$ret = create_object_entity($this->get('guid'), $this->get('title'), $this->get('description')); +		_elgg_enable_caching_for_entity($this->guid); + +		return $ret;  	}  	/** diff --git a/engine/classes/ElggPlugin.php b/engine/classes/ElggPlugin.php index ae447bddb..545b9a53c 100644 --- a/engine/classes/ElggPlugin.php +++ b/engine/classes/ElggPlugin.php @@ -299,17 +299,15 @@ class ElggPlugin extends ElggObject {  		$private_settings = get_data($q); -		if ($private_settings) { -			$return = array(); +		$return = array(); +		if ($private_settings) {  			foreach ($private_settings as $setting) {  				$return[$setting->name] = $setting->value;  			} - -			return $return;  		} -		return false; +		return $return;  	}  	/** @@ -350,11 +348,14 @@ class ElggPlugin extends ElggObject {  	 */  	public function unsetAllSettings() {  		$db_prefix = get_config('dbprefix'); -		$ps_prefix = elgg_namespace_plugin_private_setting('setting', ''); + +		$us_prefix = elgg_namespace_plugin_private_setting('user_setting', '', $this->getID()); +		$is_prefix = elgg_namespace_plugin_private_setting('internal', '', $this->getID());  		$q = "DELETE FROM {$db_prefix}private_settings  			WHERE entity_guid = $this->guid -			AND name NOT LIKE '$ps_prefix%'"; +			AND name NOT LIKE '$us_prefix%' +			AND name NOT LIKE '$is_prefix%'";  		return delete_data($q);  	} @@ -420,20 +421,18 @@ class ElggPlugin extends ElggObject {  		$private_settings = get_data($q); -		if ($private_settings) { -			$return = array(); +		$return = array(); +		if ($private_settings) {  			foreach ($private_settings as $setting) {  				$name = substr($setting->name, $ps_prefix_len);  				$value = $setting->value;  				$return[$name] = $value;  			} - -			return $return;  		} -		return false; +		return $return;  	}  	/** @@ -546,7 +545,7 @@ class ElggPlugin extends ElggObject {  	 * Returns if the plugin is complete, meaning has all required files  	 * and Elgg can read them and they make sense.  	 * -	 * @todo bad name? This could be confused with isValid() from ElggPackage. +	 * @todo bad name? This could be confused with isValid() from ElggPluginPackage.  	 *  	 * @return bool  	 */ @@ -649,8 +648,8 @@ class ElggPlugin extends ElggObject {  			// Note: this will not run re-run the init hooks!  			if ($return) {  				if ($this->canReadFile('activate.php')) { -					$flags = ELGG_PLUGIN_INCLUDE_START | ELGG_PLUGIN_REGISTER_CLASSES -							| ELGG_PLUGIN_REGISTER_LANGUAGES | ELGG_PLUGIN_REGISTER_VIEWS; +					$flags = ELGG_PLUGIN_INCLUDE_START | ELGG_PLUGIN_REGISTER_CLASSES | +							ELGG_PLUGIN_REGISTER_LANGUAGES | ELGG_PLUGIN_REGISTER_VIEWS;  					$this->start($flags); diff --git a/engine/classes/ElggPluginPackage.php b/engine/classes/ElggPluginPackage.php index 209242288..37eb4bf4d 100644 --- a/engine/classes/ElggPluginPackage.php +++ b/engine/classes/ElggPluginPackage.php @@ -294,6 +294,7 @@ class ElggPluginPackage {  			return true;  		} +		$this->errorMsg = elgg_echo('unknown_error');  		return false;  	} diff --git a/engine/classes/ElggPriorityList.php b/engine/classes/ElggPriorityList.php index b5f8fe163..416df885c 100644 --- a/engine/classes/ElggPriorityList.php +++ b/engine/classes/ElggPriorityList.php @@ -165,9 +165,9 @@ class ElggPriorityList  	/**  	 * Move an existing element to a new priority.  	 * -	 * @param mixed  $element      The element to move -	 * @param int    $new_priority The new priority for the element -	 * @param bool   $strict       Whether to check the type of the element match +	 * @param mixed $element      The element to move +	 * @param int   $new_priority The new priority for the element +	 * @param bool  $strict       Whether to check the type of the element match  	 * @return bool  	 */  	public function move($element, $new_priority, $strict = false) { @@ -354,7 +354,12 @@ class ElggPriorityList  		return ($key !== NULL && $key !== FALSE);  	} -	// Countable +	/** +	 * Countable interface +	 * +	 * @see Countable::count() +	 * @return int +	 */  	public function count() {  		return count($this->elements);  	} diff --git a/engine/classes/ElggSite.php b/engine/classes/ElggSite.php index 1a34df195..dd996fe98 100644 --- a/engine/classes/ElggSite.php +++ b/engine/classes/ElggSite.php @@ -77,28 +77,24 @@ class ElggSite extends ElggEntity {  					$msg = elgg_echo('IOException:FailedToLoadGUID', array(get_class(), $guid->guid));  					throw new IOException($msg);  				} - -			// Is $guid is an ElggSite? Use a copy constructor  			} else if ($guid instanceof ElggSite) { +				// $guid is an ElggSite so this is a copy constructor  				elgg_deprecated_notice('This type of usage of the ElggSite constructor was deprecated. Please use the clone method.', 1.7);  				foreach ($guid->attributes as $key => $value) {  					$this->attributes[$key] = $value;  				} - -			// Is this is an ElggEntity but not an ElggSite = ERROR!  			} else if ($guid instanceof ElggEntity) { +				// @todo remove and just use else clause  				throw new InvalidParameterException(elgg_echo('InvalidParameterException:NonElggSite')); - -			// See if this is a URL  			} else if (strpos($guid, "http") !== false) { +				// url so retrieve by url  				$guid = get_site_by_url($guid);  				foreach ($guid->attributes as $key => $value) {  					$this->attributes[$key] = $value;  				} - -			// Is it a GUID  			} else if (is_numeric($guid)) { +				// $guid is a GUID so load  				if (!$this->load($guid)) {  					throw new IOException(elgg_echo('IOException:FailedToLoadGUID', array(get_class(), $guid)));  				} @@ -128,7 +124,7 @@ class ElggSite extends ElggEntity {  		$this->attributes = $attrs;  		$this->attributes['tables_loaded'] = 2; -		cache_entity($this); +		_elgg_cache_entity($this);  		return true;  	} diff --git a/engine/classes/ElggStaticVariableCache.php b/engine/classes/ElggStaticVariableCache.php index 17d849400..9c14fdfba 100644 --- a/engine/classes/ElggStaticVariableCache.php +++ b/engine/classes/ElggStaticVariableCache.php @@ -11,7 +11,7 @@ class ElggStaticVariableCache extends ElggSharedMemoryCache {  	/**  	 * The cache.  	 * -	 * @var unknown_type +	 * @var array  	 */  	private static $__cache; @@ -22,7 +22,7 @@ class ElggStaticVariableCache extends ElggSharedMemoryCache {  	 * memory, optionally with a given namespace (to avoid overlap).  	 *  	 * @param string $namespace The namespace for this cache to write to. -	 * @note namespaces of the same name are shared! +	 * @warning namespaces of the same name are shared!  	 */  	function __construct($namespace = 'default') {  		$this->setNamespace($namespace); @@ -80,7 +80,7 @@ class ElggStaticVariableCache extends ElggSharedMemoryCache {  	}  	/** -	 * This was probably meant to delete everything? +	 * Clears the cache for a particular namespace  	 *  	 * @return void  	 */ diff --git a/engine/classes/ElggTranslit.php b/engine/classes/ElggTranslit.php index 676c59fc8..b4bf87797 100644 --- a/engine/classes/ElggTranslit.php +++ b/engine/classes/ElggTranslit.php @@ -20,11 +20,10 @@   * and is licensed under the LGPL. For more information, see   * <http://www.doctrine-project.org>.   * - * @author      Konsta Vesterinen <kvesteri@cc.hut.fi> - * @author      Jonathan H. Wage <jonwage@gmail.com> - * - * @author      Steve Clay <steve@mrclay.org> - * @package     Elgg.Core + * @package Elgg.Core + * @author  Konsta Vesterinen <kvesteri@cc.hut.fi> + * @author  Jonathan H. Wage <jonwage@gmail.com> + * @author  Steve Clay <steve@mrclay.org>   *   * @access private Plugin authors should not use this directly   */ @@ -32,8 +31,9 @@ class ElggTranslit {  	/**  	 * Create a version of a string for embedding in a URL -	 * @param string $string a UTF-8 string -	 * @param string $separator +	 * +	 * @param string $string    A UTF-8 string +	 * @param string $separator The character to separate words with  	 * @return string  	 */  	static public function urlize($string, $separator = '-') { @@ -49,24 +49,29 @@ class ElggTranslit {  		// Internationalization, AND 日本語!  		$string = self::transliterateAscii($string); -		// more translation +		// allow HTML tags in titles +		$string = preg_replace('~<([a-zA-Z][^>]*)>~', ' $1 ', $string); + +		// more substitutions +		// @todo put these somewhere else  		$string = strtr($string, array( -			// Euro/GBP -			"\xE2\x82\xAC" /* € */ => 'E', "\xC2\xA3" /* £ */ => 'GBP', +			// currency +			"\xE2\x82\xAC" /* € */ => ' E ', +			"\xC2\xA3" /* £ */ => ' GBP ',  		));  		// remove all ASCII except 0-9a-zA-Z, hyphen, underscore, and whitespace  		// note: "x" modifier did not work with this pattern.  		$string = preg_replace('~[' -			. '\x00-\x08'  # control chars -			. '\x0b\x0c'   # vert tab, form feed -			. '\x0e-\x1f'  # control chars -			. '\x21-\x2c'  # ! ... , -			. '\x2e\x2f'   # . slash -			. '\x3a-\x40'  # : ... @ -			. '\x5b-\x5e'  # [ ... ^ -			. '\x60'       # ` -			. '\x7b-\x7f'  # { ... DEL +			. '\x00-\x08'  // control chars +			. '\x0b\x0c'   // vert tab, form feed +			. '\x0e-\x1f'  // control chars +			. '\x21-\x2c'  // ! ... , +			. '\x2e\x2f'   // . slash +			. '\x3a-\x40'  // : ... @ +			. '\x5b-\x5e'  // [ ... ^ +			. '\x60'       // ` +			. '\x7b-\x7f'  // { ... DEL  			. ']~', '', $string);  		$string = strtr($string, '', ''); @@ -80,10 +85,10 @@ class ElggTranslit {  		// note: we cannot use [^0-9a-zA-Z] because that matches multibyte chars.  		// note: "x" modifier did not work with this pattern.  		$pattern = '~[' -			. '\x00-\x2f'  # controls ... slash -			. '\x3a-\x40'  # : ... @ -			. '\x5b-\x60'  # [ ... ` -			. '\x7b-\x7f'  # { ... DEL +			. '\x00-\x2f'  // controls ... slash +			. '\x3a-\x40'  // : ... @ +			. '\x5b-\x60'  // [ ... ` +			. '\x7b-\x7f'  // { ... DEL  			. ']+~x';  		// ['internationalization', 'and', '日本語'] @@ -98,6 +103,7 @@ class ElggTranslit {  	/**  	 * Transliterate Western multibyte chars to ASCII +	 *  	 * @param string $utf8 a UTF-8 string  	 * @return string  	 */ @@ -247,6 +253,7 @@ class ElggTranslit {  	/**  	 * Tests that "normalizer_normalize" exists and works +	 *  	 * @return bool  	 */  	static public function hasNormalizerSupport() { @@ -255,7 +262,7 @@ class ElggTranslit {  			$form_c = "\xC3\x85"; // 'LATIN CAPITAL LETTER A WITH RING ABOVE' (U+00C5)  			$form_d = "A\xCC\x8A"; // A followed by 'COMBINING RING ABOVE' (U+030A)  			$ret = (function_exists('normalizer_normalize') -				    && $form_c === normalizer_normalize($form_d)); +				&& $form_c === normalizer_normalize($form_d));  		}  		return $ret;  	} diff --git a/engine/classes/ElggUser.php b/engine/classes/ElggUser.php index 6c1cdc1de..6163f9b62 100644 --- a/engine/classes/ElggUser.php +++ b/engine/classes/ElggUser.php @@ -40,6 +40,9 @@ class ElggUser extends ElggEntity  		$this->attributes['code'] = NULL;  		$this->attributes['banned'] = "no";  		$this->attributes['admin'] = 'no'; +		$this->attributes['prev_last_action'] = NULL; +		$this->attributes['last_login'] = NULL; +		$this->attributes['prev_last_login'] = NULL;  		$this->attributes['tables_split'] = 2;  	} @@ -65,30 +68,26 @@ class ElggUser extends ElggEntity  					$msg = elgg_echo('IOException:FailedToLoadGUID', array(get_class(), $guid->guid));  					throw new IOException($msg);  				} - -			// See if this is a username  			} else if (is_string($guid)) { +				// $guid is a username  				$user = get_user_by_username($guid);  				if ($user) {  					foreach ($user->attributes as $key => $value) {  						$this->attributes[$key] = $value;  					}  				} - -			// Is $guid is an ElggUser? Use a copy constructor  			} else if ($guid instanceof ElggUser) { +				// $guid is an ElggUser so this is a copy constructor  				elgg_deprecated_notice('This type of usage of the ElggUser constructor was deprecated. Please use the clone method.', 1.7);  				foreach ($guid->attributes as $key => $value) {  					$this->attributes[$key] = $value;  				} - -			// Is this is an ElggEntity but not an ElggUser = ERROR!  			} else if ($guid instanceof ElggEntity) { +				// @todo why have a special case here  				throw new InvalidParameterException(elgg_echo('InvalidParameterException:NonElggUser')); - -			// Is it a GUID  			} else if (is_numeric($guid)) { +				// $guid is a GUID so load entity  				if (!$this->load($guid)) {  					throw new IOException(elgg_echo('IOException:FailedToLoadGUID', array(get_class(), $guid)));  				} @@ -116,7 +115,7 @@ class ElggUser extends ElggEntity  		$this->attributes = $attrs;  		$this->attributes['tables_loaded'] = 2; -		cache_entity($this); +		_elgg_cache_entity($this);  		return true;  	} @@ -133,9 +132,13 @@ class ElggUser extends ElggEntity  		}  		// Now save specific stuff -		return create_user_entity($this->get('guid'), $this->get('name'), $this->get('username'), +		_elgg_disable_caching_for_entity($this->guid); +		$ret = create_user_entity($this->get('guid'), $this->get('name'), $this->get('username'),  			$this->get('password'), $this->get('salt'), $this->get('email'), $this->get('language'),  			$this->get('code')); +		_elgg_enable_caching_for_entity($this->guid); + +		return $ret;  	}  	/** diff --git a/engine/classes/ElggVolatileMetadataCache.php b/engine/classes/ElggVolatileMetadataCache.php index 8a33c198d..4acda7cee 100644 --- a/engine/classes/ElggVolatileMetadataCache.php +++ b/engine/classes/ElggVolatileMetadataCache.php @@ -33,9 +33,11 @@ class ElggVolatileMetadataCache {  	protected $ignoreAccess = null;  	/** -	 * @param int $entity_guid -	 * -	 * @param array $values +	 * Cache metadata for an entity +	 *  +	 * @param int   $entity_guid The GUID of the entity +	 * @param array $values      The metadata values to cache +	 * @return void  	 */  	public function saveAll($entity_guid, array $values) {  		if (!$this->getIgnoreAccess()) { @@ -45,8 +47,9 @@ class ElggVolatileMetadataCache {  	}  	/** -	 * @param int $entity_guid -	 * +	 * Get the metadata for an entity +	 *  +	 * @param int $entity_guid The GUID of the entity  	 * @return array  	 */  	public function loadAll($entity_guid) { @@ -61,15 +64,17 @@ class ElggVolatileMetadataCache {  	 * Declare that there may be fetch-able metadata names in storage that this  	 * cache doesn't know about  	 * -	 * @param int $entity_guid +	 * @param int $entity_guid The GUID of the entity +	 * @return void  	 */  	public function markOutOfSync($entity_guid) {  		unset($this->isSynchronized[$entity_guid]);  	}  	/** -	 * @param $entity_guid -	 * +	 * Have all the metadata for this entity been cached? +	 *  +	 * @param int $entity_guid The GUID of the entity  	 * @return bool  	 */  	public function isSynchronized($entity_guid) { @@ -77,13 +82,15 @@ class ElggVolatileMetadataCache {  	}  	/** -	 * @param int $entity_guid -	 * -	 * @param string $name -	 * -	 * @param array|int|string|null $value  null means it is known that there is no -	 *                                      fetch-able metadata under this name -	 * @param bool $allow_multiple +	 * Cache a piece of metadata +	 *  +	 * @param int                   $entity_guid    The GUID of the entity +	 * @param string                $name           The metadata name +	 * @param array|int|string|null $value          The metadata value. null means it is  +	 *                                              known that there is no fetch-able  +	 *                                              metadata under this name +	 * @param bool                  $allow_multiple Can the metadata be an array +	 * @return void  	 */  	public function save($entity_guid, $name, $value, $allow_multiple = false) {  		if ($this->getIgnoreAccess()) { @@ -115,10 +122,8 @@ class ElggVolatileMetadataCache {  	 * function's return value should be trusted (otherwise a null return value  	 * is ambiguous).  	 * -	 * @param int $entity_guid -	 * -	 * @param string $name -	 * +	 * @param int    $entity_guid The GUID of the entity +	 * @param string $name        The metadata name  	 * @return array|string|int|null null = value does not exist  	 */  	public function load($entity_guid, $name) { @@ -133,9 +138,9 @@ class ElggVolatileMetadataCache {  	 * Forget about this metadata entry. We don't want to try to guess what the  	 * next fetch from storage will return  	 * -	 * @param int $entity_guid -	 * -	 * @param string $name +	 * @param int    $entity_guid The GUID of the entity +	 * @param string $name        The metadata name +	 * @return void  	 */  	public function markUnknown($entity_guid, $name) {  		unset($this->values[$entity_guid][$name]); @@ -145,10 +150,8 @@ class ElggVolatileMetadataCache {  	/**  	 * If true, load() will return an accurate value for this name  	 * -	 * @param int $entity_guid -	 * -	 * @param string $name -	 * +	 * @param int    $entity_guid The GUID of the entity +	 * @param string $name        The metadata name  	 * @return bool  	 */  	public function isKnown($entity_guid, $name) { @@ -163,10 +166,8 @@ class ElggVolatileMetadataCache {  	/**  	 * Declare that metadata under this name is known to be not fetch-able from storage  	 * -	 * @param int $entity_guid -	 * -	 * @param string $name -	 * +	 * @param int    $entity_guid The GUID of the entity +	 * @param string $name        The metadata name  	 * @return array  	 */  	public function markEmpty($entity_guid, $name) { @@ -176,7 +177,8 @@ class ElggVolatileMetadataCache {  	/**  	 * Forget about all metadata for an entity  	 * -	 * @param int $entity_guid +	 * @param int $entity_guid The GUID of the entity +	 * @return void  	 */  	public function clear($entity_guid) {  		$this->values[$entity_guid] = array(); @@ -185,6 +187,8 @@ class ElggVolatileMetadataCache {  	/**  	 * Clear entire cache and mark all entities as out of sync +	 *  +	 * @return void  	 */  	public function flush() {  		$this->values = array(); @@ -197,7 +201,8 @@ class ElggVolatileMetadataCache {  	 *  	 * This setting makes this component a little more loosely-coupled.  	 * -	 * @param bool $ignore +	 * @param bool $ignore Whether to ignore access or not +	 * @return void  	 */  	public function setIgnoreAccess($ignore) {  		$this->ignoreAccess = (bool) $ignore; @@ -205,12 +210,16 @@ class ElggVolatileMetadataCache {  	/**  	 * Tell the cache to call elgg_get_ignore_access() to determing access status. +	 *  +	 * @return void  	 */  	public function unsetIgnoreAccess() {  		$this->ignoreAccess = null;  	}  	/** +	 * Get the ignore access value +	 *   	 * @return bool  	 */  	protected function getIgnoreAccess() { @@ -225,12 +234,10 @@ class ElggVolatileMetadataCache {  	 * Invalidate based on options passed to the global *_metadata functions  	 *  	 * @param string $action  Action performed on metadata. "delete", "disable", or "enable" -	 * -	 * @param array $options  Options passed to elgg_(delete|disable|enable)_metadata -	 * -	 *   "guid" if given, invalidation will be limited to this entity -	 * -	 *   "metadata_name" if given, invalidation will be limited to metadata with this name +	 * @param array  $options Options passed to elgg_(delete|disable|enable)_metadata +	 *                         "guid" if given, invalidation will be limited to this entity +	 *                         "metadata_name" if given, invalidation will be limited to metadata with this name +	 * @return void  	 */  	public function invalidateByOptions($action, array $options) {  		// remove as little as possible, optimizing for common cases @@ -254,7 +261,10 @@ class ElggVolatileMetadataCache {  	}  	/** -	 * @param int|array $guids +	 * Populate the cache from a set of entities +	 *  +	 * @param int|array $guids Array of or single GUIDs +	 * @return void  	 */  	public function populateFromEntities($guids) {  		if (empty($guids)) { @@ -318,9 +328,7 @@ class ElggVolatileMetadataCache {  	 * cache if RAM usage becomes an issue.  	 *  	 * @param array $guids GUIDs of entities to examine -	 * -	 * @param int $limit Limit in characters of all metadata (with ints casted to strings) -	 * +	 * @param int   $limit Limit in characters of all metadata (with ints casted to strings)  	 * @return array  	 */  	public function filterMetadataHeavyEntities(array $guids, $limit = 1024000) { diff --git a/engine/classes/ElggWidget.php b/engine/classes/ElggWidget.php index c123e5032..66191bf47 100644 --- a/engine/classes/ElggWidget.php +++ b/engine/classes/ElggWidget.php @@ -146,10 +146,15 @@ class ElggWidget extends ElggObject {  			}  		} +		$bottom_rank = count($widgets); +		if ($column == $this->column) { +			$bottom_rank--; +		} +		  		if ($rank == 0) {  			// top of the column  			$this->order = reset($widgets)->order - 10; -		} elseif ($rank == (count($widgets) - 1)) { +		} elseif ($rank == $bottom_rank) {  			// bottom of the column of active widgets  			$this->order = end($widgets)->order + 10;  		} else { diff --git a/engine/classes/ElggXMLElement.php b/engine/classes/ElggXMLElement.php index 4e4b7e63c..cbd3fc5ce 100644 --- a/engine/classes/ElggXMLElement.php +++ b/engine/classes/ElggXMLElement.php @@ -20,7 +20,12 @@ class ElggXMLElement {  		if ($xml instanceof SimpleXMLElement) {  			$this->_element = $xml;  		} else { +			// do not load entities +			$disable_load_entities = libxml_disable_entity_loader(true); +  			$this->_element = new SimpleXMLElement($xml); + +			libxml_disable_entity_loader($disable_load_entities);  		}  	} @@ -76,6 +81,12 @@ class ElggXMLElement {  		return $result;  	} +	/** +	 * Override -> +	 *  +	 * @param string $name Property name +	 * @return mixed +	 */  	function __get($name) {  		switch ($name) {  			case 'name': @@ -94,6 +105,12 @@ class ElggXMLElement {  		return null;  	} +	/** +	 * Override isset +	 *  +	 * @param string $name Property name +	 * @return boolean +	 */  	function __isset($name) {  		switch ($name) {  			case 'name': @@ -111,5 +128,4 @@ class ElggXMLElement {  		}  		return false;  	} - -}
\ No newline at end of file +} diff --git a/engine/handlers/cache_handler.php b/engine/handlers/cache_handler.php index 9848d3531..36fc665bb 100644 --- a/engine/handlers/cache_handler.php +++ b/engine/handlers/cache_handler.php @@ -88,20 +88,18 @@ header("ETag: \"$etag\"");  $filename = $dataroot . 'views_simplecache/' . md5($viewtype . $view);  if (file_exists($filename)) { -	$contents = file_get_contents($filename); +	readfile($filename);  } else {  	// someone trying to access a non-cached file or a race condition with cache flushing  	mysql_close($mysql_dblink);  	require_once(dirname(dirname(__FILE__)) . "/start.php");  	global $CONFIG; -	if (!isset($CONFIG->views->simplecache[$view])) { +	if (!in_array($view, $CONFIG->views->simplecache)) {  		header("HTTP/1.1 404 Not Found");  		exit;  	}  	elgg_set_viewtype($viewtype); -	$contents = elgg_view($view); +	echo elgg_view($view);  } - -echo $contents; diff --git a/engine/lib/actions.php b/engine/lib/actions.php index f78ca63df..8047914ac 100644 --- a/engine/lib/actions.php +++ b/engine/lib/actions.php @@ -74,8 +74,7 @@ function action($action, $forwarder = "") {  	);  	if (!in_array($action, $exceptions)) { -		// All actions require a token. -		action_gatekeeper(); +		action_gatekeeper($action);  	}  	$forwarder = str_replace(elgg_get_site_url(), "", $forwarder); @@ -188,6 +187,26 @@ function elgg_unregister_action($action) {  }  /** + * Is the token timestamp within acceptable range? + *  + * @param int $ts timestamp from the CSRF token + *  + * @return bool + */ +function _elgg_validate_token_timestamp($ts) { +	$action_token_timeout = elgg_get_config('action_token_timeout'); +	// default is 2 hours +	$timeout = ($action_token_timeout !== null) ? $action_token_timeout : 2; + +	$hour = 60 * 60; +	$timeout = $timeout * $hour; +	$now = time(); + +	// Validate time to ensure its not crazy +	return ($timeout == 0 || ($ts > $now - $timeout) && ($ts < $now + $timeout)); +} + +/**   * Validate an action token.   *   * Calls to actions will automatically validate tokens. If tokens are not @@ -205,8 +224,6 @@ function elgg_unregister_action($action) {   * @access private   */  function validate_action_token($visibleerrors = TRUE, $token = NULL, $ts = NULL) { -	global $CONFIG; -  	if (!$token) {  		$token = get_input('__elgg_token');  	} @@ -215,29 +232,18 @@ function validate_action_token($visibleerrors = TRUE, $token = NULL, $ts = NULL)  		$ts = get_input('__elgg_ts');  	} -	if (!isset($CONFIG->action_token_timeout)) { -		// default to 2 hours -		$timeout = 2; -	} else { -		$timeout = $CONFIG->action_token_timeout; -	} -  	$session_id = session_id();  	if (($token) && ($ts) && ($session_id)) {  		// generate token, check with input and forward if invalid -		$generated_token = generate_action_token($ts); +		$required_token = generate_action_token($ts);  		// Validate token -		if ($token == $generated_token) { -			$hour = 60 * 60; -			$timeout = $timeout * $hour; -			$now = time(); - -			// Validate time to ensure its not crazy -			if ($timeout == 0 || ($ts > $now - $timeout) && ($ts < $now + $timeout)) { +		if ($token == $required_token) { +			 +			if (_elgg_validate_token_timestamp($ts)) {  				// We have already got this far, so unless anything -				// else says something to the contry we assume we're ok +				// else says something to the contrary we assume we're ok  				$returnval = true;  				$returnval = elgg_trigger_plugin_hook('action_gatekeeper:permissions:check', 'all', array( @@ -293,12 +299,33 @@ function validate_action_token($visibleerrors = TRUE, $token = NULL, $ts = NULL)   * This function verifies form input for security features (like a generated token),   * and forwards if they are invalid.   * + * @param string $action The action being performed + *    * @return mixed True if valid or redirects.   * @access private   */ -function action_gatekeeper() { -	if (validate_action_token()) { -		return TRUE; +function action_gatekeeper($action) { +	if ($action === 'login') { +		if (validate_action_token(false)) { +			return true; +		} +		 +		$token = get_input('__elgg_token'); +		$ts = (int)get_input('__elgg_ts'); +		if ($token && _elgg_validate_token_timestamp($ts)) { +			// The tokens are present and the time looks valid: this is probably a mismatch due to the  +			// login form being on a different domain. +			register_error(elgg_echo('actiongatekeeper:crosssitelogin')); +			 +			 +			forward('login', 'csrf'); +		} +		 +		// let the validator send an appropriate msg +		validate_action_token(); +		 +	} elseif (validate_action_token()) { +		return true;  	}  	forward(REFERER, 'csrf'); @@ -337,16 +364,19 @@ function generate_action_token($timestamp) {  }  /** - * Initialise the site secret hash. + * Initialise the site secret (32 bytes: "z" to indicate format + 186-bit key in Base64 URL).   *   * Used during installation and saves as a datalist.   * + * Note: Old secrets were hex encoded. + *   * @return mixed The site secret hash or false   * @access private   * @todo Move to better file.   */  function init_site_secret() { -	$secret = md5(rand() . microtime()); +	$secret = 'z' . ElggCrypto::getRandomString(31); +  	if (datalist_set('__site_secret__', $secret)) {  		return $secret;  	} @@ -373,6 +403,26 @@ function get_site_secret() {  }  /** + * Get the strength of the site secret + * + * @return string "strong", "moderate", or "weak" + * @access private + */ +function _elgg_get_site_secret_strength() { +	$secret = get_site_secret(); +	if ($secret[0] !== 'z') { +		$rand_max = getrandmax(); +		if ($rand_max < pow(2, 16)) { +			return 'weak'; +		} +		if ($rand_max < pow(2, 32)) { +			return 'moderate'; +		} +	} +	return 'strong'; +} + +/**   * Check if an action is registered and its script exists.   *   * @param string $action Action name diff --git a/engine/lib/admin.php b/engine/lib/admin.php index ec19a5476..f36f29668 100644 --- a/engine/lib/admin.php +++ b/engine/lib/admin.php @@ -134,11 +134,11 @@ function elgg_delete_admin_notice($id) {  }  /** - * List all admin messages. + * Get admin notices. An admin must be logged in since the notices are private.   *   * @param int $limit Limit   * - * @return array List of admin notices + * @return array Array of admin notices   * @since 1.8.0   */  function elgg_get_admin_notices($limit = 10) { @@ -158,11 +158,13 @@ function elgg_get_admin_notices($limit = 10) {   * @since 1.8.0   */  function elgg_admin_notice_exists($id) { +	$old_ia = elgg_set_ignore_access(true);  	$notice = elgg_get_entities_from_metadata(array(  		'type' => 'object',  		'subtype' => 'admin_notice',  		'metadata_name_value_pair' => array('name' => 'admin_notice_id', 'value' => $id)  	)); +	elgg_set_ignore_access($old_ia);  	return ($notice) ? TRUE : FALSE;  } @@ -234,6 +236,7 @@ function admin_init() {  	elgg_register_action('admin/site/update_advanced', '', 'admin');  	elgg_register_action('admin/site/flush_cache', '', 'admin');  	elgg_register_action('admin/site/unlock_upgrade', '', 'admin'); +	elgg_register_action('admin/site/regenerate_secret', '', 'admin');  	elgg_register_action('admin/menu/save', '', 'admin'); @@ -289,6 +292,7 @@ function admin_init() {  	elgg_register_admin_menu_item('configure', 'settings', null, 100);  	elgg_register_admin_menu_item('configure', 'basic', 'settings', 10);  	elgg_register_admin_menu_item('configure', 'advanced', 'settings', 20); +	elgg_register_admin_menu_item('configure', 'advanced/site_secret', 'settings', 25);  	elgg_register_admin_menu_item('configure', 'menu_items', 'appearance', 30);  	elgg_register_admin_menu_item('configure', 'profile_fields', 'appearance', 40);  	// default widgets is added via an event handler elgg_default_widgets_init() in widgets.php @@ -468,14 +472,18 @@ function admin_page_handler($page) {  	$vars = array('page' => $page);  	// special page for plugin settings since we create the form for them -	if ($page[0] == 'plugin_settings' && isset($page[1]) && -		(elgg_view_exists("settings/{$page[1]}/edit") || elgg_view_exists("plugins/{$page[1]}/settings"))) { +	if ($page[0] == 'plugin_settings') { +		if (isset($page[1]) && (elgg_view_exists("settings/{$page[1]}/edit") ||  +			elgg_view_exists("plugins/{$page[1]}/settings"))) { -		$view = 'admin/plugin_settings'; -		$plugin = elgg_get_plugin_from_id($page[1]); -		$vars['plugin'] = $plugin; +			$view = 'admin/plugin_settings'; +			$plugin = elgg_get_plugin_from_id($page[1]); +			$vars['plugin'] = $plugin; -		$title = elgg_echo("admin:{$page[0]}"); +			$title = elgg_echo("admin:{$page[0]}"); +		} else { +			forward('', '404'); +		}  	} else {  		$view = 'admin/' . implode('/', $page);  		$title = elgg_echo("admin:{$page[0]}"); diff --git a/engine/lib/annotations.php b/engine/lib/annotations.php index bd5ea1a1f..5e9b530de 100644 --- a/engine/lib/annotations.php +++ b/engine/lib/annotations.php @@ -224,7 +224,7 @@ function elgg_get_annotations(array $options = array()) {   *          annotation_name(s), annotation_value(s), or guid(s) must be set.   *   * @param array $options An options array. {@See elgg_get_annotations()} - * @return mixed Null if the metadata name is invalid. Bool on success or fail. + * @return bool|null true on success, false on failure, null if no annotations to delete.   * @since 1.8.0   */  function elgg_delete_annotations(array $options) { @@ -242,16 +242,20 @@ function elgg_delete_annotations(array $options) {   * @warning Unlike elgg_get_annotations() this will not accept an empty options array!   *   * @param array $options An options array. {@See elgg_get_annotations()} - * @return mixed + * @return bool|null true on success, false on failure, null if no annotations disabled.   * @since 1.8.0   */  function elgg_disable_annotations(array $options) {  	if (!elgg_is_valid_options_for_batch_operation($options, 'annotations')) {  		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', false); +	return elgg_batch_metastring_based_objects($options, 'elgg_batch_disable_callback', $inc_offset);  }  /** @@ -259,8 +263,11 @@ function elgg_disable_annotations(array $options) {   *   * @warning Unlike elgg_get_annotations() this will not accept an empty options array!   * + * @warning In order to enable annotations, you must first use + * {@link access_show_hidden_entities()}. + *   * @param array $options An options array. {@See elgg_get_annotations()} - * @return mixed + * @return bool|null true on success, false on failure, null if no metadata enabled.   * @since 1.8.0   */  function elgg_enable_annotations(array $options) { @@ -416,8 +423,8 @@ function elgg_list_entities_from_annotations($options = array()) {  function elgg_get_entities_from_annotation_calculation($options) {  	$db_prefix = elgg_get_config('dbprefix');  	$defaults = array( -		'calculation'	=>	'sum', -		'order_by'		=>	'annotation_calculation desc' +		'calculation' => 'sum', +		'order_by' => 'annotation_calculation desc'  	);  	$options = array_merge($defaults, $options); @@ -454,6 +461,12 @@ function elgg_get_entities_from_annotation_calculation($options) {   * @return string   */  function elgg_list_entities_from_annotation_calculation($options) { +	$defaults = array( +		'calculation' => 'sum', +		'order_by' => 'annotation_calculation desc' +	); +	$options = array_merge($defaults, $options); +  	return elgg_list_entities($options, 'elgg_get_entities_from_annotation_calculation');  } @@ -532,15 +545,16 @@ function elgg_annotation_exists($entity_guid, $annotation_type, $owner_guid = NU  		return FALSE;  	} -	$entity_guid = (int)$entity_guid; -	$annotation_type = sanitise_string($annotation_type); +	$entity_guid = sanitize_int($entity_guid); +	$owner_guid = sanitize_int($owner_guid); +	$annotation_type = sanitize_string($annotation_type); -	$sql = "select a.id" . -			" FROM {$CONFIG->dbprefix}annotations a, {$CONFIG->dbprefix}metastrings m " . -			" WHERE a.owner_guid={$owner_guid} AND a.entity_guid={$entity_guid} " . -			" AND a.name_id=m.id AND m.string='{$annotation_type}'"; +	$sql = "SELECT a.id FROM {$CONFIG->dbprefix}annotations a" . +			" JOIN {$CONFIG->dbprefix}metastrings m ON a.name_id = m.id" . +			" WHERE a.owner_guid = $owner_guid AND a.entity_guid = $entity_guid" . +			" AND m.string = '$annotation_type'"; -	if ($check_annotation = get_data_row($sql)) { +	if (get_data_row($sql)) {  		return TRUE;  	} diff --git a/engine/lib/cache.php b/engine/lib/cache.php index 59359124e..3116c1a9b 100644 --- a/engine/lib/cache.php +++ b/engine/lib/cache.php @@ -208,6 +208,7 @@ function elgg_get_simplecache_url($type, $view) {  	global $CONFIG;  	$lastcache = (int)$CONFIG->lastcache;  	$viewtype = elgg_get_viewtype(); +	elgg_register_simplecache_view("$type/$view");// see #5302  	if (elgg_is_simplecache_enabled()) {  		$url = elgg_get_site_url() . "cache/$type/$viewtype/$view.$lastcache.$type";  	} else { diff --git a/engine/lib/configuration.php b/engine/lib/configuration.php index a0f297f0c..55e5bbd36 100644 --- a/engine/lib/configuration.php +++ b/engine/lib/configuration.php @@ -486,9 +486,9 @@ function get_config($name, $site_guid = 0) {  	// @todo these haven't really been implemented in Elgg 1.8. Complete in 1.9.  	// show dep message  	if ($new_name) { -	//	$msg = "Config value $name has been renamed as $new_name"; +		//	$msg = "Config value $name has been renamed as $new_name";  		$name = $new_name; -	//	elgg_deprecated_notice($msg, $dep_version); +		//	elgg_deprecated_notice($msg, $dep_version);  	}  	// decide from where to return the value diff --git a/engine/lib/database.php b/engine/lib/database.php index 2b348366d..a7949788d 100644 --- a/engine/lib/database.php +++ b/engine/lib/database.php @@ -12,17 +12,19 @@  /**   * Query cache for all queries.   * - * Each query and its results are stored in this array as: + * Each query and its results are stored in this cache as:   * <code> - * $DB_QUERY_CACHE[$query] => array(result1, result2, ... resultN) + * $DB_QUERY_CACHE[query hash] => array(result1, result2, ... resultN)   * </code> + * @see elgg_query_runner() for details on the hash.   * - * @warning be array this var may be an array or ElggStaticVariableCache depending on when called :( + * @warning Elgg used to set this as an empty array to turn off the cache   * - * @global ElggStaticVariableCache|array $DB_QUERY_CACHE + * @global ElggLRUCache|null $DB_QUERY_CACHE + * @access private   */  global $DB_QUERY_CACHE; -$DB_QUERY_CACHE = array(); +$DB_QUERY_CACHE = null;  /**   * Queries to be executed upon shutdown. @@ -40,6 +42,7 @@ $DB_QUERY_CACHE = array();   * </code>   *   * @global array $DB_DELAYED_QUERIES + * @access private   */  global $DB_DELAYED_QUERIES;  $DB_DELAYED_QUERIES = array(); @@ -51,6 +54,7 @@ $DB_DELAYED_QUERIES = array();   * $dblink as $dblink[$name] => resource.  Use get_db_link($name) to retrieve it.   *   * @global resource[] $dblink + * @access private   */  global $dblink;  $dblink = array(); @@ -61,6 +65,7 @@ $dblink = array();   * Each call to the database increments this counter.   *   * @global integer $dbcalls + * @access private   */  global $dbcalls;  $dbcalls = 0; @@ -123,9 +128,8 @@ function establish_db_link($dblinkname = "readwrite") {  	// Set up cache if global not initialized and query cache not turned off  	if ((!$DB_QUERY_CACHE) && (!$db_cache_off)) { -		// @todo everywhere else this is assigned to array(), making it dangerous to call -		// object methods on this. We should consider making this an plain array -		$DB_QUERY_CACHE = new ElggStaticVariableCache('db_query_cache'); +		// @todo if we keep this cache in 1.9, expose the size as a config parameter +		$DB_QUERY_CACHE = new ElggLRUCache(200);  	}  } @@ -395,16 +399,14 @@ function elgg_query_runner($query, $callback = null, $single = false) {  	// Since we want to cache results of running the callback, we need to  	// need to namespace the query with the callback and single result request. -	// http://trac.elgg.org/ticket/4049 +	// https://github.com/elgg/elgg/issues/4049  	$hash = (string)$callback . (int)$single . $query;  	// Is cached?  	if ($DB_QUERY_CACHE) { -		$cached_query = $DB_QUERY_CACHE[$hash]; - -		if ($cached_query !== FALSE) { +		if (isset($DB_QUERY_CACHE[$hash])) {  			elgg_log("DB query $query results returned from cache (hash: $hash)", 'NOTICE'); -			return $cached_query; +			return $DB_QUERY_CACHE[$hash];  		}  	} @@ -456,19 +458,12 @@ function elgg_query_runner($query, $callback = null, $single = false) {   * @access private   */  function insert_data($query) { -	global $DB_QUERY_CACHE;  	elgg_log("DB query $query", 'NOTICE');  	$dblink = get_db_link('write'); -	// Invalidate query cache -	if ($DB_QUERY_CACHE) { -		/* @var ElggStaticVariableCache $DB_QUERY_CACHE */ -		$DB_QUERY_CACHE->clear(); -	} - -	elgg_log("Query cache invalidated", 'NOTICE'); +	_elgg_invalidate_query_cache();  	if (execute_query("$query", $dblink)) {  		return mysql_insert_id($dblink); @@ -478,7 +473,7 @@ function insert_data($query) {  }  /** - * Update a row in the database. + * Update the database.   *   * @note Altering the DB invalidates all queries in {@link $DB_QUERY_CACHE}.   * @@ -488,18 +483,12 @@ function insert_data($query) {   * @access private   */  function update_data($query) { -	global $DB_QUERY_CACHE;  	elgg_log("DB query $query", 'NOTICE');  	$dblink = get_db_link('write'); -	// Invalidate query cache -	if ($DB_QUERY_CACHE) { -		/* @var ElggStaticVariableCache $DB_QUERY_CACHE */ -		$DB_QUERY_CACHE->clear(); -		elgg_log("Query cache invalidated", 'NOTICE'); -	} +	_elgg_invalidate_query_cache();  	if (execute_query("$query", $dblink)) {  		return TRUE; @@ -509,7 +498,7 @@ function update_data($query) {  }  /** - * Remove a row from the database. + * Remove data from the database.   *   * @note Altering the DB invalidates all queries in {@link $DB_QUERY_CACHE}.   * @@ -519,18 +508,12 @@ function update_data($query) {   * @access private   */  function delete_data($query) { -	global $DB_QUERY_CACHE;  	elgg_log("DB query $query", 'NOTICE');  	$dblink = get_db_link('write'); -	// Invalidate query cache -	if ($DB_QUERY_CACHE) { -		/* @var ElggStaticVariableCache $DB_QUERY_CACHE */ -		$DB_QUERY_CACHE->clear(); -		elgg_log("Query cache invalidated", 'NOTICE'); -	} +	_elgg_invalidate_query_cache();  	if (execute_query("$query", $dblink)) {  		return mysql_affected_rows($dblink); @@ -539,6 +522,22 @@ function delete_data($query) {  	return FALSE;  } +/** + * Invalidate the query cache + * + * @access private + */ +function _elgg_invalidate_query_cache() { +	global $DB_QUERY_CACHE; +	if ($DB_QUERY_CACHE instanceof ElggLRUCache) { +		$DB_QUERY_CACHE->clear(); +		elgg_log("Query cache invalidated", 'NOTICE'); +	} elseif ($DB_QUERY_CACHE) { +		// In case someone sets the cache to an array and primes it with data +		$DB_QUERY_CACHE = array(); +		elgg_log("Query cache invalidated", 'NOTICE'); +	} +}  /**   * Return tables matching the database prefix {@link $CONFIG->dbprefix}% in the currently @@ -669,7 +668,7 @@ function run_sql_script($scriptlocation) {  /**   * Format a query string for logging - *  + *   * @param string $query Query string   * @return string   * @access private diff --git a/engine/lib/deprecated-1.7.php b/engine/lib/deprecated-1.7.php index 519eea89d..ee95b5611 100644 --- a/engine/lib/deprecated-1.7.php +++ b/engine/lib/deprecated-1.7.php @@ -1137,6 +1137,7 @@ function make_register_object($register_name, $register_value, $children_array =   * @param int $guid GUID   *   * @return 1 + * @deprecated 1.7   */  function delete_object_entity($guid) {  	system_message(elgg_echo('deprecatedfunction', array('delete_user_entity'))); @@ -1154,6 +1155,7 @@ function delete_object_entity($guid) {   * @param int $guid User GUID   *   * @return 1 + * @deprecated 1.7   */  function delete_user_entity($guid) {  	system_message(elgg_echo('deprecatedfunction', array('delete_user_entity'))); diff --git a/engine/lib/deprecated-1.8.php b/engine/lib/deprecated-1.8.php index 2b4ffcc4f..91068d047 100644 --- a/engine/lib/deprecated-1.8.php +++ b/engine/lib/deprecated-1.8.php @@ -3414,6 +3414,7 @@ function list_annotations($entity_guid, $name = "", $limit = 25, $asc = true) {   * @param unknown_type $timeupper   * @param unknown_type $calculation   * @internal Don't use this at all. + * @deprecated 1.8 Use elgg_get_annotations()   */  function elgg_deprecated_annotation_calculation($entity_guid = 0, $entity_type = "", $entity_subtype = "",  $name = "", $value = "", $value_type = "", $owner_guid = 0, $timelower = 0, @@ -4667,6 +4668,7 @@ function display_widget(ElggObject $widget) {   *   * @param ElggEntity $entity   * @return int Number of comments + * @deprecated 1.8 Use ElggEntity->countComments()   */  function elgg_count_comments($entity) {  	elgg_deprecated_notice('elgg_count_comments() is deprecated by ElggEntity->countComments()', 1.8); @@ -4772,3 +4774,47 @@ function default_page_handler($page, $handler) {  	return FALSE;  } + +/** + * Invalidate this class's entry in the cache. + * + * @param int $guid The entity guid + * + * @return void + * @access private + * @deprecated 1.8 + */ +function invalidate_cache_for_entity($guid) { +	elgg_deprecated_notice('invalidate_cache_for_entity() is a private function and should not be used.', 1.8); +	_elgg_invalidate_cache_for_entity($guid); +} + +/** + * Cache an entity. + * + * Stores an entity in $ENTITY_CACHE; + * + * @param ElggEntity $entity Entity to cache + * + * @return void + * @access private + * @deprecated 1.8 + */ +function cache_entity(ElggEntity $entity) { +	elgg_deprecated_notice('cache_entity() is a private function and should not be used.', 1.8); +	_elgg_cache_entity($entity); +} + +/** + * Retrieve a entity from the cache. + * + * @param int $guid The guid + * + * @return ElggEntity|bool false if entity not cached, or not fully loaded + * @access private + * @deprecated 1.8 + */ +function retrieve_cached_entity($guid) { +	elgg_deprecated_notice('retrieve_cached_entity() is a private function and should not be used.', 1.8); +	return _elgg_retrieve_cached_entity($guid); +} diff --git a/engine/lib/elgglib.php b/engine/lib/elgglib.php index 74b70f9fb..34111c69d 100644 --- a/engine/lib/elgglib.php +++ b/engine/lib/elgglib.php @@ -93,10 +93,17 @@ function elgg_register_library($name, $location) {   * @return void   * @throws InvalidParameterException   * @since 1.8.0 + * @todo return boolean in 1.9 to indicate whether the library has been loaded   */  function elgg_load_library($name) {  	global $CONFIG; +	static $loaded_libraries = array(); + +	if (in_array($name, $loaded_libraries)) { +		return; +	} +  	if (!isset($CONFIG->libraries)) {  		$CONFIG->libraries = array();  	} @@ -113,6 +120,8 @@ function elgg_load_library($name) {  		);  		throw new InvalidParameterException($error);  	} + +	$loaded_libraries[] = $name;  }  /** @@ -128,7 +137,7 @@ function elgg_load_library($name) {   * @throws SecurityException   */  function forward($location = "", $reason = 'system') { -	if (!headers_sent()) { +	if (!headers_sent($file, $line)) {  		if ($location === REFERER) {  			$location = $_SERVER['HTTP_REFERER'];  		} @@ -147,7 +156,7 @@ function forward($location = "", $reason = 'system') {  			exit;  		}  	} else { -		throw new SecurityException(elgg_echo('SecurityException:ForwardFailedToRedirect')); +		throw new SecurityException(elgg_echo('SecurityException:ForwardFailedToRedirect', array($file, $line)));  	}  } @@ -737,7 +746,7 @@ function elgg_unregister_event_handler($event, $object_type, $callback) {   * @tip When referring to events, the preferred syntax is "event, type".   *   * @internal Only rarely should events be changed, added, or removed in core. - * When making changes to events, be sure to first create a ticket in trac. + * When making changes to events, be sure to first create a ticket on Github.   *   * @internal @tip Think of $object_type as the primary namespace element, and   * $event as the secondary namespace. @@ -1185,6 +1194,11 @@ function elgg_dump($value, $to_screen = TRUE, $level = 'NOTICE') {  		$to_screen = FALSE;  	} +	// Do not want to write to JS or CSS pages +	if (elgg_in_context('js') || elgg_in_context('css')) { +		$to_screen = FALSE; +	} +  	if ($to_screen == TRUE) {  		echo '<pre>';  		print_r($value); @@ -1336,7 +1350,7 @@ function full_url() {  		"" : (":" . $_SERVER["SERVER_PORT"]);  	// This is here to prevent XSS in poorly written browsers used by 80% of the population. -	// {@trac [5813]} +	// https://github.com/Elgg/Elgg/commit/0c947e80f512cb0a482b1864fd0a6965c8a0cd4a  	$quotes = array('\'', '"');  	$encoded = array('%27', '%22'); @@ -1383,8 +1397,8 @@ function elgg_http_build_url(array $parts, $html_encode = TRUE) {   * add tokens to the action.  The form view automatically handles   * tokens.   * - * @param string  $url         Full action URL - * @param bool $html_encode HTML encode the url? (default: false) + * @param string $url         Full action URL + * @param bool   $html_encode HTML encode the url? (default: false)   *   * @return string URL with action tokens   * @since 1.7.0 @@ -1446,7 +1460,7 @@ function elgg_http_remove_url_query_element($url, $element) {   * Adds an element or elements to a URL's query string.   *   * @param string $url      The URL - * @param array $elements Key/value pairs to add to the URL + * @param array  $elements Key/value pairs to add to the URL   *   * @return string The new URL with the query strings added   * @since 1.7.0 @@ -2233,6 +2247,9 @@ function elgg_api_test($hook, $type, $value, $params) {  /**#@+   * Controls access levels on ElggEntity entities, metadata, and annotations.   * + * @warning ACCESS_DEFAULT is a place holder for the input/access view. Do not + * use it when saving an entity. + *   * @var int   */  define('ACCESS_DEFAULT', -1); diff --git a/engine/lib/entities.php b/engine/lib/entities.php index 156eec040..4fcf1c657 100644 --- a/engine/lib/entities.php +++ b/engine/lib/entities.php @@ -17,6 +17,15 @@ global $ENTITY_CACHE;  $ENTITY_CACHE = array();  /** + * GUIDs of entities banned from the entity cache (during this request) + * + * @global array $ENTITY_CACHE_DISABLED_GUIDS + * @access private + */ +global $ENTITY_CACHE_DISABLED_GUIDS; +$ENTITY_CACHE_DISABLED_GUIDS = array(); + +/**   * Cache subtypes and related class names.   *   * @global array|null $SUBTYPE_CACHE array once populated from DB, initially null @@ -26,14 +35,42 @@ global $SUBTYPE_CACHE;  $SUBTYPE_CACHE = null;  /** + * Remove this entity from the entity cache and make sure it is not re-added + * + * @param int $guid The entity guid + * + * @access private + * @todo this is a workaround until #5604 can be implemented + */ +function _elgg_disable_caching_for_entity($guid) { +	global $ENTITY_CACHE_DISABLED_GUIDS; + +	_elgg_invalidate_cache_for_entity($guid); +	$ENTITY_CACHE_DISABLED_GUIDS[$guid] = true; +} + +/** + * Allow this entity to be stored in the entity cache + * + * @param int $guid The entity guid + * + * @access private + */ +function _elgg_enable_caching_for_entity($guid) { +	global $ENTITY_CACHE_DISABLED_GUIDS; + +	unset($ENTITY_CACHE_DISABLED_GUIDS[$guid]); +} + +/**   * Invalidate this class's entry in the cache.   *   * @param int $guid The entity guid   * - * @return null + * @return void   * @access private   */ -function invalidate_cache_for_entity($guid) { +function _elgg_invalidate_cache_for_entity($guid) {  	global $ENTITY_CACHE;  	$guid = (int)$guid; @@ -50,14 +87,14 @@ function invalidate_cache_for_entity($guid) {   *   * @param ElggEntity $entity Entity to cache   * - * @return null - * @see retrieve_cached_entity() - * @see invalidate_cache_for_entity() + * @return void + * @see _elgg_retrieve_cached_entity() + * @see _elgg_invalidate_cache_for_entity()   * @access private - * TODO(evan): Use an ElggCache object + * @todo Use an ElggCache object   */ -function cache_entity(ElggEntity $entity) { -	global $ENTITY_CACHE; +function _elgg_cache_entity(ElggEntity $entity) { +	global $ENTITY_CACHE, $ENTITY_CACHE_DISABLED_GUIDS;  	// Don't cache non-plugin entities while access control is off, otherwise they could be  	// exposed to users who shouldn't see them when control is re-enabled. @@ -65,8 +102,13 @@ function cache_entity(ElggEntity $entity) {  		return;  	} +	$guid = $entity->getGUID(); +	if (isset($ENTITY_CACHE_DISABLED_GUIDS[$guid])) { +		return; +	} +  	// Don't store too many or we'll have memory problems -	// TODO(evan): Pick a less arbitrary limit +	// @todo Pick a less arbitrary limit  	if (count($ENTITY_CACHE) > 256) {  		$random_guid = array_rand($ENTITY_CACHE); @@ -79,7 +121,7 @@ function cache_entity(ElggEntity $entity) {  		elgg_get_metadata_cache()->clear($random_guid);  	} -	$ENTITY_CACHE[$entity->guid] = $entity; +	$ENTITY_CACHE[$guid] = $entity;  }  /** @@ -88,11 +130,11 @@ function cache_entity(ElggEntity $entity) {   * @param int $guid The guid   *   * @return ElggEntity|bool false if entity not cached, or not fully loaded - * @see cache_entity() - * @see invalidate_cache_for_entity() + * @see _elgg_cache_entity() + * @see _elgg_invalidate_cache_for_entity()   * @access private   */ -function retrieve_cached_entity($guid) { +function _elgg_retrieve_cached_entity($guid) {  	global $ENTITY_CACHE;  	if (isset($ENTITY_CACHE[$guid])) { @@ -105,31 +147,6 @@ function retrieve_cached_entity($guid) {  }  /** - * As retrieve_cached_entity, but returns the result as a stdClass - * (compatible with load functions that expect a database row.) - * - * @param int $guid The guid - * - * @return mixed - * @todo unused - * @access private - */ -function retrieve_cached_entity_row($guid) { -	$obj = retrieve_cached_entity($guid); -	if ($obj) { -		$tmp = new stdClass; - -		foreach ($obj as $k => $v) { -			$tmp->$k = $v; -		} - -		return $tmp; -	} - -	return false; -} - -/**   * Return the id for a given subtype.   *   * ElggEntity objects have a type and a subtype.  Subtypes @@ -432,7 +449,7 @@ function update_subtype($type, $subtype, $class = '') {   * @param int $time_created   The time creation timestamp   *   * @return bool - * @link http://docs.elgg.org/DataModel/Entities + * @throws InvalidParameterException   * @access private   */  function update_entity($guid, $owner_guid, $access_id, $container_guid = null, $time_created = null) { @@ -455,6 +472,10 @@ function update_entity($guid, $owner_guid, $access_id, $container_guid = null, $  		$time_created = (int) $time_created;  	} +	if ($access_id == ACCESS_DEFAULT) { +		throw new InvalidParameterException('ACCESS_DEFAULT is not a valid access level. See its documentation in elgglib.h'); +	} +  	if ($entity && $entity->canEdit()) {  		if (elgg_trigger_event('update', $entity->type, $entity)) {  			$ret = update_data("UPDATE {$CONFIG->dbprefix}entities @@ -581,7 +602,6 @@ $container_guid = 0) {  	$type = sanitise_string($type);  	$subtype_id = add_subtype($type, $subtype);  	$owner_guid = (int)$owner_guid; -	$access_id = (int)$access_id;  	$time = time();  	if ($site_guid == 0) {  		$site_guid = $CONFIG->site_guid; @@ -590,6 +610,10 @@ $container_guid = 0) {  	if ($container_guid == 0) {  		$container_guid = $owner_guid;  	} +	$access_id = (int)$access_id; +	if ($access_id == ACCESS_DEFAULT) { +		throw new InvalidParameterException('ACCESS_DEFAULT is not a valid access level. See its documentation in elgglib.h'); +	}  	$user_guid = elgg_get_logged_in_user_guid();  	if (!can_write_to_container($user_guid, $owner_guid, $type, $subtype)) { @@ -737,7 +761,7 @@ function get_entity($guid) {  	// @todo We need a single Memcache instance with a shared pool of namespace wrappers. This function would pull an instance from the pool.  	static $shared_cache; -	// We could also use: if (!(int) $guid) { return FALSE },  +	// We could also use: if (!(int) $guid) { return FALSE },  	// but that evaluates to a false positive for $guid = TRUE.  	// This is a bit slower, but more thorough.  	if (!is_numeric($guid) || $guid === 0 || $guid === '0') { @@ -745,7 +769,7 @@ function get_entity($guid) {  	}  	// Check local cache first -	$new_entity = retrieve_cached_entity($guid); +	$new_entity = _elgg_retrieve_cached_entity($guid);  	if ($new_entity) {  		return $new_entity;  	} @@ -767,7 +791,7 @@ function get_entity($guid) {  	if ($shared_cache) {  		$cached_entity = $shared_cache->load($guid); -		// @todo store ACLs in memcache http://trac.elgg.org/ticket/3018#comment:3 +		// @todo store ACLs in memcache https://github.com/elgg/elgg/issues/3018#issuecomment-13662617  		if ($cached_entity) {  			// @todo use ACL and cached entity access_id to determine if user can see it  			return $cached_entity; @@ -782,7 +806,7 @@ function get_entity($guid) {  	}  	if ($new_entity) { -		cache_entity($new_entity); +		_elgg_cache_entity($new_entity);  	}  	return $new_entity;  } @@ -909,6 +933,8 @@ function elgg_get_entities(array $options = array()) {  		'joins'					=>	array(),  		'callback'				=> 'entity_row_to_elggstar', + +		'__ElggBatch'			=> null,  	);  	$options = array_merge($defaults, $options); @@ -1026,7 +1052,7 @@ function elgg_get_entities(array $options = array()) {  		}  		if ($options['callback'] === 'entity_row_to_elggstar') { -			$dt = _elgg_fetch_entities_from_sql($query); +			$dt = _elgg_fetch_entities_from_sql($query, $options['__ElggBatch']);  		} else {  			$dt = get_data($query, $options['callback']);  		} @@ -1037,7 +1063,7 @@ function elgg_get_entities(array $options = 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) { -					cache_entity($item); +					_elgg_cache_entity($item);  					// plugins usually have only settings  					if (!$item instanceof ElggPlugin) {  						$guids[] = $item->guid; @@ -1061,13 +1087,14 @@ function elgg_get_entities(array $options = array()) {  /**   * Return entities from an SQL query generated by elgg_get_entities.   * - * @param string $sql + * @param string    $sql + * @param ElggBatch $batch   * @return ElggEntity[]   *   * @access private   * @throws LogicException   */ -function _elgg_fetch_entities_from_sql($sql) { +function _elgg_fetch_entities_from_sql($sql, ElggBatch $batch = null) {  	static $plugin_subtype;  	if (null === $plugin_subtype) {  		$plugin_subtype = get_subtype_id('object', 'plugin'); @@ -1102,7 +1129,7 @@ function _elgg_fetch_entities_from_sql($sql) {  		if (empty($row->guid) || empty($row->type)) {  			throw new LogicException('Entity row missing guid or type');  		} -		if ($entity = retrieve_cached_entity($row->guid)) { +		if ($entity = _elgg_retrieve_cached_entity($row->guid)) {  			$rows[$i] = $entity;  			continue;  		} @@ -1144,6 +1171,11 @@ function _elgg_fetch_entities_from_sql($sql) {  			} catch (IncompleteEntityException $e) {  				// don't let incomplete entities throw fatal errors  				unset($rows[$i]); + +				// report incompletes to the batch process that spawned this query +				if ($batch) { +					$batch->reportIncompleteEntity($row); +				}  			}  		}  	} @@ -1441,8 +1473,10 @@ function elgg_list_entities(array $options = array(), $getter = 'elgg_get_entiti  	global $autofeed;  	$autofeed = true; +	$offset_key = isset($options['offset_key']) ? $options['offset_key'] : 'offset'; +  	$defaults = array( -		'offset' => (int) max(get_input('offset', 0), 0), +		'offset' => (int) max(get_input($offset_key, 0), 0),  		'limit' => (int) max(get_input('limit', 10), 0),  		'full_view' => TRUE,  		'list_type_toggle' => FALSE, @@ -1628,7 +1662,7 @@ function disable_entity($guid, $reason = "", $recursive = true) {  				$entity->disableMetadata();  				$entity->disableAnnotations(); -				invalidate_cache_for_entity($guid); +				_elgg_invalidate_cache_for_entity($guid);  				$res = update_data("UPDATE {$CONFIG->dbprefix}entities  					SET enabled = 'no' @@ -1644,8 +1678,8 @@ function disable_entity($guid, $reason = "", $recursive = true) {  /**   * Enable an entity.   * - * @warning In order to enable an entity using ElggEntity::enable(), - * you must first use {@link access_show_hidden_entities()}. + * @warning In order to enable an entity, you must first use + * {@link access_show_hidden_entities()}.   *   * @param int  $guid      GUID of entity to enable   * @param bool $recursive Recursively enable all entities disabled with the entity? @@ -1726,7 +1760,7 @@ function delete_entity($guid, $recursive = true) {  				// delete cache  				if (isset($ENTITY_CACHE[$guid])) { -					invalidate_cache_for_entity($guid); +					_elgg_invalidate_cache_for_entity($guid);  				}  				// If memcache is available then delete this entry from the cache @@ -1773,6 +1807,10 @@ function delete_entity($guid, $recursive = true) {  					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  				$entity->deleteMetadata();  				$entity->deleteOwnedMetadata(); @@ -1780,6 +1818,9 @@ function delete_entity($guid, $recursive = true) {  				$entity->deleteOwnedAnnotations();  				$entity->deleteRelationships(); +				access_show_hidden_entities($entity_disable_override); +				elgg_set_ignore_access($ia); +  				elgg_delete_river(array('subject_guid' => $guid));  				elgg_delete_river(array('object_guid' => $guid));  				remove_all_private_settings($guid); @@ -2087,7 +2128,7 @@ function can_edit_entity_metadata($entity_guid, $user_guid = 0, $metadata = null  		$return = null; -		if ($metadata->owner_guid == 0) { +		if ($metadata && ($metadata->owner_guid == 0)) {  			$return = true;  		}  		if (is_null($return)) { @@ -2488,11 +2529,18 @@ function update_entity_last_action($guid, $posted = NULL) {  function entities_gc() {  	global $CONFIG; -	$tables = array ('sites_entity', 'objects_entity', 'groups_entity', 'users_entity'); +	$tables = array( +		'site' => 'sites_entity', +		'object' => 'objects_entity', +		'group' => 'groups_entity', +		'user' => 'users_entity' +	); -	foreach ($tables as $table) { -		delete_data("DELETE from {$CONFIG->dbprefix}{$table} -			where guid NOT IN (SELECT guid from {$CONFIG->dbprefix}entities)"); +	foreach ($tables as $type => $table) { +		delete_data("DELETE FROM {$CONFIG->dbprefix}{$table} +			WHERE guid NOT IN (SELECT guid FROM {$CONFIG->dbprefix}entities)"); +		delete_data("DELETE FROM {$CONFIG->dbprefix}entities +			WHERE type = '$type' AND guid NOT IN (SELECT guid FROM {$CONFIG->dbprefix}{$table})");  	}  } diff --git a/engine/lib/extender.php b/engine/lib/extender.php index 8756e051b..8323bd3ce 100644 --- a/engine/lib/extender.php +++ b/engine/lib/extender.php @@ -126,14 +126,20 @@ function import_extender_plugin_hook($hook, $entity_type, $returnvalue, $params)   * @return bool   */  function can_edit_extender($extender_id, $type, $user_guid = 0) { -	if (!elgg_is_logged_in()) { -		return false; +	// @todo Since Elgg 1.0, Elgg has returned false from can_edit_extender() +	// if no user was logged in. This breaks the access override. This is a +	// temporary work around. This function needs to be rewritten in Elgg 1.9  +	if (!elgg_check_access_overrides($user_guid)) { +		if (!elgg_is_logged_in()) { +			return false; +		}  	}  	$user_guid = (int)$user_guid; -	$user = get_entity($user_guid); +	$user = get_user($user_guid);  	if (!$user) {  		$user = elgg_get_logged_in_user_entity(); +		$user_guid = elgg_get_logged_in_user_guid();  	}  	$functionname = "elgg_get_{$type}_from_id"; @@ -149,16 +155,16 @@ function can_edit_extender($extender_id, $type, $user_guid = 0) {  	/* @var ElggExtender $extender */  	// If the owner is the specified user, great! They can edit. -	if ($extender->getOwnerGUID() == $user->getGUID()) { +	if ($extender->getOwnerGUID() == $user_guid) {  		return true;  	}  	// If the user can edit the entity this is attached to, great! They can edit. -	if (can_edit_entity($extender->entity_guid, $user->getGUID())) { +	if (can_edit_entity($extender->entity_guid, $user_guid)) {  		return true;  	} -	// Trigger plugin hooks +	// Trigger plugin hook - note that $user may be null  	$params = array('entity' => $extender->getEntity(), 'user' => $user);  	return elgg_trigger_plugin_hook('permissions_check', $type, $params, false);  } diff --git a/engine/lib/group.php b/engine/lib/group.php index 624029d98..6ded8a825 100644 --- a/engine/lib/group.php +++ b/engine/lib/group.php @@ -240,9 +240,11 @@ function leave_group($group_guid, $user_guid) {   */  function get_users_membership($user_guid) {  	$options = array( +		'type' => 'group',  		'relationship' => 'member',  		'relationship_guid' => $user_guid, -		'inverse_relationship' => FALSE +		'inverse_relationship' => false, +		'limit' => false,  	);  	return elgg_get_entities_from_relationship($options);  } diff --git a/engine/lib/input.php b/engine/lib/input.php index 2d9bae4dd..80b0b8766 100644 --- a/engine/lib/input.php +++ b/engine/lib/input.php @@ -60,8 +60,8 @@ function get_input($variable, $default = NULL, $filter_result = TRUE) {   *   * Note: this function does not handle nested arrays (ex: form input of param[m][n])   * - * @param string $variable The name of the variable - * @param string $value    The value of the variable + * @param string          $variable The name of the variable + * @param string|string[] $value    The value of the variable   *   * @return void   */ diff --git a/engine/lib/languages.php b/engine/lib/languages.php index 17db14d98..61ba91ddb 100644 --- a/engine/lib/languages.php +++ b/engine/lib/languages.php @@ -139,6 +139,9 @@ function get_language() {  	return false;  } +/** + * @access private + */  function _elgg_load_translations() {  	global $CONFIG; diff --git a/engine/lib/location.php b/engine/lib/location.php index b319bb3bb..1534c7d7b 100644 --- a/engine/lib/location.php +++ b/engine/lib/location.php @@ -139,7 +139,7 @@ function elgg_get_entities_from_location(array $options = array()) {  /**   * Returns a viewable list of entities from location   * - * @param array $options + * @param array $options Options array   *   * @see elgg_list_entities()   * @see elgg_get_entities_from_location() diff --git a/engine/lib/memcache.php b/engine/lib/memcache.php index f79fba4a9..79b87e850 100644 --- a/engine/lib/memcache.php +++ b/engine/lib/memcache.php @@ -35,3 +35,23 @@ function is_memcache_available() {  	return $memcache_available;  } + +/** + * Invalidate an entity in memcache + * + * @param int $entity_guid The GUID of the entity to invalidate + * + * @return void + * @access private + */ +function _elgg_invalidate_memcache_for_entity($entity_guid) { +	static $newentity_cache; +	
 +	if ((!$newentity_cache) && (is_memcache_available())) {
 +		$newentity_cache = new ElggMemcache('new_entity_cache');
 +	} +	
 +	if ($newentity_cache) {
 +		$newentity_cache->delete($entity_guid);
 +	} +}
\ No newline at end of file diff --git a/engine/lib/metadata.php b/engine/lib/metadata.php index 305e9918b..fdb1b85f6 100644 --- a/engine/lib/metadata.php +++ b/engine/lib/metadata.php @@ -191,19 +191,19 @@ function update_metadata($id, $name, $value, $value_type, $owner_guid, $access_i  	}  	// Add the metastring -	$value = add_metastring($value); -	if (!$value) { +	$value_id = add_metastring($value); +	if (!$value_id) {  		return false;  	} -	$name = add_metastring($name); -	if (!$name) { +	$name_id = add_metastring($name); +	if (!$name_id) {  		return false;  	}  	// If ok then add it  	$query = "UPDATE {$CONFIG->dbprefix}metadata" -		. " set name_id='$name', value_id='$value', value_type='$value_type', access_id=$access_id," +		. " set name_id='$name_id', value_id='$value_id', value_type='$value_type', access_id=$access_id,"  		. " owner_guid=$owner_guid where id=$id";  	$result = update_data($query); @@ -300,10 +300,8 @@ function elgg_get_metadata(array $options = array()) {   *          This requires at least one constraint: metadata_owner_guid(s),   *          metadata_name(s), metadata_value(s), or guid(s) must be set.   * - * @warning This returns null on no ops. - *   * @param array $options An options array. {@see elgg_get_metadata()} - * @return mixed Null if the metadata name is invalid. Bool on success or fail. + * @return bool|null true on success, false on failure, null if no metadata to delete.   * @since 1.8.0   */  function elgg_delete_metadata(array $options) { @@ -325,10 +323,8 @@ function elgg_delete_metadata(array $options) {   *   * @warning Unlike elgg_get_metadata() this will not accept an empty options array!   * - * @warning This returns null on no ops. - *   * @param array $options An options array. {@See elgg_get_metadata()} - * @return mixed + * @return bool|null true on success, false on failure, null if no metadata disabled.   * @since 1.8.0   */  function elgg_disable_metadata(array $options) { @@ -337,9 +333,13 @@ function elgg_disable_metadata(array $options) {  	}  	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', false); +	return elgg_batch_metastring_based_objects($options, 'elgg_batch_disable_callback', $inc_offset);  }  /** @@ -347,10 +347,11 @@ function elgg_disable_metadata(array $options) {   *   * @warning Unlike elgg_get_metadata() this will not accept an empty options array!   * - * @warning This returns null on no ops. + * @warning In order to enable metadata, you must first use + * {@link access_show_hidden_entities()}.   *   * @param array $options An options array. {@See elgg_get_metadata()} - * @return mixed + * @return bool|null true on success, false on failure, null if no metadata enabled.   * @since 1.8.0   */  function elgg_enable_metadata(array $options) { @@ -405,9 +406,11 @@ function elgg_enable_metadata(array $options) {   *                                         'operand' => '=',   *                                         'case_sensitive' => TRUE   *                                        ) - * 	                             Currently if multiple values are sent via + *                               Currently if multiple values are sent via   *                               an array (value => array('value1', 'value2')   *                               the pair's operand will be forced to "IN". + *                               If passing "IN" as the operand and a string as the value,  + *                               the value must be a properly quoted and escaped string.   *   * 	metadata_name_value_pairs_operator => NULL|STR The operator to use for combining   *                                        (name = value) OPERATOR (name = value); default AND @@ -619,6 +622,8 @@ $owner_guids = NULL) {  			// 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(); @@ -920,8 +925,8 @@ function elgg_get_metadata_cache() {   * Invalidate the metadata cache based on options passed to various *_metadata functions   *   * @param string $action  Action performed on metadata. "delete", "disable", or "enable" - * - * @param array $options  Options passed to elgg_(delete|disable|enable)_metadata + * @param array  $options Options passed to elgg_(delete|disable|enable)_metadata + * @return void   */  function elgg_invalidate_metadata_cache($action, array $options) {  	// remove as little as possible, optimizing for common cases diff --git a/engine/lib/metastrings.php b/engine/lib/metastrings.php index f49b4a163..57d876c06 100644 --- a/engine/lib/metastrings.php +++ b/engine/lib/metastrings.php @@ -421,9 +421,11 @@ function elgg_get_metastring_based_objects($options) {  	if ($metastring_clauses) {  		$wheres = array_merge($wheres, $metastring_clauses['wheres']);  		$joins = array_merge($joins, $metastring_clauses['joins']); +	} else { +		$wheres[] = get_access_sql_suffix('n_table');  	} -	if ($options['metastring_calculation'] === ELGG_ENTITIES_NO_VALUE) { +	if ($options['metastring_calculation'] === ELGG_ENTITIES_NO_VALUE && !$options['count']) {  		$selects = array_unique($selects);  		// evalutate selects  		$select_str = ''; @@ -434,6 +436,9 @@ function elgg_get_metastring_based_objects($options) {  		}  		$query = "SELECT DISTINCT n_table.*{$select_str} FROM {$db_prefix}$type n_table"; +	} elseif ($options['count']) { +		// count is over the entities +		$query = "SELECT count(DISTINCT e.guid) as calculation FROM {$db_prefix}$type n_table";  	} else {  		$query = "SELECT {$options['metastring_calculation']}(v.string) as calculation FROM {$db_prefix}$type n_table";  	} @@ -462,7 +467,7 @@ function elgg_get_metastring_based_objects($options) {  			$defaults['order_by']);  	} -	if ($options['metastring_calculation'] === ELGG_ENTITIES_NO_VALUE) { +	if ($options['metastring_calculation'] === ELGG_ENTITIES_NO_VALUE && !$options['count']) {  		if (isset($options['group_by'])) {  			$options['group_by'] = sanitise_string($options['group_by']);  			$query .= " GROUP BY {$options['group_by']}"; @@ -510,7 +515,7 @@ function elgg_get_metastring_sql($table, $names = null, $values = null,  		&& !$ids  		&& (!$pairs && $pairs !== 0)) { -		return ''; +		return array();  	}  	$db_prefix = elgg_get_config('dbprefix'); @@ -520,8 +525,6 @@ function elgg_get_metastring_sql($table, $names = null, $values = null,  	// only supported on values.  	$binary = ($case_sensitive) ? ' BINARY ' : ''; -	$access = get_access_sql_suffix($table); -  	$return = array (  		'joins' => array (),  		'wheres' => array() @@ -586,13 +589,15 @@ function elgg_get_metastring_sql($table, $names = null, $values = null,  	}  	if ($names_where && $values_where) { -		$wheres[] = "($names_where AND $values_where AND $access)"; +		$wheres[] = "($names_where AND $values_where)";  	} elseif ($names_where) { -		$wheres[] = "($names_where AND $access)"; +		$wheres[] = $names_where;  	} elseif ($values_where) { -		$wheres[] = "($values_where AND $access)"; +		$wheres[] = $values_where;  	} +	$wheres[] = get_access_sql_suffix($table); +  	if ($where = implode(' AND ', $wheres)) {  		$return['wheres'][] = "($where)";  	} diff --git a/engine/lib/navigation.php b/engine/lib/navigation.php index 118a7214c..ab9cc05e8 100644 --- a/engine/lib/navigation.php +++ b/engine/lib/navigation.php @@ -218,7 +218,7 @@ function elgg_push_breadcrumb($title, $link = NULL) {  	}  	// avoid key collisions. -	$CONFIG->breadcrumbs[] = array('title' => $title, 'link' => $link); +	$CONFIG->breadcrumbs[] = array('title' => elgg_get_excerpt($title, 100), 'link' => $link);  }  /** @@ -323,7 +323,8 @@ function elgg_site_menu_setup($hook, $type, $return, $params) {  	}  	if (!$selected) { -		// nothing selected, match name to context +		// nothing selected, match name to context or match url +		$current_url = current_page_url();  		foreach ($return as $section_name => $section) {  			foreach ($section as $key => $item) {  				// only highlight internal links @@ -332,6 +333,10 @@ function elgg_site_menu_setup($hook, $type, $return, $params) {  						$return[$section_name][$key]->setSelected(true);  						break 2;  					} +					if ($item->getHref() == $current_url) { +						$return[$section_name][$key]->setSelected(true); +						break 2; +					}  				}  			}  		} diff --git a/engine/lib/notification.php b/engine/lib/notification.php index b6399b3c6..be0c359d4 100644 --- a/engine/lib/notification.php +++ b/engine/lib/notification.php @@ -110,12 +110,15 @@ function notify_user($to, $from, $subject, $message, array $params = NULL, $meth  			// Are we overriding delivery?  			$methods = $methods_override;  			if (!$methods) { -				$tmp = (array)get_user_notification_settings($guid); +				$tmp = get_user_notification_settings($guid);  				$methods = array(); -				foreach ($tmp as $k => $v) { -					// Add method if method is turned on for user! -					if ($v) { -						$methods[] = $k; +				// $tmp may be false. don't cast +				if (is_object($tmp)) { +					foreach ($tmp as $k => $v) { +						// Add method if method is turned on for user! +						if ($v) { +							$methods[] = $k; +						}  					}  				}  			} @@ -165,7 +168,7 @@ function notify_user($to, $from, $subject, $message, array $params = NULL, $meth   *   * @param int $user_guid The user id   * - * @return stdClass + * @return stdClass|false   */  function get_user_notification_settings($user_guid = 0) {  	$user_guid = (int)$user_guid; diff --git a/engine/lib/opendd.php b/engine/lib/opendd.php index f00ea6aab..7d635a295 100644 --- a/engine/lib/opendd.php +++ b/engine/lib/opendd.php @@ -7,6 +7,8 @@   * @version 0.4   */ +// @codingStandardsIgnoreStart +  /**   * Attempt to construct an ODD object out of a XmlElement or sub-elements.   * @@ -103,3 +105,5 @@ function ODD_Import($xml) {  function ODD_Export(ODDDocument $document) {  	return "$document";  } + +// @codingStandardsIgnoreEnd diff --git a/engine/lib/output.php b/engine/lib/output.php index da8e1ab86..de4f911fb 100644 --- a/engine/lib/output.php +++ b/engine/lib/output.php @@ -13,28 +13,33 @@   * @param string $text The input string   *   * @return string The output string with formatted links - **/ + */  function parse_urls($text) { + +	// URI specification: http://www.ietf.org/rfc/rfc3986.txt +	// This varies from the specification in the following ways: +	//  * Supports non-ascii characters +	//  * Does not allow parentheses and single quotes +	//  * Cuts off commas, exclamation points, and periods off as last character +  	// @todo this causes problems with <attr = "val">  	// must be in <attr="val"> format (no space).  	// By default htmlawed rewrites tags to this format.  	// if PHP supported conditional negative lookbehinds we could use this:  	// $r = preg_replace_callback('/(?<!=)(?<![ ])?(?<!["\'])((ht|f)tps?:\/\/[^\s\r\n\t<>"\'\!\(\),]+)/i', -	// -	// we can put , in the list of excluded char but need to keep . because of domain names. -	// it is removed in the callback. -	$r = preg_replace_callback('/(?<!=)(?<!["\'])((ht|f)tps?:\/\/[^\s\r\n\t<>"\'\!\(\),]+)/i', +	$r = preg_replace_callback('/(?<![=\/"\'])((ht|f)tps?:\/\/[^\s\r\n\t<>"\']+)/i',  	create_function(  		'$matches',  		'  			$url = $matches[1]; -			$period = \'\'; -			if (substr($url, -1, 1) == \'.\') { -				$period = \'.\'; -				$url = trim($url, \'.\'); +			$punc = ""; +			$last = substr($url, -1, 1); +			if (in_array($last, array(".", "!", ",", "(", ")"))) { +				$punc = $last; +				$url = rtrim($url, ".!,()");  			}  			$urltext = str_replace("/", "/<wbr />", $url); -			return "<a href=\"$url\">$urltext</a>$period"; +			return "<a href=\"$url\" rel=\"nofollow\">$urltext</a>$punc";  		'  	), $text); @@ -284,11 +289,9 @@ function elgg_get_friendly_title($title) {  		return $result;  	} -	// handle some special cases -	$title = str_replace('&', 'and', $title); -	// quotes and angle brackets stored in the database as html encoded -	$title = htmlspecialchars_decode($title); - +	// titles are often stored HTML encoded +	$title = html_entity_decode($title, ENT_QUOTES, 'UTF-8'); +	  	$title = ElggTranslit::urlize($title);  	return $title; @@ -418,6 +421,25 @@ function _elgg_html_decode($string) {  }  /** + * Prepares query string for output to prevent CSRF attacks. + *  + * @param string $string + * @return string + * + * @access private + */ +function _elgg_get_display_query($string) { +	//encode <,>,&, quotes and characters above 127 +	if (function_exists('mb_convert_encoding')) {
 +		$display_query = mb_convert_encoding($string, 'HTML-ENTITIES', 'UTF-8');
 +	} else {
 +		// if no mbstring extension, we just strip characters
 +		$display_query = preg_replace("/[^\x01-\x7F]/", "", $string);
 +	}
 +	return htmlspecialchars($display_query, ENT_QUOTES, 'UTF-8', false); +} + +/**   * Unit tests for Output   *   * @param string  $hook   unit_test diff --git a/engine/lib/pageowner.php b/engine/lib/pageowner.php index 7fd79e68a..4aaffc160 100644 --- a/engine/lib/pageowner.php +++ b/engine/lib/pageowner.php @@ -29,7 +29,9 @@ function elgg_get_page_owner_guid($guid = 0) {  	// return guid of page owner entity  	$guid = elgg_trigger_plugin_hook('page_owner', 'system', NULL, 0); -	$page_owner_guid = $guid; +	if ($guid) { +		$page_owner_guid = $guid; +	}  	return $guid;  } diff --git a/engine/lib/plugins.php b/engine/lib/plugins.php index f281b1416..d5d3db466 100644 --- a/engine/lib/plugins.php +++ b/engine/lib/plugins.php @@ -312,10 +312,10 @@ function elgg_is_active_plugin($plugin_id, $site_guid = null) {   */  function elgg_load_plugins() {  	$plugins_path = elgg_get_plugins_path(); -	$start_flags =	ELGG_PLUGIN_INCLUDE_START -					| ELGG_PLUGIN_REGISTER_VIEWS -					| ELGG_PLUGIN_REGISTER_LANGUAGES -					| ELGG_PLUGIN_REGISTER_CLASSES; +	$start_flags = ELGG_PLUGIN_INCLUDE_START | +					ELGG_PLUGIN_REGISTER_VIEWS | +					ELGG_PLUGIN_REGISTER_LANGUAGES | +					ELGG_PLUGIN_REGISTER_CLASSES;  	if (!$plugins_path) {  		return false; @@ -865,7 +865,7 @@ function elgg_set_plugin_user_setting($name, $value, $user_guid = null, $plugin_   * Unsets a user-specific plugin setting   *   * @param string $name      Name of the setting - * @param int $user_guid Defaults to logged in user + * @param int    $user_guid Defaults to logged in user   * @param string $plugin_id Defaults to contextual plugin name   *   * @return bool @@ -1105,6 +1105,49 @@ function plugins_test($hook, $type, $value, $params) {  }  /** + * Checks on deactivate plugin event if disabling it won't create unmet dependencies and blocks disable in such case. + * + * @param string $event  deactivate + * @param string $type   plugin + * @param array  $params Parameters array containing entry with ELggPlugin instance under 'plugin_entity' key + * @return bool  false to block plugin deactivation action + * + * @access private + */ +function _plugins_deactivate_dependency_check($event, $type, $params) { +	$plugin_id = $params['plugin_entity']->getManifest()->getPluginID(); +	$plugin_name = $params['plugin_entity']->getManifest()->getName(); + +	$active_plugins = elgg_get_plugins(); + +	$dependents = array(); +	foreach ($active_plugins as $plugin) { +		$manifest = $plugin->getManifest(); +		$requires = $manifest->getRequires(); + +		foreach ($requires as $required) { +			if ($required['type'] == 'plugin' && $required['name'] == $plugin_id) { +				// there are active dependents +				$dependents[$manifest->getPluginID()] = $plugin; +			} +		} +	} + +	if ($dependents) { +		$list = '<ul>'; +		// construct error message and prevent disabling +		foreach ($dependents as $dependent) { +			$list .= '<li>' . $dependent->getManifest()->getName() . '</li>'; +		} +		$list .= '</ul>'; + +		register_error(elgg_echo('ElggPlugin:Dependencies:ActiveDependent', array($plugin_name, $list))); + +		return false; +	} +} + +/**   * Initialize the plugin system   * Listens to system init and registers actions   * @@ -1115,6 +1158,10 @@ function plugin_init() {  	run_function_once("plugin_run_once");  	elgg_register_plugin_hook_handler('unit_test', 'system', 'plugins_test'); +	 +	// note - plugins are booted by the time this handler is registered +	// deactivation due to error may have already occurred +	elgg_register_event_handler('deactivate', 'plugin', '_plugins_deactivate_dependency_check');  	elgg_register_action("plugins/settings/save", '', 'admin');  	elgg_register_action("plugins/usersettings/save"); diff --git a/engine/lib/relationships.php b/engine/lib/relationships.php index fe0b8364d..b0cd627fc 100644 --- a/engine/lib/relationships.php +++ b/engine/lib/relationships.php @@ -363,7 +363,7 @@ $relationship_guid = NULL, $inverse_relationship = FALSE) {  /**   * Returns a viewable list of entities by relationship   * - * @param array $options + * @param array $options Options array for retrieval of entities   *   * @see elgg_list_entities()   * @see elgg_get_entities_from_relationship() diff --git a/engine/lib/river.php b/engine/lib/river.php index f2ec1e101..e92040eb7 100644 --- a/engine/lib/river.php +++ b/engine/lib/river.php @@ -120,7 +120,7 @@ $posted = 0, $annotation_id = 0) {   *   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 - *  + *   *   posted_time_lower    => INT     The lower bound on the time posted   *   posted_time_upper    => INT     The upper bound on the time posted   * @@ -380,10 +380,10 @@ function _elgg_prefetch_river_entities(array $river_items) {  	// prefetch objects and subjects  	$guids = array();  	foreach ($river_items as $item) { -		if ($item->subject_guid && !retrieve_cached_entity($item->subject_guid)) { +		if ($item->subject_guid && !_elgg_retrieve_cached_entity($item->subject_guid)) {  			$guids[$item->subject_guid] = true;  		} -		if ($item->object_guid && !retrieve_cached_entity($item->object_guid)) { +		if ($item->object_guid && !_elgg_retrieve_cached_entity($item->object_guid)) {  			$guids[$item->object_guid] = true;  		}  	} @@ -402,7 +402,7 @@ function _elgg_prefetch_river_entities(array $river_items) {  	$guids = array();  	foreach ($river_items as $item) {  		$object = $item->getObjectEntity(); -		if ($object->container_guid && !retrieve_cached_entity($object->container_guid)) { +		if ($object->container_guid && !_elgg_retrieve_cached_entity($object->container_guid)) {  			$guids[$object->container_guid] = true;  		}  	} @@ -434,8 +434,13 @@ function elgg_list_river(array $options = array()) {  		'pagination' => TRUE,  		'list_class' => 'elgg-list-river elgg-river', // @todo remove elgg-river in Elgg 1.9  	); - +	  	$options = array_merge($defaults, $options); +	 +	if (!$options["limit"] && !$options["offset"]) {
 +		// no need for pagination if listing is unlimited
 +		$options["pagination"] = false;
 +	}  	$options['count'] = TRUE;  	$count = elgg_get_river($options); @@ -445,6 +450,7 @@ function elgg_list_river(array $options = array()) {  	$options['count'] = $count;  	$options['items'] = $items; +	  	return elgg_view('page/components/list', $options);  } diff --git a/engine/lib/sessions.php b/engine/lib/sessions.php index a34c2045b..e3d5ce9cd 100644 --- a/engine/lib/sessions.php +++ b/engine/lib/sessions.php @@ -87,6 +87,9 @@ function elgg_is_admin_logged_in() {   */  function elgg_is_admin_user($user_guid) {  	global $CONFIG; + +	$user_guid = (int)$user_guid; +  	// cannot use magic metadata here because of recursion  	// must support the old way of getting admin from metadata @@ -323,6 +326,12 @@ function login(ElggUser $user, $persistent = false) {  	set_last_login($_SESSION['guid']);  	reset_login_failure_count($user->guid); // Reset any previous failed login attempts +	// if memcache is enabled, invalidate the user in memcache @see https://github.com/Elgg/Elgg/issues/3143 +	if (is_memcache_available()) { +		// this needs to happen with a shutdown function because of the timing with set_last_login() +		register_shutdown_function("_elgg_invalidate_memcache_for_entity", $_SESSION['guid']); +	} +	  	return true;  } diff --git a/engine/lib/statistics.php b/engine/lib/statistics.php index 0c9a3c945..4cb0bb0b8 100644 --- a/engine/lib/statistics.php +++ b/engine/lib/statistics.php @@ -95,13 +95,17 @@ function get_number_users($show_deactivated = false) {   * @return string    */  function get_online_users() { -	$count = find_active_users(600, 10, 0, true); -	$objects = find_active_users(600, 10); +	$limit = max(0, (int) get_input("limit", 10)); +	$offset = max(0, (int) get_input("offset", 0)); +	 +	$count = find_active_users(600, $limit, $offset, true); +	$objects = find_active_users(600, $limit, $offset);  	if ($objects) {  		return elgg_view_entity_list($objects, array(  			'count' => $count, -			'limit' => 10, +			'limit' => $limit, +			'offset' => $offset  		));  	}  	return ''; diff --git a/engine/lib/system_log.php b/engine/lib/system_log.php index 5a153afb2..84302632e 100644 --- a/engine/lib/system_log.php +++ b/engine/lib/system_log.php @@ -187,7 +187,16 @@ function system_log($object, $event) {  		$object_subtype = $object->getSubtype();  		$event = sanitise_string($event);  		$time = time(); -		$ip_address = sanitise_string($_SERVER['REMOTE_ADDR']); + +		if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { +			$ip_address = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])); +		} elseif (!empty($_SERVER['HTTP_X_REAL_IP'])) { +			$ip_address = array_pop(explode(',', $_SERVER['HTTP_X_REAL_IP'])); +		} else { +			$ip_address = $_SERVER['REMOTE_ADDR']; +		} +		$ip_address = sanitise_string($ip_address); +  		$performed_by = elgg_get_logged_in_user_guid();  		if (isset($object->access_id)) { diff --git a/engine/lib/upgrade.php b/engine/lib/upgrade.php index d684af862..158ec9ec1 100644 --- a/engine/lib/upgrade.php +++ b/engine/lib/upgrade.php @@ -245,7 +245,7 @@ function version_upgrade() {  	// No version number? Oh snap...this is an upgrade from a clean installation < 1.7.  	// Run all upgrades without error reporting and hope for the best. -	// See http://trac.elgg.org/elgg/ticket/1432 for more. +	// See https://github.com/elgg/elgg/issues/1432 for more.  	$quiet = !$dbversion;  	// Note: Database upgrades are deprecated as of 1.8.  Use code upgrades.  See #1433 @@ -354,16 +354,12 @@ function _elgg_upgrade_unlock() {   * @access private   */  function _elgg_upgrade_is_locked() { -	global $CONFIG, $DB_QUERY_CACHE; -	 +	global $CONFIG; +  	$is_locked = count(get_data("show tables like '{$CONFIG->dbprefix}upgrade_lock'")); -	 -	// Invalidate query cache -	if ($DB_QUERY_CACHE) { -		/* @var ElggStaticVariableCache $DB_QUERY_CACHE */ -		$DB_QUERY_CACHE->clear(); -		elgg_log("Query cache invalidated", 'NOTICE'); -	} -	 + +	// @todo why? +	_elgg_invalidate_query_cache(); +  	return $is_locked;  } diff --git a/engine/lib/upgrades/2009102801.php b/engine/lib/upgrades/2009102801.php index cab9a6835..3ad113fb2 100644 --- a/engine/lib/upgrades/2009102801.php +++ b/engine/lib/upgrades/2009102801.php @@ -203,14 +203,15 @@ function user_file_matrix($guid) {  	return "$time_created/$user->guid/";  } -global $DB_QUERY_CACHE, $DB_PROFILE, $ENTITY_CACHE; +global $ENTITY_CACHE, $CONFIG;  /**   * Upgrade file locations   */  $users = mysql_query("SELECT guid, username  	FROM {$CONFIG->dbprefix}users_entity WHERE username != ''");  while ($user = mysql_fetch_object($users)) { -	$DB_QUERY_CACHE = $DB_PROFILE = $ENTITY_CACHE = array(); +	$ENTITY_CACHE = array(); +	_elgg_invalidate_query_cache();  	$to = $CONFIG->dataroot . user_file_matrix($user->guid);  	foreach (array('1_0', '1_1', '1_6') as $version) { diff --git a/engine/lib/upgrades/2010033101.php b/engine/lib/upgrades/2010033101.php index 0bffee001..4779295fd 100644 --- a/engine/lib/upgrades/2010033101.php +++ b/engine/lib/upgrades/2010033101.php @@ -1,7 +1,7 @@  <?php  /** - * Conditional upgrade for UTF8 as described in http://trac.elgg.org/ticket/1928 + * Conditional upgrade for UTF8 as described in https://github.com/elgg/elgg/issues/1928   */  // get_version() returns the code version. diff --git a/engine/lib/upgrades/2010061501.php b/engine/lib/upgrades/2010061501.php index 9ff7d3102..744c28fd5 100644 --- a/engine/lib/upgrades/2010061501.php +++ b/engine/lib/upgrades/2010061501.php @@ -45,7 +45,7 @@ if ($dbversion < 2009100701) {  			}  		} -		global $DB_QUERY_CACHE, $DB_PROFILE, $ENTITY_CACHE; +		global $ENTITY_CACHE;  		/**  			Upgrade file locations @@ -60,7 +60,9 @@ if ($dbversion < 2009100701) {  		$users = mysql_query("SELECT guid, username FROM {$CONFIG->dbprefix}users_entity  			WHERE username != ''", $link);  		while ($user = mysql_fetch_object($users)) { -			$DB_QUERY_CACHE = $DB_PROFILE = $ENTITY_CACHE = array(); +			$ENTITY_CACHE = array(); +			_elgg_invalidate_query_cache(); +  			$to = $CONFIG->dataroot . user_file_matrix($user->guid);  			foreach (array('1_0', '1_1', '1_6') as $version) { diff --git a/engine/lib/upgrades/2010071001.php b/engine/lib/upgrades/2010071001.php index 1b5d379d8..5594493a8 100644 --- a/engine/lib/upgrades/2010071001.php +++ b/engine/lib/upgrades/2010071001.php @@ -30,11 +30,12 @@ function user_file_matrix_2010071001($guid) {  $sizes = array('large', 'medium', 'small', 'tiny', 'master', 'topbar'); -global $DB_QUERY_CACHE, $DB_PROFILE, $ENTITY_CACHE, $CONFIG; +global $ENTITY_CACHE, $CONFIG;  $users = mysql_query("SELECT guid, username FROM {$CONFIG->dbprefix}users_entity  	WHERE username != ''");  while ($user = mysql_fetch_object($users)) { -	$DB_QUERY_CACHE = $DB_PROFILE = $ENTITY_CACHE = array(); +	$ENTITY_CACHE = array(); +	_elgg_invalidate_query_cache();  	$user_directory = user_file_matrix_2010071001($user->guid);  	if (!$user_directory) { diff --git a/engine/lib/upgrades/2010071002.php b/engine/lib/upgrades/2010071002.php index 30bd6538c..52aa15ef5 100644 --- a/engine/lib/upgrades/2010071002.php +++ b/engine/lib/upgrades/2010071002.php @@ -4,12 +4,13 @@   */  // loop through all users checking collections and notifications -global $DB_QUERY_CACHE, $DB_PROFILE, $ENTITY_CACHE, $CONFIG; +global $ENTITY_CACHE, $CONFIG;  global $NOTIFICATION_HANDLERS;  $users = mysql_query("SELECT guid, username FROM {$CONFIG->dbprefix}users_entity  	WHERE username != ''");  while ($user = mysql_fetch_object($users)) { -	$DB_QUERY_CACHE = $DB_PROFILE = $ENTITY_CACHE = array(); +	$ENTITY_CACHE = array(); +	_elgg_invalidate_query_cache();  	$user = get_entity($user->guid);  	foreach ($NOTIFICATION_HANDLERS as $method => $foo) { diff --git a/engine/lib/upgrades/2011052801.php b/engine/lib/upgrades/2011052801.php index 8084bc06c..b5a8e1018 100644 --- a/engine/lib/upgrades/2011052801.php +++ b/engine/lib/upgrades/2011052801.php @@ -2,7 +2,7 @@  /**   * Make sure all users have the relationship member_of_site   */ -global $DB_QUERY_CACHE, $DB_PROFILE, $ENTITY_CACHE, $CONFIG; +global $ENTITY_CACHE;  $db_prefix = get_config('dbprefix');  $limit = 100; @@ -17,7 +17,8 @@ $q = "SELECT e.* FROM {$db_prefix}entities e  $users = get_data($q);  while ($users) { -	$DB_QUERY_CACHE = $DB_PROFILE = $ENTITY_CACHE = array(); +	$ENTITY_CACHE = array(); +	_elgg_invalidate_query_cache();  	// do manually to not trigger any events because these aren't new users.  	foreach ($users as $user) { diff --git a/engine/lib/upgrades/2012041801-1.8.3-multiple_user_tokens-852225f7fd89f6c5.php b/engine/lib/upgrades/2012041801-1.8.3-multiple_user_tokens-852225f7fd89f6c5.php index 07732f261..780038c32 100644 --- a/engine/lib/upgrades/2012041801-1.8.3-multiple_user_tokens-852225f7fd89f6c5.php +++ b/engine/lib/upgrades/2012041801-1.8.3-multiple_user_tokens-852225f7fd89f6c5.php @@ -3,7 +3,7 @@   * Elgg 1.8.3 upgrade 2012041801   * multiple_user_tokens   * - * Fixes http://trac.elgg.org/ticket/4291 + * Fixes https://github.com/elgg/elgg/issues/4291   * Removes the unique index on users_apisessions for user_guid and site_guid   */ diff --git a/engine/lib/upgrades/2013030600-1.8.13-update_user_location-8999eb8bf1bdd9a3.php b/engine/lib/upgrades/2013030600-1.8.13-update_user_location-8999eb8bf1bdd9a3.php index b38eb5100..8eccf05e2 100644 --- a/engine/lib/upgrades/2013030600-1.8.13-update_user_location-8999eb8bf1bdd9a3.php +++ b/engine/lib/upgrades/2013030600-1.8.13-update_user_location-8999eb8bf1bdd9a3.php @@ -7,8 +7,6 @@   * This script turns that back into a string.   */ -global $DB_QUERY_CACHE; -  $ia = elgg_set_ignore_access(true);  $options = array(  	'type' => 'user', @@ -17,7 +15,7 @@ $options = array(  $batch = new ElggBatch('elgg_get_entities', $options);  foreach ($batch as $entity) { -	$DB_QUERY_CACHE = array(); +	_elgg_invalidate_query_cache();  	if (is_array($entity->location)) {  		$entity->location = implode(', ', $entity->location); diff --git a/engine/lib/upgrades/2013051700-1.8.15-add_missing_group_index-52a63a3a3ffaced2.php b/engine/lib/upgrades/2013051700-1.8.15-add_missing_group_index-52a63a3a3ffaced2.php new file mode 100644 index 000000000..ee99bdbc8 --- /dev/null +++ b/engine/lib/upgrades/2013051700-1.8.15-add_missing_group_index-52a63a3a3ffaced2.php @@ -0,0 +1,28 @@ +<?php +/** + * Elgg 1.8.15 upgrade 2013051700 + * add_missing_group_index + * + * Some Elgg sites are missing the groups_entity full text index on name and + * description. This checks if it exists and adds it if it does not. + */ + +$db_prefix = elgg_get_config('dbprefix'); + +$full_text_index_exists = false; +$results = get_data("SHOW INDEX FROM {$db_prefix}groups_entity"); +if ($results) { +	foreach ($results as $result) { +		if ($result->Index_type === 'FULLTEXT') { +			$full_text_index_exists = true; +		} +	} +} + +if ($full_text_index_exists == false) { +	$query = "ALTER TABLE {$db_prefix}groups_entity  +		ADD FULLTEXT name_2 (name, description)"; +	if (!update_data($query)) { +		elgg_log("Failed to add full text index to groups_entity table", 'ERROR'); +	} +} diff --git a/engine/lib/upgrades/2013052900-1.8.15-ipv6_in_syslog-f5c2cc0196e9e731.php b/engine/lib/upgrades/2013052900-1.8.15-ipv6_in_syslog-f5c2cc0196e9e731.php new file mode 100644 index 000000000..d333a6cd2 --- /dev/null +++ b/engine/lib/upgrades/2013052900-1.8.15-ipv6_in_syslog-f5c2cc0196e9e731.php @@ -0,0 +1,12 @@ +<?php +/** + * Elgg 1.8.15 upgrade 2013052900 + * ipv6_in_syslog + * + * Upgrade the ip column in system_log to be able to store ipv6 addresses + */ + +$db_prefix = elgg_get_config('dbprefix'); +$q = "ALTER TABLE {$db_prefix}system_log MODIFY COLUMN ip_address varchar(46) NOT NULL"; + +update_data($q);
\ No newline at end of file diff --git a/engine/lib/upgrades/2013060900-1.8.15-site_secret-404fc165cf9e0ac9.php b/engine/lib/upgrades/2013060900-1.8.15-site_secret-404fc165cf9e0ac9.php new file mode 100644 index 000000000..538d74dd6 --- /dev/null +++ b/engine/lib/upgrades/2013060900-1.8.15-site_secret-404fc165cf9e0ac9.php @@ -0,0 +1,16 @@ +<?php +/** + * Elgg 1.8.15 upgrade 2013060900 + * site_secret + * + * Description + */ + +$strength = _elgg_get_site_secret_strength(); + +if ($strength !== 'strong') { +	// a new key is needed immediately +	register_translations(elgg_get_root_path() . 'languages/'); + +	elgg_add_admin_notice('weak_site_key', elgg_echo("upgrade:site_secret_warning:$strength")); +} diff --git a/engine/lib/user_settings.php b/engine/lib/user_settings.php index 3466c25f9..0e36dc46d 100644 --- a/engine/lib/user_settings.php +++ b/engine/lib/user_settings.php @@ -308,7 +308,7 @@ function usersettings_page_handler($page) {  		$user = get_user_by_username($page[1]);  		elgg_set_page_owner_guid($user->guid);  	} else { -		$user = elgg_get_logged_in_user_guid(); +		$user = elgg_get_logged_in_user_entity();  		elgg_set_page_owner_guid($user->guid);  	} diff --git a/engine/lib/users.php b/engine/lib/users.php index 4a585c07f..a8fb9121c 100644 --- a/engine/lib/users.php +++ b/engine/lib/users.php @@ -237,7 +237,7 @@ function make_user_admin($user_guid) {  			}  			$r = update_data("UPDATE {$CONFIG->dbprefix}users_entity set admin='yes' where guid=$user_guid"); -			invalidate_cache_for_entity($user_guid); +			_elgg_invalidate_cache_for_entity($user_guid);  			return $r;  		} @@ -273,7 +273,7 @@ function remove_user_admin($user_guid) {  			}  			$r = update_data("UPDATE {$CONFIG->dbprefix}users_entity set admin='no' where guid=$user_guid"); -			invalidate_cache_for_entity($user_guid); +			_elgg_invalidate_cache_for_entity($user_guid);  			return $r;  		} @@ -553,13 +553,18 @@ function get_user($guid) {  function get_user_by_username($username) {  	global $CONFIG, $USERNAME_TO_GUID_MAP_CACHE; +	// Fixes #6052. Username is frequently sniffed from the path info, which, +	// unlike $_GET, is not URL decoded. If the username was not URL encoded, +	// this is harmless. +	$username = rawurldecode($username); +  	$username = sanitise_string($username);  	$access = get_access_sql_suffix('e');  	// Caching  	if ((isset($USERNAME_TO_GUID_MAP_CACHE[$username])) -			&& (retrieve_cached_entity($USERNAME_TO_GUID_MAP_CACHE[$username]))) { -		return retrieve_cached_entity($USERNAME_TO_GUID_MAP_CACHE[$username]); +			&& (_elgg_retrieve_cached_entity($USERNAME_TO_GUID_MAP_CACHE[$username]))) { +		return _elgg_retrieve_cached_entity($USERNAME_TO_GUID_MAP_CACHE[$username]);  	}  	$query = "SELECT e.* from {$CONFIG->dbprefix}users_entity u @@ -592,9 +597,9 @@ function get_user_by_code($code) {  	// Caching  	if ((isset($CODE_TO_GUID_MAP_CACHE[$code])) -	&& (retrieve_cached_entity($CODE_TO_GUID_MAP_CACHE[$code]))) { +	&& (_elgg_retrieve_cached_entity($CODE_TO_GUID_MAP_CACHE[$code]))) { -		return retrieve_cached_entity($CODE_TO_GUID_MAP_CACHE[$code]); +		return _elgg_retrieve_cached_entity($CODE_TO_GUID_MAP_CACHE[$code]);  	}  	$query = "SELECT e.* from {$CONFIG->dbprefix}users_entity u @@ -705,18 +710,18 @@ function send_new_password_request($user_guid) {   * @return bool   */  function force_user_password_reset($user_guid, $password) { -	global $CONFIG; -  	$user = get_entity($user_guid);  	if ($user instanceof ElggUser) { -		$salt = generate_random_cleartext_password(); // Reset the salt -		$user->salt = $salt; +		$ia = elgg_set_ignore_access(); -		$hash = generate_user_password($user, $password); +		$user->salt = generate_random_cleartext_password(); +		$hash = generate_user_password($user, $password);		 +		$user->password = $hash; +		$result = (bool)$user->save(); -		$query = "UPDATE {$CONFIG->dbprefix}users_entity -			set password='$hash', salt='$salt' where guid=$user_guid"; -		return update_data($query); +		elgg_set_ignore_access($ia); + +		return $result;  	}  	return false; @@ -1091,6 +1096,7 @@ function friends_page_handler($segments, $handler) {   * @access private   */  function collections_page_handler($page_elements) { +	gatekeeper();  	elgg_set_context('friends');  	$base = elgg_get_config('path');  	if (isset($page_elements[0])) { diff --git a/engine/lib/views.php b/engine/lib/views.php index cfceccec0..1142461fe 100644 --- a/engine/lib/views.php +++ b/engine/lib/views.php @@ -218,7 +218,7 @@ function elgg_register_ajax_view($view) {  /**   * Unregister a view for ajax calls - *  + *   * @param string $view The view name   * @return void   * @since 1.8.3 @@ -369,7 +369,7 @@ function elgg_view_exists($view, $viewtype = '', $recurse = true) {   * view, $view_name plugin hook.   *   * @warning Any variables in $_SESSION will override passed vars - * upon name collision.  See {@trac #2124}. + * upon name collision.  See https://github.com/Elgg/Elgg/issues/2124   *   * @param string  $view     The name and location of the view to use   * @param array   $vars     Variables to pass to the view. @@ -795,7 +795,7 @@ function elgg_view_menu($menu_name, array $vars = array()) {   *  - bool 'full_view' Whether to show a full or condensed view.   *   * @tip This function can automatically appends annotations to entities if in full - * view and a handler is registered for the entity:annotate.  See {@trac 964} and + * view and a handler is registered for the entity:annotate.  See https://github.com/Elgg/Elgg/issues/964 and   * {@link elgg_view_entity_annotations()}.   *   * @param ElggEntity $entity The entity to display @@ -992,6 +992,11 @@ function elgg_view_annotation(ElggAnnotation $annotation, array $vars = array(),  function elgg_view_entity_list($entities, $vars = array(), $offset = 0, $limit = 10, $full_view = true,  $list_type_toggle = true, $pagination = true) { +	if (!$vars["limit"] && !$vars["offset"]) { +		// no need for pagination if listing is unlimited
 +		$vars["pagination"] = false;
 +	}
 +		  	if (!is_int($offset)) {  		$offset = (int)get_input('offset', 0);  	} @@ -1064,8 +1069,13 @@ function elgg_view_annotation_list($annotations, array $vars = array()) {  		'full_view' => true,  		'offset_key' => 'annoff',  	); - +	  	$vars = array_merge($defaults, $vars); +	 +	if (!$vars["limit"] && !$vars["offset"]) {
 +		// no need for pagination if listing is unlimited
 +		$vars["pagination"] = false;
 +	}  	return elgg_view('page/components/list', $vars);  } @@ -1107,7 +1117,7 @@ function elgg_view_entity_annotations(ElggEntity $entity, $full_view = true) {   * This is a shortcut for {@elgg_view page/elements/title}.   *   * @param string $title The page title - * @param array $vars   View variables (was submenu be displayed? (deprecated)) + * @param array  $vars  View variables (was submenu be displayed? (deprecated))   *   * @return string The HTML (etc)   */ @@ -1179,7 +1189,7 @@ function elgg_view_comments($entity, $add_comment = true, array $vars = array())   *   * @param string $image The icon and other information   * @param string $body  Description content - * @param array $vars   Additional parameters for the view + * @param array  $vars  Additional parameters for the view   *   * @return string   * @since 1.8.0 @@ -1236,15 +1246,17 @@ function elgg_view_river_item($item, array $vars = array()) {  		// subject is disabled or subject/object deleted  		return '';  	} + +	// @todo this needs to be cleaned up  	// Don't hide objects in closed groups that a user can see. -	// see http://trac.elgg.org/ticket/4789 -//	else { -//		// hide based on object's container -//		$visibility = ElggGroupItemVisibility::factory($object->container_guid); -//		if ($visibility->shouldHideItems) { -//			return ''; -//		} -//	} +	// see https://github.com/elgg/elgg/issues/4789 +	//	else { +	//		// hide based on object's container +	//		$visibility = ElggGroupItemVisibility::factory($object->container_guid); +	//		if ($visibility->shouldHideItems) { +	//			return ''; +	//		} +	//	}  	$vars['item'] = $item; @@ -1332,12 +1344,12 @@ function elgg_view_list_item($item, array $vars = array()) {  /**   * View one of the elgg sprite icons - *  + *   * Shorthand for <span class="elgg-icon elgg-icon-$name"></span> - *  + *   * @param string $name  The specific icon to display   * @param string $class Additional class: float, float-alt, or custom class - *  + *   * @return string The html for displaying an icon   */  function elgg_view_icon($name, $class = '') { @@ -1636,7 +1648,7 @@ function elgg_views_boot() {  	}  	// set default icon sizes - can be overridden in settings.php or with plugin -	if (!$CONFIG->icon_sizes) { +	if (!isset($CONFIG->icon_sizes)) {  		$icon_sizes = array(  			'topbar' => array('w' => 16, 'h' => 16, 'square' => TRUE, 'upscale' => TRUE),  			'tiny' => array('w' => 25, 'h' => 25, 'square' => TRUE, 'upscale' => TRUE), diff --git a/engine/lib/web_services.php b/engine/lib/web_services.php index b440e3afb..51cad6f39 100644 --- a/engine/lib/web_services.php +++ b/engine/lib/web_services.php @@ -1166,6 +1166,17 @@ function list_all_apis() {   * @access private   */  function auth_gettoken($username, $password) { +	// check if username is an email address
 +	if (is_email_address($username)) {
 +		$users = get_user_by_email($username);
 +			
 +		// check if we have a unique user
 +		if (is_array($users) && (count($users) == 1)) {
 +			$username = $users[0]->username;
 +		}
 +	}
 +	
 +	// validate username and password  	if (true === elgg_authenticate($username, $password)) {  		$token = create_user_token($username);  		if ($token) { @@ -1195,7 +1206,7 @@ $ERRORS = array();   *   * @return void   * @access private - *  + *   * @throws Exception   */  function _php_api_error_handler($errno, $errmsg, $filename, $linenum, $vars) { diff --git a/engine/schema/mysql.sql b/engine/schema/mysql.sql index 6c6e9db89..4714b71bb 100644 --- a/engine/schema/mysql.sql +++ b/engine/schema/mysql.sql @@ -361,7 +361,7 @@ CREATE TABLE `prefix_system_log` (    `access_id` int(11) NOT NULL,    `enabled` enum('yes','no') NOT NULL DEFAULT 'yes',    `time_created` int(11) NOT NULL, -  `ip_address` varchar(15) NOT NULL, +  `ip_address` varchar(46) NOT NULL,    PRIMARY KEY (`id`),    KEY `object_id` (`object_id`),    KEY `object_class` (`object_class`), diff --git a/engine/tests/api/access_collections.php b/engine/tests/api/access_collections.php index ebcd7d318..4acfae596 100644 --- a/engine/tests/api/access_collections.php +++ b/engine/tests/api/access_collections.php @@ -54,7 +54,6 @@ class ElggCoreAccessCollectionsTest extends ElggCoreUnitTest {  	}  	public function testCreateGetDeleteACL() { -		global $DB_QUERY_CACHE;  		$acl_name = 'test access collection';  		$acl_id = create_access_collection($acl_name); @@ -67,8 +66,6 @@ class ElggCoreAccessCollectionsTest extends ElggCoreUnitTest {  		$this->assertEqual($acl->id, $acl_id);  		if ($acl) { -			$DB_QUERY_CACHE = array(); -			  			$this->assertEqual($acl->name, $acl_name);  			$result = delete_access_collection($acl_id); diff --git a/engine/tests/api/annotations.php b/engine/tests/api/annotations.php index 947292970..c0b0687cc 100644 --- a/engine/tests/api/annotations.php +++ b/engine/tests/api/annotations.php @@ -65,6 +65,86 @@ class ElggCoreAnnotationAPITest extends ElggCoreUnitTest {  		$annotations = elgg_get_annotations($options);  		$this->assertTrue(empty($annotations)); +		// nothing to delete so null returned +		$this->assertNull(elgg_delete_annotations($options)); + +		$this->assertTrue($e->delete()); +	} + +	public function testElggDisableAnnotations() { +		$e = new ElggObject(); +		$e->save(); + +		for ($i=0; $i<30; $i++) { +			$e->annotate('test_annotation', rand(0,10000)); +		} + +		$options = array( +			'guid' => $e->getGUID(), +			'limit' => 0 +		); + +		$this->assertTrue(elgg_disable_annotations($options)); + +		$annotations = elgg_get_annotations($options); +		$this->assertTrue(empty($annotations)); + +		access_show_hidden_entities(true); +		$annotations = elgg_get_annotations($options); +		$this->assertIdentical(30, count($annotations)); +		access_show_hidden_entities(false); + +		$this->assertTrue($e->delete()); +	} + +	public function testElggEnableAnnotations() { +		$e = new ElggObject(); +		$e->save(); + +		for ($i=0; $i<30; $i++) { +			$e->annotate('test_annotation', rand(0,10000)); +		} + +		$options = array( +			'guid' => $e->getGUID(), +			'limit' => 0 +		); + +		$this->assertTrue(elgg_disable_annotations($options)); + +		// cannot see any annotations so returns null +		$this->assertNull(elgg_enable_annotations($options)); + +		access_show_hidden_entities(true); +		$this->assertTrue(elgg_enable_annotations($options)); +		access_show_hidden_entities(false); + +		$annotations = elgg_get_annotations($options); +		$this->assertIdentical(30, count($annotations)); + +		$this->assertTrue($e->delete()); +	} + +	public function testElggAnnotationExists() { +		$e = new ElggObject(); +		$e->save(); +		$guid = $e->getGUID(); + +		$this->assertFalse(elgg_annotation_exists($guid, 'test_annotation')); + +		$e->annotate('test_annotation', rand(0, 10000)); +		$this->assertTrue(elgg_annotation_exists($guid, 'test_annotation')); +		// this metastring should always exist but an annotation of this name should not +		$this->assertFalse(elgg_annotation_exists($guid, 'email')); + +		$options = array( +			'guid' => $guid, +			'limit' => 0 +		); +		$this->assertTrue(elgg_disable_annotations($options)); +		$this->assertTrue(elgg_annotation_exists($guid, 'test_annotation')); +  		$this->assertTrue($e->delete()); +		$this->assertFalse(elgg_annotation_exists($guid, 'test_annotation'));  	}  } diff --git a/engine/tests/api/entity_getter_functions.php b/engine/tests/api/entity_getter_functions.php index 7bf8ef04a..fef9dc0c5 100644 --- a/engine/tests/api/entity_getter_functions.php +++ b/engine/tests/api/entity_getter_functions.php @@ -426,7 +426,7 @@ class ElggCoreEntityGetterFunctionsTest extends ElggCoreUnitTest {  		$options = array(  			'types' => $types, -			'subtype' => $subtype +			'subtypes' => $subtype  		);  		$es = elgg_get_entities($options); @@ -2755,7 +2755,7 @@ class ElggCoreEntityGetterFunctionsTest extends ElggCoreUnitTest {  			'calculation' => 'count',  			'count' => true,  		); -		$count = (int)elgg_get_entities_from_annotation_calculation($options); +		$count = elgg_get_entities_from_annotation_calculation($options);  		$this->assertEqual(1, $count);  	} diff --git a/engine/tests/api/helpers.php b/engine/tests/api/helpers.php index 62e4471e0..414fb4145 100644 --- a/engine/tests/api/helpers.php +++ b/engine/tests/api/helpers.php @@ -519,7 +519,7 @@ class ElggCoreHelpersTest extends ElggCoreUnitTest {  		$this->assertIdentical($elements_sorted_string, $test_elements);  	} -	// see http://trac.elgg.org/ticket/4288 +	// see https://github.com/elgg/elgg/issues/4288  	public function testElggBatchIncOffset() {  		// normal increment  		$options = array( @@ -578,6 +578,107 @@ class ElggCoreHelpersTest extends ElggCoreUnitTest {  		$this->assertEqual(11, $j);  	} +	public function testElggBatchReadHandlesBrokenEntities() { +		$num_test_entities = 8; +		$guids = array(); +		for ($i = $num_test_entities; $i > 0; $i--) { +			$entity = new ElggObject(); +			$entity->type = 'object'; +			$entity->subtype = 'test_5357_subtype'; +			$entity->access_id = ACCESS_PUBLIC; +			$entity->save(); +			$guids[] = $entity->guid; +			_elgg_invalidate_cache_for_entity($entity->guid); +		} + +		// break entities such that the first fetch has one incomplete +		// and the second and third fetches have only incompletes! +		$db_prefix = elgg_get_config('dbprefix'); +		delete_data(" +			DELETE FROM {$db_prefix}objects_entity +			WHERE guid IN ({$guids[1]}, {$guids[2]}, {$guids[3]}, {$guids[4]}, {$guids[5]}) +		"); + +		$options = array( +			'type' => 'object', +			'subtype' => 'test_5357_subtype', +			'order_by' => 'e.guid', +		); + +		$entities_visited = array(); +		$batch = new ElggBatch('elgg_get_entities', $options, null, 2); +		/* @var ElggEntity[] $batch */ +		foreach ($batch as $entity) { +			$entities_visited[] = $entity->guid; +		} + +		// The broken entities should not have been visited +		$this->assertEqual($entities_visited, array($guids[0], $guids[6], $guids[7])); + +		// cleanup (including leftovers from previous tests) +		$entity_rows = elgg_get_entities(array_merge($options, array( +			'callback' => '', +			'limit' => false, +		))); +		$guids = array(); +		foreach ($entity_rows as $row) { +			$guids[] = $row->guid; +		} +		delete_data("DELETE FROM {$db_prefix}entities WHERE guid IN (" . implode(',', $guids) . ")"); +		delete_data("DELETE FROM {$db_prefix}objects_entity WHERE guid IN (" . implode(',', $guids) . ")"); +	} + +	public function testElggBatchDeleteHandlesBrokenEntities() { +		$num_test_entities = 8; +		$guids = array(); +		for ($i = $num_test_entities; $i > 0; $i--) { +			$entity = new ElggObject(); +			$entity->type = 'object'; +			$entity->subtype = 'test_5357_subtype'; +			$entity->access_id = ACCESS_PUBLIC; +			$entity->save(); +			$guids[] = $entity->guid; +			_elgg_invalidate_cache_for_entity($entity->guid); +		} + +		// break entities such that the first fetch has one incomplete +		// and the second and third fetches have only incompletes! +		$db_prefix = elgg_get_config('dbprefix'); +		delete_data(" +			DELETE FROM {$db_prefix}objects_entity +			WHERE guid IN ({$guids[1]}, {$guids[2]}, {$guids[3]}, {$guids[4]}, {$guids[5]}) +		"); + +		$options = array( +			'type' => 'object', +			'subtype' => 'test_5357_subtype', +			'order_by' => 'e.guid', +		); + +		$entities_visited = array(); +		$batch = new ElggBatch('elgg_get_entities', $options, null, 2, false); +		/* @var ElggEntity[] $batch */ +		foreach ($batch as $entity) { +			$entities_visited[] = $entity->guid; +			$entity->delete(); +		} + +		// The broken entities should not have been visited +		$this->assertEqual($entities_visited, array($guids[0], $guids[6], $guids[7])); + +		// cleanup (including leftovers from previous tests) +		$entity_rows = elgg_get_entities(array_merge($options, array( +			'callback' => '', +			'limit' => false, +		))); +		$guids = array(); +		foreach ($entity_rows as $row) { +			$guids[] = $row->guid; +		} +		delete_data("DELETE FROM {$db_prefix}entities WHERE guid IN (" . implode(',', $guids) . ")"); +		delete_data("DELETE FROM {$db_prefix}objects_entity WHERE guid IN (" . implode(',', $guids) . ")"); +	} +  	static function elgg_batch_callback_test($options, $reset = false) {  		static $count = 1; diff --git a/engine/tests/api/metadata.php b/engine/tests/api/metadata.php index 825290d80..d23510c6a 100644 --- a/engine/tests/api/metadata.php +++ b/engine/tests/api/metadata.php @@ -123,9 +123,23 @@ class ElggCoreMetadataAPITest extends ElggCoreUnitTest {  		$e->delete();  	} +	/** +	 * https://github.com/Elgg/Elgg/issues/4867 +	 */ +	public function testElggGetEntityMetadataWhereSqlWithFalseValue() { +		$pair = array('name' => 'test' , 'value' => false); +		$result = elgg_get_entity_metadata_where_sql('e', 'metadata', null, null, $pair); +		$where = preg_replace( '/\s+/', ' ', $result['wheres'][0]); +		$this->assertTrue(strpos($where, "msn1.string = 'test' AND BINARY msv1.string = 0") > 0); + +		$result = elgg_get_entity_metadata_where_sql('e', 'metadata', array('test'), array(false)); +		$where = preg_replace( '/\s+/', ' ', $result['wheres'][0]); +		$this->assertTrue(strpos($where, "msn.string IN ('test')) AND ( BINARY msv.string IN ('0')")); +	} +  	// Make sure metadata with multiple values is correctly deleted when re-written  	// by another user -	// http://trac.elgg.org/ticket/2776 +	// https://github.com/elgg/elgg/issues/2776  	public function test_elgg_metadata_multiple_values() {  		$u1 = new ElggUser();  		$u1->username = rand(); diff --git a/engine/tests/api/metadata_cache.php b/engine/tests/api/metadata_cache.php index 846116a7b..7fb328169 100644 --- a/engine/tests/api/metadata_cache.php +++ b/engine/tests/api/metadata_cache.php @@ -166,4 +166,11 @@ class ElggCoreMetadataCacheTest extends ElggCoreUnitTest {  		$actual = $this->cache->filterMetadataHeavyEntities($guids, 6000);  		$this->assertIdentical($actual, $expected);  	} + +	public function testCreateMetadataInvalidates() { +		$this->obj1->foo = 1; +		create_metadata($this->guid1, 'foo', 2, '', elgg_get_logged_in_user_guid(), ACCESS_FRIENDS); + +		$this->assertEqual($this->obj1->foo, 2); +	}  } diff --git a/engine/tests/api/metastrings.php b/engine/tests/api/metastrings.php index 0a8945084..5efdab972 100644 --- a/engine/tests/api/metastrings.php +++ b/engine/tests/api/metastrings.php @@ -55,8 +55,11 @@ class ElggCoreMetastringsTest extends ElggCoreUnitTest {  	 * Called after each test method.  	 */  	public function tearDown() { -		// do not allow SimpleTest to interpret Elgg notices as exceptions -		$this->swallowErrors(); +		access_show_hidden_entities(true); +		elgg_delete_annotations(array( +			'guid' => $this->object->guid, +		)); +		access_show_hidden_entities(false);  	}  	/** @@ -98,6 +101,31 @@ class ElggCoreMetastringsTest extends ElggCoreUnitTest {  		}  	} +	public function testGetMetastringObjectFromIDWithDisabledAnnotation() { +		$name = 'test_annotation_name' . rand(); +		$value = 'test_annotation_value' . rand(); +		$id = create_annotation($this->object->guid, $name, $value); +		$annotation = elgg_get_annotation_from_id($id); +		$this->assertTrue($annotation->disable()); + +		$test = elgg_get_metastring_based_object_from_id($id, 'annotation'); +		$this->assertEqual(false, $test); +	} + +	public function testGetMetastringBasedObjectWithDisabledAnnotation() { +		$name = 'test_annotation_name' . rand(); +		$value = 'test_annotation_value' . rand(); +		$id = create_annotation($this->object->guid, $name, $value); +		$annotation = elgg_get_annotation_from_id($id); +		$this->assertTrue($annotation->disable()); + +		$test = elgg_get_metastring_based_objects(array( +			'metastring_type' => 'annotations', +			'guid' => $this->object->guid, +		)); +		$this->assertEqual(array(), $test); +	} +  	public function testEnableDisableByID() {  		$db_prefix = elgg_get_config('dbprefix');  		$annotations = $this->createAnnotations(1); @@ -119,7 +147,6 @@ class ElggCoreMetastringsTest extends ElggCoreUnitTest {  			// enable  			$ashe = access_get_show_hidden_status();  			access_show_hidden_entities(true); -			flush();  			$this->assertTrue(elgg_set_metastring_based_object_enabled_by_id($id, 'yes', $type));  			$test = get_data($q); diff --git a/engine/tests/api/plugins.php b/engine/tests/api/plugins.php index 114f3991b..d0f111c48 100644 --- a/engine/tests/api/plugins.php +++ b/engine/tests/api/plugins.php @@ -69,7 +69,7 @@ class ElggCorePluginsAPITest extends ElggCoreUnitTest {  			'description' => 'A longer, more interesting description.',  			'website' => 'http://www.elgg.org/',  			'repository' => 'https://github.com/Elgg/Elgg', -			'bugtracker' => 'http://trac.elgg.org', +			'bugtracker' => 'https://github.com/elgg/elgg/issues',  			'donations' => 'http://elgg.org/supporter.php',  			'copyright' => '(C) Elgg Foundation 2011',  			'license' => 'GNU General Public License version 2', @@ -174,7 +174,7 @@ class ElggCorePluginsAPITest extends ElggCoreUnitTest {  	}  		public function testElggPluginManifestGetBugtracker() { -		$this->assertEqual($this->manifest18->getBugTrackerURL(), 'http://trac.elgg.org'); +		$this->assertEqual($this->manifest18->getBugTrackerURL(), 'https://github.com/elgg/elgg/issues');  		$this->assertEqual($this->manifest17->getBugTrackerURL(), '');  	} diff --git a/engine/tests/objects/entities.php b/engine/tests/objects/entities.php index 248b85c9e..bac72079e 100644 --- a/engine/tests/objects/entities.php +++ b/engine/tests/objects/entities.php @@ -271,7 +271,7 @@ class ElggCoreEntityTest extends ElggCoreUnitTest {  		$this->save_entity();  		// test deleting incorrectly -		// @link http://trac.elgg.org/ticket/2273 +		// @link https://github.com/elgg/elgg/issues/2273  		$this->assertNull($this->entity->deleteMetadata('impotent'));  		$this->assertEqual($this->entity->important, 'indeed!'); diff --git a/engine/tests/objects/objects.php b/engine/tests/objects/objects.php index 915594e0a..263ab2414 100644 --- a/engine/tests/objects/objects.php +++ b/engine/tests/objects/objects.php @@ -194,7 +194,7 @@ class ElggCoreObjectTest extends ElggCoreUnitTest {  		$old = elgg_set_ignore_access(true);  	} -	// see http://trac.elgg.org/ticket/1196 +	// see https://github.com/elgg/elgg/issues/1196  	public function testElggEntityRecursiveDisableWhenLoggedOut() {  		$e1 = new ElggObject();  		$e1->access_id = ACCESS_PUBLIC; diff --git a/engine/tests/objects/users.php b/engine/tests/objects/users.php index a3573acb6..8a1033ac4 100644 --- a/engine/tests/objects/users.php +++ b/engine/tests/objects/users.php @@ -65,6 +65,9 @@ class ElggCoreUserTest extends ElggCoreUnitTest {  		$attributes['code'] = NULL;  		$attributes['banned'] = 'no';  		$attributes['admin'] = 'no'; +		$attributes['prev_last_action'] = NULL; +		$attributes['last_login'] = NULL; +		$attributes['prev_last_login'] = NULL;  		ksort($attributes);  		$entity_attributes = $this->user->expose_attributes(); @@ -142,7 +145,7 @@ class ElggCoreUserTest extends ElggCoreUnitTest {  	}  	public function testElggUserNameCache() { -		// Trac #1305 +		// issue https://github.com/elgg/elgg/issues/1305  		// very unlikely a user would have this username  		$name = (string)time(); @@ -156,6 +159,22 @@ class ElggCoreUserTest extends ElggCoreUnitTest {  		$this->assertFalse($user);  	} +	public function testGetUserByUsernameAcceptsUrlEncoded() { +		$username = (string)time(); +		$this->user->username = $username; +		$guid = $this->user->save(); + +		// percent encode first letter +		$first_letter = $username[0]; +		$first_letter = str_pad('%' . dechex(ord($first_letter)), 2, '0', STR_PAD_LEFT); +		$username =   $first_letter . substr($username, 1); + +		$user = get_user_by_username($username); +		$this->assertTrue((bool) $user); +		$this->assertEqual($guid, $user->guid); + +		$this->user->delete(); +	}  	public function testElggUserMakeAdmin() {  		global $CONFIG; diff --git a/engine/tests/regression/trac_bugs.php b/engine/tests/regression/trac_bugs.php index 691433a41..689275661 100644 --- a/engine/tests/regression/trac_bugs.php +++ b/engine/tests/regression/trac_bugs.php @@ -1,7 +1,7 @@  <?php  /** - * Elgg Regression Tests -- Trac Bugfixes - * Any bugfixes from Trac that require testing belong here. + * Elgg Regression Tests -- GitHub Bugfixes + * Any bugfixes from GitHub that require testing belong here.   *   * @package Elgg   * @subpackage Test @@ -201,26 +201,28 @@ class ElggCoreRegressionBugsTest extends ElggCoreUnitTest {  	}  	/** -	 * http://trac.elgg.org/ticket/3210 - Don't remove -s in friendly titles -	 * http://trac.elgg.org/ticket/2276 - improve char encoding +	 * https://github.com/elgg/elgg/issues/3210 - Don't remove -s in friendly titles +	 * https://github.com/elgg/elgg/issues/2276 - improve char encoding  	 */  	public function test_friendly_title() {  		$cases = array( +			// acid test +			"B&N > Amazon, OK? <bold> 'hey!' $34" +			=> "bn-amazon-ok-bold-hey-34", +  			// hyphen, underscore and ASCII whitespace replaced by separator,  			// other non-alphanumeric ASCII removed -			"a-a_a a\na\ra\ta\va!a\"a#a\$a%a&a'a(a)a*a+a,a.a/a:a;a<a=a>a?a@a[a\\a]a^a`a{a|a}a~a" -			=> "a-a-a-a-a-a-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - +			"a-a_a a\na\ra\ta\va!a\"a#a\$a%aa'a(a)a*a+a,a.a/a:a;a=a?a@a[a\\a]a^a`a{a|a}a~a" +			=> "a-a-a-a-a-a-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", +			  			// separators trimmed -			"-_ hello _-" => "hello", +			"-_ hello _-" +			=> "hello",  			// accents removed, lower case, other multibyte chars are URL encoded  			"I\xC3\xB1t\xC3\xABrn\xC3\xA2ti\xC3\xB4n\xC3\xA0liz\xC3\xA6ti\xC3\xB8n, AND \xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E"  				// Iñtërnâtiônàlizætiøn, AND 日本語  			=> 'internationalizaetion-and-%E6%97%A5%E6%9C%AC%E8%AA%9E', - -			// some HTML entity replacements -			"Me & You" => 'me-and-you',  		);  		// where available, string is converted to NFC before transliteration @@ -234,4 +236,170 @@ class ElggCoreRegressionBugsTest extends ElggCoreUnitTest {  			$this->assertIdentical($expected, $friendly_title);  		}  	} + +	/** +	 * Test #5369 -- parse_urls() +	 * https://github.com/Elgg/Elgg/issues/5369 +	 */ +	public function test_parse_urls() { + +		$cases = array( +			'no.link.here' => +				'no.link.here', +			'simple link http://example.org test' => +				'simple link <a href="http://example.org" rel="nofollow">http:/<wbr />/<wbr />example.org</a> test', +			'non-ascii http://ñew.org/ test' => +				'non-ascii <a href="http://ñew.org/" rel="nofollow">http:/<wbr />/<wbr />ñew.org/<wbr /></a> test', + +			// section 2.1 +			'percent encoded http://example.org/a%20b test' => +				'percent encoded <a href="http://example.org/a%20b" rel="nofollow">http:/<wbr />/<wbr />example.org/<wbr />a%20b</a> test', +			// section 2.2: skipping single quote and parenthese +			'reserved characters http://example.org/:/?#[]@!$&*+,;= test' => +				'reserved characters <a href="http://example.org/:/?#[]@!$&*+,;=" rel="nofollow">http:/<wbr />/<wbr />example.org/<wbr />:/<wbr />?#[]@!$&*+,;=</a> test', +			// section 2.3 +			'unreserved characters http://example.org/a1-._~ test' => +				'unreserved characters <a href="http://example.org/a1-._~" rel="nofollow">http:/<wbr />/<wbr />example.org/<wbr />a1-._~</a> test', + +			'parameters http://example.org/?val[]=1&val[]=2 test' => +				'parameters <a href="http://example.org/?val[]=1&val[]=2" rel="nofollow">http:/<wbr />/<wbr />example.org/<wbr />?val[]=1&val[]=2</a> test', +			'port http://example.org:80/ test' => +				'port <a href="http://example.org:80/" rel="nofollow">http:/<wbr />/<wbr />example.org:80/<wbr /></a> test', + +			'parentheses (http://www.google.com) test' => +				'parentheses (<a href="http://www.google.com" rel="nofollow">http:/<wbr />/<wbr />www.google.com</a>) test', +			'comma http://elgg.org, test' => +				'comma <a href="http://elgg.org" rel="nofollow">http:/<wbr />/<wbr />elgg.org</a>, test', +			'period http://elgg.org. test' => +				'period <a href="http://elgg.org" rel="nofollow">http:/<wbr />/<wbr />elgg.org</a>. test', +			'exclamation http://elgg.org! test' => +				'exclamation <a href="http://elgg.org" rel="nofollow">http:/<wbr />/<wbr />elgg.org</a>! test', + +			'already anchor <a href="http://twitter.com/">twitter</a> test' => +				'already anchor <a href="http://twitter.com/">twitter</a> test', + +			'ssl https://example.org/ test' => +				'ssl <a href="https://example.org/" rel="nofollow">https:/<wbr />/<wbr />example.org/<wbr /></a> test', +			'ftp ftp://example.org/ test' => +				'ftp <a href="ftp://example.org/" rel="nofollow">ftp:/<wbr />/<wbr />example.org/<wbr /></a> test', + +			'web archive anchor <a href="http://web.archive.org/web/20000229040250/http://www.google.com/">google</a>' => +				'web archive anchor <a href="http://web.archive.org/web/20000229040250/http://www.google.com/">google</a>', + +			'single quotes already anchor <a href=\'http://www.yahoo.com\'>yahoo</a>' => +				'single quotes already anchor <a href=\'http://www.yahoo.com\'>yahoo</a>', + +			'unquoted already anchor <a href=http://www.yahoo.com>yahoo</a>' => +				'unquoted already anchor <a href=http://www.yahoo.com>yahoo</a>', + +			'parens in uri http://thedailywtf.com/Articles/A-(Long-Overdue)-BuildMaster-Introduction.aspx' => +				'parens in uri <a href="http://thedailywtf.com/Articles/A-(Long-Overdue)-BuildMaster-Introduction.aspx" rel="nofollow">http:/<wbr />/<wbr />thedailywtf.com/<wbr />Articles/<wbr />A-(Long-Overdue)-BuildMaster-Introduction.aspx</a>' +		); +		foreach ($cases as $input => $output) { +			$this->assertEqual($output, parse_urls($input)); +		} +	} +	 +	/** +	 * Ensure additional select columns do not end up in entity attributes. +	 * +	 * https://github.com/Elgg/Elgg/issues/5538 +	 */ +	public function test_extra_columns_dont_appear_in_attributes() { +		global $ENTITY_CACHE; + +		// 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); +		 +		// entity cache interferes with our test +		$ENTITY_CACHE = array(); +		 +		foreach (array('site', 'user', 'group', 'object') as $type) { +			$entities = elgg_get_entities(array( +				'type' => $type, +				'selects' => array('1 as _nonexistent_test_column'), +				'limit' => 1, +			)); +			if (!$this->assertTrue($entities, "Query for '$type' did not return an entity.")) { +				continue; +			} +			$entity = $entities[0]; +			$this->assertNull($entity->_nonexistent_test_column, "Additional select columns are leaking to attributes for '$type'"); +		} +		 +		$group->delete(); +	} + +	/** +	 * 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, //using strict limit to avoid real infinite loop and just see ElggBatch limiting on it before finishing the work +		); +		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(); +	} + +	public function test_ElggXMLElement_does_not_load_external_entities() { +		$elLast = libxml_disable_entity_loader(false); + +		// build payload that should trigger loading of external entity +		$payload = file_get_contents(dirname(dirname(__FILE__)) . '/test_files/xxe/request.xml'); +		$path = realpath(dirname(dirname(__FILE__)) . '/test_files/xxe/external_entity.txt'); +		$path = str_replace('\\', '/', $path); +		if ($path[0] != '/') { +			$path = '/' . $path; +		} +		$path = 'file://' . $path; +		$payload = sprintf($payload, $path); + +		// make sure we can actually this in this environment +		$element = new SimpleXMLElement($payload); +		$can_load_entity = preg_match('/secret/', (string)$element->methodName); + +		$this->skipUnless($can_load_entity, "XXE vulnerability cannot be tested on this system"); + +		if ($can_load_entity) { +			$el = new ElggXMLElement($payload); +			$chidren = $el->getChildren(); +			$content = $chidren[0]->getContent(); +			$this->assertNoPattern('/secret/', $content); +		} + +		libxml_disable_entity_loader($elLast); +	}  } diff --git a/engine/tests/test_files/plugin_18/manifest.xml b/engine/tests/test_files/plugin_18/manifest.xml index 5d788616a..c8b407511 100644 --- a/engine/tests/test_files/plugin_18/manifest.xml +++ b/engine/tests/test_files/plugin_18/manifest.xml @@ -7,7 +7,7 @@  	<description>A longer, more interesting description.</description>  	<website>http://www.elgg.org/</website>  	<repository>https://github.com/Elgg/Elgg</repository> -	<bugtracker>http://trac.elgg.org</bugtracker> +	<bugtracker>https://github.com/elgg/elgg/issues</bugtracker>  	<donations>http://elgg.org/supporter.php</donations>  	<copyright>(C) Elgg Foundation 2011</copyright>  	<license>GNU General Public License version 2</license> diff --git a/engine/tests/test_files/xxe/external_entity.txt b/engine/tests/test_files/xxe/external_entity.txt new file mode 100644 index 000000000..536aca34d --- /dev/null +++ b/engine/tests/test_files/xxe/external_entity.txt @@ -0,0 +1 @@ +secret
\ No newline at end of file diff --git a/engine/tests/test_files/xxe/request.xml b/engine/tests/test_files/xxe/request.xml new file mode 100644 index 000000000..4390f9db2 --- /dev/null +++ b/engine/tests/test_files/xxe/request.xml @@ -0,0 +1,8 @@ +<?xml version="1.0"?> +<!DOCTYPE foo [ +<!ELEMENT methodName ANY > +<!ENTITY xxe SYSTEM "%s" > +]> +<methodCall> +    <methodName>test&xxe;test</methodName> +</methodCall>  | 
