searchresultsorter.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. /**
  3. * @author Arthur Schiwon <blizzz@owncloud.com>
  4. * @author Morris Jobke <hey@morrisjobke.de>
  5. * @author Robin McCorkell <rmccorkell@karoshi.org.uk>
  6. * @author Scrutinizer Auto-Fixer <auto-fixer@scrutinizer-ci.com>
  7. *
  8. * @copyright Copyright (c) 2015, ownCloud, Inc.
  9. * @license AGPL-3.0
  10. *
  11. * This code is free software: you can redistribute it and/or modify
  12. * it under the terms of the GNU Affero General Public License, version 3,
  13. * as published by the Free Software Foundation.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License, version 3,
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>
  22. *
  23. */
  24. namespace OC\Share;
  25. class SearchResultSorter {
  26. private $search;
  27. private $encoding;
  28. private $key;
  29. private $log;
  30. /**
  31. * @param string $search the search term as was given by the user
  32. * @param string $key the array key containing the value that should be compared
  33. * against
  34. * @param string $encoding optional, encoding to use, defaults to UTF-8
  35. * @param \OC\Log $log optional
  36. */
  37. public function __construct($search, $key, \OC\Log $log = null, $encoding = 'UTF-8') {
  38. $this->encoding = $encoding;
  39. $this->key = $key;
  40. $this->log = $log;
  41. $this->search = mb_strtolower($search, $this->encoding);
  42. }
  43. /**
  44. * User and Group names matching the search term at the beginning shall appear
  45. * on top of the share dialog. Following entries in alphabetical order.
  46. * Callback function for usort. http://php.net/usort
  47. */
  48. public function sort($a, $b) {
  49. if(!isset($a[$this->key]) || !isset($b[$this->key])) {
  50. if(!is_null($this->log)) {
  51. $this->log->error('Sharing dialogue: cannot sort due to ' .
  52. 'missing array key', array('app' => 'core'));
  53. }
  54. return 0;
  55. }
  56. $nameA = mb_strtolower($a[$this->key], $this->encoding);
  57. $nameB = mb_strtolower($b[$this->key], $this->encoding);
  58. $i = mb_strpos($nameA, $this->search, 0, $this->encoding);
  59. $j = mb_strpos($nameB, $this->search, 0, $this->encoding);
  60. if($i === $j || $i > 0 && $j > 0) {
  61. return strcmp(mb_strtolower($nameA, $this->encoding),
  62. mb_strtolower($nameB, $this->encoding));
  63. } elseif ($i === 0) {
  64. return -1;
  65. } else {
  66. return 1;
  67. }
  68. }
  69. }