summaryrefslogtreecommitdiffstats
path: root/lib/private/share/searchresultsorter.php
blob: 4dc9510601f46293d388f41f230a468c5c0a186f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php
/**
 * @author Arthur Schiwon <blizzz@owncloud.com>
 * @author Robin McCorkell <rmccorkell@karoshi.org.uk>
 * @author Scrutinizer Auto-Fixer <auto-fixer@scrutinizer-ci.com>
 *
 * @copyright Copyright (c) 2015, ownCloud, Inc.
 * @license AGPL-3.0
 *
 * This code is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License, version 3,
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 */
namespace OC\Share;

class SearchResultSorter {
	private $search;
	private $encoding;
	private $key;
	private $log;

	/**
	 * @param string $search the search term as was given by the user
	 * @param string $key the array key containing the value that should be compared
	 * against
	 * @param string $encoding optional, encoding to use, defaults to UTF-8
	 * @param \OC\Log $log optional
	 */
	public function __construct($search, $key, \OC\Log $log = null, $encoding = 'UTF-8') {
		$this->encoding = $encoding;
		$this->key = $key;
		$this->log = $log;
		$this->search = mb_strtolower($search, $this->encoding);
	}

	/**
	 * User and Group names matching the search term at the beginning shall appear
	 * on top of the share dialog. Following entries in alphabetical order.
	 * Callback function for usort. http://php.net/usort
	 */
	public function sort($a, $b) {
		if(!isset($a[$this->key]) || !isset($b[$this->key])) {
			if(!is_null($this->log)) {
				$this->log->error('Sharing dialogue: cannot sort due to ' .
								  'missing array key', array('app' => 'core'));
			}
			return 0;
		}
		$nameA = mb_strtolower($a[$this->key], $this->encoding);
		$nameB = mb_strtolower($b[$this->key], $this->encoding);
		$i = mb_strpos($nameA, $this->search, 0, $this->encoding);
		$j = mb_strpos($nameB, $this->search, 0, $this->encoding);

		if($i === $j || $i > 0 && $j > 0) {
			return strcmp(mb_strtolower($nameA, $this->encoding),
						  mb_strtolower($nameB, $this->encoding));
		} elseif ($i === 0) {
			return -1;
		} else {
			return 1;
		}
	}
}