| @@ -35,41 +35,41 @@ discard block | ||
| 35 | 35 | |
| 36 | 36 | $application = new Application(); | 
| 37 | 37 | $application->registerRoutes($this, [ | 
| 38 | - 'routes' => [ | |
| 39 | - ['name' => 'lost#email', 'url' => '/lostpassword/email', 'verb' => 'POST'], | |
| 40 | -		['name' => 'lost#resetform', 'url' => '/lostpassword/reset/form/{token}/{userId}', 'verb' => 'GET'], | |
| 41 | -		['name' => 'lost#setPassword', 'url' => '/lostpassword/set/{token}/{userId}', 'verb' => 'POST'], | |
| 42 | - ['name' => 'user#getDisplayNames', 'url' => '/displaynames', 'verb' => 'POST'], | |
| 43 | -		['name' => 'avatar#getAvatar', 'url' => '/avatar/{userId}/{size}', 'verb' => 'GET'], | |
| 44 | - ['name' => 'avatar#deleteAvatar', 'url' => '/avatar/', 'verb' => 'DELETE'], | |
| 45 | - ['name' => 'avatar#postCroppedAvatar', 'url' => '/avatar/cropped', 'verb' => 'POST'], | |
| 46 | - ['name' => 'avatar#getTmpAvatar', 'url' => '/avatar/tmp', 'verb' => 'GET'], | |
| 47 | - ['name' => 'avatar#postAvatar', 'url' => '/avatar/', 'verb' => 'POST'], | |
| 48 | - ['name' => 'login#tryLogin', 'url' => '/login', 'verb' => 'POST'], | |
| 49 | - ['name' => 'login#confirmPassword', 'url' => '/login/confirm', 'verb' => 'POST'], | |
| 50 | - ['name' => 'login#showLoginForm', 'url' => '/login', 'verb' => 'GET'], | |
| 51 | - ['name' => 'login#logout', 'url' => '/logout', 'verb' => 'GET'], | |
| 52 | - ['name' => 'ClientFlowLogin#showAuthPickerPage', 'url' => '/login/flow', 'verb' => 'GET'], | |
| 53 | - ['name' => 'ClientFlowLogin#redirectPage', 'url' => '/login/flow/redirect', 'verb' => 'GET'], | |
| 54 | - ['name' => 'ClientFlowLogin#generateAppPassword', 'url' => '/login/flow', 'verb' => 'POST'], | |
| 55 | - ['name' => 'TwoFactorChallenge#selectChallenge', 'url' => '/login/selectchallenge', 'verb' => 'GET'], | |
| 56 | -		['name' => 'TwoFactorChallenge#showChallenge', 'url' => '/login/challenge/{challengeProviderId}', 'verb' => 'GET'], | |
| 57 | -		['name' => 'TwoFactorChallenge#solveChallenge', 'url' => '/login/challenge/{challengeProviderId}', 'verb' => 'POST'], | |
| 58 | - ['name' => 'OCJS#getConfig', 'url' => '/core/js/oc.js', 'verb' => 'GET'], | |
| 59 | - ['name' => 'Preview#getPreview', 'url' => '/core/preview', 'verb' => 'GET'], | |
| 60 | - ['name' => 'Preview#getPreview', 'url' => '/core/preview.png', 'verb' => 'GET'], | |
| 61 | -		['name' => 'Css#getCss', 'url' => '/css/{appName}/{fileName}', 'verb' => 'GET'], | |
| 62 | -		['name' => 'Js#getJs', 'url' => '/js/{appName}/{fileName}', 'verb' => 'GET'], | |
| 63 | - ['name' => 'contactsMenu#index', 'url' => '/contactsmenu/contacts', 'verb' => 'POST'], | |
| 64 | - ['name' => 'contactsMenu#findOne', 'url' => '/contactsmenu/findOne', 'verb' => 'POST'], | |
| 65 | - ['name' => 'AutoComplete#get', 'url' => 'autocomplete/get', 'verb' => 'GET'] | |
| 66 | - ], | |
| 67 | - 'ocs' => [ | |
| 68 | - ['root' => '/cloud', 'name' => 'OCS#getCapabilities', 'url' => '/capabilities', 'verb' => 'GET'], | |
| 69 | - ['root' => '', 'name' => 'OCS#getConfig', 'url' => '/config', 'verb' => 'GET'], | |
| 70 | - ['root' => '/person', 'name' => 'OCS#personCheck', 'url' => '/check', 'verb' => 'POST'], | |
| 71 | -		['root' => '/identityproof', 'name' => 'OCS#getIdentityProof', 'url' => '/key/{cloudId}', 'verb' => 'GET'], | |
| 72 | - ], | |
| 38 | + 'routes' => [ | |
| 39 | + ['name' => 'lost#email', 'url' => '/lostpassword/email', 'verb' => 'POST'], | |
| 40 | +        ['name' => 'lost#resetform', 'url' => '/lostpassword/reset/form/{token}/{userId}', 'verb' => 'GET'], | |
| 41 | +        ['name' => 'lost#setPassword', 'url' => '/lostpassword/set/{token}/{userId}', 'verb' => 'POST'], | |
| 42 | + ['name' => 'user#getDisplayNames', 'url' => '/displaynames', 'verb' => 'POST'], | |
| 43 | +        ['name' => 'avatar#getAvatar', 'url' => '/avatar/{userId}/{size}', 'verb' => 'GET'], | |
| 44 | + ['name' => 'avatar#deleteAvatar', 'url' => '/avatar/', 'verb' => 'DELETE'], | |
| 45 | + ['name' => 'avatar#postCroppedAvatar', 'url' => '/avatar/cropped', 'verb' => 'POST'], | |
| 46 | + ['name' => 'avatar#getTmpAvatar', 'url' => '/avatar/tmp', 'verb' => 'GET'], | |
| 47 | + ['name' => 'avatar#postAvatar', 'url' => '/avatar/', 'verb' => 'POST'], | |
| 48 | + ['name' => 'login#tryLogin', 'url' => '/login', 'verb' => 'POST'], | |
| 49 | + ['name' => 'login#confirmPassword', 'url' => '/login/confirm', 'verb' => 'POST'], | |
| 50 | + ['name' => 'login#showLoginForm', 'url' => '/login', 'verb' => 'GET'], | |
| 51 | + ['name' => 'login#logout', 'url' => '/logout', 'verb' => 'GET'], | |
| 52 | + ['name' => 'ClientFlowLogin#showAuthPickerPage', 'url' => '/login/flow', 'verb' => 'GET'], | |
| 53 | + ['name' => 'ClientFlowLogin#redirectPage', 'url' => '/login/flow/redirect', 'verb' => 'GET'], | |
| 54 | + ['name' => 'ClientFlowLogin#generateAppPassword', 'url' => '/login/flow', 'verb' => 'POST'], | |
| 55 | + ['name' => 'TwoFactorChallenge#selectChallenge', 'url' => '/login/selectchallenge', 'verb' => 'GET'], | |
| 56 | +        ['name' => 'TwoFactorChallenge#showChallenge', 'url' => '/login/challenge/{challengeProviderId}', 'verb' => 'GET'], | |
| 57 | +        ['name' => 'TwoFactorChallenge#solveChallenge', 'url' => '/login/challenge/{challengeProviderId}', 'verb' => 'POST'], | |
| 58 | + ['name' => 'OCJS#getConfig', 'url' => '/core/js/oc.js', 'verb' => 'GET'], | |
| 59 | + ['name' => 'Preview#getPreview', 'url' => '/core/preview', 'verb' => 'GET'], | |
| 60 | + ['name' => 'Preview#getPreview', 'url' => '/core/preview.png', 'verb' => 'GET'], | |
| 61 | +        ['name' => 'Css#getCss', 'url' => '/css/{appName}/{fileName}', 'verb' => 'GET'], | |
| 62 | +        ['name' => 'Js#getJs', 'url' => '/js/{appName}/{fileName}', 'verb' => 'GET'], | |
| 63 | + ['name' => 'contactsMenu#index', 'url' => '/contactsmenu/contacts', 'verb' => 'POST'], | |
| 64 | + ['name' => 'contactsMenu#findOne', 'url' => '/contactsmenu/findOne', 'verb' => 'POST'], | |
| 65 | + ['name' => 'AutoComplete#get', 'url' => 'autocomplete/get', 'verb' => 'GET'] | |
| 66 | + ], | |
| 67 | + 'ocs' => [ | |
| 68 | + ['root' => '/cloud', 'name' => 'OCS#getCapabilities', 'url' => '/capabilities', 'verb' => 'GET'], | |
| 69 | + ['root' => '', 'name' => 'OCS#getConfig', 'url' => '/config', 'verb' => 'GET'], | |
| 70 | + ['root' => '/person', 'name' => 'OCS#personCheck', 'url' => '/check', 'verb' => 'POST'], | |
| 71 | +        ['root' => '/identityproof', 'name' => 'OCS#getIdentityProof', 'url' => '/key/{cloudId}', 'verb' => 'GET'], | |
| 72 | + ], | |
| 73 | 73 | ]); | 
| 74 | 74 | |
| 75 | 75 | // Post installation check | 
| @@ -78,15 +78,15 @@ discard block | ||
| 78 | 78 | // Core ajax actions | 
| 79 | 79 | // Search | 
| 80 | 80 |  $this->create('search_ajax_search', '/core/search') | 
| 81 | -	->actionInclude('core/search/ajax/search.php'); | |
| 81 | +    ->actionInclude('core/search/ajax/search.php'); | |
| 82 | 82 | // Routing | 
| 83 | 83 |  $this->create('core_ajax_update', '/core/ajax/update.php') | 
| 84 | -	->actionInclude('core/ajax/update.php'); | |
| 84 | +    ->actionInclude('core/ajax/update.php'); | |
| 85 | 85 | |
| 86 | 86 | // File routes | 
| 87 | 87 |  $this->create('files.viewcontroller.showFile', '/f/{fileid}')->action(function($urlParams) { | 
| 88 | - $app = new \OCA\Files\AppInfo\Application($urlParams); | |
| 89 | -	$app->dispatch('ViewController', 'index'); | |
| 88 | + $app = new \OCA\Files\AppInfo\Application($urlParams); | |
| 89 | +    $app->dispatch('ViewController', 'index'); | |
| 90 | 90 | }); | 
| 91 | 91 | |
| 92 | 92 | // Call routes | 
| @@ -95,57 +95,57 @@ discard block | ||
| 95 | 95 | * @suppress PhanUndeclaredClassMethod | 
| 96 | 96 | */ | 
| 97 | 97 |  $this->create('spreed.pagecontroller.showCall', '/call/{token}')->action(function($urlParams) { | 
| 98 | -	if (class_exists(\OCA\Spreed\AppInfo\Application::class, false)) { | |
| 99 | - $app = new \OCA\Spreed\AppInfo\Application($urlParams); | |
| 100 | -		$app->dispatch('PageController', 'index'); | |
| 101 | -	} else { | |
| 102 | -		throw new \OC\HintException('App spreed is not enabled'); | |
| 103 | - } | |
| 98 | +    if (class_exists(\OCA\Spreed\AppInfo\Application::class, false)) { | |
| 99 | + $app = new \OCA\Spreed\AppInfo\Application($urlParams); | |
| 100 | +        $app->dispatch('PageController', 'index'); | |
| 101 | +    } else { | |
| 102 | +        throw new \OC\HintException('App spreed is not enabled'); | |
| 103 | + } | |
| 104 | 104 | }); | 
| 105 | 105 | |
| 106 | 106 | // Sharing routes | 
| 107 | 107 |  $this->create('files_sharing.sharecontroller.showShare', '/s/{token}')->action(function($urlParams) { | 
| 108 | -	if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) { | |
| 109 | - $app = new \OCA\Files_Sharing\AppInfo\Application($urlParams); | |
| 110 | -		$app->dispatch('ShareController', 'showShare'); | |
| 111 | -	} else { | |
| 112 | -		throw new \OC\HintException('App file sharing is not enabled'); | |
| 113 | - } | |
| 108 | +    if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) { | |
| 109 | + $app = new \OCA\Files_Sharing\AppInfo\Application($urlParams); | |
| 110 | +        $app->dispatch('ShareController', 'showShare'); | |
| 111 | +    } else { | |
| 112 | +        throw new \OC\HintException('App file sharing is not enabled'); | |
| 113 | + } | |
| 114 | 114 | }); | 
| 115 | 115 |  $this->create('files_sharing.sharecontroller.authenticate', '/s/{token}/authenticate')->post()->action(function($urlParams) { | 
| 116 | -	if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) { | |
| 117 | - $app = new \OCA\Files_Sharing\AppInfo\Application($urlParams); | |
| 118 | -		$app->dispatch('ShareController', 'authenticate'); | |
| 119 | -	} else { | |
| 120 | -		throw new \OC\HintException('App file sharing is not enabled'); | |
| 121 | - } | |
| 116 | +    if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) { | |
| 117 | + $app = new \OCA\Files_Sharing\AppInfo\Application($urlParams); | |
| 118 | +        $app->dispatch('ShareController', 'authenticate'); | |
| 119 | +    } else { | |
| 120 | +        throw new \OC\HintException('App file sharing is not enabled'); | |
| 121 | + } | |
| 122 | 122 | }); | 
| 123 | 123 |  $this->create('files_sharing.sharecontroller.showAuthenticate', '/s/{token}/authenticate')->get()->action(function($urlParams) { | 
| 124 | -	if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) { | |
| 125 | - $app = new \OCA\Files_Sharing\AppInfo\Application($urlParams); | |
| 126 | -		$app->dispatch('ShareController', 'showAuthenticate'); | |
| 127 | -	} else { | |
| 128 | -		throw new \OC\HintException('App file sharing is not enabled'); | |
| 129 | - } | |
| 124 | +    if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) { | |
| 125 | + $app = new \OCA\Files_Sharing\AppInfo\Application($urlParams); | |
| 126 | +        $app->dispatch('ShareController', 'showAuthenticate'); | |
| 127 | +    } else { | |
| 128 | +        throw new \OC\HintException('App file sharing is not enabled'); | |
| 129 | + } | |
| 130 | 130 | }); | 
| 131 | 131 |  $this->create('files_sharing.sharecontroller.downloadShare', '/s/{token}/download')->get()->action(function($urlParams) { | 
| 132 | -	if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) { | |
| 133 | - $app = new \OCA\Files_Sharing\AppInfo\Application($urlParams); | |
| 134 | -		$app->dispatch('ShareController', 'downloadShare'); | |
| 135 | -	} else { | |
| 136 | -		throw new \OC\HintException('App file sharing is not enabled'); | |
| 137 | - } | |
| 132 | +    if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) { | |
| 133 | + $app = new \OCA\Files_Sharing\AppInfo\Application($urlParams); | |
| 134 | +        $app->dispatch('ShareController', 'downloadShare'); | |
| 135 | +    } else { | |
| 136 | +        throw new \OC\HintException('App file sharing is not enabled'); | |
| 137 | + } | |
| 138 | 138 | }); | 
| 139 | 139 |  $this->create('files_sharing.publicpreview.directLink', '/s/{token}/preview')->get()->action(function($urlParams) { | 
| 140 | -	if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) { | |
| 141 | - $app = new \OCA\Files_Sharing\AppInfo\Application($urlParams); | |
| 142 | -		$app->dispatch('PublicPreviewController', 'directLink'); | |
| 143 | -	} else { | |
| 144 | -		throw new \OC\HintException('App file sharing is not enabled'); | |
| 145 | - } | |
| 140 | +    if (class_exists(\OCA\Files_Sharing\AppInfo\Application::class, false)) { | |
| 141 | + $app = new \OCA\Files_Sharing\AppInfo\Application($urlParams); | |
| 142 | +        $app->dispatch('PublicPreviewController', 'directLink'); | |
| 143 | +    } else { | |
| 144 | +        throw new \OC\HintException('App file sharing is not enabled'); | |
| 145 | + } | |
| 146 | 146 | }); | 
| 147 | 147 | |
| 148 | 148 | // used for heartbeat | 
| 149 | 149 |  $this->create('heartbeat', '/heartbeat')->action(function(){ | 
| 150 | - // do nothing | |
| 150 | + // do nothing | |
| 151 | 151 | }); | 
| @@ -30,17 +30,17 @@ | ||
| 30 | 30 | * @since 13.0.0 | 
| 31 | 31 | */ | 
| 32 | 32 |  interface IManager { | 
| 33 | - /** | |
| 34 | - * @param string $className – class name of the ISorter implementation | |
| 35 | - * @since 13.0.0 | |
| 36 | - */ | |
| 37 | - public function registerSorter($className); | |
| 33 | + /** | |
| 34 | + * @param string $className – class name of the ISorter implementation | |
| 35 | + * @since 13.0.0 | |
| 36 | + */ | |
| 37 | + public function registerSorter($className); | |
| 38 | 38 | |
| 39 | - /** | |
| 40 | - * @param array $sorters list of sorter IDs, seperated by "|" | |
| 41 | - * @param array $sortArray array representation of OCP\Collaboration\Collaborators\ISearchResult | |
| 42 | - * @param array $context context info of the search, keys: itemType, itemId | |
| 43 | - * @since 13.0.0 | |
| 44 | - */ | |
| 45 | - public function runSorters(array $sorters, array &$sortArray, array $context); | |
| 39 | + /** | |
| 40 | + * @param array $sorters list of sorter IDs, seperated by "|" | |
| 41 | + * @param array $sortArray array representation of OCP\Collaboration\Collaborators\ISearchResult | |
| 42 | + * @param array $context context info of the search, keys: itemType, itemId | |
| 43 | + * @since 13.0.0 | |
| 44 | + */ | |
| 45 | + public function runSorters(array $sorters, array &$sortArray, array $context); | |
| 46 | 46 | } | 
| @@ -33,18 +33,18 @@ | ||
| 33 | 33 | */ | 
| 34 | 34 |  interface ISorter { | 
| 35 | 35 | |
| 36 | - /** | |
| 37 | - * @return string The ID of the sorter, e.g. commenters | |
| 38 | - * @since 13.0.0 | |
| 39 | - */ | |
| 40 | - public function getId(); | |
| 36 | + /** | |
| 37 | + * @return string The ID of the sorter, e.g. commenters | |
| 38 | + * @since 13.0.0 | |
| 39 | + */ | |
| 40 | + public function getId(); | |
| 41 | 41 | |
| 42 | - /** | |
| 43 | - * executes the sort action | |
| 44 | - * | |
| 45 | - * @param array $sortArray the array to be sorted, provided as reference | |
| 46 | - * @param array $context carries key 'itemType' and 'itemId' of the source object (e.g. a file) | |
| 47 | - * @since 13.0.0 | |
| 48 | - */ | |
| 49 | - public function sort(array &$sortArray, array $context); | |
| 42 | + /** | |
| 43 | + * executes the sort action | |
| 44 | + * | |
| 45 | + * @param array $sortArray the array to be sorted, provided as reference | |
| 46 | + * @param array $context carries key 'itemType' and 'itemId' of the source object (e.g. a file) | |
| 47 | + * @since 13.0.0 | |
| 48 | + */ | |
| 49 | + public function sort(array &$sortArray, array $context); | |
| 50 | 50 | } | 
| @@ -52,582 +52,582 @@ | ||
| 52 | 52 | * @property string ldapUuidGroupAttribute | 
| 53 | 53 | */ | 
| 54 | 54 |  class Connection extends LDAPUtility { | 
| 55 | - private $ldapConnectionRes = null; | |
| 56 | - private $configPrefix; | |
| 57 | - private $configID; | |
| 58 | - private $configured = false; | |
| 59 | - private $hasPagedResultSupport = true; | |
| 60 | - //whether connection should be kept on __destruct | |
| 61 | - private $dontDestruct = false; | |
| 62 | - | |
| 63 | - /** | |
| 64 | - * @var bool runtime flag that indicates whether supported primary groups are available | |
| 65 | - */ | |
| 66 | - public $hasPrimaryGroups = true; | |
| 67 | - | |
| 68 | - /** | |
| 69 | - * @var bool runtime flag that indicates whether supported POSIX gidNumber are available | |
| 70 | - */ | |
| 71 | - public $hasGidNumber = true; | |
| 72 | - | |
| 73 | - //cache handler | |
| 74 | - protected $cache; | |
| 75 | - | |
| 76 | - /** @var Configuration settings handler **/ | |
| 77 | - protected $configuration; | |
| 78 | - | |
| 79 | - protected $doNotValidate = false; | |
| 80 | - | |
| 81 | - protected $ignoreValidation = false; | |
| 82 | - | |
| 83 | - /** | |
| 84 | - * Constructor | |
| 85 | - * @param ILDAPWrapper $ldap | |
| 86 | - * @param string $configPrefix a string with the prefix for the configkey column (appconfig table) | |
| 87 | - * @param string|null $configID a string with the value for the appid column (appconfig table) or null for on-the-fly connections | |
| 88 | - */ | |
| 89 | -	public function __construct(ILDAPWrapper $ldap, $configPrefix = '', $configID = 'user_ldap') { | |
| 90 | - parent::__construct($ldap); | |
| 91 | - $this->configPrefix = $configPrefix; | |
| 92 | - $this->configID = $configID; | |
| 93 | - $this->configuration = new Configuration($configPrefix, | |
| 94 | - !is_null($configID)); | |
| 95 | - $memcache = \OC::$server->getMemCacheFactory(); | |
| 96 | -		if($memcache->isAvailable()) { | |
| 97 | - $this->cache = $memcache->create(); | |
| 98 | - } | |
| 99 | - $helper = new Helper(\OC::$server->getConfig()); | |
| 100 | - $this->doNotValidate = !in_array($this->configPrefix, | |
| 101 | - $helper->getServerConfigurationPrefixes()); | |
| 102 | - $this->hasPagedResultSupport = | |
| 103 | - intval($this->configuration->ldapPagingSize) !== 0 | |
| 104 | - || $this->ldap->hasPagedResultSupport(); | |
| 105 | - } | |
| 106 | - | |
| 107 | -	public function __destruct() { | |
| 108 | -		if(!$this->dontDestruct && $this->ldap->isResource($this->ldapConnectionRes)) { | |
| 109 | - @$this->ldap->unbind($this->ldapConnectionRes); | |
| 110 | - }; | |
| 111 | - } | |
| 112 | - | |
| 113 | - /** | |
| 114 | - * defines behaviour when the instance is cloned | |
| 115 | - */ | |
| 116 | -	public function __clone() { | |
| 117 | - $this->configuration = new Configuration($this->configPrefix, | |
| 118 | - !is_null($this->configID)); | |
| 119 | - $this->ldapConnectionRes = null; | |
| 120 | - $this->dontDestruct = true; | |
| 121 | - } | |
| 122 | - | |
| 123 | - /** | |
| 124 | - * @param string $name | |
| 125 | - * @return bool|mixed | |
| 126 | - */ | |
| 127 | -	public function __get($name) { | |
| 128 | -		if(!$this->configured) { | |
| 129 | - $this->readConfiguration(); | |
| 130 | - } | |
| 131 | - | |
| 132 | -		if($name === 'hasPagedResultSupport') { | |
| 133 | - return $this->hasPagedResultSupport; | |
| 134 | - } | |
| 135 | - | |
| 136 | - return $this->configuration->$name; | |
| 137 | - } | |
| 138 | - | |
| 139 | - /** | |
| 140 | - * @param string $name | |
| 141 | - * @param mixed $value | |
| 142 | - */ | |
| 143 | -	public function __set($name, $value) { | |
| 144 | - $this->doNotValidate = false; | |
| 145 | - $before = $this->configuration->$name; | |
| 146 | - $this->configuration->$name = $value; | |
| 147 | - $after = $this->configuration->$name; | |
| 148 | -		if($before !== $after) { | |
| 149 | -			if ($this->configID !== '') { | |
| 150 | - $this->configuration->saveConfiguration(); | |
| 151 | - } | |
| 152 | - $this->validateConfiguration(); | |
| 153 | - } | |
| 154 | - } | |
| 155 | - | |
| 156 | - /** | |
| 157 | - * sets whether the result of the configuration validation shall | |
| 158 | - * be ignored when establishing the connection. Used by the Wizard | |
| 159 | - * in early configuration state. | |
| 160 | - * @param bool $state | |
| 161 | - */ | |
| 162 | -	public function setIgnoreValidation($state) { | |
| 163 | - $this->ignoreValidation = (bool)$state; | |
| 164 | - } | |
| 165 | - | |
| 166 | - /** | |
| 167 | - * initializes the LDAP backend | |
| 168 | - * @param bool $force read the config settings no matter what | |
| 169 | - */ | |
| 170 | -	public function init($force = false) { | |
| 171 | - $this->readConfiguration($force); | |
| 172 | - $this->establishConnection(); | |
| 173 | - } | |
| 174 | - | |
| 175 | - /** | |
| 176 | - * Returns the LDAP handler | |
| 177 | - */ | |
| 178 | -	public function getConnectionResource() { | |
| 179 | -		if(!$this->ldapConnectionRes) { | |
| 180 | - $this->init(); | |
| 181 | -		} else if(!$this->ldap->isResource($this->ldapConnectionRes)) { | |
| 182 | - $this->ldapConnectionRes = null; | |
| 183 | - $this->establishConnection(); | |
| 184 | - } | |
| 185 | -		if(is_null($this->ldapConnectionRes)) { | |
| 186 | -			\OCP\Util::writeLog('user_ldap', 'No LDAP Connection to server ' . $this->configuration->ldapHost, \OCP\Util::ERROR); | |
| 187 | -			throw new ServerNotAvailableException('Connection to LDAP server could not be established'); | |
| 188 | - } | |
| 189 | - return $this->ldapConnectionRes; | |
| 190 | - } | |
| 191 | - | |
| 192 | - /** | |
| 193 | - * resets the connection resource | |
| 194 | - */ | |
| 195 | -	public function resetConnectionResource() { | |
| 196 | -		if(!is_null($this->ldapConnectionRes)) { | |
| 197 | - @$this->ldap->unbind($this->ldapConnectionRes); | |
| 198 | - $this->ldapConnectionRes = null; | |
| 199 | - } | |
| 200 | - } | |
| 201 | - | |
| 202 | - /** | |
| 203 | - * @param string|null $key | |
| 204 | - * @return string | |
| 205 | - */ | |
| 206 | -	private function getCacheKey($key) { | |
| 207 | - $prefix = 'LDAP-'.$this->configID.'-'.$this->configPrefix.'-'; | |
| 208 | -		if(is_null($key)) { | |
| 209 | - return $prefix; | |
| 210 | - } | |
| 211 | - return $prefix.md5($key); | |
| 212 | - } | |
| 213 | - | |
| 214 | - /** | |
| 215 | - * @param string $key | |
| 216 | - * @return mixed|null | |
| 217 | - */ | |
| 218 | -	public function getFromCache($key) { | |
| 219 | -		if(!$this->configured) { | |
| 220 | - $this->readConfiguration(); | |
| 221 | - } | |
| 222 | -		if(is_null($this->cache) || !$this->configuration->ldapCacheTTL) { | |
| 223 | - return null; | |
| 224 | - } | |
| 225 | - $key = $this->getCacheKey($key); | |
| 226 | - | |
| 227 | - return json_decode(base64_decode($this->cache->get($key)), true); | |
| 228 | - } | |
| 229 | - | |
| 230 | - /** | |
| 231 | - * @param string $key | |
| 232 | - * @param mixed $value | |
| 233 | - * | |
| 234 | - * @return string | |
| 235 | - */ | |
| 236 | -	public function writeToCache($key, $value) { | |
| 237 | -		if(!$this->configured) { | |
| 238 | - $this->readConfiguration(); | |
| 239 | - } | |
| 240 | - if(is_null($this->cache) | |
| 241 | - || !$this->configuration->ldapCacheTTL | |
| 242 | -			|| !$this->configuration->ldapConfigurationActive) { | |
| 243 | - return null; | |
| 244 | - } | |
| 245 | - $key = $this->getCacheKey($key); | |
| 246 | - $value = base64_encode(json_encode($value)); | |
| 247 | - $this->cache->set($key, $value, $this->configuration->ldapCacheTTL); | |
| 248 | - } | |
| 249 | - | |
| 250 | -	public function clearCache() { | |
| 251 | -		if(!is_null($this->cache)) { | |
| 252 | - $this->cache->clear($this->getCacheKey(null)); | |
| 253 | - } | |
| 254 | - } | |
| 255 | - | |
| 256 | - /** | |
| 257 | - * Caches the general LDAP configuration. | |
| 258 | - * @param bool $force optional. true, if the re-read should be forced. defaults | |
| 259 | - * to false. | |
| 260 | - * @return null | |
| 261 | - */ | |
| 262 | -	private function readConfiguration($force = false) { | |
| 263 | -		if((!$this->configured || $force) && !is_null($this->configID)) { | |
| 264 | - $this->configuration->readConfiguration(); | |
| 265 | - $this->configured = $this->validateConfiguration(); | |
| 266 | - } | |
| 267 | - } | |
| 268 | - | |
| 269 | - /** | |
| 270 | - * set LDAP configuration with values delivered by an array, not read from configuration | |
| 271 | - * @param array $config array that holds the config parameters in an associated array | |
| 272 | - * @param array &$setParameters optional; array where the set fields will be given to | |
| 273 | - * @return boolean true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters | |
| 274 | - */ | |
| 275 | -	public function setConfiguration($config, &$setParameters = null) { | |
| 276 | -		if(is_null($setParameters)) { | |
| 277 | - $setParameters = array(); | |
| 278 | - } | |
| 279 | - $this->doNotValidate = false; | |
| 280 | - $this->configuration->setConfiguration($config, $setParameters); | |
| 281 | -		if(count($setParameters) > 0) { | |
| 282 | - $this->configured = $this->validateConfiguration(); | |
| 283 | - } | |
| 284 | - | |
| 285 | - | |
| 286 | - return $this->configured; | |
| 287 | - } | |
| 288 | - | |
| 289 | - /** | |
| 290 | - * saves the current Configuration in the database and empties the | |
| 291 | - * cache | |
| 292 | - * @return null | |
| 293 | - */ | |
| 294 | -	public function saveConfiguration() { | |
| 295 | - $this->configuration->saveConfiguration(); | |
| 296 | - $this->clearCache(); | |
| 297 | - } | |
| 298 | - | |
| 299 | - /** | |
| 300 | - * get the current LDAP configuration | |
| 301 | - * @return array | |
| 302 | - */ | |
| 303 | -	public function getConfiguration() { | |
| 304 | - $this->readConfiguration(); | |
| 305 | - $config = $this->configuration->getConfiguration(); | |
| 306 | - $cta = $this->configuration->getConfigTranslationArray(); | |
| 307 | - $result = array(); | |
| 308 | -		foreach($cta as $dbkey => $configkey) { | |
| 309 | -			switch($configkey) { | |
| 310 | - case 'homeFolderNamingRule': | |
| 311 | -					if(strpos($config[$configkey], 'attr:') === 0) { | |
| 312 | - $result[$dbkey] = substr($config[$configkey], 5); | |
| 313 | -					} else { | |
| 314 | - $result[$dbkey] = ''; | |
| 315 | - } | |
| 316 | - break; | |
| 317 | - case 'ldapBase': | |
| 318 | - case 'ldapBaseUsers': | |
| 319 | - case 'ldapBaseGroups': | |
| 320 | - case 'ldapAttributesForUserSearch': | |
| 321 | - case 'ldapAttributesForGroupSearch': | |
| 322 | -					if(is_array($config[$configkey])) { | |
| 323 | -						$result[$dbkey] = implode("\n", $config[$configkey]); | |
| 324 | - break; | |
| 325 | - } //else follows default | |
| 326 | - default: | |
| 327 | - $result[$dbkey] = $config[$configkey]; | |
| 328 | - } | |
| 329 | - } | |
| 330 | - return $result; | |
| 331 | - } | |
| 332 | - | |
| 333 | -	private function doSoftValidation() { | |
| 334 | - //if User or Group Base are not set, take over Base DN setting | |
| 335 | -		foreach(array('ldapBaseUsers', 'ldapBaseGroups') as $keyBase) { | |
| 336 | - $val = $this->configuration->$keyBase; | |
| 337 | -			if(empty($val)) { | |
| 338 | - $this->configuration->$keyBase = $this->configuration->ldapBase; | |
| 339 | - } | |
| 340 | - } | |
| 341 | - | |
| 342 | -		foreach(array('ldapExpertUUIDUserAttr'  => 'ldapUuidUserAttribute', | |
| 343 | - 'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute') | |
| 344 | -				as $expertSetting => $effectiveSetting) { | |
| 345 | - $uuidOverride = $this->configuration->$expertSetting; | |
| 346 | -			if(!empty($uuidOverride)) { | |
| 347 | - $this->configuration->$effectiveSetting = $uuidOverride; | |
| 348 | -			} else { | |
| 349 | -				$uuidAttributes = array('auto', 'entryuuid', 'nsuniqueid', | |
| 350 | - 'objectguid', 'guid', 'ipauniqueid'); | |
| 351 | - if(!in_array($this->configuration->$effectiveSetting, | |
| 352 | - $uuidAttributes) | |
| 353 | -					&& (!is_null($this->configID))) { | |
| 354 | - $this->configuration->$effectiveSetting = 'auto'; | |
| 355 | - $this->configuration->saveConfiguration(); | |
| 356 | -					\OCP\Util::writeLog('user_ldap', | |
| 357 | - 'Illegal value for the '. | |
| 358 | - $effectiveSetting.', '.'reset to '. | |
| 359 | - 'autodetect.', \OCP\Util::INFO); | |
| 360 | - } | |
| 361 | - | |
| 362 | - } | |
| 363 | - } | |
| 364 | - | |
| 365 | - $backupPort = intval($this->configuration->ldapBackupPort); | |
| 366 | -		if ($backupPort <= 0) { | |
| 367 | - $this->configuration->backupPort = $this->configuration->ldapPort; | |
| 368 | - } | |
| 369 | - | |
| 370 | - //make sure empty search attributes are saved as simple, empty array | |
| 371 | -		$saKeys = array('ldapAttributesForUserSearch', | |
| 372 | - 'ldapAttributesForGroupSearch'); | |
| 373 | -		foreach($saKeys as $key) { | |
| 374 | - $val = $this->configuration->$key; | |
| 375 | -			if(is_array($val) && count($val) === 1 && empty($val[0])) { | |
| 376 | - $this->configuration->$key = array(); | |
| 377 | - } | |
| 378 | - } | |
| 379 | - | |
| 380 | - if((stripos($this->configuration->ldapHost, 'ldaps://') === 0) | |
| 381 | -			&& $this->configuration->ldapTLS) { | |
| 382 | - $this->configuration->ldapTLS = false; | |
| 383 | -			\OCP\Util::writeLog('user_ldap', | |
| 384 | - 'LDAPS (already using secure connection) and '. | |
| 385 | - 'TLS do not work together. Switched off TLS.', | |
| 386 | - \OCP\Util::INFO); | |
| 387 | - } | |
| 388 | - } | |
| 389 | - | |
| 390 | - /** | |
| 391 | - * @return bool | |
| 392 | - */ | |
| 393 | -	private function doCriticalValidation() { | |
| 394 | - $configurationOK = true; | |
| 395 | - $errorStr = 'Configuration Error (prefix '. | |
| 396 | - strval($this->configPrefix).'): '; | |
| 397 | - | |
| 398 | - //options that shall not be empty | |
| 399 | -		$options = array('ldapHost', 'ldapPort', 'ldapUserDisplayName', | |
| 400 | - 'ldapGroupDisplayName', 'ldapLoginFilter'); | |
| 401 | -		foreach($options as $key) { | |
| 402 | - $val = $this->configuration->$key; | |
| 403 | -			if(empty($val)) { | |
| 404 | -				switch($key) { | |
| 405 | - case 'ldapHost': | |
| 406 | - $subj = 'LDAP Host'; | |
| 407 | - break; | |
| 408 | - case 'ldapPort': | |
| 409 | - $subj = 'LDAP Port'; | |
| 410 | - break; | |
| 411 | - case 'ldapUserDisplayName': | |
| 412 | - $subj = 'LDAP User Display Name'; | |
| 413 | - break; | |
| 414 | - case 'ldapGroupDisplayName': | |
| 415 | - $subj = 'LDAP Group Display Name'; | |
| 416 | - break; | |
| 417 | - case 'ldapLoginFilter': | |
| 418 | - $subj = 'LDAP Login Filter'; | |
| 419 | - break; | |
| 420 | - default: | |
| 421 | - $subj = $key; | |
| 422 | - break; | |
| 423 | - } | |
| 424 | - $configurationOK = false; | |
| 425 | -				\OCP\Util::writeLog('user_ldap', | |
| 426 | - $errorStr.'No '.$subj.' given!', | |
| 427 | - \OCP\Util::WARN); | |
| 428 | - } | |
| 429 | - } | |
| 430 | - | |
| 431 | - //combinations | |
| 432 | - $agent = $this->configuration->ldapAgentName; | |
| 433 | - $pwd = $this->configuration->ldapAgentPassword; | |
| 434 | - if ( | |
| 435 | - ($agent === '' && $pwd !== '') | |
| 436 | - || ($agent !== '' && $pwd === '') | |
| 437 | -		) { | |
| 438 | -			\OCP\Util::writeLog('user_ldap', | |
| 439 | - $errorStr.'either no password is given for the '. | |
| 440 | - 'user agent or a password is given, but not an '. | |
| 441 | - 'LDAP agent.', | |
| 442 | - \OCP\Util::WARN); | |
| 443 | - $configurationOK = false; | |
| 444 | - } | |
| 445 | - | |
| 446 | - $base = $this->configuration->ldapBase; | |
| 447 | - $baseUsers = $this->configuration->ldapBaseUsers; | |
| 448 | - $baseGroups = $this->configuration->ldapBaseGroups; | |
| 449 | - | |
| 450 | -		if(empty($base) && empty($baseUsers) && empty($baseGroups)) { | |
| 451 | -			\OCP\Util::writeLog('user_ldap', | |
| 452 | - $errorStr.'Not a single Base DN given.', | |
| 453 | - \OCP\Util::WARN); | |
| 454 | - $configurationOK = false; | |
| 455 | - } | |
| 456 | - | |
| 457 | - if(mb_strpos($this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8') | |
| 458 | -		   === false) { | |
| 459 | -			\OCP\Util::writeLog('user_ldap', | |
| 460 | - $errorStr.'login filter does not contain %uid '. | |
| 461 | - 'place holder.', | |
| 462 | - \OCP\Util::WARN); | |
| 463 | - $configurationOK = false; | |
| 464 | - } | |
| 465 | - | |
| 466 | - return $configurationOK; | |
| 467 | - } | |
| 468 | - | |
| 469 | - /** | |
| 470 | - * Validates the user specified configuration | |
| 471 | - * @return bool true if configuration seems OK, false otherwise | |
| 472 | - */ | |
| 473 | -	private function validateConfiguration() { | |
| 474 | - | |
| 475 | -		if($this->doNotValidate) { | |
| 476 | - //don't do a validation if it is a new configuration with pure | |
| 477 | - //default values. Will be allowed on changes via __set or | |
| 478 | - //setConfiguration | |
| 479 | - return false; | |
| 480 | - } | |
| 481 | - | |
| 482 | - // first step: "soft" checks: settings that are not really | |
| 483 | - // necessary, but advisable. If left empty, give an info message | |
| 484 | - $this->doSoftValidation(); | |
| 485 | - | |
| 486 | - //second step: critical checks. If left empty or filled wrong, mark as | |
| 487 | - //not configured and give a warning. | |
| 488 | - return $this->doCriticalValidation(); | |
| 489 | - } | |
| 490 | - | |
| 491 | - | |
| 492 | - /** | |
| 493 | - * Connects and Binds to LDAP | |
| 494 | - */ | |
| 495 | -	private function establishConnection() { | |
| 496 | -		if(!$this->configuration->ldapConfigurationActive) { | |
| 497 | - return null; | |
| 498 | - } | |
| 499 | - static $phpLDAPinstalled = true; | |
| 500 | -		if(!$phpLDAPinstalled) { | |
| 501 | - return false; | |
| 502 | - } | |
| 503 | -		if(!$this->ignoreValidation && !$this->configured) { | |
| 504 | -			\OCP\Util::writeLog('user_ldap', | |
| 505 | - 'Configuration is invalid, cannot connect', | |
| 506 | - \OCP\Util::WARN); | |
| 507 | - return false; | |
| 508 | - } | |
| 509 | -		if(!$this->ldapConnectionRes) { | |
| 510 | -			if(!$this->ldap->areLDAPFunctionsAvailable()) { | |
| 511 | - $phpLDAPinstalled = false; | |
| 512 | -				\OCP\Util::writeLog('user_ldap', | |
| 513 | - 'function ldap_connect is not available. Make '. | |
| 514 | - 'sure that the PHP ldap module is installed.', | |
| 515 | - \OCP\Util::ERROR); | |
| 516 | - | |
| 517 | - return false; | |
| 518 | - } | |
| 519 | -			if($this->configuration->turnOffCertCheck) { | |
| 520 | -				if(putenv('LDAPTLS_REQCERT=never')) { | |
| 521 | -					\OCP\Util::writeLog('user_ldap', | |
| 522 | - 'Turned off SSL certificate validation successfully.', | |
| 523 | - \OCP\Util::DEBUG); | |
| 524 | -				} else { | |
| 525 | -					\OCP\Util::writeLog('user_ldap', | |
| 526 | - 'Could not turn off SSL certificate validation.', | |
| 527 | - \OCP\Util::WARN); | |
| 528 | - } | |
| 529 | - } | |
| 530 | - | |
| 531 | - $isOverrideMainServer = ($this->configuration->ldapOverrideMainServer | |
| 532 | -				|| $this->getFromCache('overrideMainServer')); | |
| 533 | - $isBackupHost = (trim($this->configuration->ldapBackupHost) !== ""); | |
| 534 | - $bindStatus = false; | |
| 535 | - $error = -1; | |
| 536 | -			try { | |
| 537 | -				if (!$isOverrideMainServer) { | |
| 538 | - $this->doConnect($this->configuration->ldapHost, | |
| 539 | - $this->configuration->ldapPort); | |
| 540 | - $bindStatus = $this->bind(); | |
| 541 | - $error = $this->ldap->isResource($this->ldapConnectionRes) ? | |
| 542 | - $this->ldap->errno($this->ldapConnectionRes) : -1; | |
| 543 | - } | |
| 544 | -				if($bindStatus === true) { | |
| 545 | - return $bindStatus; | |
| 546 | - } | |
| 547 | -			} catch (ServerNotAvailableException $e) { | |
| 548 | -				if(!$isBackupHost) { | |
| 549 | - throw $e; | |
| 550 | - } | |
| 551 | - } | |
| 552 | - | |
| 553 | - //if LDAP server is not reachable, try the Backup (Replica!) Server | |
| 554 | -			if($isBackupHost && ($error !== 0 || $isOverrideMainServer)) { | |
| 555 | - $this->doConnect($this->configuration->ldapBackupHost, | |
| 556 | - $this->configuration->ldapBackupPort); | |
| 557 | - $bindStatus = $this->bind(); | |
| 558 | - $error = $this->ldap->isResource($this->ldapConnectionRes) ? | |
| 559 | - $this->ldap->errno($this->ldapConnectionRes) : -1; | |
| 560 | -				if($bindStatus && $error === 0 && !$this->getFromCache('overrideMainServer')) { | |
| 561 | - //when bind to backup server succeeded and failed to main server, | |
| 562 | - //skip contacting him until next cache refresh | |
| 563 | -					$this->writeToCache('overrideMainServer', true); | |
| 564 | - } | |
| 565 | - } | |
| 566 | - | |
| 567 | - return $bindStatus; | |
| 568 | - } | |
| 569 | - return null; | |
| 570 | - } | |
| 571 | - | |
| 572 | - /** | |
| 573 | - * @param string $host | |
| 574 | - * @param string $port | |
| 575 | - * @return bool | |
| 576 | - * @throws \OC\ServerNotAvailableException | |
| 577 | - */ | |
| 578 | -	private function doConnect($host, $port) { | |
| 579 | -		if ($host === '') { | |
| 580 | - return false; | |
| 581 | - } | |
| 582 | - | |
| 583 | - $this->ldapConnectionRes = $this->ldap->connect($host, $port); | |
| 584 | - | |
| 585 | -		if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) { | |
| 586 | -			throw new ServerNotAvailableException('Could not set required LDAP Protocol version.'); | |
| 587 | - } | |
| 588 | - | |
| 589 | -		if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) { | |
| 590 | -			throw new ServerNotAvailableException('Could not disable LDAP referrals.'); | |
| 591 | - } | |
| 592 | - | |
| 593 | -		if($this->configuration->ldapTLS) { | |
| 594 | -			if(!$this->ldap->startTls($this->ldapConnectionRes)) { | |
| 595 | -				throw new ServerNotAvailableException('Start TLS failed, when connecting to LDAP host ' . $host . '.'); | |
| 596 | - } | |
| 597 | - } | |
| 598 | - | |
| 599 | - return true; | |
| 600 | - } | |
| 601 | - | |
| 602 | - /** | |
| 603 | - * Binds to LDAP | |
| 604 | - */ | |
| 605 | -	public function bind() { | |
| 606 | -		if(!$this->configuration->ldapConfigurationActive) { | |
| 607 | - return false; | |
| 608 | - } | |
| 609 | - $cr = $this->getConnectionResource(); | |
| 610 | -		if(!$this->ldap->isResource($cr)) { | |
| 611 | - return false; | |
| 612 | - } | |
| 613 | - $ldapLogin = @$this->ldap->bind($cr, | |
| 614 | - $this->configuration->ldapAgentName, | |
| 615 | - $this->configuration->ldapAgentPassword); | |
| 616 | -		if(!$ldapLogin) { | |
| 617 | - $errno = $this->ldap->errno($cr); | |
| 618 | - | |
| 619 | -			\OCP\Util::writeLog('user_ldap', | |
| 620 | - 'Bind failed: ' . $errno . ': ' . $this->ldap->error($cr), | |
| 621 | - \OCP\Util::WARN); | |
| 622 | - | |
| 623 | - // Set to failure mode, if LDAP error code is not LDAP_SUCCESS or LDAP_INVALID_CREDENTIALS | |
| 624 | -			if($errno !== 0x00 && $errno !== 0x31) { | |
| 625 | - $this->ldapConnectionRes = null; | |
| 626 | - } | |
| 627 | - | |
| 628 | - return false; | |
| 629 | - } | |
| 630 | - return true; | |
| 631 | - } | |
| 55 | + private $ldapConnectionRes = null; | |
| 56 | + private $configPrefix; | |
| 57 | + private $configID; | |
| 58 | + private $configured = false; | |
| 59 | + private $hasPagedResultSupport = true; | |
| 60 | + //whether connection should be kept on __destruct | |
| 61 | + private $dontDestruct = false; | |
| 62 | + | |
| 63 | + /** | |
| 64 | + * @var bool runtime flag that indicates whether supported primary groups are available | |
| 65 | + */ | |
| 66 | + public $hasPrimaryGroups = true; | |
| 67 | + | |
| 68 | + /** | |
| 69 | + * @var bool runtime flag that indicates whether supported POSIX gidNumber are available | |
| 70 | + */ | |
| 71 | + public $hasGidNumber = true; | |
| 72 | + | |
| 73 | + //cache handler | |
| 74 | + protected $cache; | |
| 75 | + | |
| 76 | + /** @var Configuration settings handler **/ | |
| 77 | + protected $configuration; | |
| 78 | + | |
| 79 | + protected $doNotValidate = false; | |
| 80 | + | |
| 81 | + protected $ignoreValidation = false; | |
| 82 | + | |
| 83 | + /** | |
| 84 | + * Constructor | |
| 85 | + * @param ILDAPWrapper $ldap | |
| 86 | + * @param string $configPrefix a string with the prefix for the configkey column (appconfig table) | |
| 87 | + * @param string|null $configID a string with the value for the appid column (appconfig table) or null for on-the-fly connections | |
| 88 | + */ | |
| 89 | +    public function __construct(ILDAPWrapper $ldap, $configPrefix = '', $configID = 'user_ldap') { | |
| 90 | + parent::__construct($ldap); | |
| 91 | + $this->configPrefix = $configPrefix; | |
| 92 | + $this->configID = $configID; | |
| 93 | + $this->configuration = new Configuration($configPrefix, | |
| 94 | + !is_null($configID)); | |
| 95 | + $memcache = \OC::$server->getMemCacheFactory(); | |
| 96 | +        if($memcache->isAvailable()) { | |
| 97 | + $this->cache = $memcache->create(); | |
| 98 | + } | |
| 99 | + $helper = new Helper(\OC::$server->getConfig()); | |
| 100 | + $this->doNotValidate = !in_array($this->configPrefix, | |
| 101 | + $helper->getServerConfigurationPrefixes()); | |
| 102 | + $this->hasPagedResultSupport = | |
| 103 | + intval($this->configuration->ldapPagingSize) !== 0 | |
| 104 | + || $this->ldap->hasPagedResultSupport(); | |
| 105 | + } | |
| 106 | + | |
| 107 | +    public function __destruct() { | |
| 108 | +        if(!$this->dontDestruct && $this->ldap->isResource($this->ldapConnectionRes)) { | |
| 109 | + @$this->ldap->unbind($this->ldapConnectionRes); | |
| 110 | + }; | |
| 111 | + } | |
| 112 | + | |
| 113 | + /** | |
| 114 | + * defines behaviour when the instance is cloned | |
| 115 | + */ | |
| 116 | +    public function __clone() { | |
| 117 | + $this->configuration = new Configuration($this->configPrefix, | |
| 118 | + !is_null($this->configID)); | |
| 119 | + $this->ldapConnectionRes = null; | |
| 120 | + $this->dontDestruct = true; | |
| 121 | + } | |
| 122 | + | |
| 123 | + /** | |
| 124 | + * @param string $name | |
| 125 | + * @return bool|mixed | |
| 126 | + */ | |
| 127 | +    public function __get($name) { | |
| 128 | +        if(!$this->configured) { | |
| 129 | + $this->readConfiguration(); | |
| 130 | + } | |
| 131 | + | |
| 132 | +        if($name === 'hasPagedResultSupport') { | |
| 133 | + return $this->hasPagedResultSupport; | |
| 134 | + } | |
| 135 | + | |
| 136 | + return $this->configuration->$name; | |
| 137 | + } | |
| 138 | + | |
| 139 | + /** | |
| 140 | + * @param string $name | |
| 141 | + * @param mixed $value | |
| 142 | + */ | |
| 143 | +    public function __set($name, $value) { | |
| 144 | + $this->doNotValidate = false; | |
| 145 | + $before = $this->configuration->$name; | |
| 146 | + $this->configuration->$name = $value; | |
| 147 | + $after = $this->configuration->$name; | |
| 148 | +        if($before !== $after) { | |
| 149 | +            if ($this->configID !== '') { | |
| 150 | + $this->configuration->saveConfiguration(); | |
| 151 | + } | |
| 152 | + $this->validateConfiguration(); | |
| 153 | + } | |
| 154 | + } | |
| 155 | + | |
| 156 | + /** | |
| 157 | + * sets whether the result of the configuration validation shall | |
| 158 | + * be ignored when establishing the connection. Used by the Wizard | |
| 159 | + * in early configuration state. | |
| 160 | + * @param bool $state | |
| 161 | + */ | |
| 162 | +    public function setIgnoreValidation($state) { | |
| 163 | + $this->ignoreValidation = (bool)$state; | |
| 164 | + } | |
| 165 | + | |
| 166 | + /** | |
| 167 | + * initializes the LDAP backend | |
| 168 | + * @param bool $force read the config settings no matter what | |
| 169 | + */ | |
| 170 | +    public function init($force = false) { | |
| 171 | + $this->readConfiguration($force); | |
| 172 | + $this->establishConnection(); | |
| 173 | + } | |
| 174 | + | |
| 175 | + /** | |
| 176 | + * Returns the LDAP handler | |
| 177 | + */ | |
| 178 | +    public function getConnectionResource() { | |
| 179 | +        if(!$this->ldapConnectionRes) { | |
| 180 | + $this->init(); | |
| 181 | +        } else if(!$this->ldap->isResource($this->ldapConnectionRes)) { | |
| 182 | + $this->ldapConnectionRes = null; | |
| 183 | + $this->establishConnection(); | |
| 184 | + } | |
| 185 | +        if(is_null($this->ldapConnectionRes)) { | |
| 186 | +            \OCP\Util::writeLog('user_ldap', 'No LDAP Connection to server ' . $this->configuration->ldapHost, \OCP\Util::ERROR); | |
| 187 | +            throw new ServerNotAvailableException('Connection to LDAP server could not be established'); | |
| 188 | + } | |
| 189 | + return $this->ldapConnectionRes; | |
| 190 | + } | |
| 191 | + | |
| 192 | + /** | |
| 193 | + * resets the connection resource | |
| 194 | + */ | |
| 195 | +    public function resetConnectionResource() { | |
| 196 | +        if(!is_null($this->ldapConnectionRes)) { | |
| 197 | + @$this->ldap->unbind($this->ldapConnectionRes); | |
| 198 | + $this->ldapConnectionRes = null; | |
| 199 | + } | |
| 200 | + } | |
| 201 | + | |
| 202 | + /** | |
| 203 | + * @param string|null $key | |
| 204 | + * @return string | |
| 205 | + */ | |
| 206 | +    private function getCacheKey($key) { | |
| 207 | + $prefix = 'LDAP-'.$this->configID.'-'.$this->configPrefix.'-'; | |
| 208 | +        if(is_null($key)) { | |
| 209 | + return $prefix; | |
| 210 | + } | |
| 211 | + return $prefix.md5($key); | |
| 212 | + } | |
| 213 | + | |
| 214 | + /** | |
| 215 | + * @param string $key | |
| 216 | + * @return mixed|null | |
| 217 | + */ | |
| 218 | +    public function getFromCache($key) { | |
| 219 | +        if(!$this->configured) { | |
| 220 | + $this->readConfiguration(); | |
| 221 | + } | |
| 222 | +        if(is_null($this->cache) || !$this->configuration->ldapCacheTTL) { | |
| 223 | + return null; | |
| 224 | + } | |
| 225 | + $key = $this->getCacheKey($key); | |
| 226 | + | |
| 227 | + return json_decode(base64_decode($this->cache->get($key)), true); | |
| 228 | + } | |
| 229 | + | |
| 230 | + /** | |
| 231 | + * @param string $key | |
| 232 | + * @param mixed $value | |
| 233 | + * | |
| 234 | + * @return string | |
| 235 | + */ | |
| 236 | +    public function writeToCache($key, $value) { | |
| 237 | +        if(!$this->configured) { | |
| 238 | + $this->readConfiguration(); | |
| 239 | + } | |
| 240 | + if(is_null($this->cache) | |
| 241 | + || !$this->configuration->ldapCacheTTL | |
| 242 | +            || !$this->configuration->ldapConfigurationActive) { | |
| 243 | + return null; | |
| 244 | + } | |
| 245 | + $key = $this->getCacheKey($key); | |
| 246 | + $value = base64_encode(json_encode($value)); | |
| 247 | + $this->cache->set($key, $value, $this->configuration->ldapCacheTTL); | |
| 248 | + } | |
| 249 | + | |
| 250 | +    public function clearCache() { | |
| 251 | +        if(!is_null($this->cache)) { | |
| 252 | + $this->cache->clear($this->getCacheKey(null)); | |
| 253 | + } | |
| 254 | + } | |
| 255 | + | |
| 256 | + /** | |
| 257 | + * Caches the general LDAP configuration. | |
| 258 | + * @param bool $force optional. true, if the re-read should be forced. defaults | |
| 259 | + * to false. | |
| 260 | + * @return null | |
| 261 | + */ | |
| 262 | +    private function readConfiguration($force = false) { | |
| 263 | +        if((!$this->configured || $force) && !is_null($this->configID)) { | |
| 264 | + $this->configuration->readConfiguration(); | |
| 265 | + $this->configured = $this->validateConfiguration(); | |
| 266 | + } | |
| 267 | + } | |
| 268 | + | |
| 269 | + /** | |
| 270 | + * set LDAP configuration with values delivered by an array, not read from configuration | |
| 271 | + * @param array $config array that holds the config parameters in an associated array | |
| 272 | + * @param array &$setParameters optional; array where the set fields will be given to | |
| 273 | + * @return boolean true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters | |
| 274 | + */ | |
| 275 | +    public function setConfiguration($config, &$setParameters = null) { | |
| 276 | +        if(is_null($setParameters)) { | |
| 277 | + $setParameters = array(); | |
| 278 | + } | |
| 279 | + $this->doNotValidate = false; | |
| 280 | + $this->configuration->setConfiguration($config, $setParameters); | |
| 281 | +        if(count($setParameters) > 0) { | |
| 282 | + $this->configured = $this->validateConfiguration(); | |
| 283 | + } | |
| 284 | + | |
| 285 | + | |
| 286 | + return $this->configured; | |
| 287 | + } | |
| 288 | + | |
| 289 | + /** | |
| 290 | + * saves the current Configuration in the database and empties the | |
| 291 | + * cache | |
| 292 | + * @return null | |
| 293 | + */ | |
| 294 | +    public function saveConfiguration() { | |
| 295 | + $this->configuration->saveConfiguration(); | |
| 296 | + $this->clearCache(); | |
| 297 | + } | |
| 298 | + | |
| 299 | + /** | |
| 300 | + * get the current LDAP configuration | |
| 301 | + * @return array | |
| 302 | + */ | |
| 303 | +    public function getConfiguration() { | |
| 304 | + $this->readConfiguration(); | |
| 305 | + $config = $this->configuration->getConfiguration(); | |
| 306 | + $cta = $this->configuration->getConfigTranslationArray(); | |
| 307 | + $result = array(); | |
| 308 | +        foreach($cta as $dbkey => $configkey) { | |
| 309 | +            switch($configkey) { | |
| 310 | + case 'homeFolderNamingRule': | |
| 311 | +                    if(strpos($config[$configkey], 'attr:') === 0) { | |
| 312 | + $result[$dbkey] = substr($config[$configkey], 5); | |
| 313 | +                    } else { | |
| 314 | + $result[$dbkey] = ''; | |
| 315 | + } | |
| 316 | + break; | |
| 317 | + case 'ldapBase': | |
| 318 | + case 'ldapBaseUsers': | |
| 319 | + case 'ldapBaseGroups': | |
| 320 | + case 'ldapAttributesForUserSearch': | |
| 321 | + case 'ldapAttributesForGroupSearch': | |
| 322 | +                    if(is_array($config[$configkey])) { | |
| 323 | +                        $result[$dbkey] = implode("\n", $config[$configkey]); | |
| 324 | + break; | |
| 325 | + } //else follows default | |
| 326 | + default: | |
| 327 | + $result[$dbkey] = $config[$configkey]; | |
| 328 | + } | |
| 329 | + } | |
| 330 | + return $result; | |
| 331 | + } | |
| 332 | + | |
| 333 | +    private function doSoftValidation() { | |
| 334 | + //if User or Group Base are not set, take over Base DN setting | |
| 335 | +        foreach(array('ldapBaseUsers', 'ldapBaseGroups') as $keyBase) { | |
| 336 | + $val = $this->configuration->$keyBase; | |
| 337 | +            if(empty($val)) { | |
| 338 | + $this->configuration->$keyBase = $this->configuration->ldapBase; | |
| 339 | + } | |
| 340 | + } | |
| 341 | + | |
| 342 | +        foreach(array('ldapExpertUUIDUserAttr'  => 'ldapUuidUserAttribute', | |
| 343 | + 'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute') | |
| 344 | +                as $expertSetting => $effectiveSetting) { | |
| 345 | + $uuidOverride = $this->configuration->$expertSetting; | |
| 346 | +            if(!empty($uuidOverride)) { | |
| 347 | + $this->configuration->$effectiveSetting = $uuidOverride; | |
| 348 | +            } else { | |
| 349 | +                $uuidAttributes = array('auto', 'entryuuid', 'nsuniqueid', | |
| 350 | + 'objectguid', 'guid', 'ipauniqueid'); | |
| 351 | + if(!in_array($this->configuration->$effectiveSetting, | |
| 352 | + $uuidAttributes) | |
| 353 | +                    && (!is_null($this->configID))) { | |
| 354 | + $this->configuration->$effectiveSetting = 'auto'; | |
| 355 | + $this->configuration->saveConfiguration(); | |
| 356 | +                    \OCP\Util::writeLog('user_ldap', | |
| 357 | + 'Illegal value for the '. | |
| 358 | + $effectiveSetting.', '.'reset to '. | |
| 359 | + 'autodetect.', \OCP\Util::INFO); | |
| 360 | + } | |
| 361 | + | |
| 362 | + } | |
| 363 | + } | |
| 364 | + | |
| 365 | + $backupPort = intval($this->configuration->ldapBackupPort); | |
| 366 | +        if ($backupPort <= 0) { | |
| 367 | + $this->configuration->backupPort = $this->configuration->ldapPort; | |
| 368 | + } | |
| 369 | + | |
| 370 | + //make sure empty search attributes are saved as simple, empty array | |
| 371 | +        $saKeys = array('ldapAttributesForUserSearch', | |
| 372 | + 'ldapAttributesForGroupSearch'); | |
| 373 | +        foreach($saKeys as $key) { | |
| 374 | + $val = $this->configuration->$key; | |
| 375 | +            if(is_array($val) && count($val) === 1 && empty($val[0])) { | |
| 376 | + $this->configuration->$key = array(); | |
| 377 | + } | |
| 378 | + } | |
| 379 | + | |
| 380 | + if((stripos($this->configuration->ldapHost, 'ldaps://') === 0) | |
| 381 | +            && $this->configuration->ldapTLS) { | |
| 382 | + $this->configuration->ldapTLS = false; | |
| 383 | +            \OCP\Util::writeLog('user_ldap', | |
| 384 | + 'LDAPS (already using secure connection) and '. | |
| 385 | + 'TLS do not work together. Switched off TLS.', | |
| 386 | + \OCP\Util::INFO); | |
| 387 | + } | |
| 388 | + } | |
| 389 | + | |
| 390 | + /** | |
| 391 | + * @return bool | |
| 392 | + */ | |
| 393 | +    private function doCriticalValidation() { | |
| 394 | + $configurationOK = true; | |
| 395 | + $errorStr = 'Configuration Error (prefix '. | |
| 396 | + strval($this->configPrefix).'): '; | |
| 397 | + | |
| 398 | + //options that shall not be empty | |
| 399 | +        $options = array('ldapHost', 'ldapPort', 'ldapUserDisplayName', | |
| 400 | + 'ldapGroupDisplayName', 'ldapLoginFilter'); | |
| 401 | +        foreach($options as $key) { | |
| 402 | + $val = $this->configuration->$key; | |
| 403 | +            if(empty($val)) { | |
| 404 | +                switch($key) { | |
| 405 | + case 'ldapHost': | |
| 406 | + $subj = 'LDAP Host'; | |
| 407 | + break; | |
| 408 | + case 'ldapPort': | |
| 409 | + $subj = 'LDAP Port'; | |
| 410 | + break; | |
| 411 | + case 'ldapUserDisplayName': | |
| 412 | + $subj = 'LDAP User Display Name'; | |
| 413 | + break; | |
| 414 | + case 'ldapGroupDisplayName': | |
| 415 | + $subj = 'LDAP Group Display Name'; | |
| 416 | + break; | |
| 417 | + case 'ldapLoginFilter': | |
| 418 | + $subj = 'LDAP Login Filter'; | |
| 419 | + break; | |
| 420 | + default: | |
| 421 | + $subj = $key; | |
| 422 | + break; | |
| 423 | + } | |
| 424 | + $configurationOK = false; | |
| 425 | +                \OCP\Util::writeLog('user_ldap', | |
| 426 | + $errorStr.'No '.$subj.' given!', | |
| 427 | + \OCP\Util::WARN); | |
| 428 | + } | |
| 429 | + } | |
| 430 | + | |
| 431 | + //combinations | |
| 432 | + $agent = $this->configuration->ldapAgentName; | |
| 433 | + $pwd = $this->configuration->ldapAgentPassword; | |
| 434 | + if ( | |
| 435 | + ($agent === '' && $pwd !== '') | |
| 436 | + || ($agent !== '' && $pwd === '') | |
| 437 | +        ) { | |
| 438 | +            \OCP\Util::writeLog('user_ldap', | |
| 439 | + $errorStr.'either no password is given for the '. | |
| 440 | + 'user agent or a password is given, but not an '. | |
| 441 | + 'LDAP agent.', | |
| 442 | + \OCP\Util::WARN); | |
| 443 | + $configurationOK = false; | |
| 444 | + } | |
| 445 | + | |
| 446 | + $base = $this->configuration->ldapBase; | |
| 447 | + $baseUsers = $this->configuration->ldapBaseUsers; | |
| 448 | + $baseGroups = $this->configuration->ldapBaseGroups; | |
| 449 | + | |
| 450 | +        if(empty($base) && empty($baseUsers) && empty($baseGroups)) { | |
| 451 | +            \OCP\Util::writeLog('user_ldap', | |
| 452 | + $errorStr.'Not a single Base DN given.', | |
| 453 | + \OCP\Util::WARN); | |
| 454 | + $configurationOK = false; | |
| 455 | + } | |
| 456 | + | |
| 457 | + if(mb_strpos($this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8') | |
| 458 | +            === false) { | |
| 459 | +            \OCP\Util::writeLog('user_ldap', | |
| 460 | + $errorStr.'login filter does not contain %uid '. | |
| 461 | + 'place holder.', | |
| 462 | + \OCP\Util::WARN); | |
| 463 | + $configurationOK = false; | |
| 464 | + } | |
| 465 | + | |
| 466 | + return $configurationOK; | |
| 467 | + } | |
| 468 | + | |
| 469 | + /** | |
| 470 | + * Validates the user specified configuration | |
| 471 | + * @return bool true if configuration seems OK, false otherwise | |
| 472 | + */ | |
| 473 | +    private function validateConfiguration() { | |
| 474 | + | |
| 475 | +        if($this->doNotValidate) { | |
| 476 | + //don't do a validation if it is a new configuration with pure | |
| 477 | + //default values. Will be allowed on changes via __set or | |
| 478 | + //setConfiguration | |
| 479 | + return false; | |
| 480 | + } | |
| 481 | + | |
| 482 | + // first step: "soft" checks: settings that are not really | |
| 483 | + // necessary, but advisable. If left empty, give an info message | |
| 484 | + $this->doSoftValidation(); | |
| 485 | + | |
| 486 | + //second step: critical checks. If left empty or filled wrong, mark as | |
| 487 | + //not configured and give a warning. | |
| 488 | + return $this->doCriticalValidation(); | |
| 489 | + } | |
| 490 | + | |
| 491 | + | |
| 492 | + /** | |
| 493 | + * Connects and Binds to LDAP | |
| 494 | + */ | |
| 495 | +    private function establishConnection() { | |
| 496 | +        if(!$this->configuration->ldapConfigurationActive) { | |
| 497 | + return null; | |
| 498 | + } | |
| 499 | + static $phpLDAPinstalled = true; | |
| 500 | +        if(!$phpLDAPinstalled) { | |
| 501 | + return false; | |
| 502 | + } | |
| 503 | +        if(!$this->ignoreValidation && !$this->configured) { | |
| 504 | +            \OCP\Util::writeLog('user_ldap', | |
| 505 | + 'Configuration is invalid, cannot connect', | |
| 506 | + \OCP\Util::WARN); | |
| 507 | + return false; | |
| 508 | + } | |
| 509 | +        if(!$this->ldapConnectionRes) { | |
| 510 | +            if(!$this->ldap->areLDAPFunctionsAvailable()) { | |
| 511 | + $phpLDAPinstalled = false; | |
| 512 | +                \OCP\Util::writeLog('user_ldap', | |
| 513 | + 'function ldap_connect is not available. Make '. | |
| 514 | + 'sure that the PHP ldap module is installed.', | |
| 515 | + \OCP\Util::ERROR); | |
| 516 | + | |
| 517 | + return false; | |
| 518 | + } | |
| 519 | +            if($this->configuration->turnOffCertCheck) { | |
| 520 | +                if(putenv('LDAPTLS_REQCERT=never')) { | |
| 521 | +                    \OCP\Util::writeLog('user_ldap', | |
| 522 | + 'Turned off SSL certificate validation successfully.', | |
| 523 | + \OCP\Util::DEBUG); | |
| 524 | +                } else { | |
| 525 | +                    \OCP\Util::writeLog('user_ldap', | |
| 526 | + 'Could not turn off SSL certificate validation.', | |
| 527 | + \OCP\Util::WARN); | |
| 528 | + } | |
| 529 | + } | |
| 530 | + | |
| 531 | + $isOverrideMainServer = ($this->configuration->ldapOverrideMainServer | |
| 532 | +                || $this->getFromCache('overrideMainServer')); | |
| 533 | + $isBackupHost = (trim($this->configuration->ldapBackupHost) !== ""); | |
| 534 | + $bindStatus = false; | |
| 535 | + $error = -1; | |
| 536 | +            try { | |
| 537 | +                if (!$isOverrideMainServer) { | |
| 538 | + $this->doConnect($this->configuration->ldapHost, | |
| 539 | + $this->configuration->ldapPort); | |
| 540 | + $bindStatus = $this->bind(); | |
| 541 | + $error = $this->ldap->isResource($this->ldapConnectionRes) ? | |
| 542 | + $this->ldap->errno($this->ldapConnectionRes) : -1; | |
| 543 | + } | |
| 544 | +                if($bindStatus === true) { | |
| 545 | + return $bindStatus; | |
| 546 | + } | |
| 547 | +            } catch (ServerNotAvailableException $e) { | |
| 548 | +                if(!$isBackupHost) { | |
| 549 | + throw $e; | |
| 550 | + } | |
| 551 | + } | |
| 552 | + | |
| 553 | + //if LDAP server is not reachable, try the Backup (Replica!) Server | |
| 554 | +            if($isBackupHost && ($error !== 0 || $isOverrideMainServer)) { | |
| 555 | + $this->doConnect($this->configuration->ldapBackupHost, | |
| 556 | + $this->configuration->ldapBackupPort); | |
| 557 | + $bindStatus = $this->bind(); | |
| 558 | + $error = $this->ldap->isResource($this->ldapConnectionRes) ? | |
| 559 | + $this->ldap->errno($this->ldapConnectionRes) : -1; | |
| 560 | +                if($bindStatus && $error === 0 && !$this->getFromCache('overrideMainServer')) { | |
| 561 | + //when bind to backup server succeeded and failed to main server, | |
| 562 | + //skip contacting him until next cache refresh | |
| 563 | +                    $this->writeToCache('overrideMainServer', true); | |
| 564 | + } | |
| 565 | + } | |
| 566 | + | |
| 567 | + return $bindStatus; | |
| 568 | + } | |
| 569 | + return null; | |
| 570 | + } | |
| 571 | + | |
| 572 | + /** | |
| 573 | + * @param string $host | |
| 574 | + * @param string $port | |
| 575 | + * @return bool | |
| 576 | + * @throws \OC\ServerNotAvailableException | |
| 577 | + */ | |
| 578 | +    private function doConnect($host, $port) { | |
| 579 | +        if ($host === '') { | |
| 580 | + return false; | |
| 581 | + } | |
| 582 | + | |
| 583 | + $this->ldapConnectionRes = $this->ldap->connect($host, $port); | |
| 584 | + | |
| 585 | +        if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) { | |
| 586 | +            throw new ServerNotAvailableException('Could not set required LDAP Protocol version.'); | |
| 587 | + } | |
| 588 | + | |
| 589 | +        if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) { | |
| 590 | +            throw new ServerNotAvailableException('Could not disable LDAP referrals.'); | |
| 591 | + } | |
| 592 | + | |
| 593 | +        if($this->configuration->ldapTLS) { | |
| 594 | +            if(!$this->ldap->startTls($this->ldapConnectionRes)) { | |
| 595 | +                throw new ServerNotAvailableException('Start TLS failed, when connecting to LDAP host ' . $host . '.'); | |
| 596 | + } | |
| 597 | + } | |
| 598 | + | |
| 599 | + return true; | |
| 600 | + } | |
| 601 | + | |
| 602 | + /** | |
| 603 | + * Binds to LDAP | |
| 604 | + */ | |
| 605 | +    public function bind() { | |
| 606 | +        if(!$this->configuration->ldapConfigurationActive) { | |
| 607 | + return false; | |
| 608 | + } | |
| 609 | + $cr = $this->getConnectionResource(); | |
| 610 | +        if(!$this->ldap->isResource($cr)) { | |
| 611 | + return false; | |
| 612 | + } | |
| 613 | + $ldapLogin = @$this->ldap->bind($cr, | |
| 614 | + $this->configuration->ldapAgentName, | |
| 615 | + $this->configuration->ldapAgentPassword); | |
| 616 | +        if(!$ldapLogin) { | |
| 617 | + $errno = $this->ldap->errno($cr); | |
| 618 | + | |
| 619 | +            \OCP\Util::writeLog('user_ldap', | |
| 620 | + 'Bind failed: ' . $errno . ': ' . $this->ldap->error($cr), | |
| 621 | + \OCP\Util::WARN); | |
| 622 | + | |
| 623 | + // Set to failure mode, if LDAP error code is not LDAP_SUCCESS or LDAP_INVALID_CREDENTIALS | |
| 624 | +            if($errno !== 0x00 && $errno !== 0x31) { | |
| 625 | + $this->ldapConnectionRes = null; | |
| 626 | + } | |
| 627 | + | |
| 628 | + return false; | |
| 629 | + } | |
| 630 | + return true; | |
| 631 | + } | |
| 632 | 632 | |
| 633 | 633 | } | 
| @@ -54,1580 +54,1580 @@ discard block | ||
| 54 | 54 | * @package OCA\User_LDAP | 
| 55 | 55 | */ | 
| 56 | 56 |  class Access extends LDAPUtility implements IUserTools { | 
| 57 | - /** | |
| 58 | - * @var \OCA\User_LDAP\Connection | |
| 59 | - */ | |
| 60 | - public $connection; | |
| 61 | - /** @var Manager */ | |
| 62 | - public $userManager; | |
| 63 | - //never ever check this var directly, always use getPagedSearchResultState | |
| 64 | - protected $pagedSearchedSuccessful; | |
| 65 | - | |
| 66 | - /** | |
| 67 | - * @var string[] $cookies an array of returned Paged Result cookies | |
| 68 | - */ | |
| 69 | - protected $cookies = array(); | |
| 70 | - | |
| 71 | - /** | |
| 72 | - * @var string $lastCookie the last cookie returned from a Paged Results | |
| 73 | - * operation, defaults to an empty string | |
| 74 | - */ | |
| 75 | - protected $lastCookie = ''; | |
| 76 | - | |
| 77 | - /** | |
| 78 | - * @var AbstractMapping $userMapper | |
| 79 | - */ | |
| 80 | - protected $userMapper; | |
| 81 | - | |
| 82 | - /** | |
| 83 | - * @var AbstractMapping $userMapper | |
| 84 | - */ | |
| 85 | - protected $groupMapper; | |
| 57 | + /** | |
| 58 | + * @var \OCA\User_LDAP\Connection | |
| 59 | + */ | |
| 60 | + public $connection; | |
| 61 | + /** @var Manager */ | |
| 62 | + public $userManager; | |
| 63 | + //never ever check this var directly, always use getPagedSearchResultState | |
| 64 | + protected $pagedSearchedSuccessful; | |
| 65 | + | |
| 66 | + /** | |
| 67 | + * @var string[] $cookies an array of returned Paged Result cookies | |
| 68 | + */ | |
| 69 | + protected $cookies = array(); | |
| 70 | + | |
| 71 | + /** | |
| 72 | + * @var string $lastCookie the last cookie returned from a Paged Results | |
| 73 | + * operation, defaults to an empty string | |
| 74 | + */ | |
| 75 | + protected $lastCookie = ''; | |
| 76 | + | |
| 77 | + /** | |
| 78 | + * @var AbstractMapping $userMapper | |
| 79 | + */ | |
| 80 | + protected $userMapper; | |
| 81 | + | |
| 82 | + /** | |
| 83 | + * @var AbstractMapping $userMapper | |
| 84 | + */ | |
| 85 | + protected $groupMapper; | |
| 86 | 86 | |
| 87 | - /** | |
| 88 | - * @var \OCA\User_LDAP\Helper | |
| 89 | - */ | |
| 90 | - private $helper; | |
| 91 | - | |
| 92 | - public function __construct(Connection $connection, ILDAPWrapper $ldap, | |
| 93 | -		Manager $userManager, Helper $helper) { | |
| 94 | - parent::__construct($ldap); | |
| 95 | - $this->connection = $connection; | |
| 96 | - $this->userManager = $userManager; | |
| 97 | - $this->userManager->setLdapAccess($this); | |
| 98 | - $this->helper = $helper; | |
| 99 | - } | |
| 100 | - | |
| 101 | - /** | |
| 102 | - * sets the User Mapper | |
| 103 | - * @param AbstractMapping $mapper | |
| 104 | - */ | |
| 105 | -	public function setUserMapper(AbstractMapping $mapper) { | |
| 106 | - $this->userMapper = $mapper; | |
| 107 | - } | |
| 108 | - | |
| 109 | - /** | |
| 110 | - * returns the User Mapper | |
| 111 | - * @throws \Exception | |
| 112 | - * @return AbstractMapping | |
| 113 | - */ | |
| 114 | -	public function getUserMapper() { | |
| 115 | -		if(is_null($this->userMapper)) { | |
| 116 | -			throw new \Exception('UserMapper was not assigned to this Access instance.'); | |
| 117 | - } | |
| 118 | - return $this->userMapper; | |
| 119 | - } | |
| 120 | - | |
| 121 | - /** | |
| 122 | - * sets the Group Mapper | |
| 123 | - * @param AbstractMapping $mapper | |
| 124 | - */ | |
| 125 | -	public function setGroupMapper(AbstractMapping $mapper) { | |
| 126 | - $this->groupMapper = $mapper; | |
| 127 | - } | |
| 128 | - | |
| 129 | - /** | |
| 130 | - * returns the Group Mapper | |
| 131 | - * @throws \Exception | |
| 132 | - * @return AbstractMapping | |
| 133 | - */ | |
| 134 | -	public function getGroupMapper() { | |
| 135 | -		if(is_null($this->groupMapper)) { | |
| 136 | -			throw new \Exception('GroupMapper was not assigned to this Access instance.'); | |
| 137 | - } | |
| 138 | - return $this->groupMapper; | |
| 139 | - } | |
| 140 | - | |
| 141 | - /** | |
| 142 | - * @return bool | |
| 143 | - */ | |
| 144 | -	private function checkConnection() { | |
| 145 | - return ($this->connection instanceof Connection); | |
| 146 | - } | |
| 147 | - | |
| 148 | - /** | |
| 149 | - * returns the Connection instance | |
| 150 | - * @return \OCA\User_LDAP\Connection | |
| 151 | - */ | |
| 152 | -	public function getConnection() { | |
| 153 | - return $this->connection; | |
| 154 | - } | |
| 155 | - | |
| 156 | - /** | |
| 157 | - * reads a given attribute for an LDAP record identified by a DN | |
| 158 | - * @param string $dn the record in question | |
| 159 | - * @param string $attr the attribute that shall be retrieved | |
| 160 | - * if empty, just check the record's existence | |
| 161 | - * @param string $filter | |
| 162 | - * @return array|false an array of values on success or an empty | |
| 163 | - * array if $attr is empty, false otherwise | |
| 164 | - */ | |
| 165 | -	public function readAttribute($dn, $attr, $filter = 'objectClass=*') { | |
| 166 | -		if(!$this->checkConnection()) { | |
| 167 | -			\OCP\Util::writeLog('user_ldap', | |
| 168 | - 'No LDAP Connector assigned, access impossible for readAttribute.', | |
| 169 | - \OCP\Util::WARN); | |
| 170 | - return false; | |
| 171 | - } | |
| 172 | - $cr = $this->connection->getConnectionResource(); | |
| 173 | -		if(!$this->ldap->isResource($cr)) { | |
| 174 | - //LDAP not available | |
| 175 | -			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG); | |
| 176 | - return false; | |
| 177 | - } | |
| 178 | - //Cancel possibly running Paged Results operation, otherwise we run in | |
| 179 | - //LDAP protocol errors | |
| 180 | - $this->abandonPagedSearch(); | |
| 181 | - // openLDAP requires that we init a new Paged Search. Not needed by AD, | |
| 182 | - // but does not hurt either. | |
| 183 | - $pagingSize = intval($this->connection->ldapPagingSize); | |
| 184 | - // 0 won't result in replies, small numbers may leave out groups | |
| 185 | - // (cf. #12306), 500 is default for paging and should work everywhere. | |
| 186 | - $maxResults = $pagingSize > 20 ? $pagingSize : 500; | |
| 187 | - $attr = mb_strtolower($attr, 'UTF-8'); | |
| 188 | - // the actual read attribute later may contain parameters on a ranged | |
| 189 | - // request, e.g. member;range=99-199. Depends on server reply. | |
| 190 | - $attrToRead = $attr; | |
| 191 | - | |
| 192 | - $values = []; | |
| 193 | - $isRangeRequest = false; | |
| 194 | -		do { | |
| 195 | - $result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults); | |
| 196 | -			if(is_bool($result)) { | |
| 197 | - // when an exists request was run and it was successful, an empty | |
| 198 | - // array must be returned | |
| 199 | - return $result ? [] : false; | |
| 200 | - } | |
| 201 | - | |
| 202 | -			if (!$isRangeRequest) { | |
| 203 | - $values = $this->extractAttributeValuesFromResult($result, $attr); | |
| 204 | -				if (!empty($values)) { | |
| 205 | - return $values; | |
| 206 | - } | |
| 207 | - } | |
| 208 | - | |
| 209 | - $isRangeRequest = false; | |
| 210 | - $result = $this->extractRangeData($result, $attr); | |
| 211 | -			if (!empty($result)) { | |
| 212 | - $normalizedResult = $this->extractAttributeValuesFromResult( | |
| 213 | - [ $attr => $result['values'] ], | |
| 214 | - $attr | |
| 215 | - ); | |
| 216 | - $values = array_merge($values, $normalizedResult); | |
| 217 | - | |
| 218 | -				if($result['rangeHigh'] === '*') { | |
| 219 | - // when server replies with * as high range value, there are | |
| 220 | - // no more results left | |
| 221 | - return $values; | |
| 222 | -				} else { | |
| 223 | - $low = $result['rangeHigh'] + 1; | |
| 224 | - $attrToRead = $result['attributeName'] . ';range=' . $low . '-*'; | |
| 225 | - $isRangeRequest = true; | |
| 226 | - } | |
| 227 | - } | |
| 228 | - } while($isRangeRequest); | |
| 229 | - | |
| 230 | -		\OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, \OCP\Util::DEBUG); | |
| 231 | - return false; | |
| 232 | - } | |
| 233 | - | |
| 234 | - /** | |
| 235 | - * Runs an read operation against LDAP | |
| 236 | - * | |
| 237 | - * @param resource $cr the LDAP connection | |
| 238 | - * @param string $dn | |
| 239 | - * @param string $attribute | |
| 240 | - * @param string $filter | |
| 241 | - * @param int $maxResults | |
| 242 | - * @return array|bool false if there was any error, true if an exists check | |
| 243 | - * was performed and the requested DN found, array with the | |
| 244 | - * returned data on a successful usual operation | |
| 245 | - */ | |
| 246 | -	public function executeRead($cr, $dn, $attribute, $filter, $maxResults) { | |
| 247 | - $this->initPagedSearch($filter, array($dn), array($attribute), $maxResults, 0); | |
| 248 | - $dn = $this->helper->DNasBaseParameter($dn); | |
| 249 | -		$rr = @$this->invokeLDAPMethod('read', $cr, $dn, $filter, array($attribute)); | |
| 250 | -		if (!$this->ldap->isResource($rr)) { | |
| 251 | -			if ($attribute !== '') { | |
| 252 | - //do not throw this message on userExists check, irritates | |
| 253 | -				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, \OCP\Util::DEBUG); | |
| 254 | - } | |
| 255 | - //in case an error occurs , e.g. object does not exist | |
| 256 | - return false; | |
| 257 | - } | |
| 258 | -		if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) { | |
| 259 | -			\OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', \OCP\Util::DEBUG); | |
| 260 | - return true; | |
| 261 | - } | |
| 262 | -		$er = $this->invokeLDAPMethod('firstEntry', $cr, $rr); | |
| 263 | -		if (!$this->ldap->isResource($er)) { | |
| 264 | - //did not match the filter, return false | |
| 265 | - return false; | |
| 266 | - } | |
| 267 | - //LDAP attributes are not case sensitive | |
| 268 | - $result = \OCP\Util::mb_array_change_key_case( | |
| 269 | -			$this->invokeLDAPMethod('getAttributes', $cr, $er), MB_CASE_LOWER, 'UTF-8'); | |
| 270 | - | |
| 271 | - return $result; | |
| 272 | - } | |
| 273 | - | |
| 274 | - /** | |
| 275 | - * Normalizes a result grom getAttributes(), i.e. handles DNs and binary | |
| 276 | - * data if present. | |
| 277 | - * | |
| 278 | - * @param array $result from ILDAPWrapper::getAttributes() | |
| 279 | - * @param string $attribute the attribute name that was read | |
| 280 | - * @return string[] | |
| 281 | - */ | |
| 282 | -	public function extractAttributeValuesFromResult($result, $attribute) { | |
| 283 | - $values = []; | |
| 284 | -		if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) { | |
| 285 | - $lowercaseAttribute = strtolower($attribute); | |
| 286 | -			for($i=0;$i<$result[$attribute]['count'];$i++) { | |
| 287 | -				if($this->resemblesDN($attribute)) { | |
| 288 | - $values[] = $this->helper->sanitizeDN($result[$attribute][$i]); | |
| 289 | -				} elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') { | |
| 290 | - $values[] = $this->convertObjectGUID2Str($result[$attribute][$i]); | |
| 291 | -				} else { | |
| 292 | - $values[] = $result[$attribute][$i]; | |
| 293 | - } | |
| 294 | - } | |
| 295 | - } | |
| 296 | - return $values; | |
| 297 | - } | |
| 298 | - | |
| 299 | - /** | |
| 300 | - * Attempts to find ranged data in a getAttribute results and extracts the | |
| 301 | - * returned values as well as information on the range and full attribute | |
| 302 | - * name for further processing. | |
| 303 | - * | |
| 304 | - * @param array $result from ILDAPWrapper::getAttributes() | |
| 305 | - * @param string $attribute the attribute name that was read. Without ";range=…" | |
| 306 | - * @return array If a range was detected with keys 'values', 'attributeName', | |
| 307 | - * 'attributeFull' and 'rangeHigh', otherwise empty. | |
| 308 | - */ | |
| 309 | -	public function extractRangeData($result, $attribute) { | |
| 310 | - $keys = array_keys($result); | |
| 311 | -		foreach($keys as $key) { | |
| 312 | -			if($key !== $attribute && strpos($key, $attribute) === 0) { | |
| 313 | -				$queryData = explode(';', $key); | |
| 314 | -				if(strpos($queryData[1], 'range=') === 0) { | |
| 315 | - $high = substr($queryData[1], 1 + strpos($queryData[1], '-')); | |
| 316 | - $data = [ | |
| 317 | - 'values' => $result[$key], | |
| 318 | - 'attributeName' => $queryData[0], | |
| 319 | - 'attributeFull' => $key, | |
| 320 | - 'rangeHigh' => $high, | |
| 321 | - ]; | |
| 322 | - return $data; | |
| 323 | - } | |
| 324 | - } | |
| 325 | - } | |
| 326 | - return []; | |
| 327 | - } | |
| 87 | + /** | |
| 88 | + * @var \OCA\User_LDAP\Helper | |
| 89 | + */ | |
| 90 | + private $helper; | |
| 91 | + | |
| 92 | + public function __construct(Connection $connection, ILDAPWrapper $ldap, | |
| 93 | +        Manager $userManager, Helper $helper) { | |
| 94 | + parent::__construct($ldap); | |
| 95 | + $this->connection = $connection; | |
| 96 | + $this->userManager = $userManager; | |
| 97 | + $this->userManager->setLdapAccess($this); | |
| 98 | + $this->helper = $helper; | |
| 99 | + } | |
| 100 | + | |
| 101 | + /** | |
| 102 | + * sets the User Mapper | |
| 103 | + * @param AbstractMapping $mapper | |
| 104 | + */ | |
| 105 | +    public function setUserMapper(AbstractMapping $mapper) { | |
| 106 | + $this->userMapper = $mapper; | |
| 107 | + } | |
| 108 | + | |
| 109 | + /** | |
| 110 | + * returns the User Mapper | |
| 111 | + * @throws \Exception | |
| 112 | + * @return AbstractMapping | |
| 113 | + */ | |
| 114 | +    public function getUserMapper() { | |
| 115 | +        if(is_null($this->userMapper)) { | |
| 116 | +            throw new \Exception('UserMapper was not assigned to this Access instance.'); | |
| 117 | + } | |
| 118 | + return $this->userMapper; | |
| 119 | + } | |
| 120 | + | |
| 121 | + /** | |
| 122 | + * sets the Group Mapper | |
| 123 | + * @param AbstractMapping $mapper | |
| 124 | + */ | |
| 125 | +    public function setGroupMapper(AbstractMapping $mapper) { | |
| 126 | + $this->groupMapper = $mapper; | |
| 127 | + } | |
| 128 | + | |
| 129 | + /** | |
| 130 | + * returns the Group Mapper | |
| 131 | + * @throws \Exception | |
| 132 | + * @return AbstractMapping | |
| 133 | + */ | |
| 134 | +    public function getGroupMapper() { | |
| 135 | +        if(is_null($this->groupMapper)) { | |
| 136 | +            throw new \Exception('GroupMapper was not assigned to this Access instance.'); | |
| 137 | + } | |
| 138 | + return $this->groupMapper; | |
| 139 | + } | |
| 140 | + | |
| 141 | + /** | |
| 142 | + * @return bool | |
| 143 | + */ | |
| 144 | +    private function checkConnection() { | |
| 145 | + return ($this->connection instanceof Connection); | |
| 146 | + } | |
| 147 | + | |
| 148 | + /** | |
| 149 | + * returns the Connection instance | |
| 150 | + * @return \OCA\User_LDAP\Connection | |
| 151 | + */ | |
| 152 | +    public function getConnection() { | |
| 153 | + return $this->connection; | |
| 154 | + } | |
| 155 | + | |
| 156 | + /** | |
| 157 | + * reads a given attribute for an LDAP record identified by a DN | |
| 158 | + * @param string $dn the record in question | |
| 159 | + * @param string $attr the attribute that shall be retrieved | |
| 160 | + * if empty, just check the record's existence | |
| 161 | + * @param string $filter | |
| 162 | + * @return array|false an array of values on success or an empty | |
| 163 | + * array if $attr is empty, false otherwise | |
| 164 | + */ | |
| 165 | +    public function readAttribute($dn, $attr, $filter = 'objectClass=*') { | |
| 166 | +        if(!$this->checkConnection()) { | |
| 167 | +            \OCP\Util::writeLog('user_ldap', | |
| 168 | + 'No LDAP Connector assigned, access impossible for readAttribute.', | |
| 169 | + \OCP\Util::WARN); | |
| 170 | + return false; | |
| 171 | + } | |
| 172 | + $cr = $this->connection->getConnectionResource(); | |
| 173 | +        if(!$this->ldap->isResource($cr)) { | |
| 174 | + //LDAP not available | |
| 175 | +            \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG); | |
| 176 | + return false; | |
| 177 | + } | |
| 178 | + //Cancel possibly running Paged Results operation, otherwise we run in | |
| 179 | + //LDAP protocol errors | |
| 180 | + $this->abandonPagedSearch(); | |
| 181 | + // openLDAP requires that we init a new Paged Search. Not needed by AD, | |
| 182 | + // but does not hurt either. | |
| 183 | + $pagingSize = intval($this->connection->ldapPagingSize); | |
| 184 | + // 0 won't result in replies, small numbers may leave out groups | |
| 185 | + // (cf. #12306), 500 is default for paging and should work everywhere. | |
| 186 | + $maxResults = $pagingSize > 20 ? $pagingSize : 500; | |
| 187 | + $attr = mb_strtolower($attr, 'UTF-8'); | |
| 188 | + // the actual read attribute later may contain parameters on a ranged | |
| 189 | + // request, e.g. member;range=99-199. Depends on server reply. | |
| 190 | + $attrToRead = $attr; | |
| 191 | + | |
| 192 | + $values = []; | |
| 193 | + $isRangeRequest = false; | |
| 194 | +        do { | |
| 195 | + $result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults); | |
| 196 | +            if(is_bool($result)) { | |
| 197 | + // when an exists request was run and it was successful, an empty | |
| 198 | + // array must be returned | |
| 199 | + return $result ? [] : false; | |
| 200 | + } | |
| 201 | + | |
| 202 | +            if (!$isRangeRequest) { | |
| 203 | + $values = $this->extractAttributeValuesFromResult($result, $attr); | |
| 204 | +                if (!empty($values)) { | |
| 205 | + return $values; | |
| 206 | + } | |
| 207 | + } | |
| 208 | + | |
| 209 | + $isRangeRequest = false; | |
| 210 | + $result = $this->extractRangeData($result, $attr); | |
| 211 | +            if (!empty($result)) { | |
| 212 | + $normalizedResult = $this->extractAttributeValuesFromResult( | |
| 213 | + [ $attr => $result['values'] ], | |
| 214 | + $attr | |
| 215 | + ); | |
| 216 | + $values = array_merge($values, $normalizedResult); | |
| 217 | + | |
| 218 | +                if($result['rangeHigh'] === '*') { | |
| 219 | + // when server replies with * as high range value, there are | |
| 220 | + // no more results left | |
| 221 | + return $values; | |
| 222 | +                } else { | |
| 223 | + $low = $result['rangeHigh'] + 1; | |
| 224 | + $attrToRead = $result['attributeName'] . ';range=' . $low . '-*'; | |
| 225 | + $isRangeRequest = true; | |
| 226 | + } | |
| 227 | + } | |
| 228 | + } while($isRangeRequest); | |
| 229 | + | |
| 230 | +        \OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, \OCP\Util::DEBUG); | |
| 231 | + return false; | |
| 232 | + } | |
| 233 | + | |
| 234 | + /** | |
| 235 | + * Runs an read operation against LDAP | |
| 236 | + * | |
| 237 | + * @param resource $cr the LDAP connection | |
| 238 | + * @param string $dn | |
| 239 | + * @param string $attribute | |
| 240 | + * @param string $filter | |
| 241 | + * @param int $maxResults | |
| 242 | + * @return array|bool false if there was any error, true if an exists check | |
| 243 | + * was performed and the requested DN found, array with the | |
| 244 | + * returned data on a successful usual operation | |
| 245 | + */ | |
| 246 | +    public function executeRead($cr, $dn, $attribute, $filter, $maxResults) { | |
| 247 | + $this->initPagedSearch($filter, array($dn), array($attribute), $maxResults, 0); | |
| 248 | + $dn = $this->helper->DNasBaseParameter($dn); | |
| 249 | +        $rr = @$this->invokeLDAPMethod('read', $cr, $dn, $filter, array($attribute)); | |
| 250 | +        if (!$this->ldap->isResource($rr)) { | |
| 251 | +            if ($attribute !== '') { | |
| 252 | + //do not throw this message on userExists check, irritates | |
| 253 | +                \OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, \OCP\Util::DEBUG); | |
| 254 | + } | |
| 255 | + //in case an error occurs , e.g. object does not exist | |
| 256 | + return false; | |
| 257 | + } | |
| 258 | +        if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) { | |
| 259 | +            \OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', \OCP\Util::DEBUG); | |
| 260 | + return true; | |
| 261 | + } | |
| 262 | +        $er = $this->invokeLDAPMethod('firstEntry', $cr, $rr); | |
| 263 | +        if (!$this->ldap->isResource($er)) { | |
| 264 | + //did not match the filter, return false | |
| 265 | + return false; | |
| 266 | + } | |
| 267 | + //LDAP attributes are not case sensitive | |
| 268 | + $result = \OCP\Util::mb_array_change_key_case( | |
| 269 | +            $this->invokeLDAPMethod('getAttributes', $cr, $er), MB_CASE_LOWER, 'UTF-8'); | |
| 270 | + | |
| 271 | + return $result; | |
| 272 | + } | |
| 273 | + | |
| 274 | + /** | |
| 275 | + * Normalizes a result grom getAttributes(), i.e. handles DNs and binary | |
| 276 | + * data if present. | |
| 277 | + * | |
| 278 | + * @param array $result from ILDAPWrapper::getAttributes() | |
| 279 | + * @param string $attribute the attribute name that was read | |
| 280 | + * @return string[] | |
| 281 | + */ | |
| 282 | +    public function extractAttributeValuesFromResult($result, $attribute) { | |
| 283 | + $values = []; | |
| 284 | +        if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) { | |
| 285 | + $lowercaseAttribute = strtolower($attribute); | |
| 286 | +            for($i=0;$i<$result[$attribute]['count'];$i++) { | |
| 287 | +                if($this->resemblesDN($attribute)) { | |
| 288 | + $values[] = $this->helper->sanitizeDN($result[$attribute][$i]); | |
| 289 | +                } elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') { | |
| 290 | + $values[] = $this->convertObjectGUID2Str($result[$attribute][$i]); | |
| 291 | +                } else { | |
| 292 | + $values[] = $result[$attribute][$i]; | |
| 293 | + } | |
| 294 | + } | |
| 295 | + } | |
| 296 | + return $values; | |
| 297 | + } | |
| 298 | + | |
| 299 | + /** | |
| 300 | + * Attempts to find ranged data in a getAttribute results and extracts the | |
| 301 | + * returned values as well as information on the range and full attribute | |
| 302 | + * name for further processing. | |
| 303 | + * | |
| 304 | + * @param array $result from ILDAPWrapper::getAttributes() | |
| 305 | + * @param string $attribute the attribute name that was read. Without ";range=…" | |
| 306 | + * @return array If a range was detected with keys 'values', 'attributeName', | |
| 307 | + * 'attributeFull' and 'rangeHigh', otherwise empty. | |
| 308 | + */ | |
| 309 | +    public function extractRangeData($result, $attribute) { | |
| 310 | + $keys = array_keys($result); | |
| 311 | +        foreach($keys as $key) { | |
| 312 | +            if($key !== $attribute && strpos($key, $attribute) === 0) { | |
| 313 | +                $queryData = explode(';', $key); | |
| 314 | +                if(strpos($queryData[1], 'range=') === 0) { | |
| 315 | + $high = substr($queryData[1], 1 + strpos($queryData[1], '-')); | |
| 316 | + $data = [ | |
| 317 | + 'values' => $result[$key], | |
| 318 | + 'attributeName' => $queryData[0], | |
| 319 | + 'attributeFull' => $key, | |
| 320 | + 'rangeHigh' => $high, | |
| 321 | + ]; | |
| 322 | + return $data; | |
| 323 | + } | |
| 324 | + } | |
| 325 | + } | |
| 326 | + return []; | |
| 327 | + } | |
| 328 | 328 | |
| 329 | - /** | |
| 330 | - * Set password for an LDAP user identified by a DN | |
| 331 | - * | |
| 332 | - * @param string $userDN the user in question | |
| 333 | - * @param string $password the new password | |
| 334 | - * @return bool | |
| 335 | - * @throws HintException | |
| 336 | - * @throws \Exception | |
| 337 | - */ | |
| 338 | -	public function setPassword($userDN, $password) { | |
| 339 | -		if(intval($this->connection->turnOnPasswordChange) !== 1) { | |
| 340 | -			throw new \Exception('LDAP password changes are disabled.'); | |
| 341 | - } | |
| 342 | - $cr = $this->connection->getConnectionResource(); | |
| 343 | -		if(!$this->ldap->isResource($cr)) { | |
| 344 | - //LDAP not available | |
| 345 | -			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG); | |
| 346 | - return false; | |
| 347 | - } | |
| 348 | -		try { | |
| 349 | -			return @$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password); | |
| 350 | -		} catch(ConstraintViolationException $e) { | |
| 351 | -			throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode()); | |
| 352 | - } | |
| 353 | - } | |
| 354 | - | |
| 355 | - /** | |
| 356 | - * checks whether the given attributes value is probably a DN | |
| 357 | - * @param string $attr the attribute in question | |
| 358 | - * @return boolean if so true, otherwise false | |
| 359 | - */ | |
| 360 | -	private function resemblesDN($attr) { | |
| 361 | - $resemblingAttributes = array( | |
| 362 | - 'dn', | |
| 363 | - 'uniquemember', | |
| 364 | - 'member', | |
| 365 | - // memberOf is an "operational" attribute, without a definition in any RFC | |
| 366 | - 'memberof' | |
| 367 | - ); | |
| 368 | - return in_array($attr, $resemblingAttributes); | |
| 369 | - } | |
| 370 | - | |
| 371 | - /** | |
| 372 | - * checks whether the given string is probably a DN | |
| 373 | - * @param string $string | |
| 374 | - * @return boolean | |
| 375 | - */ | |
| 376 | -	public function stringResemblesDN($string) { | |
| 377 | - $r = $this->ldap->explodeDN($string, 0); | |
| 378 | - // if exploding a DN succeeds and does not end up in | |
| 379 | - // an empty array except for $r[count] being 0. | |
| 380 | - return (is_array($r) && count($r) > 1); | |
| 381 | - } | |
| 382 | - | |
| 383 | - /** | |
| 384 | - * returns a DN-string that is cleaned from not domain parts, e.g. | |
| 385 | - * cn=foo,cn=bar,dc=foobar,dc=server,dc=org | |
| 386 | - * becomes dc=foobar,dc=server,dc=org | |
| 387 | - * @param string $dn | |
| 388 | - * @return string | |
| 389 | - */ | |
| 390 | -	public function getDomainDNFromDN($dn) { | |
| 391 | - $allParts = $this->ldap->explodeDN($dn, 0); | |
| 392 | -		if($allParts === false) { | |
| 393 | - //not a valid DN | |
| 394 | - return ''; | |
| 395 | - } | |
| 396 | - $domainParts = array(); | |
| 397 | - $dcFound = false; | |
| 398 | -		foreach($allParts as $part) { | |
| 399 | -			if(!$dcFound && strpos($part, 'dc=') === 0) { | |
| 400 | - $dcFound = true; | |
| 401 | - } | |
| 402 | -			if($dcFound) { | |
| 403 | - $domainParts[] = $part; | |
| 404 | - } | |
| 405 | - } | |
| 406 | -		$domainDN = implode(',', $domainParts); | |
| 407 | - return $domainDN; | |
| 408 | - } | |
| 409 | - | |
| 410 | - /** | |
| 411 | - * returns the LDAP DN for the given internal Nextcloud name of the group | |
| 412 | - * @param string $name the Nextcloud name in question | |
| 413 | - * @return string|false LDAP DN on success, otherwise false | |
| 414 | - */ | |
| 415 | -	public function groupname2dn($name) { | |
| 416 | - return $this->groupMapper->getDNByName($name); | |
| 417 | - } | |
| 418 | - | |
| 419 | - /** | |
| 420 | - * returns the LDAP DN for the given internal Nextcloud name of the user | |
| 421 | - * @param string $name the Nextcloud name in question | |
| 422 | - * @return string|false with the LDAP DN on success, otherwise false | |
| 423 | - */ | |
| 424 | -	public function username2dn($name) { | |
| 425 | - $fdn = $this->userMapper->getDNByName($name); | |
| 426 | - | |
| 427 | - //Check whether the DN belongs to the Base, to avoid issues on multi- | |
| 428 | - //server setups | |
| 429 | -		if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) { | |
| 430 | - return $fdn; | |
| 431 | - } | |
| 432 | - | |
| 433 | - return false; | |
| 434 | - } | |
| 435 | - | |
| 436 | - /** | |
| 437 | - * returns the internal Nextcloud name for the given LDAP DN of the group, false on DN outside of search DN or failure | |
| 438 | - * @param string $fdn the dn of the group object | |
| 439 | - * @param string $ldapName optional, the display name of the object | |
| 440 | - * @return string|false with the name to use in Nextcloud, false on DN outside of search DN | |
| 441 | - */ | |
| 442 | -	public function dn2groupname($fdn, $ldapName = null) { | |
| 443 | - //To avoid bypassing the base DN settings under certain circumstances | |
| 444 | - //with the group support, check whether the provided DN matches one of | |
| 445 | - //the given Bases | |
| 446 | -		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) { | |
| 447 | - return false; | |
| 448 | - } | |
| 449 | - | |
| 450 | - return $this->dn2ocname($fdn, $ldapName, false); | |
| 451 | - } | |
| 452 | - | |
| 453 | - /** | |
| 454 | - * accepts an array of group DNs and tests whether they match the user | |
| 455 | - * filter by doing read operations against the group entries. Returns an | |
| 456 | - * array of DNs that match the filter. | |
| 457 | - * | |
| 458 | - * @param string[] $groupDNs | |
| 459 | - * @return string[] | |
| 460 | - */ | |
| 461 | -	public function groupsMatchFilter($groupDNs) { | |
| 462 | - $validGroupDNs = []; | |
| 463 | -		foreach($groupDNs as $dn) { | |
| 464 | - $cacheKey = 'groupsMatchFilter-'.$dn; | |
| 465 | - $groupMatchFilter = $this->connection->getFromCache($cacheKey); | |
| 466 | -			if(!is_null($groupMatchFilter)) { | |
| 467 | -				if($groupMatchFilter) { | |
| 468 | - $validGroupDNs[] = $dn; | |
| 469 | - } | |
| 470 | - continue; | |
| 471 | - } | |
| 472 | - | |
| 473 | - // Check the base DN first. If this is not met already, we don't | |
| 474 | - // need to ask the server at all. | |
| 475 | -			if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) { | |
| 476 | - $this->connection->writeToCache($cacheKey, false); | |
| 477 | - continue; | |
| 478 | - } | |
| 479 | - | |
| 480 | - $result = $this->readAttribute($dn, 'cn', $this->connection->ldapGroupFilter); | |
| 481 | -			if(is_array($result)) { | |
| 482 | - $this->connection->writeToCache($cacheKey, true); | |
| 483 | - $validGroupDNs[] = $dn; | |
| 484 | -			} else { | |
| 485 | - $this->connection->writeToCache($cacheKey, false); | |
| 486 | - } | |
| 487 | - | |
| 488 | - } | |
| 489 | - return $validGroupDNs; | |
| 490 | - } | |
| 491 | - | |
| 492 | - /** | |
| 493 | - * returns the internal Nextcloud name for the given LDAP DN of the user, false on DN outside of search DN or failure | |
| 494 | - * @param string $dn the dn of the user object | |
| 495 | - * @param string $ldapName optional, the display name of the object | |
| 496 | - * @return string|false with with the name to use in Nextcloud | |
| 497 | - */ | |
| 498 | -	public function dn2username($fdn, $ldapName = null) { | |
| 499 | - //To avoid bypassing the base DN settings under certain circumstances | |
| 500 | - //with the group support, check whether the provided DN matches one of | |
| 501 | - //the given Bases | |
| 502 | -		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) { | |
| 503 | - return false; | |
| 504 | - } | |
| 505 | - | |
| 506 | - return $this->dn2ocname($fdn, $ldapName, true); | |
| 507 | - } | |
| 508 | - | |
| 509 | - /** | |
| 510 | - * returns an internal Nextcloud name for the given LDAP DN, false on DN outside of search DN | |
| 511 | - * @param string $dn the dn of the user object | |
| 512 | - * @param string $ldapName optional, the display name of the object | |
| 513 | - * @param bool $isUser optional, whether it is a user object (otherwise group assumed) | |
| 514 | - * @return string|false with with the name to use in Nextcloud | |
| 515 | - */ | |
| 516 | -	public function dn2ocname($fdn, $ldapName = null, $isUser = true) { | |
| 517 | -		if($isUser) { | |
| 518 | - $mapper = $this->getUserMapper(); | |
| 519 | - $nameAttribute = $this->connection->ldapUserDisplayName; | |
| 520 | -		} else { | |
| 521 | - $mapper = $this->getGroupMapper(); | |
| 522 | - $nameAttribute = $this->connection->ldapGroupDisplayName; | |
| 523 | - } | |
| 524 | - | |
| 525 | - //let's try to retrieve the Nextcloud name from the mappings table | |
| 526 | - $ocName = $mapper->getNameByDN($fdn); | |
| 527 | -		if(is_string($ocName)) { | |
| 528 | - return $ocName; | |
| 529 | - } | |
| 530 | - | |
| 531 | - //second try: get the UUID and check if it is known. Then, update the DN and return the name. | |
| 532 | - $uuid = $this->getUUID($fdn, $isUser); | |
| 533 | -		if(is_string($uuid)) { | |
| 534 | - $ocName = $mapper->getNameByUUID($uuid); | |
| 535 | -			if(is_string($ocName)) { | |
| 536 | - $mapper->setDNbyUUID($fdn, $uuid); | |
| 537 | - return $ocName; | |
| 538 | - } | |
| 539 | -		} else { | |
| 540 | - //If the UUID can't be detected something is foul. | |
| 541 | -			\OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for '.$fdn.'. Skipping.', \OCP\Util::INFO); | |
| 542 | - return false; | |
| 543 | - } | |
| 544 | - | |
| 545 | -		if(is_null($ldapName)) { | |
| 546 | - $ldapName = $this->readAttribute($fdn, $nameAttribute); | |
| 547 | -			if(!isset($ldapName[0]) && empty($ldapName[0])) { | |
| 548 | -				\OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.'.', \OCP\Util::INFO); | |
| 549 | - return false; | |
| 550 | - } | |
| 551 | - $ldapName = $ldapName[0]; | |
| 552 | - } | |
| 553 | - | |
| 554 | -		if($isUser) { | |
| 555 | - $usernameAttribute = strval($this->connection->ldapExpertUsernameAttr); | |
| 556 | -			if ($usernameAttribute !== '') { | |
| 557 | - $username = $this->readAttribute($fdn, $usernameAttribute); | |
| 558 | - $username = $username[0]; | |
| 559 | -			} else { | |
| 560 | - $username = $uuid; | |
| 561 | - } | |
| 562 | - $intName = $this->sanitizeUsername($username); | |
| 563 | -		} else { | |
| 564 | - $intName = $ldapName; | |
| 565 | - } | |
| 566 | - | |
| 567 | - //a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups | |
| 568 | - //disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check | |
| 569 | - //NOTE: mind, disabling cache affects only this instance! Using it | |
| 570 | - // outside of core user management will still cache the user as non-existing. | |
| 571 | - $originalTTL = $this->connection->ldapCacheTTL; | |
| 572 | -		$this->connection->setConfiguration(array('ldapCacheTTL' => 0)); | |
| 573 | - if(($isUser && !\OCP\User::userExists($intName)) | |
| 574 | -			|| (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))) { | |
| 575 | -			if($mapper->map($fdn, $intName, $uuid)) { | |
| 576 | -				$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL)); | |
| 577 | - return $intName; | |
| 578 | - } | |
| 579 | - } | |
| 580 | -		$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL)); | |
| 581 | - | |
| 582 | - $altName = $this->createAltInternalOwnCloudName($intName, $isUser); | |
| 583 | -		if(is_string($altName) && $mapper->map($fdn, $altName, $uuid)) { | |
| 584 | - return $altName; | |
| 585 | - } | |
| 586 | - | |
| 587 | - //if everything else did not help.. | |
| 588 | -		\OCP\Util::writeLog('user_ldap', 'Could not create unique name for '.$fdn.'.', \OCP\Util::INFO); | |
| 589 | - return false; | |
| 590 | - } | |
| 591 | - | |
| 592 | - /** | |
| 593 | - * gives back the user names as they are used ownClod internally | |
| 594 | - * @param array $ldapUsers as returned by fetchList() | |
| 595 | - * @return array an array with the user names to use in Nextcloud | |
| 596 | - * | |
| 597 | - * gives back the user names as they are used ownClod internally | |
| 598 | - */ | |
| 599 | -	public function nextcloudUserNames($ldapUsers) { | |
| 600 | - return $this->ldap2NextcloudNames($ldapUsers, true); | |
| 601 | - } | |
| 602 | - | |
| 603 | - /** | |
| 604 | - * gives back the group names as they are used ownClod internally | |
| 605 | - * @param array $ldapGroups as returned by fetchList() | |
| 606 | - * @return array an array with the group names to use in Nextcloud | |
| 607 | - * | |
| 608 | - * gives back the group names as they are used ownClod internally | |
| 609 | - */ | |
| 610 | -	public function nextcloudGroupNames($ldapGroups) { | |
| 611 | - return $this->ldap2NextcloudNames($ldapGroups, false); | |
| 612 | - } | |
| 613 | - | |
| 614 | - /** | |
| 615 | - * @param array $ldapObjects as returned by fetchList() | |
| 616 | - * @param bool $isUsers | |
| 617 | - * @return array | |
| 618 | - */ | |
| 619 | -	private function ldap2NextcloudNames($ldapObjects, $isUsers) { | |
| 620 | -		if($isUsers) { | |
| 621 | - $nameAttribute = $this->connection->ldapUserDisplayName; | |
| 622 | - $sndAttribute = $this->connection->ldapUserDisplayName2; | |
| 623 | -		} else { | |
| 624 | - $nameAttribute = $this->connection->ldapGroupDisplayName; | |
| 625 | - } | |
| 626 | - $nextcloudNames = array(); | |
| 627 | - | |
| 628 | -		foreach($ldapObjects as $ldapObject) { | |
| 629 | - $nameByLDAP = null; | |
| 630 | - if( isset($ldapObject[$nameAttribute]) | |
| 631 | - && is_array($ldapObject[$nameAttribute]) | |
| 632 | - && isset($ldapObject[$nameAttribute][0]) | |
| 633 | -			) { | |
| 634 | - // might be set, but not necessarily. if so, we use it. | |
| 635 | - $nameByLDAP = $ldapObject[$nameAttribute][0]; | |
| 636 | - } | |
| 637 | - | |
| 638 | - $ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers); | |
| 639 | -			if($ncName) { | |
| 640 | - $nextcloudNames[] = $ncName; | |
| 641 | -				if($isUsers) { | |
| 642 | - //cache the user names so it does not need to be retrieved | |
| 643 | - //again later (e.g. sharing dialogue). | |
| 644 | -					if(is_null($nameByLDAP)) { | |
| 645 | - continue; | |
| 646 | - } | |
| 647 | - $sndName = isset($ldapObject[$sndAttribute][0]) | |
| 648 | - ? $ldapObject[$sndAttribute][0] : ''; | |
| 649 | - $this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName); | |
| 650 | - } | |
| 651 | - } | |
| 652 | - } | |
| 653 | - return $nextcloudNames; | |
| 654 | - } | |
| 655 | - | |
| 656 | - /** | |
| 657 | - * caches the user display name | |
| 658 | - * @param string $ocName the internal Nextcloud username | |
| 659 | - * @param string|false $home the home directory path | |
| 660 | - */ | |
| 661 | -	public function cacheUserHome($ocName, $home) { | |
| 662 | - $cacheKey = 'getHome'.$ocName; | |
| 663 | - $this->connection->writeToCache($cacheKey, $home); | |
| 664 | - } | |
| 665 | - | |
| 666 | - /** | |
| 667 | - * caches a user as existing | |
| 668 | - * @param string $ocName the internal Nextcloud username | |
| 669 | - */ | |
| 670 | -	public function cacheUserExists($ocName) { | |
| 671 | -		$this->connection->writeToCache('userExists'.$ocName, true); | |
| 672 | - } | |
| 673 | - | |
| 674 | - /** | |
| 675 | - * caches the user display name | |
| 676 | - * @param string $ocName the internal Nextcloud username | |
| 677 | - * @param string $displayName the display name | |
| 678 | - * @param string $displayName2 the second display name | |
| 679 | - */ | |
| 680 | -	public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') { | |
| 681 | - $user = $this->userManager->get($ocName); | |
| 682 | -		if($user === null) { | |
| 683 | - return; | |
| 684 | - } | |
| 685 | - $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2); | |
| 686 | - $cacheKeyTrunk = 'getDisplayName'; | |
| 687 | - $this->connection->writeToCache($cacheKeyTrunk.$ocName, $displayName); | |
| 688 | - } | |
| 689 | - | |
| 690 | - /** | |
| 691 | - * creates a unique name for internal Nextcloud use for users. Don't call it directly. | |
| 692 | - * @param string $name the display name of the object | |
| 693 | - * @return string|false with with the name to use in Nextcloud or false if unsuccessful | |
| 694 | - * | |
| 695 | - * Instead of using this method directly, call | |
| 696 | - * createAltInternalOwnCloudName($name, true) | |
| 697 | - */ | |
| 698 | -	private function _createAltInternalOwnCloudNameForUsers($name) { | |
| 699 | - $attempts = 0; | |
| 700 | - //while loop is just a precaution. If a name is not generated within | |
| 701 | - //20 attempts, something else is very wrong. Avoids infinite loop. | |
| 702 | -		while($attempts < 20){ | |
| 703 | - $altName = $name . '_' . rand(1000,9999); | |
| 704 | -			if(!\OCP\User::userExists($altName)) { | |
| 705 | - return $altName; | |
| 706 | - } | |
| 707 | - $attempts++; | |
| 708 | - } | |
| 709 | - return false; | |
| 710 | - } | |
| 711 | - | |
| 712 | - /** | |
| 713 | - * creates a unique name for internal Nextcloud use for groups. Don't call it directly. | |
| 714 | - * @param string $name the display name of the object | |
| 715 | - * @return string|false with with the name to use in Nextcloud or false if unsuccessful. | |
| 716 | - * | |
| 717 | - * Instead of using this method directly, call | |
| 718 | - * createAltInternalOwnCloudName($name, false) | |
| 719 | - * | |
| 720 | - * Group names are also used as display names, so we do a sequential | |
| 721 | - * numbering, e.g. Developers_42 when there are 41 other groups called | |
| 722 | - * "Developers" | |
| 723 | - */ | |
| 724 | -	private function _createAltInternalOwnCloudNameForGroups($name) { | |
| 725 | - $usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%'); | |
| 726 | -		if(!($usedNames) || count($usedNames) === 0) { | |
| 727 | - $lastNo = 1; //will become name_2 | |
| 728 | -		} else { | |
| 729 | - natsort($usedNames); | |
| 730 | - $lastName = array_pop($usedNames); | |
| 731 | - $lastNo = intval(substr($lastName, strrpos($lastName, '_') + 1)); | |
| 732 | - } | |
| 733 | - $altName = $name.'_'.strval($lastNo+1); | |
| 734 | - unset($usedNames); | |
| 735 | - | |
| 736 | - $attempts = 1; | |
| 737 | -		while($attempts < 21){ | |
| 738 | - // Check to be really sure it is unique | |
| 739 | - // while loop is just a precaution. If a name is not generated within | |
| 740 | - // 20 attempts, something else is very wrong. Avoids infinite loop. | |
| 741 | -			if(!\OC::$server->getGroupManager()->groupExists($altName)) { | |
| 742 | - return $altName; | |
| 743 | - } | |
| 744 | - $altName = $name . '_' . ($lastNo + $attempts); | |
| 745 | - $attempts++; | |
| 746 | - } | |
| 747 | - return false; | |
| 748 | - } | |
| 749 | - | |
| 750 | - /** | |
| 751 | - * creates a unique name for internal Nextcloud use. | |
| 752 | - * @param string $name the display name of the object | |
| 753 | - * @param boolean $isUser whether name should be created for a user (true) or a group (false) | |
| 754 | - * @return string|false with with the name to use in Nextcloud or false if unsuccessful | |
| 755 | - */ | |
| 756 | -	private function createAltInternalOwnCloudName($name, $isUser) { | |
| 757 | - $originalTTL = $this->connection->ldapCacheTTL; | |
| 758 | -		$this->connection->setConfiguration(array('ldapCacheTTL' => 0)); | |
| 759 | -		if($isUser) { | |
| 760 | - $altName = $this->_createAltInternalOwnCloudNameForUsers($name); | |
| 761 | -		} else { | |
| 762 | - $altName = $this->_createAltInternalOwnCloudNameForGroups($name); | |
| 763 | - } | |
| 764 | -		$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL)); | |
| 765 | - | |
| 766 | - return $altName; | |
| 767 | - } | |
| 768 | - | |
| 769 | - /** | |
| 770 | - * fetches a list of users according to a provided loginName and utilizing | |
| 771 | - * the login filter. | |
| 772 | - * | |
| 773 | - * @param string $loginName | |
| 774 | - * @param array $attributes optional, list of attributes to read | |
| 775 | - * @return array | |
| 776 | - */ | |
| 777 | -	public function fetchUsersByLoginName($loginName, $attributes = array('dn')) { | |
| 778 | - $loginName = $this->escapeFilterPart($loginName); | |
| 779 | -		$filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter); | |
| 780 | - $users = $this->fetchListOfUsers($filter, $attributes); | |
| 781 | - return $users; | |
| 782 | - } | |
| 783 | - | |
| 784 | - /** | |
| 785 | - * counts the number of users according to a provided loginName and | |
| 786 | - * utilizing the login filter. | |
| 787 | - * | |
| 788 | - * @param string $loginName | |
| 789 | - * @return array | |
| 790 | - */ | |
| 791 | -	public function countUsersByLoginName($loginName) { | |
| 792 | - $loginName = $this->escapeFilterPart($loginName); | |
| 793 | -		$filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter); | |
| 794 | - $users = $this->countUsers($filter); | |
| 795 | - return $users; | |
| 796 | - } | |
| 797 | - | |
| 798 | - /** | |
| 799 | - * @param string $filter | |
| 800 | - * @param string|string[] $attr | |
| 801 | - * @param int $limit | |
| 802 | - * @param int $offset | |
| 803 | - * @return array | |
| 804 | - */ | |
| 805 | -	public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null) { | |
| 806 | - $ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset); | |
| 807 | - $this->batchApplyUserAttributes($ldapRecords); | |
| 808 | - return $this->fetchList($ldapRecords, (count($attr) > 1)); | |
| 809 | - } | |
| 810 | - | |
| 811 | - /** | |
| 812 | - * provided with an array of LDAP user records the method will fetch the | |
| 813 | - * user object and requests it to process the freshly fetched attributes and | |
| 814 | - * and their values | |
| 815 | - * @param array $ldapRecords | |
| 816 | - */ | |
| 817 | -	public function batchApplyUserAttributes(array $ldapRecords){ | |
| 818 | - $displayNameAttribute = strtolower($this->connection->ldapUserDisplayName); | |
| 819 | -		foreach($ldapRecords as $userRecord) { | |
| 820 | -			if(!isset($userRecord[$displayNameAttribute])) { | |
| 821 | - // displayName is obligatory | |
| 822 | - continue; | |
| 823 | - } | |
| 824 | - $ocName = $this->dn2ocname($userRecord['dn'][0]); | |
| 825 | -			if($ocName === false) { | |
| 826 | - continue; | |
| 827 | - } | |
| 828 | - $this->cacheUserExists($ocName); | |
| 829 | - $user = $this->userManager->get($ocName); | |
| 830 | -			if($user instanceof OfflineUser) { | |
| 831 | - $user->unmark(); | |
| 832 | - $user = $this->userManager->get($ocName); | |
| 833 | - } | |
| 834 | -			if ($user !== null) { | |
| 835 | - $user->processAttributes($userRecord); | |
| 836 | -			} else { | |
| 837 | - \OC::$server->getLogger()->debug( | |
| 838 | - "The ldap user manager returned null for $ocName", | |
| 839 | - ['app'=>'user_ldap'] | |
| 840 | - ); | |
| 841 | - } | |
| 842 | - } | |
| 843 | - } | |
| 844 | - | |
| 845 | - /** | |
| 846 | - * @param string $filter | |
| 847 | - * @param string|string[] $attr | |
| 848 | - * @param int $limit | |
| 849 | - * @param int $offset | |
| 850 | - * @return array | |
| 851 | - */ | |
| 852 | -	public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) { | |
| 853 | - return $this->fetchList($this->searchGroups($filter, $attr, $limit, $offset), (count($attr) > 1)); | |
| 854 | - } | |
| 855 | - | |
| 856 | - /** | |
| 857 | - * @param array $list | |
| 858 | - * @param bool $manyAttributes | |
| 859 | - * @return array | |
| 860 | - */ | |
| 861 | -	private function fetchList($list, $manyAttributes) { | |
| 862 | -		if(is_array($list)) { | |
| 863 | -			if($manyAttributes) { | |
| 864 | - return $list; | |
| 865 | -			} else { | |
| 866 | -				$list = array_reduce($list, function($carry, $item) { | |
| 867 | - $attribute = array_keys($item)[0]; | |
| 868 | - $carry[] = $item[$attribute][0]; | |
| 869 | - return $carry; | |
| 870 | - }, array()); | |
| 871 | - return array_unique($list, SORT_LOCALE_STRING); | |
| 872 | - } | |
| 873 | - } | |
| 874 | - | |
| 875 | - //error cause actually, maybe throw an exception in future. | |
| 876 | - return array(); | |
| 877 | - } | |
| 878 | - | |
| 879 | - /** | |
| 880 | - * executes an LDAP search, optimized for Users | |
| 881 | - * @param string $filter the LDAP filter for the search | |
| 882 | - * @param string|string[] $attr optional, when a certain attribute shall be filtered out | |
| 883 | - * @param integer $limit | |
| 884 | - * @param integer $offset | |
| 885 | - * @return array with the search result | |
| 886 | - * | |
| 887 | - * Executes an LDAP search | |
| 888 | - */ | |
| 889 | -	public function searchUsers($filter, $attr = null, $limit = null, $offset = null) { | |
| 890 | - return $this->search($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset); | |
| 891 | - } | |
| 892 | - | |
| 893 | - /** | |
| 894 | - * @param string $filter | |
| 895 | - * @param string|string[] $attr | |
| 896 | - * @param int $limit | |
| 897 | - * @param int $offset | |
| 898 | - * @return false|int | |
| 899 | - */ | |
| 900 | -	public function countUsers($filter, $attr = array('dn'), $limit = null, $offset = null) { | |
| 901 | - return $this->count($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset); | |
| 902 | - } | |
| 903 | - | |
| 904 | - /** | |
| 905 | - * executes an LDAP search, optimized for Groups | |
| 906 | - * @param string $filter the LDAP filter for the search | |
| 907 | - * @param string|string[] $attr optional, when a certain attribute shall be filtered out | |
| 908 | - * @param integer $limit | |
| 909 | - * @param integer $offset | |
| 910 | - * @return array with the search result | |
| 911 | - * | |
| 912 | - * Executes an LDAP search | |
| 913 | - */ | |
| 914 | -	public function searchGroups($filter, $attr = null, $limit = null, $offset = null) { | |
| 915 | - return $this->search($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset); | |
| 916 | - } | |
| 917 | - | |
| 918 | - /** | |
| 919 | - * returns the number of available groups | |
| 920 | - * @param string $filter the LDAP search filter | |
| 921 | - * @param string[] $attr optional | |
| 922 | - * @param int|null $limit | |
| 923 | - * @param int|null $offset | |
| 924 | - * @return int|bool | |
| 925 | - */ | |
| 926 | -	public function countGroups($filter, $attr = array('dn'), $limit = null, $offset = null) { | |
| 927 | - return $this->count($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset); | |
| 928 | - } | |
| 929 | - | |
| 930 | - /** | |
| 931 | - * returns the number of available objects on the base DN | |
| 932 | - * | |
| 933 | - * @param int|null $limit | |
| 934 | - * @param int|null $offset | |
| 935 | - * @return int|bool | |
| 936 | - */ | |
| 937 | -	public function countObjects($limit = null, $offset = null) { | |
| 938 | -		return $this->count('objectclass=*', $this->connection->ldapBase, array('dn'), $limit, $offset); | |
| 939 | - } | |
| 940 | - | |
| 941 | - /** | |
| 942 | - * Returns the LDAP handler | |
| 943 | - * @throws \OC\ServerNotAvailableException | |
| 944 | - */ | |
| 945 | - | |
| 946 | - /** | |
| 947 | - * @return mixed | |
| 948 | - * @throws \OC\ServerNotAvailableException | |
| 949 | - */ | |
| 950 | -	private function invokeLDAPMethod() { | |
| 951 | - $arguments = func_get_args(); | |
| 952 | - $command = array_shift($arguments); | |
| 953 | - $cr = array_shift($arguments); | |
| 954 | -		if (!method_exists($this->ldap, $command)) { | |
| 955 | - return null; | |
| 956 | - } | |
| 957 | - array_unshift($arguments, $cr); | |
| 958 | - // php no longer supports call-time pass-by-reference | |
| 959 | - // thus cannot support controlPagedResultResponse as the third argument | |
| 960 | - // is a reference | |
| 961 | -		$doMethod = function () use ($command, &$arguments) { | |
| 962 | -			if ($command == 'controlPagedResultResponse') { | |
| 963 | -				throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.'); | |
| 964 | -			} else { | |
| 965 | - return call_user_func_array(array($this->ldap, $command), $arguments); | |
| 966 | - } | |
| 967 | - }; | |
| 968 | -		try { | |
| 969 | - $ret = $doMethod(); | |
| 970 | -		} catch (ServerNotAvailableException $e) { | |
| 971 | - /* Server connection lost, attempt to reestablish it | |
| 329 | + /** | |
| 330 | + * Set password for an LDAP user identified by a DN | |
| 331 | + * | |
| 332 | + * @param string $userDN the user in question | |
| 333 | + * @param string $password the new password | |
| 334 | + * @return bool | |
| 335 | + * @throws HintException | |
| 336 | + * @throws \Exception | |
| 337 | + */ | |
| 338 | +    public function setPassword($userDN, $password) { | |
| 339 | +        if(intval($this->connection->turnOnPasswordChange) !== 1) { | |
| 340 | +            throw new \Exception('LDAP password changes are disabled.'); | |
| 341 | + } | |
| 342 | + $cr = $this->connection->getConnectionResource(); | |
| 343 | +        if(!$this->ldap->isResource($cr)) { | |
| 344 | + //LDAP not available | |
| 345 | +            \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG); | |
| 346 | + return false; | |
| 347 | + } | |
| 348 | +        try { | |
| 349 | +            return @$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password); | |
| 350 | +        } catch(ConstraintViolationException $e) { | |
| 351 | +            throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode()); | |
| 352 | + } | |
| 353 | + } | |
| 354 | + | |
| 355 | + /** | |
| 356 | + * checks whether the given attributes value is probably a DN | |
| 357 | + * @param string $attr the attribute in question | |
| 358 | + * @return boolean if so true, otherwise false | |
| 359 | + */ | |
| 360 | +    private function resemblesDN($attr) { | |
| 361 | + $resemblingAttributes = array( | |
| 362 | + 'dn', | |
| 363 | + 'uniquemember', | |
| 364 | + 'member', | |
| 365 | + // memberOf is an "operational" attribute, without a definition in any RFC | |
| 366 | + 'memberof' | |
| 367 | + ); | |
| 368 | + return in_array($attr, $resemblingAttributes); | |
| 369 | + } | |
| 370 | + | |
| 371 | + /** | |
| 372 | + * checks whether the given string is probably a DN | |
| 373 | + * @param string $string | |
| 374 | + * @return boolean | |
| 375 | + */ | |
| 376 | +    public function stringResemblesDN($string) { | |
| 377 | + $r = $this->ldap->explodeDN($string, 0); | |
| 378 | + // if exploding a DN succeeds and does not end up in | |
| 379 | + // an empty array except for $r[count] being 0. | |
| 380 | + return (is_array($r) && count($r) > 1); | |
| 381 | + } | |
| 382 | + | |
| 383 | + /** | |
| 384 | + * returns a DN-string that is cleaned from not domain parts, e.g. | |
| 385 | + * cn=foo,cn=bar,dc=foobar,dc=server,dc=org | |
| 386 | + * becomes dc=foobar,dc=server,dc=org | |
| 387 | + * @param string $dn | |
| 388 | + * @return string | |
| 389 | + */ | |
| 390 | +    public function getDomainDNFromDN($dn) { | |
| 391 | + $allParts = $this->ldap->explodeDN($dn, 0); | |
| 392 | +        if($allParts === false) { | |
| 393 | + //not a valid DN | |
| 394 | + return ''; | |
| 395 | + } | |
| 396 | + $domainParts = array(); | |
| 397 | + $dcFound = false; | |
| 398 | +        foreach($allParts as $part) { | |
| 399 | +            if(!$dcFound && strpos($part, 'dc=') === 0) { | |
| 400 | + $dcFound = true; | |
| 401 | + } | |
| 402 | +            if($dcFound) { | |
| 403 | + $domainParts[] = $part; | |
| 404 | + } | |
| 405 | + } | |
| 406 | +        $domainDN = implode(',', $domainParts); | |
| 407 | + return $domainDN; | |
| 408 | + } | |
| 409 | + | |
| 410 | + /** | |
| 411 | + * returns the LDAP DN for the given internal Nextcloud name of the group | |
| 412 | + * @param string $name the Nextcloud name in question | |
| 413 | + * @return string|false LDAP DN on success, otherwise false | |
| 414 | + */ | |
| 415 | +    public function groupname2dn($name) { | |
| 416 | + return $this->groupMapper->getDNByName($name); | |
| 417 | + } | |
| 418 | + | |
| 419 | + /** | |
| 420 | + * returns the LDAP DN for the given internal Nextcloud name of the user | |
| 421 | + * @param string $name the Nextcloud name in question | |
| 422 | + * @return string|false with the LDAP DN on success, otherwise false | |
| 423 | + */ | |
| 424 | +    public function username2dn($name) { | |
| 425 | + $fdn = $this->userMapper->getDNByName($name); | |
| 426 | + | |
| 427 | + //Check whether the DN belongs to the Base, to avoid issues on multi- | |
| 428 | + //server setups | |
| 429 | +        if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) { | |
| 430 | + return $fdn; | |
| 431 | + } | |
| 432 | + | |
| 433 | + return false; | |
| 434 | + } | |
| 435 | + | |
| 436 | + /** | |
| 437 | + * returns the internal Nextcloud name for the given LDAP DN of the group, false on DN outside of search DN or failure | |
| 438 | + * @param string $fdn the dn of the group object | |
| 439 | + * @param string $ldapName optional, the display name of the object | |
| 440 | + * @return string|false with the name to use in Nextcloud, false on DN outside of search DN | |
| 441 | + */ | |
| 442 | +    public function dn2groupname($fdn, $ldapName = null) { | |
| 443 | + //To avoid bypassing the base DN settings under certain circumstances | |
| 444 | + //with the group support, check whether the provided DN matches one of | |
| 445 | + //the given Bases | |
| 446 | +        if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) { | |
| 447 | + return false; | |
| 448 | + } | |
| 449 | + | |
| 450 | + return $this->dn2ocname($fdn, $ldapName, false); | |
| 451 | + } | |
| 452 | + | |
| 453 | + /** | |
| 454 | + * accepts an array of group DNs and tests whether they match the user | |
| 455 | + * filter by doing read operations against the group entries. Returns an | |
| 456 | + * array of DNs that match the filter. | |
| 457 | + * | |
| 458 | + * @param string[] $groupDNs | |
| 459 | + * @return string[] | |
| 460 | + */ | |
| 461 | +    public function groupsMatchFilter($groupDNs) { | |
| 462 | + $validGroupDNs = []; | |
| 463 | +        foreach($groupDNs as $dn) { | |
| 464 | + $cacheKey = 'groupsMatchFilter-'.$dn; | |
| 465 | + $groupMatchFilter = $this->connection->getFromCache($cacheKey); | |
| 466 | +            if(!is_null($groupMatchFilter)) { | |
| 467 | +                if($groupMatchFilter) { | |
| 468 | + $validGroupDNs[] = $dn; | |
| 469 | + } | |
| 470 | + continue; | |
| 471 | + } | |
| 472 | + | |
| 473 | + // Check the base DN first. If this is not met already, we don't | |
| 474 | + // need to ask the server at all. | |
| 475 | +            if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) { | |
| 476 | + $this->connection->writeToCache($cacheKey, false); | |
| 477 | + continue; | |
| 478 | + } | |
| 479 | + | |
| 480 | + $result = $this->readAttribute($dn, 'cn', $this->connection->ldapGroupFilter); | |
| 481 | +            if(is_array($result)) { | |
| 482 | + $this->connection->writeToCache($cacheKey, true); | |
| 483 | + $validGroupDNs[] = $dn; | |
| 484 | +            } else { | |
| 485 | + $this->connection->writeToCache($cacheKey, false); | |
| 486 | + } | |
| 487 | + | |
| 488 | + } | |
| 489 | + return $validGroupDNs; | |
| 490 | + } | |
| 491 | + | |
| 492 | + /** | |
| 493 | + * returns the internal Nextcloud name for the given LDAP DN of the user, false on DN outside of search DN or failure | |
| 494 | + * @param string $dn the dn of the user object | |
| 495 | + * @param string $ldapName optional, the display name of the object | |
| 496 | + * @return string|false with with the name to use in Nextcloud | |
| 497 | + */ | |
| 498 | +    public function dn2username($fdn, $ldapName = null) { | |
| 499 | + //To avoid bypassing the base DN settings under certain circumstances | |
| 500 | + //with the group support, check whether the provided DN matches one of | |
| 501 | + //the given Bases | |
| 502 | +        if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) { | |
| 503 | + return false; | |
| 504 | + } | |
| 505 | + | |
| 506 | + return $this->dn2ocname($fdn, $ldapName, true); | |
| 507 | + } | |
| 508 | + | |
| 509 | + /** | |
| 510 | + * returns an internal Nextcloud name for the given LDAP DN, false on DN outside of search DN | |
| 511 | + * @param string $dn the dn of the user object | |
| 512 | + * @param string $ldapName optional, the display name of the object | |
| 513 | + * @param bool $isUser optional, whether it is a user object (otherwise group assumed) | |
| 514 | + * @return string|false with with the name to use in Nextcloud | |
| 515 | + */ | |
| 516 | +    public function dn2ocname($fdn, $ldapName = null, $isUser = true) { | |
| 517 | +        if($isUser) { | |
| 518 | + $mapper = $this->getUserMapper(); | |
| 519 | + $nameAttribute = $this->connection->ldapUserDisplayName; | |
| 520 | +        } else { | |
| 521 | + $mapper = $this->getGroupMapper(); | |
| 522 | + $nameAttribute = $this->connection->ldapGroupDisplayName; | |
| 523 | + } | |
| 524 | + | |
| 525 | + //let's try to retrieve the Nextcloud name from the mappings table | |
| 526 | + $ocName = $mapper->getNameByDN($fdn); | |
| 527 | +        if(is_string($ocName)) { | |
| 528 | + return $ocName; | |
| 529 | + } | |
| 530 | + | |
| 531 | + //second try: get the UUID and check if it is known. Then, update the DN and return the name. | |
| 532 | + $uuid = $this->getUUID($fdn, $isUser); | |
| 533 | +        if(is_string($uuid)) { | |
| 534 | + $ocName = $mapper->getNameByUUID($uuid); | |
| 535 | +            if(is_string($ocName)) { | |
| 536 | + $mapper->setDNbyUUID($fdn, $uuid); | |
| 537 | + return $ocName; | |
| 538 | + } | |
| 539 | +        } else { | |
| 540 | + //If the UUID can't be detected something is foul. | |
| 541 | +            \OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for '.$fdn.'. Skipping.', \OCP\Util::INFO); | |
| 542 | + return false; | |
| 543 | + } | |
| 544 | + | |
| 545 | +        if(is_null($ldapName)) { | |
| 546 | + $ldapName = $this->readAttribute($fdn, $nameAttribute); | |
| 547 | +            if(!isset($ldapName[0]) && empty($ldapName[0])) { | |
| 548 | +                \OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.'.', \OCP\Util::INFO); | |
| 549 | + return false; | |
| 550 | + } | |
| 551 | + $ldapName = $ldapName[0]; | |
| 552 | + } | |
| 553 | + | |
| 554 | +        if($isUser) { | |
| 555 | + $usernameAttribute = strval($this->connection->ldapExpertUsernameAttr); | |
| 556 | +            if ($usernameAttribute !== '') { | |
| 557 | + $username = $this->readAttribute($fdn, $usernameAttribute); | |
| 558 | + $username = $username[0]; | |
| 559 | +            } else { | |
| 560 | + $username = $uuid; | |
| 561 | + } | |
| 562 | + $intName = $this->sanitizeUsername($username); | |
| 563 | +        } else { | |
| 564 | + $intName = $ldapName; | |
| 565 | + } | |
| 566 | + | |
| 567 | + //a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups | |
| 568 | + //disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check | |
| 569 | + //NOTE: mind, disabling cache affects only this instance! Using it | |
| 570 | + // outside of core user management will still cache the user as non-existing. | |
| 571 | + $originalTTL = $this->connection->ldapCacheTTL; | |
| 572 | +        $this->connection->setConfiguration(array('ldapCacheTTL' => 0)); | |
| 573 | + if(($isUser && !\OCP\User::userExists($intName)) | |
| 574 | +            || (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))) { | |
| 575 | +            if($mapper->map($fdn, $intName, $uuid)) { | |
| 576 | +                $this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL)); | |
| 577 | + return $intName; | |
| 578 | + } | |
| 579 | + } | |
| 580 | +        $this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL)); | |
| 581 | + | |
| 582 | + $altName = $this->createAltInternalOwnCloudName($intName, $isUser); | |
| 583 | +        if(is_string($altName) && $mapper->map($fdn, $altName, $uuid)) { | |
| 584 | + return $altName; | |
| 585 | + } | |
| 586 | + | |
| 587 | + //if everything else did not help.. | |
| 588 | +        \OCP\Util::writeLog('user_ldap', 'Could not create unique name for '.$fdn.'.', \OCP\Util::INFO); | |
| 589 | + return false; | |
| 590 | + } | |
| 591 | + | |
| 592 | + /** | |
| 593 | + * gives back the user names as they are used ownClod internally | |
| 594 | + * @param array $ldapUsers as returned by fetchList() | |
| 595 | + * @return array an array with the user names to use in Nextcloud | |
| 596 | + * | |
| 597 | + * gives back the user names as they are used ownClod internally | |
| 598 | + */ | |
| 599 | +    public function nextcloudUserNames($ldapUsers) { | |
| 600 | + return $this->ldap2NextcloudNames($ldapUsers, true); | |
| 601 | + } | |
| 602 | + | |
| 603 | + /** | |
| 604 | + * gives back the group names as they are used ownClod internally | |
| 605 | + * @param array $ldapGroups as returned by fetchList() | |
| 606 | + * @return array an array with the group names to use in Nextcloud | |
| 607 | + * | |
| 608 | + * gives back the group names as they are used ownClod internally | |
| 609 | + */ | |
| 610 | +    public function nextcloudGroupNames($ldapGroups) { | |
| 611 | + return $this->ldap2NextcloudNames($ldapGroups, false); | |
| 612 | + } | |
| 613 | + | |
| 614 | + /** | |
| 615 | + * @param array $ldapObjects as returned by fetchList() | |
| 616 | + * @param bool $isUsers | |
| 617 | + * @return array | |
| 618 | + */ | |
| 619 | +    private function ldap2NextcloudNames($ldapObjects, $isUsers) { | |
| 620 | +        if($isUsers) { | |
| 621 | + $nameAttribute = $this->connection->ldapUserDisplayName; | |
| 622 | + $sndAttribute = $this->connection->ldapUserDisplayName2; | |
| 623 | +        } else { | |
| 624 | + $nameAttribute = $this->connection->ldapGroupDisplayName; | |
| 625 | + } | |
| 626 | + $nextcloudNames = array(); | |
| 627 | + | |
| 628 | +        foreach($ldapObjects as $ldapObject) { | |
| 629 | + $nameByLDAP = null; | |
| 630 | + if( isset($ldapObject[$nameAttribute]) | |
| 631 | + && is_array($ldapObject[$nameAttribute]) | |
| 632 | + && isset($ldapObject[$nameAttribute][0]) | |
| 633 | +            ) { | |
| 634 | + // might be set, but not necessarily. if so, we use it. | |
| 635 | + $nameByLDAP = $ldapObject[$nameAttribute][0]; | |
| 636 | + } | |
| 637 | + | |
| 638 | + $ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers); | |
| 639 | +            if($ncName) { | |
| 640 | + $nextcloudNames[] = $ncName; | |
| 641 | +                if($isUsers) { | |
| 642 | + //cache the user names so it does not need to be retrieved | |
| 643 | + //again later (e.g. sharing dialogue). | |
| 644 | +                    if(is_null($nameByLDAP)) { | |
| 645 | + continue; | |
| 646 | + } | |
| 647 | + $sndName = isset($ldapObject[$sndAttribute][0]) | |
| 648 | + ? $ldapObject[$sndAttribute][0] : ''; | |
| 649 | + $this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName); | |
| 650 | + } | |
| 651 | + } | |
| 652 | + } | |
| 653 | + return $nextcloudNames; | |
| 654 | + } | |
| 655 | + | |
| 656 | + /** | |
| 657 | + * caches the user display name | |
| 658 | + * @param string $ocName the internal Nextcloud username | |
| 659 | + * @param string|false $home the home directory path | |
| 660 | + */ | |
| 661 | +    public function cacheUserHome($ocName, $home) { | |
| 662 | + $cacheKey = 'getHome'.$ocName; | |
| 663 | + $this->connection->writeToCache($cacheKey, $home); | |
| 664 | + } | |
| 665 | + | |
| 666 | + /** | |
| 667 | + * caches a user as existing | |
| 668 | + * @param string $ocName the internal Nextcloud username | |
| 669 | + */ | |
| 670 | +    public function cacheUserExists($ocName) { | |
| 671 | +        $this->connection->writeToCache('userExists'.$ocName, true); | |
| 672 | + } | |
| 673 | + | |
| 674 | + /** | |
| 675 | + * caches the user display name | |
| 676 | + * @param string $ocName the internal Nextcloud username | |
| 677 | + * @param string $displayName the display name | |
| 678 | + * @param string $displayName2 the second display name | |
| 679 | + */ | |
| 680 | +    public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') { | |
| 681 | + $user = $this->userManager->get($ocName); | |
| 682 | +        if($user === null) { | |
| 683 | + return; | |
| 684 | + } | |
| 685 | + $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2); | |
| 686 | + $cacheKeyTrunk = 'getDisplayName'; | |
| 687 | + $this->connection->writeToCache($cacheKeyTrunk.$ocName, $displayName); | |
| 688 | + } | |
| 689 | + | |
| 690 | + /** | |
| 691 | + * creates a unique name for internal Nextcloud use for users. Don't call it directly. | |
| 692 | + * @param string $name the display name of the object | |
| 693 | + * @return string|false with with the name to use in Nextcloud or false if unsuccessful | |
| 694 | + * | |
| 695 | + * Instead of using this method directly, call | |
| 696 | + * createAltInternalOwnCloudName($name, true) | |
| 697 | + */ | |
| 698 | +    private function _createAltInternalOwnCloudNameForUsers($name) { | |
| 699 | + $attempts = 0; | |
| 700 | + //while loop is just a precaution. If a name is not generated within | |
| 701 | + //20 attempts, something else is very wrong. Avoids infinite loop. | |
| 702 | +        while($attempts < 20){ | |
| 703 | + $altName = $name . '_' . rand(1000,9999); | |
| 704 | +            if(!\OCP\User::userExists($altName)) { | |
| 705 | + return $altName; | |
| 706 | + } | |
| 707 | + $attempts++; | |
| 708 | + } | |
| 709 | + return false; | |
| 710 | + } | |
| 711 | + | |
| 712 | + /** | |
| 713 | + * creates a unique name for internal Nextcloud use for groups. Don't call it directly. | |
| 714 | + * @param string $name the display name of the object | |
| 715 | + * @return string|false with with the name to use in Nextcloud or false if unsuccessful. | |
| 716 | + * | |
| 717 | + * Instead of using this method directly, call | |
| 718 | + * createAltInternalOwnCloudName($name, false) | |
| 719 | + * | |
| 720 | + * Group names are also used as display names, so we do a sequential | |
| 721 | + * numbering, e.g. Developers_42 when there are 41 other groups called | |
| 722 | + * "Developers" | |
| 723 | + */ | |
| 724 | +    private function _createAltInternalOwnCloudNameForGroups($name) { | |
| 725 | + $usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%'); | |
| 726 | +        if(!($usedNames) || count($usedNames) === 0) { | |
| 727 | + $lastNo = 1; //will become name_2 | |
| 728 | +        } else { | |
| 729 | + natsort($usedNames); | |
| 730 | + $lastName = array_pop($usedNames); | |
| 731 | + $lastNo = intval(substr($lastName, strrpos($lastName, '_') + 1)); | |
| 732 | + } | |
| 733 | + $altName = $name.'_'.strval($lastNo+1); | |
| 734 | + unset($usedNames); | |
| 735 | + | |
| 736 | + $attempts = 1; | |
| 737 | +        while($attempts < 21){ | |
| 738 | + // Check to be really sure it is unique | |
| 739 | + // while loop is just a precaution. If a name is not generated within | |
| 740 | + // 20 attempts, something else is very wrong. Avoids infinite loop. | |
| 741 | +            if(!\OC::$server->getGroupManager()->groupExists($altName)) { | |
| 742 | + return $altName; | |
| 743 | + } | |
| 744 | + $altName = $name . '_' . ($lastNo + $attempts); | |
| 745 | + $attempts++; | |
| 746 | + } | |
| 747 | + return false; | |
| 748 | + } | |
| 749 | + | |
| 750 | + /** | |
| 751 | + * creates a unique name for internal Nextcloud use. | |
| 752 | + * @param string $name the display name of the object | |
| 753 | + * @param boolean $isUser whether name should be created for a user (true) or a group (false) | |
| 754 | + * @return string|false with with the name to use in Nextcloud or false if unsuccessful | |
| 755 | + */ | |
| 756 | +    private function createAltInternalOwnCloudName($name, $isUser) { | |
| 757 | + $originalTTL = $this->connection->ldapCacheTTL; | |
| 758 | +        $this->connection->setConfiguration(array('ldapCacheTTL' => 0)); | |
| 759 | +        if($isUser) { | |
| 760 | + $altName = $this->_createAltInternalOwnCloudNameForUsers($name); | |
| 761 | +        } else { | |
| 762 | + $altName = $this->_createAltInternalOwnCloudNameForGroups($name); | |
| 763 | + } | |
| 764 | +        $this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL)); | |
| 765 | + | |
| 766 | + return $altName; | |
| 767 | + } | |
| 768 | + | |
| 769 | + /** | |
| 770 | + * fetches a list of users according to a provided loginName and utilizing | |
| 771 | + * the login filter. | |
| 772 | + * | |
| 773 | + * @param string $loginName | |
| 774 | + * @param array $attributes optional, list of attributes to read | |
| 775 | + * @return array | |
| 776 | + */ | |
| 777 | +    public function fetchUsersByLoginName($loginName, $attributes = array('dn')) { | |
| 778 | + $loginName = $this->escapeFilterPart($loginName); | |
| 779 | +        $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter); | |
| 780 | + $users = $this->fetchListOfUsers($filter, $attributes); | |
| 781 | + return $users; | |
| 782 | + } | |
| 783 | + | |
| 784 | + /** | |
| 785 | + * counts the number of users according to a provided loginName and | |
| 786 | + * utilizing the login filter. | |
| 787 | + * | |
| 788 | + * @param string $loginName | |
| 789 | + * @return array | |
| 790 | + */ | |
| 791 | +    public function countUsersByLoginName($loginName) { | |
| 792 | + $loginName = $this->escapeFilterPart($loginName); | |
| 793 | +        $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter); | |
| 794 | + $users = $this->countUsers($filter); | |
| 795 | + return $users; | |
| 796 | + } | |
| 797 | + | |
| 798 | + /** | |
| 799 | + * @param string $filter | |
| 800 | + * @param string|string[] $attr | |
| 801 | + * @param int $limit | |
| 802 | + * @param int $offset | |
| 803 | + * @return array | |
| 804 | + */ | |
| 805 | +    public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null) { | |
| 806 | + $ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset); | |
| 807 | + $this->batchApplyUserAttributes($ldapRecords); | |
| 808 | + return $this->fetchList($ldapRecords, (count($attr) > 1)); | |
| 809 | + } | |
| 810 | + | |
| 811 | + /** | |
| 812 | + * provided with an array of LDAP user records the method will fetch the | |
| 813 | + * user object and requests it to process the freshly fetched attributes and | |
| 814 | + * and their values | |
| 815 | + * @param array $ldapRecords | |
| 816 | + */ | |
| 817 | +    public function batchApplyUserAttributes(array $ldapRecords){ | |
| 818 | + $displayNameAttribute = strtolower($this->connection->ldapUserDisplayName); | |
| 819 | +        foreach($ldapRecords as $userRecord) { | |
| 820 | +            if(!isset($userRecord[$displayNameAttribute])) { | |
| 821 | + // displayName is obligatory | |
| 822 | + continue; | |
| 823 | + } | |
| 824 | + $ocName = $this->dn2ocname($userRecord['dn'][0]); | |
| 825 | +            if($ocName === false) { | |
| 826 | + continue; | |
| 827 | + } | |
| 828 | + $this->cacheUserExists($ocName); | |
| 829 | + $user = $this->userManager->get($ocName); | |
| 830 | +            if($user instanceof OfflineUser) { | |
| 831 | + $user->unmark(); | |
| 832 | + $user = $this->userManager->get($ocName); | |
| 833 | + } | |
| 834 | +            if ($user !== null) { | |
| 835 | + $user->processAttributes($userRecord); | |
| 836 | +            } else { | |
| 837 | + \OC::$server->getLogger()->debug( | |
| 838 | + "The ldap user manager returned null for $ocName", | |
| 839 | + ['app'=>'user_ldap'] | |
| 840 | + ); | |
| 841 | + } | |
| 842 | + } | |
| 843 | + } | |
| 844 | + | |
| 845 | + /** | |
| 846 | + * @param string $filter | |
| 847 | + * @param string|string[] $attr | |
| 848 | + * @param int $limit | |
| 849 | + * @param int $offset | |
| 850 | + * @return array | |
| 851 | + */ | |
| 852 | +    public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) { | |
| 853 | + return $this->fetchList($this->searchGroups($filter, $attr, $limit, $offset), (count($attr) > 1)); | |
| 854 | + } | |
| 855 | + | |
| 856 | + /** | |
| 857 | + * @param array $list | |
| 858 | + * @param bool $manyAttributes | |
| 859 | + * @return array | |
| 860 | + */ | |
| 861 | +    private function fetchList($list, $manyAttributes) { | |
| 862 | +        if(is_array($list)) { | |
| 863 | +            if($manyAttributes) { | |
| 864 | + return $list; | |
| 865 | +            } else { | |
| 866 | +                $list = array_reduce($list, function($carry, $item) { | |
| 867 | + $attribute = array_keys($item)[0]; | |
| 868 | + $carry[] = $item[$attribute][0]; | |
| 869 | + return $carry; | |
| 870 | + }, array()); | |
| 871 | + return array_unique($list, SORT_LOCALE_STRING); | |
| 872 | + } | |
| 873 | + } | |
| 874 | + | |
| 875 | + //error cause actually, maybe throw an exception in future. | |
| 876 | + return array(); | |
| 877 | + } | |
| 878 | + | |
| 879 | + /** | |
| 880 | + * executes an LDAP search, optimized for Users | |
| 881 | + * @param string $filter the LDAP filter for the search | |
| 882 | + * @param string|string[] $attr optional, when a certain attribute shall be filtered out | |
| 883 | + * @param integer $limit | |
| 884 | + * @param integer $offset | |
| 885 | + * @return array with the search result | |
| 886 | + * | |
| 887 | + * Executes an LDAP search | |
| 888 | + */ | |
| 889 | +    public function searchUsers($filter, $attr = null, $limit = null, $offset = null) { | |
| 890 | + return $this->search($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset); | |
| 891 | + } | |
| 892 | + | |
| 893 | + /** | |
| 894 | + * @param string $filter | |
| 895 | + * @param string|string[] $attr | |
| 896 | + * @param int $limit | |
| 897 | + * @param int $offset | |
| 898 | + * @return false|int | |
| 899 | + */ | |
| 900 | +    public function countUsers($filter, $attr = array('dn'), $limit = null, $offset = null) { | |
| 901 | + return $this->count($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset); | |
| 902 | + } | |
| 903 | + | |
| 904 | + /** | |
| 905 | + * executes an LDAP search, optimized for Groups | |
| 906 | + * @param string $filter the LDAP filter for the search | |
| 907 | + * @param string|string[] $attr optional, when a certain attribute shall be filtered out | |
| 908 | + * @param integer $limit | |
| 909 | + * @param integer $offset | |
| 910 | + * @return array with the search result | |
| 911 | + * | |
| 912 | + * Executes an LDAP search | |
| 913 | + */ | |
| 914 | +    public function searchGroups($filter, $attr = null, $limit = null, $offset = null) { | |
| 915 | + return $this->search($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset); | |
| 916 | + } | |
| 917 | + | |
| 918 | + /** | |
| 919 | + * returns the number of available groups | |
| 920 | + * @param string $filter the LDAP search filter | |
| 921 | + * @param string[] $attr optional | |
| 922 | + * @param int|null $limit | |
| 923 | + * @param int|null $offset | |
| 924 | + * @return int|bool | |
| 925 | + */ | |
| 926 | +    public function countGroups($filter, $attr = array('dn'), $limit = null, $offset = null) { | |
| 927 | + return $this->count($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset); | |
| 928 | + } | |
| 929 | + | |
| 930 | + /** | |
| 931 | + * returns the number of available objects on the base DN | |
| 932 | + * | |
| 933 | + * @param int|null $limit | |
| 934 | + * @param int|null $offset | |
| 935 | + * @return int|bool | |
| 936 | + */ | |
| 937 | +    public function countObjects($limit = null, $offset = null) { | |
| 938 | +        return $this->count('objectclass=*', $this->connection->ldapBase, array('dn'), $limit, $offset); | |
| 939 | + } | |
| 940 | + | |
| 941 | + /** | |
| 942 | + * Returns the LDAP handler | |
| 943 | + * @throws \OC\ServerNotAvailableException | |
| 944 | + */ | |
| 945 | + | |
| 946 | + /** | |
| 947 | + * @return mixed | |
| 948 | + * @throws \OC\ServerNotAvailableException | |
| 949 | + */ | |
| 950 | +    private function invokeLDAPMethod() { | |
| 951 | + $arguments = func_get_args(); | |
| 952 | + $command = array_shift($arguments); | |
| 953 | + $cr = array_shift($arguments); | |
| 954 | +        if (!method_exists($this->ldap, $command)) { | |
| 955 | + return null; | |
| 956 | + } | |
| 957 | + array_unshift($arguments, $cr); | |
| 958 | + // php no longer supports call-time pass-by-reference | |
| 959 | + // thus cannot support controlPagedResultResponse as the third argument | |
| 960 | + // is a reference | |
| 961 | +        $doMethod = function () use ($command, &$arguments) { | |
| 962 | +            if ($command == 'controlPagedResultResponse') { | |
| 963 | +                throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.'); | |
| 964 | +            } else { | |
| 965 | + return call_user_func_array(array($this->ldap, $command), $arguments); | |
| 966 | + } | |
| 967 | + }; | |
| 968 | +        try { | |
| 969 | + $ret = $doMethod(); | |
| 970 | +        } catch (ServerNotAvailableException $e) { | |
| 971 | + /* Server connection lost, attempt to reestablish it | |
| 972 | 972 | * Maybe implement exponential backoff? | 
| 973 | 973 | * This was enough to get solr indexer working which has large delays between LDAP fetches. | 
| 974 | 974 | */ | 
| 975 | -			\OCP\Util::writeLog('user_ldap', "Connection lost on $command, attempting to reestablish.", \OCP\Util::DEBUG); | |
| 976 | - $this->connection->resetConnectionResource(); | |
| 977 | - $cr = $this->connection->getConnectionResource(); | |
| 978 | - | |
| 979 | -			if(!$this->ldap->isResource($cr)) { | |
| 980 | - // Seems like we didn't find any resource. | |
| 981 | -				\OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", \OCP\Util::DEBUG); | |
| 982 | - throw $e; | |
| 983 | - } | |
| 984 | - | |
| 985 | - $arguments[0] = array_pad([], count($arguments[0]), $cr); | |
| 986 | - $ret = $doMethod(); | |
| 987 | - } | |
| 988 | - return $ret; | |
| 989 | - } | |
| 990 | - | |
| 991 | - /** | |
| 992 | - * retrieved. Results will according to the order in the array. | |
| 993 | - * @param int $limit optional, maximum results to be counted | |
| 994 | - * @param int $offset optional, a starting point | |
| 995 | - * @return array|false array with the search result as first value and pagedSearchOK as | |
| 996 | - * second | false if not successful | |
| 997 | - * @throws \OC\ServerNotAvailableException | |
| 998 | - */ | |
| 999 | -	private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) { | |
| 1000 | -		if(!is_null($attr) && !is_array($attr)) { | |
| 1001 | - $attr = array(mb_strtolower($attr, 'UTF-8')); | |
| 1002 | - } | |
| 1003 | - | |
| 1004 | - // See if we have a resource, in case not cancel with message | |
| 1005 | - $cr = $this->connection->getConnectionResource(); | |
| 1006 | -		if(!$this->ldap->isResource($cr)) { | |
| 1007 | - // Seems like we didn't find any resource. | |
| 1008 | - // Return an empty array just like before. | |
| 1009 | -			\OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', \OCP\Util::DEBUG); | |
| 1010 | - return false; | |
| 1011 | - } | |
| 1012 | - | |
| 1013 | - //check whether paged search should be attempted | |
| 1014 | - $pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, intval($limit), $offset); | |
| 1015 | - | |
| 1016 | - $linkResources = array_pad(array(), count($base), $cr); | |
| 1017 | -		$sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr); | |
| 1018 | - // cannot use $cr anymore, might have changed in the previous call! | |
| 1019 | - $error = $this->ldap->errno($this->connection->getConnectionResource()); | |
| 1020 | -		if(!is_array($sr) || $error !== 0) { | |
| 1021 | -			\OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), \OCP\Util::ERROR); | |
| 1022 | - return false; | |
| 1023 | - } | |
| 1024 | - | |
| 1025 | - return array($sr, $pagedSearchOK); | |
| 1026 | - } | |
| 1027 | - | |
| 1028 | - /** | |
| 1029 | - * processes an LDAP paged search operation | |
| 1030 | - * @param array $sr the array containing the LDAP search resources | |
| 1031 | - * @param string $filter the LDAP filter for the search | |
| 1032 | - * @param array $base an array containing the LDAP subtree(s) that shall be searched | |
| 1033 | - * @param int $iFoundItems number of results in the single search operation | |
| 1034 | - * @param int $limit maximum results to be counted | |
| 1035 | - * @param int $offset a starting point | |
| 1036 | - * @param bool $pagedSearchOK whether a paged search has been executed | |
| 1037 | - * @param bool $skipHandling required for paged search when cookies to | |
| 1038 | - * prior results need to be gained | |
| 1039 | - * @return bool cookie validity, true if we have more pages, false otherwise. | |
| 1040 | - */ | |
| 1041 | -	private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) { | |
| 1042 | - $cookie = null; | |
| 1043 | -		if($pagedSearchOK) { | |
| 1044 | - $cr = $this->connection->getConnectionResource(); | |
| 1045 | -			foreach($sr as $key => $res) { | |
| 1046 | -				if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) { | |
| 1047 | - $this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie); | |
| 1048 | - } | |
| 1049 | - } | |
| 1050 | - | |
| 1051 | - //browsing through prior pages to get the cookie for the new one | |
| 1052 | -			if($skipHandling) { | |
| 1053 | - return false; | |
| 1054 | - } | |
| 1055 | - // if count is bigger, then the server does not support | |
| 1056 | - // paged search. Instead, he did a normal search. We set a | |
| 1057 | - // flag here, so the callee knows how to deal with it. | |
| 1058 | -			if($iFoundItems <= $limit) { | |
| 1059 | - $this->pagedSearchedSuccessful = true; | |
| 1060 | - } | |
| 1061 | -		} else { | |
| 1062 | -			if(!is_null($limit)) { | |
| 1063 | -				\OCP\Util::writeLog('user_ldap', 'Paged search was not available', \OCP\Util::INFO); | |
| 1064 | - } | |
| 1065 | - } | |
| 1066 | - /* ++ Fixing RHDS searches with pages with zero results ++ | |
| 975 | +            \OCP\Util::writeLog('user_ldap', "Connection lost on $command, attempting to reestablish.", \OCP\Util::DEBUG); | |
| 976 | + $this->connection->resetConnectionResource(); | |
| 977 | + $cr = $this->connection->getConnectionResource(); | |
| 978 | + | |
| 979 | +            if(!$this->ldap->isResource($cr)) { | |
| 980 | + // Seems like we didn't find any resource. | |
| 981 | +                \OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", \OCP\Util::DEBUG); | |
| 982 | + throw $e; | |
| 983 | + } | |
| 984 | + | |
| 985 | + $arguments[0] = array_pad([], count($arguments[0]), $cr); | |
| 986 | + $ret = $doMethod(); | |
| 987 | + } | |
| 988 | + return $ret; | |
| 989 | + } | |
| 990 | + | |
| 991 | + /** | |
| 992 | + * retrieved. Results will according to the order in the array. | |
| 993 | + * @param int $limit optional, maximum results to be counted | |
| 994 | + * @param int $offset optional, a starting point | |
| 995 | + * @return array|false array with the search result as first value and pagedSearchOK as | |
| 996 | + * second | false if not successful | |
| 997 | + * @throws \OC\ServerNotAvailableException | |
| 998 | + */ | |
| 999 | +    private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) { | |
| 1000 | +        if(!is_null($attr) && !is_array($attr)) { | |
| 1001 | + $attr = array(mb_strtolower($attr, 'UTF-8')); | |
| 1002 | + } | |
| 1003 | + | |
| 1004 | + // See if we have a resource, in case not cancel with message | |
| 1005 | + $cr = $this->connection->getConnectionResource(); | |
| 1006 | +        if(!$this->ldap->isResource($cr)) { | |
| 1007 | + // Seems like we didn't find any resource. | |
| 1008 | + // Return an empty array just like before. | |
| 1009 | +            \OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', \OCP\Util::DEBUG); | |
| 1010 | + return false; | |
| 1011 | + } | |
| 1012 | + | |
| 1013 | + //check whether paged search should be attempted | |
| 1014 | + $pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, intval($limit), $offset); | |
| 1015 | + | |
| 1016 | + $linkResources = array_pad(array(), count($base), $cr); | |
| 1017 | +        $sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr); | |
| 1018 | + // cannot use $cr anymore, might have changed in the previous call! | |
| 1019 | + $error = $this->ldap->errno($this->connection->getConnectionResource()); | |
| 1020 | +        if(!is_array($sr) || $error !== 0) { | |
| 1021 | +            \OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), \OCP\Util::ERROR); | |
| 1022 | + return false; | |
| 1023 | + } | |
| 1024 | + | |
| 1025 | + return array($sr, $pagedSearchOK); | |
| 1026 | + } | |
| 1027 | + | |
| 1028 | + /** | |
| 1029 | + * processes an LDAP paged search operation | |
| 1030 | + * @param array $sr the array containing the LDAP search resources | |
| 1031 | + * @param string $filter the LDAP filter for the search | |
| 1032 | + * @param array $base an array containing the LDAP subtree(s) that shall be searched | |
| 1033 | + * @param int $iFoundItems number of results in the single search operation | |
| 1034 | + * @param int $limit maximum results to be counted | |
| 1035 | + * @param int $offset a starting point | |
| 1036 | + * @param bool $pagedSearchOK whether a paged search has been executed | |
| 1037 | + * @param bool $skipHandling required for paged search when cookies to | |
| 1038 | + * prior results need to be gained | |
| 1039 | + * @return bool cookie validity, true if we have more pages, false otherwise. | |
| 1040 | + */ | |
| 1041 | +    private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) { | |
| 1042 | + $cookie = null; | |
| 1043 | +        if($pagedSearchOK) { | |
| 1044 | + $cr = $this->connection->getConnectionResource(); | |
| 1045 | +            foreach($sr as $key => $res) { | |
| 1046 | +                if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) { | |
| 1047 | + $this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie); | |
| 1048 | + } | |
| 1049 | + } | |
| 1050 | + | |
| 1051 | + //browsing through prior pages to get the cookie for the new one | |
| 1052 | +            if($skipHandling) { | |
| 1053 | + return false; | |
| 1054 | + } | |
| 1055 | + // if count is bigger, then the server does not support | |
| 1056 | + // paged search. Instead, he did a normal search. We set a | |
| 1057 | + // flag here, so the callee knows how to deal with it. | |
| 1058 | +            if($iFoundItems <= $limit) { | |
| 1059 | + $this->pagedSearchedSuccessful = true; | |
| 1060 | + } | |
| 1061 | +        } else { | |
| 1062 | +            if(!is_null($limit)) { | |
| 1063 | +                \OCP\Util::writeLog('user_ldap', 'Paged search was not available', \OCP\Util::INFO); | |
| 1064 | + } | |
| 1065 | + } | |
| 1066 | + /* ++ Fixing RHDS searches with pages with zero results ++ | |
| 1067 | 1067 | * Return cookie status. If we don't have more pages, with RHDS | 
| 1068 | 1068 | * cookie is null, with openldap cookie is an empty string and | 
| 1069 | 1069 | * to 386ds '0' is a valid cookie. Even if $iFoundItems == 0 | 
| 1070 | 1070 | */ | 
| 1071 | - return !empty($cookie) || $cookie === '0'; | |
| 1072 | - } | |
| 1073 | - | |
| 1074 | - /** | |
| 1075 | - * executes an LDAP search, but counts the results only | |
| 1076 | - * @param string $filter the LDAP filter for the search | |
| 1077 | - * @param array $base an array containing the LDAP subtree(s) that shall be searched | |
| 1078 | - * @param string|string[] $attr optional, array, one or more attributes that shall be | |
| 1079 | - * retrieved. Results will according to the order in the array. | |
| 1080 | - * @param int $limit optional, maximum results to be counted | |
| 1081 | - * @param int $offset optional, a starting point | |
| 1082 | - * @param bool $skipHandling indicates whether the pages search operation is | |
| 1083 | - * completed | |
| 1084 | - * @return int|false Integer or false if the search could not be initialized | |
| 1085 | - * | |
| 1086 | - */ | |
| 1087 | -	private function count($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) { | |
| 1088 | -		\OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), \OCP\Util::DEBUG); | |
| 1089 | - | |
| 1090 | - $limitPerPage = intval($this->connection->ldapPagingSize); | |
| 1091 | -		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) { | |
| 1092 | - $limitPerPage = $limit; | |
| 1093 | - } | |
| 1094 | - | |
| 1095 | - $counter = 0; | |
| 1096 | - $count = null; | |
| 1097 | - $this->connection->getConnectionResource(); | |
| 1098 | - | |
| 1099 | -		do { | |
| 1100 | - $search = $this->executeSearch($filter, $base, $attr, | |
| 1101 | - $limitPerPage, $offset); | |
| 1102 | -			if($search === false) { | |
| 1103 | - return $counter > 0 ? $counter : false; | |
| 1104 | - } | |
| 1105 | - list($sr, $pagedSearchOK) = $search; | |
| 1106 | - | |
| 1107 | - /* ++ Fixing RHDS searches with pages with zero results ++ | |
| 1071 | + return !empty($cookie) || $cookie === '0'; | |
| 1072 | + } | |
| 1073 | + | |
| 1074 | + /** | |
| 1075 | + * executes an LDAP search, but counts the results only | |
| 1076 | + * @param string $filter the LDAP filter for the search | |
| 1077 | + * @param array $base an array containing the LDAP subtree(s) that shall be searched | |
| 1078 | + * @param string|string[] $attr optional, array, one or more attributes that shall be | |
| 1079 | + * retrieved. Results will according to the order in the array. | |
| 1080 | + * @param int $limit optional, maximum results to be counted | |
| 1081 | + * @param int $offset optional, a starting point | |
| 1082 | + * @param bool $skipHandling indicates whether the pages search operation is | |
| 1083 | + * completed | |
| 1084 | + * @return int|false Integer or false if the search could not be initialized | |
| 1085 | + * | |
| 1086 | + */ | |
| 1087 | +    private function count($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) { | |
| 1088 | +        \OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), \OCP\Util::DEBUG); | |
| 1089 | + | |
| 1090 | + $limitPerPage = intval($this->connection->ldapPagingSize); | |
| 1091 | +        if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) { | |
| 1092 | + $limitPerPage = $limit; | |
| 1093 | + } | |
| 1094 | + | |
| 1095 | + $counter = 0; | |
| 1096 | + $count = null; | |
| 1097 | + $this->connection->getConnectionResource(); | |
| 1098 | + | |
| 1099 | +        do { | |
| 1100 | + $search = $this->executeSearch($filter, $base, $attr, | |
| 1101 | + $limitPerPage, $offset); | |
| 1102 | +            if($search === false) { | |
| 1103 | + return $counter > 0 ? $counter : false; | |
| 1104 | + } | |
| 1105 | + list($sr, $pagedSearchOK) = $search; | |
| 1106 | + | |
| 1107 | + /* ++ Fixing RHDS searches with pages with zero results ++ | |
| 1108 | 1108 | * countEntriesInSearchResults() method signature changed | 
| 1109 | 1109 | * by removing $limit and &$hasHitLimit parameters | 
| 1110 | 1110 | */ | 
| 1111 | - $count = $this->countEntriesInSearchResults($sr); | |
| 1112 | - $counter += $count; | |
| 1111 | + $count = $this->countEntriesInSearchResults($sr); | |
| 1112 | + $counter += $count; | |
| 1113 | 1113 | |
| 1114 | - $hasMorePages = $this->processPagedSearchStatus($sr, $filter, $base, $count, $limitPerPage, | |
| 1115 | - $offset, $pagedSearchOK, $skipHandling); | |
| 1116 | - $offset += $limitPerPage; | |
| 1117 | - /* ++ Fixing RHDS searches with pages with zero results ++ | |
| 1114 | + $hasMorePages = $this->processPagedSearchStatus($sr, $filter, $base, $count, $limitPerPage, | |
| 1115 | + $offset, $pagedSearchOK, $skipHandling); | |
| 1116 | + $offset += $limitPerPage; | |
| 1117 | + /* ++ Fixing RHDS searches with pages with zero results ++ | |
| 1118 | 1118 | * Continue now depends on $hasMorePages value | 
| 1119 | 1119 | */ | 
| 1120 | - $continue = $pagedSearchOK && $hasMorePages; | |
| 1121 | - } while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter)); | |
| 1122 | - | |
| 1123 | - return $counter; | |
| 1124 | - } | |
| 1125 | - | |
| 1126 | - /** | |
| 1127 | - * @param array $searchResults | |
| 1128 | - * @return int | |
| 1129 | - */ | |
| 1130 | -	private function countEntriesInSearchResults($searchResults) { | |
| 1131 | - $counter = 0; | |
| 1132 | - | |
| 1133 | -		foreach($searchResults as $res) { | |
| 1134 | -			$count = intval($this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res)); | |
| 1135 | - $counter += $count; | |
| 1136 | - } | |
| 1137 | - | |
| 1138 | - return $counter; | |
| 1139 | - } | |
| 1140 | - | |
| 1141 | - /** | |
| 1142 | - * Executes an LDAP search | |
| 1143 | - * @param string $filter the LDAP filter for the search | |
| 1144 | - * @param array $base an array containing the LDAP subtree(s) that shall be searched | |
| 1145 | - * @param string|string[] $attr optional, array, one or more attributes that shall be | |
| 1146 | - * @param int $limit | |
| 1147 | - * @param int $offset | |
| 1148 | - * @param bool $skipHandling | |
| 1149 | - * @return array with the search result | |
| 1150 | - */ | |
| 1151 | -	public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) { | |
| 1152 | - $limitPerPage = intval($this->connection->ldapPagingSize); | |
| 1153 | -		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) { | |
| 1154 | - $limitPerPage = $limit; | |
| 1155 | - } | |
| 1156 | - | |
| 1157 | - /* ++ Fixing RHDS searches with pages with zero results ++ | |
| 1120 | + $continue = $pagedSearchOK && $hasMorePages; | |
| 1121 | + } while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter)); | |
| 1122 | + | |
| 1123 | + return $counter; | |
| 1124 | + } | |
| 1125 | + | |
| 1126 | + /** | |
| 1127 | + * @param array $searchResults | |
| 1128 | + * @return int | |
| 1129 | + */ | |
| 1130 | +    private function countEntriesInSearchResults($searchResults) { | |
| 1131 | + $counter = 0; | |
| 1132 | + | |
| 1133 | +        foreach($searchResults as $res) { | |
| 1134 | +            $count = intval($this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res)); | |
| 1135 | + $counter += $count; | |
| 1136 | + } | |
| 1137 | + | |
| 1138 | + return $counter; | |
| 1139 | + } | |
| 1140 | + | |
| 1141 | + /** | |
| 1142 | + * Executes an LDAP search | |
| 1143 | + * @param string $filter the LDAP filter for the search | |
| 1144 | + * @param array $base an array containing the LDAP subtree(s) that shall be searched | |
| 1145 | + * @param string|string[] $attr optional, array, one or more attributes that shall be | |
| 1146 | + * @param int $limit | |
| 1147 | + * @param int $offset | |
| 1148 | + * @param bool $skipHandling | |
| 1149 | + * @return array with the search result | |
| 1150 | + */ | |
| 1151 | +    public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) { | |
| 1152 | + $limitPerPage = intval($this->connection->ldapPagingSize); | |
| 1153 | +        if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) { | |
| 1154 | + $limitPerPage = $limit; | |
| 1155 | + } | |
| 1156 | + | |
| 1157 | + /* ++ Fixing RHDS searches with pages with zero results ++ | |
| 1158 | 1158 | * As we can have pages with zero results and/or pages with less | 
| 1159 | 1159 | * than $limit results but with a still valid server 'cookie', | 
| 1160 | 1160 | * loops through until we get $continue equals true and | 
| 1161 | 1161 | * $findings['count'] < $limit | 
| 1162 | 1162 | */ | 
| 1163 | - $findings = array(); | |
| 1164 | - $savedoffset = $offset; | |
| 1165 | -		do { | |
| 1166 | - $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset); | |
| 1167 | -			if($search === false) { | |
| 1168 | - return array(); | |
| 1169 | - } | |
| 1170 | - list($sr, $pagedSearchOK) = $search; | |
| 1171 | - $cr = $this->connection->getConnectionResource(); | |
| 1172 | - | |
| 1173 | -			if($skipHandling) { | |
| 1174 | - //i.e. result do not need to be fetched, we just need the cookie | |
| 1175 | - //thus pass 1 or any other value as $iFoundItems because it is not | |
| 1176 | - //used | |
| 1177 | - $this->processPagedSearchStatus($sr, $filter, $base, 1, $limitPerPage, | |
| 1178 | - $offset, $pagedSearchOK, | |
| 1179 | - $skipHandling); | |
| 1180 | - return array(); | |
| 1181 | - } | |
| 1182 | - | |
| 1183 | - $iFoundItems = 0; | |
| 1184 | -			foreach($sr as $res) { | |
| 1185 | -				$findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res)); | |
| 1186 | - $iFoundItems = max($iFoundItems, $findings['count']); | |
| 1187 | - unset($findings['count']); | |
| 1188 | - } | |
| 1189 | - | |
| 1190 | - $continue = $this->processPagedSearchStatus($sr, $filter, $base, $iFoundItems, | |
| 1191 | - $limitPerPage, $offset, $pagedSearchOK, | |
| 1192 | - $skipHandling); | |
| 1193 | - $offset += $limitPerPage; | |
| 1194 | - } while ($continue && $pagedSearchOK && ($limit === null || count($findings) < $limit)); | |
| 1195 | - // reseting offset | |
| 1196 | - $offset = $savedoffset; | |
| 1197 | - | |
| 1198 | - // if we're here, probably no connection resource is returned. | |
| 1199 | - // to make Nextcloud behave nicely, we simply give back an empty array. | |
| 1200 | -		if(is_null($findings)) { | |
| 1201 | - return array(); | |
| 1202 | - } | |
| 1203 | - | |
| 1204 | -		if(!is_null($attr)) { | |
| 1205 | - $selection = array(); | |
| 1206 | - $i = 0; | |
| 1207 | -			foreach($findings as $item) { | |
| 1208 | -				if(!is_array($item)) { | |
| 1209 | - continue; | |
| 1210 | - } | |
| 1211 | - $item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8'); | |
| 1212 | -				foreach($attr as $key) { | |
| 1213 | - $key = mb_strtolower($key, 'UTF-8'); | |
| 1214 | -					if(isset($item[$key])) { | |
| 1215 | -						if(is_array($item[$key]) && isset($item[$key]['count'])) { | |
| 1216 | - unset($item[$key]['count']); | |
| 1217 | - } | |
| 1218 | -						if($key !== 'dn') { | |
| 1219 | - $selection[$i][$key] = $this->resemblesDN($key) ? | |
| 1220 | - $this->helper->sanitizeDN($item[$key]) | |
| 1221 | - : $item[$key]; | |
| 1222 | -						} else { | |
| 1223 | - $selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])]; | |
| 1224 | - } | |
| 1225 | - } | |
| 1226 | - | |
| 1227 | - } | |
| 1228 | - $i++; | |
| 1229 | - } | |
| 1230 | - $findings = $selection; | |
| 1231 | - } | |
| 1232 | - //we slice the findings, when | |
| 1233 | - //a) paged search unsuccessful, though attempted | |
| 1234 | - //b) no paged search, but limit set | |
| 1235 | - if((!$this->getPagedSearchResultState() | |
| 1236 | - && $pagedSearchOK) | |
| 1237 | - || ( | |
| 1238 | - !$pagedSearchOK | |
| 1239 | - && !is_null($limit) | |
| 1240 | - ) | |
| 1241 | -		) { | |
| 1242 | - $findings = array_slice($findings, intval($offset), $limit); | |
| 1243 | - } | |
| 1244 | - return $findings; | |
| 1245 | - } | |
| 1246 | - | |
| 1247 | - /** | |
| 1248 | - * @param string $name | |
| 1249 | - * @return bool|mixed|string | |
| 1250 | - */ | |
| 1251 | -	public function sanitizeUsername($name) { | |
| 1252 | -		if($this->connection->ldapIgnoreNamingRules) { | |
| 1253 | - return $name; | |
| 1254 | - } | |
| 1255 | - | |
| 1256 | - // Transliteration | |
| 1257 | - // latin characters to ASCII | |
| 1258 | -		$name = iconv('UTF-8', 'ASCII//TRANSLIT', $name); | |
| 1259 | - | |
| 1260 | - // Replacements | |
| 1261 | -		$name = str_replace(' ', '_', $name); | |
| 1262 | - | |
| 1263 | - // Every remaining disallowed characters will be removed | |
| 1264 | -		$name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name); | |
| 1265 | - | |
| 1266 | - return $name; | |
| 1267 | - } | |
| 1268 | - | |
| 1269 | - /** | |
| 1270 | - * escapes (user provided) parts for LDAP filter | |
| 1271 | - * @param string $input, the provided value | |
| 1272 | - * @param bool $allowAsterisk whether in * at the beginning should be preserved | |
| 1273 | - * @return string the escaped string | |
| 1274 | - */ | |
| 1275 | -	public function escapeFilterPart($input, $allowAsterisk = false) { | |
| 1276 | - $asterisk = ''; | |
| 1277 | -		if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') { | |
| 1278 | - $asterisk = '*'; | |
| 1279 | - $input = mb_substr($input, 1, null, 'UTF-8'); | |
| 1280 | - } | |
| 1281 | -		$search  = array('*', '\\', '(', ')'); | |
| 1282 | -		$replace = array('\\*', '\\\\', '\\(', '\\)'); | |
| 1283 | - return $asterisk . str_replace($search, $replace, $input); | |
| 1284 | - } | |
| 1285 | - | |
| 1286 | - /** | |
| 1287 | - * combines the input filters with AND | |
| 1288 | - * @param string[] $filters the filters to connect | |
| 1289 | - * @return string the combined filter | |
| 1290 | - */ | |
| 1291 | -	public function combineFilterWithAnd($filters) { | |
| 1292 | - return $this->combineFilter($filters, '&'); | |
| 1293 | - } | |
| 1294 | - | |
| 1295 | - /** | |
| 1296 | - * combines the input filters with OR | |
| 1297 | - * @param string[] $filters the filters to connect | |
| 1298 | - * @return string the combined filter | |
| 1299 | - * Combines Filter arguments with OR | |
| 1300 | - */ | |
| 1301 | -	public function combineFilterWithOr($filters) { | |
| 1302 | - return $this->combineFilter($filters, '|'); | |
| 1303 | - } | |
| 1304 | - | |
| 1305 | - /** | |
| 1306 | - * combines the input filters with given operator | |
| 1307 | - * @param string[] $filters the filters to connect | |
| 1308 | - * @param string $operator either & or | | |
| 1309 | - * @return string the combined filter | |
| 1310 | - */ | |
| 1311 | -	private function combineFilter($filters, $operator) { | |
| 1312 | -		$combinedFilter = '('.$operator; | |
| 1313 | -		foreach($filters as $filter) { | |
| 1314 | -			if ($filter !== '' && $filter[0] !== '(') { | |
| 1315 | -				$filter = '('.$filter.')'; | |
| 1316 | - } | |
| 1317 | - $combinedFilter.=$filter; | |
| 1318 | - } | |
| 1319 | - $combinedFilter.=')'; | |
| 1320 | - return $combinedFilter; | |
| 1321 | - } | |
| 1322 | - | |
| 1323 | - /** | |
| 1324 | - * creates a filter part for to perform search for users | |
| 1325 | - * @param string $search the search term | |
| 1326 | - * @return string the final filter part to use in LDAP searches | |
| 1327 | - */ | |
| 1328 | -	public function getFilterPartForUserSearch($search) { | |
| 1329 | - return $this->getFilterPartForSearch($search, | |
| 1330 | - $this->connection->ldapAttributesForUserSearch, | |
| 1331 | - $this->connection->ldapUserDisplayName); | |
| 1332 | - } | |
| 1333 | - | |
| 1334 | - /** | |
| 1335 | - * creates a filter part for to perform search for groups | |
| 1336 | - * @param string $search the search term | |
| 1337 | - * @return string the final filter part to use in LDAP searches | |
| 1338 | - */ | |
| 1339 | -	public function getFilterPartForGroupSearch($search) { | |
| 1340 | - return $this->getFilterPartForSearch($search, | |
| 1341 | - $this->connection->ldapAttributesForGroupSearch, | |
| 1342 | - $this->connection->ldapGroupDisplayName); | |
| 1343 | - } | |
| 1344 | - | |
| 1345 | - /** | |
| 1346 | - * creates a filter part for searches by splitting up the given search | |
| 1347 | - * string into single words | |
| 1348 | - * @param string $search the search term | |
| 1349 | - * @param string[] $searchAttributes needs to have at least two attributes, | |
| 1350 | - * otherwise it does not make sense :) | |
| 1351 | - * @return string the final filter part to use in LDAP searches | |
| 1352 | - * @throws \Exception | |
| 1353 | - */ | |
| 1354 | -	private function getAdvancedFilterPartForSearch($search, $searchAttributes) { | |
| 1355 | -		if(!is_array($searchAttributes) || count($searchAttributes) < 2) { | |
| 1356 | -			throw new \Exception('searchAttributes must be an array with at least two string'); | |
| 1357 | - } | |
| 1358 | -		$searchWords = explode(' ', trim($search)); | |
| 1359 | - $wordFilters = array(); | |
| 1360 | -		foreach($searchWords as $word) { | |
| 1361 | - $word = $this->prepareSearchTerm($word); | |
| 1362 | - //every word needs to appear at least once | |
| 1363 | - $wordMatchOneAttrFilters = array(); | |
| 1364 | -			foreach($searchAttributes as $attr) { | |
| 1365 | - $wordMatchOneAttrFilters[] = $attr . '=' . $word; | |
| 1366 | - } | |
| 1367 | - $wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters); | |
| 1368 | - } | |
| 1369 | - return $this->combineFilterWithAnd($wordFilters); | |
| 1370 | - } | |
| 1371 | - | |
| 1372 | - /** | |
| 1373 | - * creates a filter part for searches | |
| 1374 | - * @param string $search the search term | |
| 1375 | - * @param string[]|null $searchAttributes | |
| 1376 | - * @param string $fallbackAttribute a fallback attribute in case the user | |
| 1377 | - * did not define search attributes. Typically the display name attribute. | |
| 1378 | - * @return string the final filter part to use in LDAP searches | |
| 1379 | - */ | |
| 1380 | -	private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) { | |
| 1381 | - $filter = array(); | |
| 1382 | - $haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0); | |
| 1383 | -		if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) { | |
| 1384 | -			try { | |
| 1385 | - return $this->getAdvancedFilterPartForSearch($search, $searchAttributes); | |
| 1386 | -			} catch(\Exception $e) { | |
| 1387 | - \OCP\Util::writeLog( | |
| 1388 | - 'user_ldap', | |
| 1389 | - 'Creating advanced filter for search failed, falling back to simple method.', | |
| 1390 | - \OCP\Util::INFO | |
| 1391 | - ); | |
| 1392 | - } | |
| 1393 | - } | |
| 1394 | - | |
| 1395 | - $search = $this->prepareSearchTerm($search); | |
| 1396 | -		if(!is_array($searchAttributes) || count($searchAttributes) === 0) { | |
| 1397 | -			if ($fallbackAttribute === '') { | |
| 1398 | - return ''; | |
| 1399 | - } | |
| 1400 | - $filter[] = $fallbackAttribute . '=' . $search; | |
| 1401 | -		} else { | |
| 1402 | -			foreach($searchAttributes as $attribute) { | |
| 1403 | - $filter[] = $attribute . '=' . $search; | |
| 1404 | - } | |
| 1405 | - } | |
| 1406 | -		if(count($filter) === 1) { | |
| 1407 | -			return '('.$filter[0].')'; | |
| 1408 | - } | |
| 1409 | - return $this->combineFilterWithOr($filter); | |
| 1410 | - } | |
| 1411 | - | |
| 1412 | - /** | |
| 1413 | - * returns the search term depending on whether we are allowed | |
| 1414 | - * list users found by ldap with the current input appended by | |
| 1415 | - * a * | |
| 1416 | - * @return string | |
| 1417 | - */ | |
| 1418 | -	private function prepareSearchTerm($term) { | |
| 1419 | - $config = \OC::$server->getConfig(); | |
| 1420 | - | |
| 1421 | -		$allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes'); | |
| 1422 | - | |
| 1423 | - $result = $term; | |
| 1424 | -		if ($term === '') { | |
| 1425 | - $result = '*'; | |
| 1426 | -		} else if ($allowEnum !== 'no') { | |
| 1427 | - $result = $term . '*'; | |
| 1428 | - } | |
| 1429 | - return $result; | |
| 1430 | - } | |
| 1431 | - | |
| 1432 | - /** | |
| 1433 | - * returns the filter used for counting users | |
| 1434 | - * @return string | |
| 1435 | - */ | |
| 1436 | -	public function getFilterForUserCount() { | |
| 1437 | - $filter = $this->combineFilterWithAnd(array( | |
| 1438 | - $this->connection->ldapUserFilter, | |
| 1439 | - $this->connection->ldapUserDisplayName . '=*' | |
| 1440 | - )); | |
| 1441 | - | |
| 1442 | - return $filter; | |
| 1443 | - } | |
| 1444 | - | |
| 1445 | - /** | |
| 1446 | - * @param string $name | |
| 1447 | - * @param string $password | |
| 1448 | - * @return bool | |
| 1449 | - */ | |
| 1450 | -	public function areCredentialsValid($name, $password) { | |
| 1451 | - $name = $this->helper->DNasBaseParameter($name); | |
| 1452 | - $testConnection = clone $this->connection; | |
| 1453 | - $credentials = array( | |
| 1454 | - 'ldapAgentName' => $name, | |
| 1455 | - 'ldapAgentPassword' => $password | |
| 1456 | - ); | |
| 1457 | -		if(!$testConnection->setConfiguration($credentials)) { | |
| 1458 | - return false; | |
| 1459 | - } | |
| 1460 | - return $testConnection->bind(); | |
| 1461 | - } | |
| 1462 | - | |
| 1463 | - /** | |
| 1464 | - * reverse lookup of a DN given a known UUID | |
| 1465 | - * | |
| 1466 | - * @param string $uuid | |
| 1467 | - * @return string | |
| 1468 | - * @throws \Exception | |
| 1469 | - */ | |
| 1470 | -	public function getUserDnByUuid($uuid) { | |
| 1471 | - $uuidOverride = $this->connection->ldapExpertUUIDUserAttr; | |
| 1472 | - $filter = $this->connection->ldapUserFilter; | |
| 1473 | - $base = $this->connection->ldapBaseUsers; | |
| 1474 | - | |
| 1475 | -		if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') { | |
| 1476 | - // Sacrebleu! The UUID attribute is unknown :( We need first an | |
| 1477 | - // existing DN to be able to reliably detect it. | |
| 1478 | - $result = $this->search($filter, $base, ['dn'], 1); | |
| 1479 | -			if(!isset($result[0]) || !isset($result[0]['dn'])) { | |
| 1480 | -				throw new \Exception('Cannot determine UUID attribute'); | |
| 1481 | - } | |
| 1482 | - $dn = $result[0]['dn'][0]; | |
| 1483 | -			if(!$this->detectUuidAttribute($dn, true)) { | |
| 1484 | -				throw new \Exception('Cannot determine UUID attribute'); | |
| 1485 | - } | |
| 1486 | -		} else { | |
| 1487 | - // The UUID attribute is either known or an override is given. | |
| 1488 | - // By calling this method we ensure that $this->connection->$uuidAttr | |
| 1489 | - // is definitely set | |
| 1490 | -			if(!$this->detectUuidAttribute('', true)) { | |
| 1491 | -				throw new \Exception('Cannot determine UUID attribute'); | |
| 1492 | - } | |
| 1493 | - } | |
| 1494 | - | |
| 1495 | - $uuidAttr = $this->connection->ldapUuidUserAttribute; | |
| 1496 | -		if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') { | |
| 1497 | - $uuid = $this->formatGuid2ForFilterUser($uuid); | |
| 1498 | - } | |
| 1499 | - | |
| 1500 | - $filter = $uuidAttr . '=' . $uuid; | |
| 1501 | - $result = $this->searchUsers($filter, ['dn'], 2); | |
| 1502 | -		if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) { | |
| 1503 | - // we put the count into account to make sure that this is | |
| 1504 | - // really unique | |
| 1505 | - return $result[0]['dn'][0]; | |
| 1506 | - } | |
| 1507 | - | |
| 1508 | -		throw new \Exception('Cannot determine UUID attribute'); | |
| 1509 | - } | |
| 1510 | - | |
| 1511 | - /** | |
| 1512 | - * auto-detects the directory's UUID attribute | |
| 1513 | - * @param string $dn a known DN used to check against | |
| 1514 | - * @param bool $isUser | |
| 1515 | - * @param bool $force the detection should be run, even if it is not set to auto | |
| 1516 | - * @return bool true on success, false otherwise | |
| 1517 | - */ | |
| 1518 | -	private function detectUuidAttribute($dn, $isUser = true, $force = false) { | |
| 1519 | -		if($isUser) { | |
| 1520 | - $uuidAttr = 'ldapUuidUserAttribute'; | |
| 1521 | - $uuidOverride = $this->connection->ldapExpertUUIDUserAttr; | |
| 1522 | -		} else { | |
| 1523 | - $uuidAttr = 'ldapUuidGroupAttribute'; | |
| 1524 | - $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr; | |
| 1525 | - } | |
| 1526 | - | |
| 1527 | -		if(($this->connection->$uuidAttr !== 'auto') && !$force) { | |
| 1528 | - return true; | |
| 1529 | - } | |
| 1530 | - | |
| 1531 | -		if (is_string($uuidOverride) && trim($uuidOverride) !== '' && !$force) { | |
| 1532 | - $this->connection->$uuidAttr = $uuidOverride; | |
| 1533 | - return true; | |
| 1534 | - } | |
| 1535 | - | |
| 1536 | - // for now, supported attributes are entryUUID, nsuniqueid, objectGUID, ipaUniqueID | |
| 1537 | -		$testAttributes = array('entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid'); | |
| 1538 | - | |
| 1539 | -		foreach($testAttributes as $attribute) { | |
| 1540 | - $value = $this->readAttribute($dn, $attribute); | |
| 1541 | -			if(is_array($value) && isset($value[0]) && !empty($value[0])) { | |
| 1542 | -				\OCP\Util::writeLog('user_ldap', | |
| 1543 | - 'Setting '.$attribute.' as '.$uuidAttr, | |
| 1544 | - \OCP\Util::DEBUG); | |
| 1545 | - $this->connection->$uuidAttr = $attribute; | |
| 1546 | - return true; | |
| 1547 | - } | |
| 1548 | - } | |
| 1549 | -		\OCP\Util::writeLog('user_ldap', | |
| 1550 | - 'Could not autodetect the UUID attribute', | |
| 1551 | - \OCP\Util::ERROR); | |
| 1552 | - | |
| 1553 | - return false; | |
| 1554 | - } | |
| 1555 | - | |
| 1556 | - /** | |
| 1557 | - * @param string $dn | |
| 1558 | - * @param bool $isUser | |
| 1559 | - * @return string|bool | |
| 1560 | - */ | |
| 1561 | -	public function getUUID($dn, $isUser = true) { | |
| 1562 | -		if($isUser) { | |
| 1563 | - $uuidAttr = 'ldapUuidUserAttribute'; | |
| 1564 | - $uuidOverride = $this->connection->ldapExpertUUIDUserAttr; | |
| 1565 | -		} else { | |
| 1566 | - $uuidAttr = 'ldapUuidGroupAttribute'; | |
| 1567 | - $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr; | |
| 1568 | - } | |
| 1569 | - | |
| 1570 | - $uuid = false; | |
| 1571 | -		if($this->detectUuidAttribute($dn, $isUser)) { | |
| 1572 | - $uuid = $this->readAttribute($dn, $this->connection->$uuidAttr); | |
| 1573 | - if( !is_array($uuid) | |
| 1574 | - && $uuidOverride !== '' | |
| 1575 | -				&& $this->detectUuidAttribute($dn, $isUser, true)) { | |
| 1576 | - $uuid = $this->readAttribute($dn, | |
| 1577 | - $this->connection->$uuidAttr); | |
| 1578 | - } | |
| 1579 | -			if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) { | |
| 1580 | - $uuid = $uuid[0]; | |
| 1581 | - } | |
| 1582 | - } | |
| 1583 | - | |
| 1584 | - return $uuid; | |
| 1585 | - } | |
| 1586 | - | |
| 1587 | - /** | |
| 1588 | - * converts a binary ObjectGUID into a string representation | |
| 1589 | - * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD | |
| 1590 | - * @return string | |
| 1591 | - * @link http://www.php.net/manual/en/function.ldap-get-values-len.php#73198 | |
| 1592 | - */ | |
| 1593 | -	private function convertObjectGUID2Str($oguid) { | |
| 1594 | - $hex_guid = bin2hex($oguid); | |
| 1595 | - $hex_guid_to_guid_str = ''; | |
| 1596 | -		for($k = 1; $k <= 4; ++$k) { | |
| 1597 | - $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2); | |
| 1598 | - } | |
| 1599 | - $hex_guid_to_guid_str .= '-'; | |
| 1600 | -		for($k = 1; $k <= 2; ++$k) { | |
| 1601 | - $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2); | |
| 1602 | - } | |
| 1603 | - $hex_guid_to_guid_str .= '-'; | |
| 1604 | -		for($k = 1; $k <= 2; ++$k) { | |
| 1605 | - $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2); | |
| 1606 | - } | |
| 1607 | - $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4); | |
| 1608 | - $hex_guid_to_guid_str .= '-' . substr($hex_guid, 20); | |
| 1609 | - | |
| 1610 | - return strtoupper($hex_guid_to_guid_str); | |
| 1611 | - } | |
| 1612 | - | |
| 1613 | - /** | |
| 1614 | - * the first three blocks of the string-converted GUID happen to be in | |
| 1615 | - * reverse order. In order to use it in a filter, this needs to be | |
| 1616 | - * corrected. Furthermore the dashes need to be replaced and \\ preprended | |
| 1617 | - * to every two hax figures. | |
| 1618 | - * | |
| 1619 | - * If an invalid string is passed, it will be returned without change. | |
| 1620 | - * | |
| 1621 | - * @param string $guid | |
| 1622 | - * @return string | |
| 1623 | - */ | |
| 1624 | -	public function formatGuid2ForFilterUser($guid) { | |
| 1625 | -		if(!is_string($guid)) { | |
| 1626 | -			throw new \InvalidArgumentException('String expected'); | |
| 1627 | - } | |
| 1628 | -		$blocks = explode('-', $guid); | |
| 1629 | -		if(count($blocks) !== 5) { | |
| 1630 | - /* | |
| 1163 | + $findings = array(); | |
| 1164 | + $savedoffset = $offset; | |
| 1165 | +        do { | |
| 1166 | + $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset); | |
| 1167 | +            if($search === false) { | |
| 1168 | + return array(); | |
| 1169 | + } | |
| 1170 | + list($sr, $pagedSearchOK) = $search; | |
| 1171 | + $cr = $this->connection->getConnectionResource(); | |
| 1172 | + | |
| 1173 | +            if($skipHandling) { | |
| 1174 | + //i.e. result do not need to be fetched, we just need the cookie | |
| 1175 | + //thus pass 1 or any other value as $iFoundItems because it is not | |
| 1176 | + //used | |
| 1177 | + $this->processPagedSearchStatus($sr, $filter, $base, 1, $limitPerPage, | |
| 1178 | + $offset, $pagedSearchOK, | |
| 1179 | + $skipHandling); | |
| 1180 | + return array(); | |
| 1181 | + } | |
| 1182 | + | |
| 1183 | + $iFoundItems = 0; | |
| 1184 | +            foreach($sr as $res) { | |
| 1185 | +                $findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res)); | |
| 1186 | + $iFoundItems = max($iFoundItems, $findings['count']); | |
| 1187 | + unset($findings['count']); | |
| 1188 | + } | |
| 1189 | + | |
| 1190 | + $continue = $this->processPagedSearchStatus($sr, $filter, $base, $iFoundItems, | |
| 1191 | + $limitPerPage, $offset, $pagedSearchOK, | |
| 1192 | + $skipHandling); | |
| 1193 | + $offset += $limitPerPage; | |
| 1194 | + } while ($continue && $pagedSearchOK && ($limit === null || count($findings) < $limit)); | |
| 1195 | + // reseting offset | |
| 1196 | + $offset = $savedoffset; | |
| 1197 | + | |
| 1198 | + // if we're here, probably no connection resource is returned. | |
| 1199 | + // to make Nextcloud behave nicely, we simply give back an empty array. | |
| 1200 | +        if(is_null($findings)) { | |
| 1201 | + return array(); | |
| 1202 | + } | |
| 1203 | + | |
| 1204 | +        if(!is_null($attr)) { | |
| 1205 | + $selection = array(); | |
| 1206 | + $i = 0; | |
| 1207 | +            foreach($findings as $item) { | |
| 1208 | +                if(!is_array($item)) { | |
| 1209 | + continue; | |
| 1210 | + } | |
| 1211 | + $item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8'); | |
| 1212 | +                foreach($attr as $key) { | |
| 1213 | + $key = mb_strtolower($key, 'UTF-8'); | |
| 1214 | +                    if(isset($item[$key])) { | |
| 1215 | +                        if(is_array($item[$key]) && isset($item[$key]['count'])) { | |
| 1216 | + unset($item[$key]['count']); | |
| 1217 | + } | |
| 1218 | +                        if($key !== 'dn') { | |
| 1219 | + $selection[$i][$key] = $this->resemblesDN($key) ? | |
| 1220 | + $this->helper->sanitizeDN($item[$key]) | |
| 1221 | + : $item[$key]; | |
| 1222 | +                        } else { | |
| 1223 | + $selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])]; | |
| 1224 | + } | |
| 1225 | + } | |
| 1226 | + | |
| 1227 | + } | |
| 1228 | + $i++; | |
| 1229 | + } | |
| 1230 | + $findings = $selection; | |
| 1231 | + } | |
| 1232 | + //we slice the findings, when | |
| 1233 | + //a) paged search unsuccessful, though attempted | |
| 1234 | + //b) no paged search, but limit set | |
| 1235 | + if((!$this->getPagedSearchResultState() | |
| 1236 | + && $pagedSearchOK) | |
| 1237 | + || ( | |
| 1238 | + !$pagedSearchOK | |
| 1239 | + && !is_null($limit) | |
| 1240 | + ) | |
| 1241 | +        ) { | |
| 1242 | + $findings = array_slice($findings, intval($offset), $limit); | |
| 1243 | + } | |
| 1244 | + return $findings; | |
| 1245 | + } | |
| 1246 | + | |
| 1247 | + /** | |
| 1248 | + * @param string $name | |
| 1249 | + * @return bool|mixed|string | |
| 1250 | + */ | |
| 1251 | +    public function sanitizeUsername($name) { | |
| 1252 | +        if($this->connection->ldapIgnoreNamingRules) { | |
| 1253 | + return $name; | |
| 1254 | + } | |
| 1255 | + | |
| 1256 | + // Transliteration | |
| 1257 | + // latin characters to ASCII | |
| 1258 | +        $name = iconv('UTF-8', 'ASCII//TRANSLIT', $name); | |
| 1259 | + | |
| 1260 | + // Replacements | |
| 1261 | +        $name = str_replace(' ', '_', $name); | |
| 1262 | + | |
| 1263 | + // Every remaining disallowed characters will be removed | |
| 1264 | +        $name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name); | |
| 1265 | + | |
| 1266 | + return $name; | |
| 1267 | + } | |
| 1268 | + | |
| 1269 | + /** | |
| 1270 | + * escapes (user provided) parts for LDAP filter | |
| 1271 | + * @param string $input, the provided value | |
| 1272 | + * @param bool $allowAsterisk whether in * at the beginning should be preserved | |
| 1273 | + * @return string the escaped string | |
| 1274 | + */ | |
| 1275 | +    public function escapeFilterPart($input, $allowAsterisk = false) { | |
| 1276 | + $asterisk = ''; | |
| 1277 | +        if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') { | |
| 1278 | + $asterisk = '*'; | |
| 1279 | + $input = mb_substr($input, 1, null, 'UTF-8'); | |
| 1280 | + } | |
| 1281 | +        $search  = array('*', '\\', '(', ')'); | |
| 1282 | +        $replace = array('\\*', '\\\\', '\\(', '\\)'); | |
| 1283 | + return $asterisk . str_replace($search, $replace, $input); | |
| 1284 | + } | |
| 1285 | + | |
| 1286 | + /** | |
| 1287 | + * combines the input filters with AND | |
| 1288 | + * @param string[] $filters the filters to connect | |
| 1289 | + * @return string the combined filter | |
| 1290 | + */ | |
| 1291 | +    public function combineFilterWithAnd($filters) { | |
| 1292 | + return $this->combineFilter($filters, '&'); | |
| 1293 | + } | |
| 1294 | + | |
| 1295 | + /** | |
| 1296 | + * combines the input filters with OR | |
| 1297 | + * @param string[] $filters the filters to connect | |
| 1298 | + * @return string the combined filter | |
| 1299 | + * Combines Filter arguments with OR | |
| 1300 | + */ | |
| 1301 | +    public function combineFilterWithOr($filters) { | |
| 1302 | + return $this->combineFilter($filters, '|'); | |
| 1303 | + } | |
| 1304 | + | |
| 1305 | + /** | |
| 1306 | + * combines the input filters with given operator | |
| 1307 | + * @param string[] $filters the filters to connect | |
| 1308 | + * @param string $operator either & or | | |
| 1309 | + * @return string the combined filter | |
| 1310 | + */ | |
| 1311 | +    private function combineFilter($filters, $operator) { | |
| 1312 | +        $combinedFilter = '('.$operator; | |
| 1313 | +        foreach($filters as $filter) { | |
| 1314 | +            if ($filter !== '' && $filter[0] !== '(') { | |
| 1315 | +                $filter = '('.$filter.')'; | |
| 1316 | + } | |
| 1317 | + $combinedFilter.=$filter; | |
| 1318 | + } | |
| 1319 | + $combinedFilter.=')'; | |
| 1320 | + return $combinedFilter; | |
| 1321 | + } | |
| 1322 | + | |
| 1323 | + /** | |
| 1324 | + * creates a filter part for to perform search for users | |
| 1325 | + * @param string $search the search term | |
| 1326 | + * @return string the final filter part to use in LDAP searches | |
| 1327 | + */ | |
| 1328 | +    public function getFilterPartForUserSearch($search) { | |
| 1329 | + return $this->getFilterPartForSearch($search, | |
| 1330 | + $this->connection->ldapAttributesForUserSearch, | |
| 1331 | + $this->connection->ldapUserDisplayName); | |
| 1332 | + } | |
| 1333 | + | |
| 1334 | + /** | |
| 1335 | + * creates a filter part for to perform search for groups | |
| 1336 | + * @param string $search the search term | |
| 1337 | + * @return string the final filter part to use in LDAP searches | |
| 1338 | + */ | |
| 1339 | +    public function getFilterPartForGroupSearch($search) { | |
| 1340 | + return $this->getFilterPartForSearch($search, | |
| 1341 | + $this->connection->ldapAttributesForGroupSearch, | |
| 1342 | + $this->connection->ldapGroupDisplayName); | |
| 1343 | + } | |
| 1344 | + | |
| 1345 | + /** | |
| 1346 | + * creates a filter part for searches by splitting up the given search | |
| 1347 | + * string into single words | |
| 1348 | + * @param string $search the search term | |
| 1349 | + * @param string[] $searchAttributes needs to have at least two attributes, | |
| 1350 | + * otherwise it does not make sense :) | |
| 1351 | + * @return string the final filter part to use in LDAP searches | |
| 1352 | + * @throws \Exception | |
| 1353 | + */ | |
| 1354 | +    private function getAdvancedFilterPartForSearch($search, $searchAttributes) { | |
| 1355 | +        if(!is_array($searchAttributes) || count($searchAttributes) < 2) { | |
| 1356 | +            throw new \Exception('searchAttributes must be an array with at least two string'); | |
| 1357 | + } | |
| 1358 | +        $searchWords = explode(' ', trim($search)); | |
| 1359 | + $wordFilters = array(); | |
| 1360 | +        foreach($searchWords as $word) { | |
| 1361 | + $word = $this->prepareSearchTerm($word); | |
| 1362 | + //every word needs to appear at least once | |
| 1363 | + $wordMatchOneAttrFilters = array(); | |
| 1364 | +            foreach($searchAttributes as $attr) { | |
| 1365 | + $wordMatchOneAttrFilters[] = $attr . '=' . $word; | |
| 1366 | + } | |
| 1367 | + $wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters); | |
| 1368 | + } | |
| 1369 | + return $this->combineFilterWithAnd($wordFilters); | |
| 1370 | + } | |
| 1371 | + | |
| 1372 | + /** | |
| 1373 | + * creates a filter part for searches | |
| 1374 | + * @param string $search the search term | |
| 1375 | + * @param string[]|null $searchAttributes | |
| 1376 | + * @param string $fallbackAttribute a fallback attribute in case the user | |
| 1377 | + * did not define search attributes. Typically the display name attribute. | |
| 1378 | + * @return string the final filter part to use in LDAP searches | |
| 1379 | + */ | |
| 1380 | +    private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) { | |
| 1381 | + $filter = array(); | |
| 1382 | + $haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0); | |
| 1383 | +        if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) { | |
| 1384 | +            try { | |
| 1385 | + return $this->getAdvancedFilterPartForSearch($search, $searchAttributes); | |
| 1386 | +            } catch(\Exception $e) { | |
| 1387 | + \OCP\Util::writeLog( | |
| 1388 | + 'user_ldap', | |
| 1389 | + 'Creating advanced filter for search failed, falling back to simple method.', | |
| 1390 | + \OCP\Util::INFO | |
| 1391 | + ); | |
| 1392 | + } | |
| 1393 | + } | |
| 1394 | + | |
| 1395 | + $search = $this->prepareSearchTerm($search); | |
| 1396 | +        if(!is_array($searchAttributes) || count($searchAttributes) === 0) { | |
| 1397 | +            if ($fallbackAttribute === '') { | |
| 1398 | + return ''; | |
| 1399 | + } | |
| 1400 | + $filter[] = $fallbackAttribute . '=' . $search; | |
| 1401 | +        } else { | |
| 1402 | +            foreach($searchAttributes as $attribute) { | |
| 1403 | + $filter[] = $attribute . '=' . $search; | |
| 1404 | + } | |
| 1405 | + } | |
| 1406 | +        if(count($filter) === 1) { | |
| 1407 | +            return '('.$filter[0].')'; | |
| 1408 | + } | |
| 1409 | + return $this->combineFilterWithOr($filter); | |
| 1410 | + } | |
| 1411 | + | |
| 1412 | + /** | |
| 1413 | + * returns the search term depending on whether we are allowed | |
| 1414 | + * list users found by ldap with the current input appended by | |
| 1415 | + * a * | |
| 1416 | + * @return string | |
| 1417 | + */ | |
| 1418 | +    private function prepareSearchTerm($term) { | |
| 1419 | + $config = \OC::$server->getConfig(); | |
| 1420 | + | |
| 1421 | +        $allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes'); | |
| 1422 | + | |
| 1423 | + $result = $term; | |
| 1424 | +        if ($term === '') { | |
| 1425 | + $result = '*'; | |
| 1426 | +        } else if ($allowEnum !== 'no') { | |
| 1427 | + $result = $term . '*'; | |
| 1428 | + } | |
| 1429 | + return $result; | |
| 1430 | + } | |
| 1431 | + | |
| 1432 | + /** | |
| 1433 | + * returns the filter used for counting users | |
| 1434 | + * @return string | |
| 1435 | + */ | |
| 1436 | +    public function getFilterForUserCount() { | |
| 1437 | + $filter = $this->combineFilterWithAnd(array( | |
| 1438 | + $this->connection->ldapUserFilter, | |
| 1439 | + $this->connection->ldapUserDisplayName . '=*' | |
| 1440 | + )); | |
| 1441 | + | |
| 1442 | + return $filter; | |
| 1443 | + } | |
| 1444 | + | |
| 1445 | + /** | |
| 1446 | + * @param string $name | |
| 1447 | + * @param string $password | |
| 1448 | + * @return bool | |
| 1449 | + */ | |
| 1450 | +    public function areCredentialsValid($name, $password) { | |
| 1451 | + $name = $this->helper->DNasBaseParameter($name); | |
| 1452 | + $testConnection = clone $this->connection; | |
| 1453 | + $credentials = array( | |
| 1454 | + 'ldapAgentName' => $name, | |
| 1455 | + 'ldapAgentPassword' => $password | |
| 1456 | + ); | |
| 1457 | +        if(!$testConnection->setConfiguration($credentials)) { | |
| 1458 | + return false; | |
| 1459 | + } | |
| 1460 | + return $testConnection->bind(); | |
| 1461 | + } | |
| 1462 | + | |
| 1463 | + /** | |
| 1464 | + * reverse lookup of a DN given a known UUID | |
| 1465 | + * | |
| 1466 | + * @param string $uuid | |
| 1467 | + * @return string | |
| 1468 | + * @throws \Exception | |
| 1469 | + */ | |
| 1470 | +    public function getUserDnByUuid($uuid) { | |
| 1471 | + $uuidOverride = $this->connection->ldapExpertUUIDUserAttr; | |
| 1472 | + $filter = $this->connection->ldapUserFilter; | |
| 1473 | + $base = $this->connection->ldapBaseUsers; | |
| 1474 | + | |
| 1475 | +        if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') { | |
| 1476 | + // Sacrebleu! The UUID attribute is unknown :( We need first an | |
| 1477 | + // existing DN to be able to reliably detect it. | |
| 1478 | + $result = $this->search($filter, $base, ['dn'], 1); | |
| 1479 | +            if(!isset($result[0]) || !isset($result[0]['dn'])) { | |
| 1480 | +                throw new \Exception('Cannot determine UUID attribute'); | |
| 1481 | + } | |
| 1482 | + $dn = $result[0]['dn'][0]; | |
| 1483 | +            if(!$this->detectUuidAttribute($dn, true)) { | |
| 1484 | +                throw new \Exception('Cannot determine UUID attribute'); | |
| 1485 | + } | |
| 1486 | +        } else { | |
| 1487 | + // The UUID attribute is either known or an override is given. | |
| 1488 | + // By calling this method we ensure that $this->connection->$uuidAttr | |
| 1489 | + // is definitely set | |
| 1490 | +            if(!$this->detectUuidAttribute('', true)) { | |
| 1491 | +                throw new \Exception('Cannot determine UUID attribute'); | |
| 1492 | + } | |
| 1493 | + } | |
| 1494 | + | |
| 1495 | + $uuidAttr = $this->connection->ldapUuidUserAttribute; | |
| 1496 | +        if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') { | |
| 1497 | + $uuid = $this->formatGuid2ForFilterUser($uuid); | |
| 1498 | + } | |
| 1499 | + | |
| 1500 | + $filter = $uuidAttr . '=' . $uuid; | |
| 1501 | + $result = $this->searchUsers($filter, ['dn'], 2); | |
| 1502 | +        if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) { | |
| 1503 | + // we put the count into account to make sure that this is | |
| 1504 | + // really unique | |
| 1505 | + return $result[0]['dn'][0]; | |
| 1506 | + } | |
| 1507 | + | |
| 1508 | +        throw new \Exception('Cannot determine UUID attribute'); | |
| 1509 | + } | |
| 1510 | + | |
| 1511 | + /** | |
| 1512 | + * auto-detects the directory's UUID attribute | |
| 1513 | + * @param string $dn a known DN used to check against | |
| 1514 | + * @param bool $isUser | |
| 1515 | + * @param bool $force the detection should be run, even if it is not set to auto | |
| 1516 | + * @return bool true on success, false otherwise | |
| 1517 | + */ | |
| 1518 | +    private function detectUuidAttribute($dn, $isUser = true, $force = false) { | |
| 1519 | +        if($isUser) { | |
| 1520 | + $uuidAttr = 'ldapUuidUserAttribute'; | |
| 1521 | + $uuidOverride = $this->connection->ldapExpertUUIDUserAttr; | |
| 1522 | +        } else { | |
| 1523 | + $uuidAttr = 'ldapUuidGroupAttribute'; | |
| 1524 | + $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr; | |
| 1525 | + } | |
| 1526 | + | |
| 1527 | +        if(($this->connection->$uuidAttr !== 'auto') && !$force) { | |
| 1528 | + return true; | |
| 1529 | + } | |
| 1530 | + | |
| 1531 | +        if (is_string($uuidOverride) && trim($uuidOverride) !== '' && !$force) { | |
| 1532 | + $this->connection->$uuidAttr = $uuidOverride; | |
| 1533 | + return true; | |
| 1534 | + } | |
| 1535 | + | |
| 1536 | + // for now, supported attributes are entryUUID, nsuniqueid, objectGUID, ipaUniqueID | |
| 1537 | +        $testAttributes = array('entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid'); | |
| 1538 | + | |
| 1539 | +        foreach($testAttributes as $attribute) { | |
| 1540 | + $value = $this->readAttribute($dn, $attribute); | |
| 1541 | +            if(is_array($value) && isset($value[0]) && !empty($value[0])) { | |
| 1542 | +                \OCP\Util::writeLog('user_ldap', | |
| 1543 | + 'Setting '.$attribute.' as '.$uuidAttr, | |
| 1544 | + \OCP\Util::DEBUG); | |
| 1545 | + $this->connection->$uuidAttr = $attribute; | |
| 1546 | + return true; | |
| 1547 | + } | |
| 1548 | + } | |
| 1549 | +        \OCP\Util::writeLog('user_ldap', | |
| 1550 | + 'Could not autodetect the UUID attribute', | |
| 1551 | + \OCP\Util::ERROR); | |
| 1552 | + | |
| 1553 | + return false; | |
| 1554 | + } | |
| 1555 | + | |
| 1556 | + /** | |
| 1557 | + * @param string $dn | |
| 1558 | + * @param bool $isUser | |
| 1559 | + * @return string|bool | |
| 1560 | + */ | |
| 1561 | +    public function getUUID($dn, $isUser = true) { | |
| 1562 | +        if($isUser) { | |
| 1563 | + $uuidAttr = 'ldapUuidUserAttribute'; | |
| 1564 | + $uuidOverride = $this->connection->ldapExpertUUIDUserAttr; | |
| 1565 | +        } else { | |
| 1566 | + $uuidAttr = 'ldapUuidGroupAttribute'; | |
| 1567 | + $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr; | |
| 1568 | + } | |
| 1569 | + | |
| 1570 | + $uuid = false; | |
| 1571 | +        if($this->detectUuidAttribute($dn, $isUser)) { | |
| 1572 | + $uuid = $this->readAttribute($dn, $this->connection->$uuidAttr); | |
| 1573 | + if( !is_array($uuid) | |
| 1574 | + && $uuidOverride !== '' | |
| 1575 | +                && $this->detectUuidAttribute($dn, $isUser, true)) { | |
| 1576 | + $uuid = $this->readAttribute($dn, | |
| 1577 | + $this->connection->$uuidAttr); | |
| 1578 | + } | |
| 1579 | +            if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) { | |
| 1580 | + $uuid = $uuid[0]; | |
| 1581 | + } | |
| 1582 | + } | |
| 1583 | + | |
| 1584 | + return $uuid; | |
| 1585 | + } | |
| 1586 | + | |
| 1587 | + /** | |
| 1588 | + * converts a binary ObjectGUID into a string representation | |
| 1589 | + * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD | |
| 1590 | + * @return string | |
| 1591 | + * @link http://www.php.net/manual/en/function.ldap-get-values-len.php#73198 | |
| 1592 | + */ | |
| 1593 | +    private function convertObjectGUID2Str($oguid) { | |
| 1594 | + $hex_guid = bin2hex($oguid); | |
| 1595 | + $hex_guid_to_guid_str = ''; | |
| 1596 | +        for($k = 1; $k <= 4; ++$k) { | |
| 1597 | + $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2); | |
| 1598 | + } | |
| 1599 | + $hex_guid_to_guid_str .= '-'; | |
| 1600 | +        for($k = 1; $k <= 2; ++$k) { | |
| 1601 | + $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2); | |
| 1602 | + } | |
| 1603 | + $hex_guid_to_guid_str .= '-'; | |
| 1604 | +        for($k = 1; $k <= 2; ++$k) { | |
| 1605 | + $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2); | |
| 1606 | + } | |
| 1607 | + $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4); | |
| 1608 | + $hex_guid_to_guid_str .= '-' . substr($hex_guid, 20); | |
| 1609 | + | |
| 1610 | + return strtoupper($hex_guid_to_guid_str); | |
| 1611 | + } | |
| 1612 | + | |
| 1613 | + /** | |
| 1614 | + * the first three blocks of the string-converted GUID happen to be in | |
| 1615 | + * reverse order. In order to use it in a filter, this needs to be | |
| 1616 | + * corrected. Furthermore the dashes need to be replaced and \\ preprended | |
| 1617 | + * to every two hax figures. | |
| 1618 | + * | |
| 1619 | + * If an invalid string is passed, it will be returned without change. | |
| 1620 | + * | |
| 1621 | + * @param string $guid | |
| 1622 | + * @return string | |
| 1623 | + */ | |
| 1624 | +    public function formatGuid2ForFilterUser($guid) { | |
| 1625 | +        if(!is_string($guid)) { | |
| 1626 | +            throw new \InvalidArgumentException('String expected'); | |
| 1627 | + } | |
| 1628 | +        $blocks = explode('-', $guid); | |
| 1629 | +        if(count($blocks) !== 5) { | |
| 1630 | + /* | |
| 1631 | 1631 | * Why not throw an Exception instead? This method is a utility | 
| 1632 | 1632 | * called only when trying to figure out whether a "missing" known | 
| 1633 | 1633 | * LDAP user was or was not renamed on the LDAP server. And this | 
| @@ -1638,274 +1638,274 @@ discard block | ||
| 1638 | 1638 | * an exception here would kill the experience for a valid, acting | 
| 1639 | 1639 | * user. Instead we write a log message. | 
| 1640 | 1640 | */ | 
| 1641 | - \OC::$server->getLogger()->info( | |
| 1642 | - 'Passed string does not resemble a valid GUID. Known UUID ' . | |
| 1643 | -				'({uuid}) probably does not match UUID configuration.', | |
| 1644 | - [ 'app' => 'user_ldap', 'uuid' => $guid ] | |
| 1645 | - ); | |
| 1646 | - return $guid; | |
| 1647 | - } | |
| 1648 | -		for($i=0; $i < 3; $i++) { | |
| 1649 | - $pairs = str_split($blocks[$i], 2); | |
| 1650 | - $pairs = array_reverse($pairs); | |
| 1651 | -			$blocks[$i] = implode('', $pairs); | |
| 1652 | - } | |
| 1653 | -		for($i=0; $i < 5; $i++) { | |
| 1654 | - $pairs = str_split($blocks[$i], 2); | |
| 1655 | -			$blocks[$i] = '\\' . implode('\\', $pairs); | |
| 1656 | - } | |
| 1657 | -		return implode('', $blocks); | |
| 1658 | - } | |
| 1659 | - | |
| 1660 | - /** | |
| 1661 | - * gets a SID of the domain of the given dn | |
| 1662 | - * @param string $dn | |
| 1663 | - * @return string|bool | |
| 1664 | - */ | |
| 1665 | -	public function getSID($dn) { | |
| 1666 | - $domainDN = $this->getDomainDNFromDN($dn); | |
| 1667 | - $cacheKey = 'getSID-'.$domainDN; | |
| 1668 | - $sid = $this->connection->getFromCache($cacheKey); | |
| 1669 | -		if(!is_null($sid)) { | |
| 1670 | - return $sid; | |
| 1671 | - } | |
| 1672 | - | |
| 1673 | - $objectSid = $this->readAttribute($domainDN, 'objectsid'); | |
| 1674 | -		if(!is_array($objectSid) || empty($objectSid)) { | |
| 1675 | - $this->connection->writeToCache($cacheKey, false); | |
| 1676 | - return false; | |
| 1677 | - } | |
| 1678 | - $domainObjectSid = $this->convertSID2Str($objectSid[0]); | |
| 1679 | - $this->connection->writeToCache($cacheKey, $domainObjectSid); | |
| 1680 | - | |
| 1681 | - return $domainObjectSid; | |
| 1682 | - } | |
| 1683 | - | |
| 1684 | - /** | |
| 1685 | - * converts a binary SID into a string representation | |
| 1686 | - * @param string $sid | |
| 1687 | - * @return string | |
| 1688 | - */ | |
| 1689 | -	public function convertSID2Str($sid) { | |
| 1690 | - // The format of a SID binary string is as follows: | |
| 1691 | - // 1 byte for the revision level | |
| 1692 | - // 1 byte for the number n of variable sub-ids | |
| 1693 | - // 6 bytes for identifier authority value | |
| 1694 | - // n*4 bytes for n sub-ids | |
| 1695 | - // | |
| 1696 | - // Example: 010400000000000515000000a681e50e4d6c6c2bca32055f | |
| 1697 | - // Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444 | |
| 1698 | - $revision = ord($sid[0]); | |
| 1699 | - $numberSubID = ord($sid[1]); | |
| 1700 | - | |
| 1701 | - $subIdStart = 8; // 1 + 1 + 6 | |
| 1702 | - $subIdLength = 4; | |
| 1703 | -		if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) { | |
| 1704 | - // Incorrect number of bytes present. | |
| 1705 | - return ''; | |
| 1706 | - } | |
| 1707 | - | |
| 1708 | - // 6 bytes = 48 bits can be represented using floats without loss of | |
| 1709 | - // precision (see https://gist.github.com/bantu/886ac680b0aef5812f71) | |
| 1710 | - $iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', ''); | |
| 1711 | - | |
| 1712 | - $subIDs = array(); | |
| 1713 | -		for ($i = 0; $i < $numberSubID; $i++) { | |
| 1714 | -			$subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength)); | |
| 1715 | -			$subIDs[] = sprintf('%u', $subID[1]); | |
| 1716 | - } | |
| 1717 | - | |
| 1718 | - // Result for example above: S-1-5-21-249921958-728525901-1594176202 | |
| 1719 | -		return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs)); | |
| 1720 | - } | |
| 1721 | - | |
| 1722 | - /** | |
| 1723 | - * checks if the given DN is part of the given base DN(s) | |
| 1724 | - * @param string $dn the DN | |
| 1725 | - * @param string[] $bases array containing the allowed base DN or DNs | |
| 1726 | - * @return bool | |
| 1727 | - */ | |
| 1728 | -	public function isDNPartOfBase($dn, $bases) { | |
| 1729 | - $belongsToBase = false; | |
| 1730 | - $bases = $this->helper->sanitizeDN($bases); | |
| 1731 | - | |
| 1732 | -		foreach($bases as $base) { | |
| 1733 | - $belongsToBase = true; | |
| 1734 | -			if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) { | |
| 1735 | - $belongsToBase = false; | |
| 1736 | - } | |
| 1737 | -			if($belongsToBase) { | |
| 1738 | - break; | |
| 1739 | - } | |
| 1740 | - } | |
| 1741 | - return $belongsToBase; | |
| 1742 | - } | |
| 1743 | - | |
| 1744 | - /** | |
| 1745 | - * resets a running Paged Search operation | |
| 1746 | - */ | |
| 1747 | -	private function abandonPagedSearch() { | |
| 1748 | -		if($this->connection->hasPagedResultSupport) { | |
| 1749 | - $cr = $this->connection->getConnectionResource(); | |
| 1750 | -			$this->invokeLDAPMethod('controlPagedResult', $cr, 0, false, $this->lastCookie); | |
| 1751 | - $this->getPagedSearchResultState(); | |
| 1752 | - $this->lastCookie = ''; | |
| 1753 | - $this->cookies = array(); | |
| 1754 | - } | |
| 1755 | - } | |
| 1756 | - | |
| 1757 | - /** | |
| 1758 | - * get a cookie for the next LDAP paged search | |
| 1759 | - * @param string $base a string with the base DN for the search | |
| 1760 | - * @param string $filter the search filter to identify the correct search | |
| 1761 | - * @param int $limit the limit (or 'pageSize'), to identify the correct search well | |
| 1762 | - * @param int $offset the offset for the new search to identify the correct search really good | |
| 1763 | - * @return string containing the key or empty if none is cached | |
| 1764 | - */ | |
| 1765 | -	private function getPagedResultCookie($base, $filter, $limit, $offset) { | |
| 1766 | -		if($offset === 0) { | |
| 1767 | - return ''; | |
| 1768 | - } | |
| 1769 | - $offset -= $limit; | |
| 1770 | - //we work with cache here | |
| 1771 | - $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . intval($limit) . '-' . intval($offset); | |
| 1772 | - $cookie = ''; | |
| 1773 | -		if(isset($this->cookies[$cacheKey])) { | |
| 1774 | - $cookie = $this->cookies[$cacheKey]; | |
| 1775 | -			if(is_null($cookie)) { | |
| 1776 | - $cookie = ''; | |
| 1777 | - } | |
| 1778 | - } | |
| 1779 | - return $cookie; | |
| 1780 | - } | |
| 1781 | - | |
| 1782 | - /** | |
| 1783 | - * checks whether an LDAP paged search operation has more pages that can be | |
| 1784 | - * retrieved, typically when offset and limit are provided. | |
| 1785 | - * | |
| 1786 | - * Be very careful to use it: the last cookie value, which is inspected, can | |
| 1787 | - * be reset by other operations. Best, call it immediately after a search(), | |
| 1788 | - * searchUsers() or searchGroups() call. count-methods are probably safe as | |
| 1789 | - * well. Don't rely on it with any fetchList-method. | |
| 1790 | - * @return bool | |
| 1791 | - */ | |
| 1792 | -	public function hasMoreResults() { | |
| 1793 | -		if(!$this->connection->hasPagedResultSupport) { | |
| 1794 | - return false; | |
| 1795 | - } | |
| 1796 | - | |
| 1797 | -		if(empty($this->lastCookie) && $this->lastCookie !== '0') { | |
| 1798 | - // as in RFC 2696, when all results are returned, the cookie will | |
| 1799 | - // be empty. | |
| 1800 | - return false; | |
| 1801 | - } | |
| 1802 | - | |
| 1803 | - return true; | |
| 1804 | - } | |
| 1805 | - | |
| 1806 | - /** | |
| 1807 | - * set a cookie for LDAP paged search run | |
| 1808 | - * @param string $base a string with the base DN for the search | |
| 1809 | - * @param string $filter the search filter to identify the correct search | |
| 1810 | - * @param int $limit the limit (or 'pageSize'), to identify the correct search well | |
| 1811 | - * @param int $offset the offset for the run search to identify the correct search really good | |
| 1812 | - * @param string $cookie string containing the cookie returned by ldap_control_paged_result_response | |
| 1813 | - * @return void | |
| 1814 | - */ | |
| 1815 | -	private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) { | |
| 1816 | - // allow '0' for 389ds | |
| 1817 | -		if(!empty($cookie) || $cookie === '0') { | |
| 1818 | - $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' .intval($limit) . '-' . intval($offset); | |
| 1819 | - $this->cookies[$cacheKey] = $cookie; | |
| 1820 | - $this->lastCookie = $cookie; | |
| 1821 | - } | |
| 1822 | - } | |
| 1823 | - | |
| 1824 | - /** | |
| 1825 | - * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search. | |
| 1826 | - * @return boolean|null true on success, null or false otherwise | |
| 1827 | - */ | |
| 1828 | -	public function getPagedSearchResultState() { | |
| 1829 | - $result = $this->pagedSearchedSuccessful; | |
| 1830 | - $this->pagedSearchedSuccessful = null; | |
| 1831 | - return $result; | |
| 1832 | - } | |
| 1833 | - | |
| 1834 | - /** | |
| 1835 | - * Prepares a paged search, if possible | |
| 1836 | - * @param string $filter the LDAP filter for the search | |
| 1837 | - * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched | |
| 1838 | - * @param string[] $attr optional, when a certain attribute shall be filtered outside | |
| 1839 | - * @param int $limit | |
| 1840 | - * @param int $offset | |
| 1841 | - * @return bool|true | |
| 1842 | - */ | |
| 1843 | -	private function initPagedSearch($filter, $bases, $attr, $limit, $offset) { | |
| 1844 | - $pagedSearchOK = false; | |
| 1845 | -		if($this->connection->hasPagedResultSupport && ($limit !== 0)) { | |
| 1846 | - $offset = intval($offset); //can be null | |
| 1847 | -			\OCP\Util::writeLog('user_ldap', | |
| 1848 | - 'initializing paged search for Filter '.$filter.' base '.print_r($bases, true) | |
| 1849 | - .' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset, | |
| 1850 | - \OCP\Util::DEBUG); | |
| 1851 | - //get the cookie from the search for the previous search, required by LDAP | |
| 1852 | -			foreach($bases as $base) { | |
| 1853 | - | |
| 1854 | - $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset); | |
| 1855 | -				if(empty($cookie) && $cookie !== "0" && ($offset > 0)) { | |
| 1856 | - // no cookie known from a potential previous search. We need | |
| 1857 | - // to start from 0 to come to the desired page. cookie value | |
| 1858 | - // of '0' is valid, because 389ds | |
| 1859 | - $reOffset = 0; | |
| 1860 | -					while($reOffset < $offset) { | |
| 1861 | - $this->search($filter, array($base), $attr, $limit, $reOffset, true); | |
| 1862 | - $reOffset += $limit; | |
| 1863 | - } | |
| 1864 | - $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset); | |
| 1865 | - //still no cookie? obviously, the server does not like us. Let's skip paging efforts. | |
| 1866 | - // '0' is valid, because 389ds | |
| 1867 | - //TODO: remember this, probably does not change in the next request... | |
| 1868 | -					if(empty($cookie) && $cookie !== '0') { | |
| 1869 | - $cookie = null; | |
| 1870 | - } | |
| 1871 | - } | |
| 1872 | -				if(!is_null($cookie)) { | |
| 1873 | - //since offset = 0, this is a new search. We abandon other searches that might be ongoing. | |
| 1874 | - $this->abandonPagedSearch(); | |
| 1875 | -					$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult', | |
| 1876 | - $this->connection->getConnectionResource(), $limit, | |
| 1877 | - false, $cookie); | |
| 1878 | -					if(!$pagedSearchOK) { | |
| 1879 | - return false; | |
| 1880 | - } | |
| 1881 | -					\OCP\Util::writeLog('user_ldap', 'Ready for a paged search', \OCP\Util::DEBUG); | |
| 1882 | -				} else { | |
| 1883 | -					\OCP\Util::writeLog('user_ldap', | |
| 1884 | - 'No paged search for us, Cpt., Limit '.$limit.' Offset '.$offset, | |
| 1885 | - \OCP\Util::INFO); | |
| 1886 | - } | |
| 1887 | - | |
| 1888 | - } | |
| 1889 | - /* ++ Fixing RHDS searches with pages with zero results ++ | |
| 1641 | + \OC::$server->getLogger()->info( | |
| 1642 | + 'Passed string does not resemble a valid GUID. Known UUID ' . | |
| 1643 | +                '({uuid}) probably does not match UUID configuration.', | |
| 1644 | + [ 'app' => 'user_ldap', 'uuid' => $guid ] | |
| 1645 | + ); | |
| 1646 | + return $guid; | |
| 1647 | + } | |
| 1648 | +        for($i=0; $i < 3; $i++) { | |
| 1649 | + $pairs = str_split($blocks[$i], 2); | |
| 1650 | + $pairs = array_reverse($pairs); | |
| 1651 | +            $blocks[$i] = implode('', $pairs); | |
| 1652 | + } | |
| 1653 | +        for($i=0; $i < 5; $i++) { | |
| 1654 | + $pairs = str_split($blocks[$i], 2); | |
| 1655 | +            $blocks[$i] = '\\' . implode('\\', $pairs); | |
| 1656 | + } | |
| 1657 | +        return implode('', $blocks); | |
| 1658 | + } | |
| 1659 | + | |
| 1660 | + /** | |
| 1661 | + * gets a SID of the domain of the given dn | |
| 1662 | + * @param string $dn | |
| 1663 | + * @return string|bool | |
| 1664 | + */ | |
| 1665 | +    public function getSID($dn) { | |
| 1666 | + $domainDN = $this->getDomainDNFromDN($dn); | |
| 1667 | + $cacheKey = 'getSID-'.$domainDN; | |
| 1668 | + $sid = $this->connection->getFromCache($cacheKey); | |
| 1669 | +        if(!is_null($sid)) { | |
| 1670 | + return $sid; | |
| 1671 | + } | |
| 1672 | + | |
| 1673 | + $objectSid = $this->readAttribute($domainDN, 'objectsid'); | |
| 1674 | +        if(!is_array($objectSid) || empty($objectSid)) { | |
| 1675 | + $this->connection->writeToCache($cacheKey, false); | |
| 1676 | + return false; | |
| 1677 | + } | |
| 1678 | + $domainObjectSid = $this->convertSID2Str($objectSid[0]); | |
| 1679 | + $this->connection->writeToCache($cacheKey, $domainObjectSid); | |
| 1680 | + | |
| 1681 | + return $domainObjectSid; | |
| 1682 | + } | |
| 1683 | + | |
| 1684 | + /** | |
| 1685 | + * converts a binary SID into a string representation | |
| 1686 | + * @param string $sid | |
| 1687 | + * @return string | |
| 1688 | + */ | |
| 1689 | +    public function convertSID2Str($sid) { | |
| 1690 | + // The format of a SID binary string is as follows: | |
| 1691 | + // 1 byte for the revision level | |
| 1692 | + // 1 byte for the number n of variable sub-ids | |
| 1693 | + // 6 bytes for identifier authority value | |
| 1694 | + // n*4 bytes for n sub-ids | |
| 1695 | + // | |
| 1696 | + // Example: 010400000000000515000000a681e50e4d6c6c2bca32055f | |
| 1697 | + // Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444 | |
| 1698 | + $revision = ord($sid[0]); | |
| 1699 | + $numberSubID = ord($sid[1]); | |
| 1700 | + | |
| 1701 | + $subIdStart = 8; // 1 + 1 + 6 | |
| 1702 | + $subIdLength = 4; | |
| 1703 | +        if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) { | |
| 1704 | + // Incorrect number of bytes present. | |
| 1705 | + return ''; | |
| 1706 | + } | |
| 1707 | + | |
| 1708 | + // 6 bytes = 48 bits can be represented using floats without loss of | |
| 1709 | + // precision (see https://gist.github.com/bantu/886ac680b0aef5812f71) | |
| 1710 | + $iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', ''); | |
| 1711 | + | |
| 1712 | + $subIDs = array(); | |
| 1713 | +        for ($i = 0; $i < $numberSubID; $i++) { | |
| 1714 | +            $subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength)); | |
| 1715 | +            $subIDs[] = sprintf('%u', $subID[1]); | |
| 1716 | + } | |
| 1717 | + | |
| 1718 | + // Result for example above: S-1-5-21-249921958-728525901-1594176202 | |
| 1719 | +        return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs)); | |
| 1720 | + } | |
| 1721 | + | |
| 1722 | + /** | |
| 1723 | + * checks if the given DN is part of the given base DN(s) | |
| 1724 | + * @param string $dn the DN | |
| 1725 | + * @param string[] $bases array containing the allowed base DN or DNs | |
| 1726 | + * @return bool | |
| 1727 | + */ | |
| 1728 | +    public function isDNPartOfBase($dn, $bases) { | |
| 1729 | + $belongsToBase = false; | |
| 1730 | + $bases = $this->helper->sanitizeDN($bases); | |
| 1731 | + | |
| 1732 | +        foreach($bases as $base) { | |
| 1733 | + $belongsToBase = true; | |
| 1734 | +            if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) { | |
| 1735 | + $belongsToBase = false; | |
| 1736 | + } | |
| 1737 | +            if($belongsToBase) { | |
| 1738 | + break; | |
| 1739 | + } | |
| 1740 | + } | |
| 1741 | + return $belongsToBase; | |
| 1742 | + } | |
| 1743 | + | |
| 1744 | + /** | |
| 1745 | + * resets a running Paged Search operation | |
| 1746 | + */ | |
| 1747 | +    private function abandonPagedSearch() { | |
| 1748 | +        if($this->connection->hasPagedResultSupport) { | |
| 1749 | + $cr = $this->connection->getConnectionResource(); | |
| 1750 | +            $this->invokeLDAPMethod('controlPagedResult', $cr, 0, false, $this->lastCookie); | |
| 1751 | + $this->getPagedSearchResultState(); | |
| 1752 | + $this->lastCookie = ''; | |
| 1753 | + $this->cookies = array(); | |
| 1754 | + } | |
| 1755 | + } | |
| 1756 | + | |
| 1757 | + /** | |
| 1758 | + * get a cookie for the next LDAP paged search | |
| 1759 | + * @param string $base a string with the base DN for the search | |
| 1760 | + * @param string $filter the search filter to identify the correct search | |
| 1761 | + * @param int $limit the limit (or 'pageSize'), to identify the correct search well | |
| 1762 | + * @param int $offset the offset for the new search to identify the correct search really good | |
| 1763 | + * @return string containing the key or empty if none is cached | |
| 1764 | + */ | |
| 1765 | +    private function getPagedResultCookie($base, $filter, $limit, $offset) { | |
| 1766 | +        if($offset === 0) { | |
| 1767 | + return ''; | |
| 1768 | + } | |
| 1769 | + $offset -= $limit; | |
| 1770 | + //we work with cache here | |
| 1771 | + $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . intval($limit) . '-' . intval($offset); | |
| 1772 | + $cookie = ''; | |
| 1773 | +        if(isset($this->cookies[$cacheKey])) { | |
| 1774 | + $cookie = $this->cookies[$cacheKey]; | |
| 1775 | +            if(is_null($cookie)) { | |
| 1776 | + $cookie = ''; | |
| 1777 | + } | |
| 1778 | + } | |
| 1779 | + return $cookie; | |
| 1780 | + } | |
| 1781 | + | |
| 1782 | + /** | |
| 1783 | + * checks whether an LDAP paged search operation has more pages that can be | |
| 1784 | + * retrieved, typically when offset and limit are provided. | |
| 1785 | + * | |
| 1786 | + * Be very careful to use it: the last cookie value, which is inspected, can | |
| 1787 | + * be reset by other operations. Best, call it immediately after a search(), | |
| 1788 | + * searchUsers() or searchGroups() call. count-methods are probably safe as | |
| 1789 | + * well. Don't rely on it with any fetchList-method. | |
| 1790 | + * @return bool | |
| 1791 | + */ | |
| 1792 | +    public function hasMoreResults() { | |
| 1793 | +        if(!$this->connection->hasPagedResultSupport) { | |
| 1794 | + return false; | |
| 1795 | + } | |
| 1796 | + | |
| 1797 | +        if(empty($this->lastCookie) && $this->lastCookie !== '0') { | |
| 1798 | + // as in RFC 2696, when all results are returned, the cookie will | |
| 1799 | + // be empty. | |
| 1800 | + return false; | |
| 1801 | + } | |
| 1802 | + | |
| 1803 | + return true; | |
| 1804 | + } | |
| 1805 | + | |
| 1806 | + /** | |
| 1807 | + * set a cookie for LDAP paged search run | |
| 1808 | + * @param string $base a string with the base DN for the search | |
| 1809 | + * @param string $filter the search filter to identify the correct search | |
| 1810 | + * @param int $limit the limit (or 'pageSize'), to identify the correct search well | |
| 1811 | + * @param int $offset the offset for the run search to identify the correct search really good | |
| 1812 | + * @param string $cookie string containing the cookie returned by ldap_control_paged_result_response | |
| 1813 | + * @return void | |
| 1814 | + */ | |
| 1815 | +    private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) { | |
| 1816 | + // allow '0' for 389ds | |
| 1817 | +        if(!empty($cookie) || $cookie === '0') { | |
| 1818 | + $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' .intval($limit) . '-' . intval($offset); | |
| 1819 | + $this->cookies[$cacheKey] = $cookie; | |
| 1820 | + $this->lastCookie = $cookie; | |
| 1821 | + } | |
| 1822 | + } | |
| 1823 | + | |
| 1824 | + /** | |
| 1825 | + * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search. | |
| 1826 | + * @return boolean|null true on success, null or false otherwise | |
| 1827 | + */ | |
| 1828 | +    public function getPagedSearchResultState() { | |
| 1829 | + $result = $this->pagedSearchedSuccessful; | |
| 1830 | + $this->pagedSearchedSuccessful = null; | |
| 1831 | + return $result; | |
| 1832 | + } | |
| 1833 | + | |
| 1834 | + /** | |
| 1835 | + * Prepares a paged search, if possible | |
| 1836 | + * @param string $filter the LDAP filter for the search | |
| 1837 | + * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched | |
| 1838 | + * @param string[] $attr optional, when a certain attribute shall be filtered outside | |
| 1839 | + * @param int $limit | |
| 1840 | + * @param int $offset | |
| 1841 | + * @return bool|true | |
| 1842 | + */ | |
| 1843 | +    private function initPagedSearch($filter, $bases, $attr, $limit, $offset) { | |
| 1844 | + $pagedSearchOK = false; | |
| 1845 | +        if($this->connection->hasPagedResultSupport && ($limit !== 0)) { | |
| 1846 | + $offset = intval($offset); //can be null | |
| 1847 | +            \OCP\Util::writeLog('user_ldap', | |
| 1848 | + 'initializing paged search for Filter '.$filter.' base '.print_r($bases, true) | |
| 1849 | + .' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset, | |
| 1850 | + \OCP\Util::DEBUG); | |
| 1851 | + //get the cookie from the search for the previous search, required by LDAP | |
| 1852 | +            foreach($bases as $base) { | |
| 1853 | + | |
| 1854 | + $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset); | |
| 1855 | +                if(empty($cookie) && $cookie !== "0" && ($offset > 0)) { | |
| 1856 | + // no cookie known from a potential previous search. We need | |
| 1857 | + // to start from 0 to come to the desired page. cookie value | |
| 1858 | + // of '0' is valid, because 389ds | |
| 1859 | + $reOffset = 0; | |
| 1860 | +                    while($reOffset < $offset) { | |
| 1861 | + $this->search($filter, array($base), $attr, $limit, $reOffset, true); | |
| 1862 | + $reOffset += $limit; | |
| 1863 | + } | |
| 1864 | + $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset); | |
| 1865 | + //still no cookie? obviously, the server does not like us. Let's skip paging efforts. | |
| 1866 | + // '0' is valid, because 389ds | |
| 1867 | + //TODO: remember this, probably does not change in the next request... | |
| 1868 | +                    if(empty($cookie) && $cookie !== '0') { | |
| 1869 | + $cookie = null; | |
| 1870 | + } | |
| 1871 | + } | |
| 1872 | +                if(!is_null($cookie)) { | |
| 1873 | + //since offset = 0, this is a new search. We abandon other searches that might be ongoing. | |
| 1874 | + $this->abandonPagedSearch(); | |
| 1875 | +                    $pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult', | |
| 1876 | + $this->connection->getConnectionResource(), $limit, | |
| 1877 | + false, $cookie); | |
| 1878 | +                    if(!$pagedSearchOK) { | |
| 1879 | + return false; | |
| 1880 | + } | |
| 1881 | +                    \OCP\Util::writeLog('user_ldap', 'Ready for a paged search', \OCP\Util::DEBUG); | |
| 1882 | +                } else { | |
| 1883 | +                    \OCP\Util::writeLog('user_ldap', | |
| 1884 | + 'No paged search for us, Cpt., Limit '.$limit.' Offset '.$offset, | |
| 1885 | + \OCP\Util::INFO); | |
| 1886 | + } | |
| 1887 | + | |
| 1888 | + } | |
| 1889 | + /* ++ Fixing RHDS searches with pages with zero results ++ | |
| 1890 | 1890 | * We coudn't get paged searches working with our RHDS for login ($limit = 0), | 
| 1891 | 1891 | * due to pages with zero results. | 
| 1892 | 1892 | * So we added "&& !empty($this->lastCookie)" to this test to ignore pagination | 
| 1893 | 1893 | * if we don't have a previous paged search. | 
| 1894 | 1894 | */ | 
| 1895 | -		} else if($this->connection->hasPagedResultSupport && $limit === 0 && !empty($this->lastCookie)) { | |
| 1896 | - // a search without limit was requested. However, if we do use | |
| 1897 | - // Paged Search once, we always must do it. This requires us to | |
| 1898 | - // initialize it with the configured page size. | |
| 1899 | - $this->abandonPagedSearch(); | |
| 1900 | - // in case someone set it to 0 … use 500, otherwise no results will | |
| 1901 | - // be returned. | |
| 1902 | - $pageSize = intval($this->connection->ldapPagingSize) > 0 ? intval($this->connection->ldapPagingSize) : 500; | |
| 1903 | -			$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult', | |
| 1904 | - $this->connection->getConnectionResource(), | |
| 1905 | - $pageSize, false, ''); | |
| 1906 | - } | |
| 1907 | - | |
| 1908 | - return $pagedSearchOK; | |
| 1909 | - } | |
| 1895 | +        } else if($this->connection->hasPagedResultSupport && $limit === 0 && !empty($this->lastCookie)) { | |
| 1896 | + // a search without limit was requested. However, if we do use | |
| 1897 | + // Paged Search once, we always must do it. This requires us to | |
| 1898 | + // initialize it with the configured page size. | |
| 1899 | + $this->abandonPagedSearch(); | |
| 1900 | + // in case someone set it to 0 … use 500, otherwise no results will | |
| 1901 | + // be returned. | |
| 1902 | + $pageSize = intval($this->connection->ldapPagingSize) > 0 ? intval($this->connection->ldapPagingSize) : 500; | |
| 1903 | +            $pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult', | |
| 1904 | + $this->connection->getConnectionResource(), | |
| 1905 | + $pageSize, false, ''); | |
| 1906 | + } | |
| 1907 | + | |
| 1908 | + return $pagedSearchOK; | |
| 1909 | + } | |
| 1910 | 1910 | |
| 1911 | 1911 | } | 
| @@ -23,49 +23,49 @@ | ||
| 23 | 23 | |
| 24 | 24 | $eventDispatcher = \OC::$server->getEventDispatcher(); | 
| 25 | 25 | $eventDispatcher->addListener( | 
| 26 | - 'OCA\Files::loadAdditionalScripts', | |
| 27 | -	function() { | |
| 28 | -		\OCP\Util::addScript('oc-backbone-webdav'); | |
| 29 | -		\OCP\Util::addScript('comments', 'merged'); | |
| 30 | -		\OCP\Util::addStyle('comments', 'autocomplete'); | |
| 31 | -		\OCP\Util::addStyle('comments', 'comments'); | |
| 32 | - } | |
| 26 | + 'OCA\Files::loadAdditionalScripts', | |
| 27 | +    function() { | |
| 28 | +        \OCP\Util::addScript('oc-backbone-webdav'); | |
| 29 | +        \OCP\Util::addScript('comments', 'merged'); | |
| 30 | +        \OCP\Util::addStyle('comments', 'autocomplete'); | |
| 31 | +        \OCP\Util::addStyle('comments', 'comments'); | |
| 32 | + } | |
| 33 | 33 | ); | 
| 34 | 34 | |
| 35 | 35 |  $eventDispatcher->addListener(\OCP\Comments\CommentsEntityEvent::EVENT_ENTITY, function(\OCP\Comments\CommentsEntityEvent $event) { | 
| 36 | -	$event->addEntityCollection('files', function($name) { | |
| 37 | - $nodes = \OC::$server->getUserFolder()->getById(intval($name)); | |
| 38 | - return !empty($nodes); | |
| 39 | - }); | |
| 36 | +    $event->addEntityCollection('files', function($name) { | |
| 37 | + $nodes = \OC::$server->getUserFolder()->getById(intval($name)); | |
| 38 | + return !empty($nodes); | |
| 39 | + }); | |
| 40 | 40 | }); | 
| 41 | 41 | |
| 42 | 42 | $notificationManager = \OC::$server->getNotificationManager(); | 
| 43 | 43 | $notificationManager->registerNotifier( | 
| 44 | -	function() { | |
| 45 | -		$application = new \OCP\AppFramework\App('comments'); | |
| 46 | - return $application->getContainer()->query(\OCA\Comments\Notification\Notifier::class); | |
| 47 | - }, | |
| 48 | -	function () { | |
| 49 | -		$l = \OC::$server->getL10N('comments'); | |
| 50 | -		return ['id' => 'comments', 'name' => $l->t('Comments')]; | |
| 51 | - } | |
| 44 | +    function() { | |
| 45 | +        $application = new \OCP\AppFramework\App('comments'); | |
| 46 | + return $application->getContainer()->query(\OCA\Comments\Notification\Notifier::class); | |
| 47 | + }, | |
| 48 | +    function () { | |
| 49 | +        $l = \OC::$server->getL10N('comments'); | |
| 50 | +        return ['id' => 'comments', 'name' => $l->t('Comments')]; | |
| 51 | + } | |
| 52 | 52 | ); | 
| 53 | 53 | |
| 54 | 54 | $commentsManager = \OC::$server->getCommentsManager(); | 
| 55 | 55 |  $commentsManager->registerEventHandler(function () { | 
| 56 | -	$application = new \OCP\AppFramework\App('comments'); | |
| 57 | - /** @var \OCA\Comments\EventHandler $handler */ | |
| 58 | - $handler = $application->getContainer()->query(\OCA\Comments\EventHandler::class); | |
| 59 | - return $handler; | |
| 56 | +    $application = new \OCP\AppFramework\App('comments'); | |
| 57 | + /** @var \OCA\Comments\EventHandler $handler */ | |
| 58 | + $handler = $application->getContainer()->query(\OCA\Comments\EventHandler::class); | |
| 59 | + return $handler; | |
| 60 | 60 | }); | 
| 61 | 61 |  $commentsManager->registerDisplayNameResolver('user', function($id) { | 
| 62 | - $manager = \OC::$server->getUserManager(); | |
| 63 | - $user = $manager->get($id); | |
| 64 | -	if(is_null($user)) { | |
| 65 | -		$l = \OC::$server->getL10N('comments'); | |
| 66 | -		$displayName = $l->t('Unknown user'); | |
| 67 | -	} else { | |
| 68 | - $displayName = $user->getDisplayName(); | |
| 69 | - } | |
| 70 | - return $displayName; | |
| 62 | + $manager = \OC::$server->getUserManager(); | |
| 63 | + $user = $manager->get($id); | |
| 64 | +    if(is_null($user)) { | |
| 65 | +        $l = \OC::$server->getL10N('comments'); | |
| 66 | +        $displayName = $l->t('Unknown user'); | |
| 67 | +    } else { | |
| 68 | + $displayName = $user->getDisplayName(); | |
| 69 | + } | |
| 70 | + return $displayName; | |
| 71 | 71 | }); | 
| @@ -60,1487 +60,1487 @@ | ||
| 60 | 60 | */ | 
| 61 | 61 |  class Manager implements IManager { | 
| 62 | 62 | |
| 63 | - /** @var IProviderFactory */ | |
| 64 | - private $factory; | |
| 65 | - /** @var ILogger */ | |
| 66 | - private $logger; | |
| 67 | - /** @var IConfig */ | |
| 68 | - private $config; | |
| 69 | - /** @var ISecureRandom */ | |
| 70 | - private $secureRandom; | |
| 71 | - /** @var IHasher */ | |
| 72 | - private $hasher; | |
| 73 | - /** @var IMountManager */ | |
| 74 | - private $mountManager; | |
| 75 | - /** @var IGroupManager */ | |
| 76 | - private $groupManager; | |
| 77 | - /** @var IL10N */ | |
| 78 | - private $l; | |
| 79 | - /** @var IFactory */ | |
| 80 | - private $l10nFactory; | |
| 81 | - /** @var IUserManager */ | |
| 82 | - private $userManager; | |
| 83 | - /** @var IRootFolder */ | |
| 84 | - private $rootFolder; | |
| 85 | - /** @var CappedMemoryCache */ | |
| 86 | - private $sharingDisabledForUsersCache; | |
| 87 | - /** @var EventDispatcher */ | |
| 88 | - private $eventDispatcher; | |
| 89 | - /** @var LegacyHooks */ | |
| 90 | - private $legacyHooks; | |
| 91 | - /** @var IMailer */ | |
| 92 | - private $mailer; | |
| 93 | - /** @var IURLGenerator */ | |
| 94 | - private $urlGenerator; | |
| 95 | - /** @var \OC_Defaults */ | |
| 96 | - private $defaults; | |
| 97 | - | |
| 98 | - | |
| 99 | - /** | |
| 100 | - * Manager constructor. | |
| 101 | - * | |
| 102 | - * @param ILogger $logger | |
| 103 | - * @param IConfig $config | |
| 104 | - * @param ISecureRandom $secureRandom | |
| 105 | - * @param IHasher $hasher | |
| 106 | - * @param IMountManager $mountManager | |
| 107 | - * @param IGroupManager $groupManager | |
| 108 | - * @param IL10N $l | |
| 109 | - * @param IFactory $l10nFactory | |
| 110 | - * @param IProviderFactory $factory | |
| 111 | - * @param IUserManager $userManager | |
| 112 | - * @param IRootFolder $rootFolder | |
| 113 | - * @param EventDispatcher $eventDispatcher | |
| 114 | - * @param IMailer $mailer | |
| 115 | - * @param IURLGenerator $urlGenerator | |
| 116 | - * @param \OC_Defaults $defaults | |
| 117 | - */ | |
| 118 | - public function __construct( | |
| 119 | - ILogger $logger, | |
| 120 | - IConfig $config, | |
| 121 | - ISecureRandom $secureRandom, | |
| 122 | - IHasher $hasher, | |
| 123 | - IMountManager $mountManager, | |
| 124 | - IGroupManager $groupManager, | |
| 125 | - IL10N $l, | |
| 126 | - IFactory $l10nFactory, | |
| 127 | - IProviderFactory $factory, | |
| 128 | - IUserManager $userManager, | |
| 129 | - IRootFolder $rootFolder, | |
| 130 | - EventDispatcher $eventDispatcher, | |
| 131 | - IMailer $mailer, | |
| 132 | - IURLGenerator $urlGenerator, | |
| 133 | - \OC_Defaults $defaults | |
| 134 | -	) { | |
| 135 | - $this->logger = $logger; | |
| 136 | - $this->config = $config; | |
| 137 | - $this->secureRandom = $secureRandom; | |
| 138 | - $this->hasher = $hasher; | |
| 139 | - $this->mountManager = $mountManager; | |
| 140 | - $this->groupManager = $groupManager; | |
| 141 | - $this->l = $l; | |
| 142 | - $this->l10nFactory = $l10nFactory; | |
| 143 | - $this->factory = $factory; | |
| 144 | - $this->userManager = $userManager; | |
| 145 | - $this->rootFolder = $rootFolder; | |
| 146 | - $this->eventDispatcher = $eventDispatcher; | |
| 147 | - $this->sharingDisabledForUsersCache = new CappedMemoryCache(); | |
| 148 | - $this->legacyHooks = new LegacyHooks($this->eventDispatcher); | |
| 149 | - $this->mailer = $mailer; | |
| 150 | - $this->urlGenerator = $urlGenerator; | |
| 151 | - $this->defaults = $defaults; | |
| 152 | - } | |
| 153 | - | |
| 154 | - /** | |
| 155 | - * Convert from a full share id to a tuple (providerId, shareId) | |
| 156 | - * | |
| 157 | - * @param string $id | |
| 158 | - * @return string[] | |
| 159 | - */ | |
| 160 | -	private function splitFullId($id) { | |
| 161 | -		return explode(':', $id, 2); | |
| 162 | - } | |
| 163 | - | |
| 164 | - /** | |
| 165 | - * Verify if a password meets all requirements | |
| 166 | - * | |
| 167 | - * @param string $password | |
| 168 | - * @throws \Exception | |
| 169 | - */ | |
| 170 | -	protected function verifyPassword($password) { | |
| 171 | -		if ($password === null) { | |
| 172 | - // No password is set, check if this is allowed. | |
| 173 | -			if ($this->shareApiLinkEnforcePassword()) { | |
| 174 | -				throw new \InvalidArgumentException('Passwords are enforced for link shares'); | |
| 175 | - } | |
| 176 | - | |
| 177 | - return; | |
| 178 | - } | |
| 179 | - | |
| 180 | - // Let others verify the password | |
| 181 | -		try { | |
| 182 | - $event = new GenericEvent($password); | |
| 183 | -			$this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event); | |
| 184 | -		} catch (HintException $e) { | |
| 185 | - throw new \Exception($e->getHint()); | |
| 186 | - } | |
| 187 | - } | |
| 188 | - | |
| 189 | - /** | |
| 190 | - * Check for generic requirements before creating a share | |
| 191 | - * | |
| 192 | - * @param \OCP\Share\IShare $share | |
| 193 | - * @throws \InvalidArgumentException | |
| 194 | - * @throws GenericShareException | |
| 195 | - * | |
| 196 | - * @suppress PhanUndeclaredClassMethod | |
| 197 | - */ | |
| 198 | -	protected function generalCreateChecks(\OCP\Share\IShare $share) { | |
| 199 | -		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) { | |
| 200 | - // We expect a valid user as sharedWith for user shares | |
| 201 | -			if (!$this->userManager->userExists($share->getSharedWith())) { | |
| 202 | -				throw new \InvalidArgumentException('SharedWith is not a valid user'); | |
| 203 | - } | |
| 204 | -		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) { | |
| 205 | - // We expect a valid group as sharedWith for group shares | |
| 206 | -			if (!$this->groupManager->groupExists($share->getSharedWith())) { | |
| 207 | -				throw new \InvalidArgumentException('SharedWith is not a valid group'); | |
| 208 | - } | |
| 209 | -		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) { | |
| 210 | -			if ($share->getSharedWith() !== null) { | |
| 211 | -				throw new \InvalidArgumentException('SharedWith should be empty'); | |
| 212 | - } | |
| 213 | -		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) { | |
| 214 | -			if ($share->getSharedWith() === null) { | |
| 215 | -				throw new \InvalidArgumentException('SharedWith should not be empty'); | |
| 216 | - } | |
| 217 | -		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) { | |
| 218 | -			if ($share->getSharedWith() === null) { | |
| 219 | -				throw new \InvalidArgumentException('SharedWith should not be empty'); | |
| 220 | - } | |
| 221 | -		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) { | |
| 222 | - $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith()); | |
| 223 | -			if ($circle === null) { | |
| 224 | -				throw new \InvalidArgumentException('SharedWith is not a valid circle'); | |
| 225 | - } | |
| 226 | -		} else { | |
| 227 | - // We can't handle other types yet | |
| 228 | -			throw new \InvalidArgumentException('unknown share type'); | |
| 229 | - } | |
| 230 | - | |
| 231 | - // Verify the initiator of the share is set | |
| 232 | -		if ($share->getSharedBy() === null) { | |
| 233 | -			throw new \InvalidArgumentException('SharedBy should be set'); | |
| 234 | - } | |
| 235 | - | |
| 236 | - // Cannot share with yourself | |
| 237 | - if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && | |
| 238 | -			$share->getSharedWith() === $share->getSharedBy()) { | |
| 239 | -			throw new \InvalidArgumentException('Can’t share with yourself'); | |
| 240 | - } | |
| 241 | - | |
| 242 | - // The path should be set | |
| 243 | -		if ($share->getNode() === null) { | |
| 244 | -			throw new \InvalidArgumentException('Path should be set'); | |
| 245 | - } | |
| 246 | - | |
| 247 | - // And it should be a file or a folder | |
| 248 | - if (!($share->getNode() instanceof \OCP\Files\File) && | |
| 249 | -				!($share->getNode() instanceof \OCP\Files\Folder)) { | |
| 250 | -			throw new \InvalidArgumentException('Path should be either a file or a folder'); | |
| 251 | - } | |
| 252 | - | |
| 253 | - // And you can't share your rootfolder | |
| 254 | -		if ($this->userManager->userExists($share->getSharedBy())) { | |
| 255 | - $sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath(); | |
| 256 | -		} else { | |
| 257 | - $sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath(); | |
| 258 | - } | |
| 259 | -		if ($sharedPath === $share->getNode()->getPath()) { | |
| 260 | -			throw new \InvalidArgumentException('You can’t share your root folder'); | |
| 261 | - } | |
| 262 | - | |
| 263 | - // Check if we actually have share permissions | |
| 264 | -		if (!$share->getNode()->isShareable()) { | |
| 265 | -			$message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]); | |
| 266 | - throw new GenericShareException($message_t, $message_t, 404); | |
| 267 | - } | |
| 268 | - | |
| 269 | - // Permissions should be set | |
| 270 | -		if ($share->getPermissions() === null) { | |
| 271 | -			throw new \InvalidArgumentException('A share requires permissions'); | |
| 272 | - } | |
| 273 | - | |
| 274 | - /* | |
| 63 | + /** @var IProviderFactory */ | |
| 64 | + private $factory; | |
| 65 | + /** @var ILogger */ | |
| 66 | + private $logger; | |
| 67 | + /** @var IConfig */ | |
| 68 | + private $config; | |
| 69 | + /** @var ISecureRandom */ | |
| 70 | + private $secureRandom; | |
| 71 | + /** @var IHasher */ | |
| 72 | + private $hasher; | |
| 73 | + /** @var IMountManager */ | |
| 74 | + private $mountManager; | |
| 75 | + /** @var IGroupManager */ | |
| 76 | + private $groupManager; | |
| 77 | + /** @var IL10N */ | |
| 78 | + private $l; | |
| 79 | + /** @var IFactory */ | |
| 80 | + private $l10nFactory; | |
| 81 | + /** @var IUserManager */ | |
| 82 | + private $userManager; | |
| 83 | + /** @var IRootFolder */ | |
| 84 | + private $rootFolder; | |
| 85 | + /** @var CappedMemoryCache */ | |
| 86 | + private $sharingDisabledForUsersCache; | |
| 87 | + /** @var EventDispatcher */ | |
| 88 | + private $eventDispatcher; | |
| 89 | + /** @var LegacyHooks */ | |
| 90 | + private $legacyHooks; | |
| 91 | + /** @var IMailer */ | |
| 92 | + private $mailer; | |
| 93 | + /** @var IURLGenerator */ | |
| 94 | + private $urlGenerator; | |
| 95 | + /** @var \OC_Defaults */ | |
| 96 | + private $defaults; | |
| 97 | + | |
| 98 | + | |
| 99 | + /** | |
| 100 | + * Manager constructor. | |
| 101 | + * | |
| 102 | + * @param ILogger $logger | |
| 103 | + * @param IConfig $config | |
| 104 | + * @param ISecureRandom $secureRandom | |
| 105 | + * @param IHasher $hasher | |
| 106 | + * @param IMountManager $mountManager | |
| 107 | + * @param IGroupManager $groupManager | |
| 108 | + * @param IL10N $l | |
| 109 | + * @param IFactory $l10nFactory | |
| 110 | + * @param IProviderFactory $factory | |
| 111 | + * @param IUserManager $userManager | |
| 112 | + * @param IRootFolder $rootFolder | |
| 113 | + * @param EventDispatcher $eventDispatcher | |
| 114 | + * @param IMailer $mailer | |
| 115 | + * @param IURLGenerator $urlGenerator | |
| 116 | + * @param \OC_Defaults $defaults | |
| 117 | + */ | |
| 118 | + public function __construct( | |
| 119 | + ILogger $logger, | |
| 120 | + IConfig $config, | |
| 121 | + ISecureRandom $secureRandom, | |
| 122 | + IHasher $hasher, | |
| 123 | + IMountManager $mountManager, | |
| 124 | + IGroupManager $groupManager, | |
| 125 | + IL10N $l, | |
| 126 | + IFactory $l10nFactory, | |
| 127 | + IProviderFactory $factory, | |
| 128 | + IUserManager $userManager, | |
| 129 | + IRootFolder $rootFolder, | |
| 130 | + EventDispatcher $eventDispatcher, | |
| 131 | + IMailer $mailer, | |
| 132 | + IURLGenerator $urlGenerator, | |
| 133 | + \OC_Defaults $defaults | |
| 134 | +    ) { | |
| 135 | + $this->logger = $logger; | |
| 136 | + $this->config = $config; | |
| 137 | + $this->secureRandom = $secureRandom; | |
| 138 | + $this->hasher = $hasher; | |
| 139 | + $this->mountManager = $mountManager; | |
| 140 | + $this->groupManager = $groupManager; | |
| 141 | + $this->l = $l; | |
| 142 | + $this->l10nFactory = $l10nFactory; | |
| 143 | + $this->factory = $factory; | |
| 144 | + $this->userManager = $userManager; | |
| 145 | + $this->rootFolder = $rootFolder; | |
| 146 | + $this->eventDispatcher = $eventDispatcher; | |
| 147 | + $this->sharingDisabledForUsersCache = new CappedMemoryCache(); | |
| 148 | + $this->legacyHooks = new LegacyHooks($this->eventDispatcher); | |
| 149 | + $this->mailer = $mailer; | |
| 150 | + $this->urlGenerator = $urlGenerator; | |
| 151 | + $this->defaults = $defaults; | |
| 152 | + } | |
| 153 | + | |
| 154 | + /** | |
| 155 | + * Convert from a full share id to a tuple (providerId, shareId) | |
| 156 | + * | |
| 157 | + * @param string $id | |
| 158 | + * @return string[] | |
| 159 | + */ | |
| 160 | +    private function splitFullId($id) { | |
| 161 | +        return explode(':', $id, 2); | |
| 162 | + } | |
| 163 | + | |
| 164 | + /** | |
| 165 | + * Verify if a password meets all requirements | |
| 166 | + * | |
| 167 | + * @param string $password | |
| 168 | + * @throws \Exception | |
| 169 | + */ | |
| 170 | +    protected function verifyPassword($password) { | |
| 171 | +        if ($password === null) { | |
| 172 | + // No password is set, check if this is allowed. | |
| 173 | +            if ($this->shareApiLinkEnforcePassword()) { | |
| 174 | +                throw new \InvalidArgumentException('Passwords are enforced for link shares'); | |
| 175 | + } | |
| 176 | + | |
| 177 | + return; | |
| 178 | + } | |
| 179 | + | |
| 180 | + // Let others verify the password | |
| 181 | +        try { | |
| 182 | + $event = new GenericEvent($password); | |
| 183 | +            $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event); | |
| 184 | +        } catch (HintException $e) { | |
| 185 | + throw new \Exception($e->getHint()); | |
| 186 | + } | |
| 187 | + } | |
| 188 | + | |
| 189 | + /** | |
| 190 | + * Check for generic requirements before creating a share | |
| 191 | + * | |
| 192 | + * @param \OCP\Share\IShare $share | |
| 193 | + * @throws \InvalidArgumentException | |
| 194 | + * @throws GenericShareException | |
| 195 | + * | |
| 196 | + * @suppress PhanUndeclaredClassMethod | |
| 197 | + */ | |
| 198 | +    protected function generalCreateChecks(\OCP\Share\IShare $share) { | |
| 199 | +        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) { | |
| 200 | + // We expect a valid user as sharedWith for user shares | |
| 201 | +            if (!$this->userManager->userExists($share->getSharedWith())) { | |
| 202 | +                throw new \InvalidArgumentException('SharedWith is not a valid user'); | |
| 203 | + } | |
| 204 | +        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) { | |
| 205 | + // We expect a valid group as sharedWith for group shares | |
| 206 | +            if (!$this->groupManager->groupExists($share->getSharedWith())) { | |
| 207 | +                throw new \InvalidArgumentException('SharedWith is not a valid group'); | |
| 208 | + } | |
| 209 | +        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) { | |
| 210 | +            if ($share->getSharedWith() !== null) { | |
| 211 | +                throw new \InvalidArgumentException('SharedWith should be empty'); | |
| 212 | + } | |
| 213 | +        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) { | |
| 214 | +            if ($share->getSharedWith() === null) { | |
| 215 | +                throw new \InvalidArgumentException('SharedWith should not be empty'); | |
| 216 | + } | |
| 217 | +        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) { | |
| 218 | +            if ($share->getSharedWith() === null) { | |
| 219 | +                throw new \InvalidArgumentException('SharedWith should not be empty'); | |
| 220 | + } | |
| 221 | +        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) { | |
| 222 | + $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith()); | |
| 223 | +            if ($circle === null) { | |
| 224 | +                throw new \InvalidArgumentException('SharedWith is not a valid circle'); | |
| 225 | + } | |
| 226 | +        } else { | |
| 227 | + // We can't handle other types yet | |
| 228 | +            throw new \InvalidArgumentException('unknown share type'); | |
| 229 | + } | |
| 230 | + | |
| 231 | + // Verify the initiator of the share is set | |
| 232 | +        if ($share->getSharedBy() === null) { | |
| 233 | +            throw new \InvalidArgumentException('SharedBy should be set'); | |
| 234 | + } | |
| 235 | + | |
| 236 | + // Cannot share with yourself | |
| 237 | + if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && | |
| 238 | +            $share->getSharedWith() === $share->getSharedBy()) { | |
| 239 | +            throw new \InvalidArgumentException('Can’t share with yourself'); | |
| 240 | + } | |
| 241 | + | |
| 242 | + // The path should be set | |
| 243 | +        if ($share->getNode() === null) { | |
| 244 | +            throw new \InvalidArgumentException('Path should be set'); | |
| 245 | + } | |
| 246 | + | |
| 247 | + // And it should be a file or a folder | |
| 248 | + if (!($share->getNode() instanceof \OCP\Files\File) && | |
| 249 | +                !($share->getNode() instanceof \OCP\Files\Folder)) { | |
| 250 | +            throw new \InvalidArgumentException('Path should be either a file or a folder'); | |
| 251 | + } | |
| 252 | + | |
| 253 | + // And you can't share your rootfolder | |
| 254 | +        if ($this->userManager->userExists($share->getSharedBy())) { | |
| 255 | + $sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath(); | |
| 256 | +        } else { | |
| 257 | + $sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath(); | |
| 258 | + } | |
| 259 | +        if ($sharedPath === $share->getNode()->getPath()) { | |
| 260 | +            throw new \InvalidArgumentException('You can’t share your root folder'); | |
| 261 | + } | |
| 262 | + | |
| 263 | + // Check if we actually have share permissions | |
| 264 | +        if (!$share->getNode()->isShareable()) { | |
| 265 | +            $message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]); | |
| 266 | + throw new GenericShareException($message_t, $message_t, 404); | |
| 267 | + } | |
| 268 | + | |
| 269 | + // Permissions should be set | |
| 270 | +        if ($share->getPermissions() === null) { | |
| 271 | +            throw new \InvalidArgumentException('A share requires permissions'); | |
| 272 | + } | |
| 273 | + | |
| 274 | + /* | |
| 275 | 275 | * Quick fix for #23536 | 
| 276 | 276 | * Non moveable mount points do not have update and delete permissions | 
| 277 | 277 | * while we 'most likely' do have that on the storage. | 
| 278 | 278 | */ | 
| 279 | - $permissions = $share->getNode()->getPermissions(); | |
| 280 | - $mount = $share->getNode()->getMountPoint(); | |
| 281 | -		if (!($mount instanceof MoveableMount)) { | |
| 282 | - $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE; | |
| 283 | - } | |
| 284 | - | |
| 285 | - // Check that we do not share with more permissions than we have | |
| 286 | -		if ($share->getPermissions() & ~$permissions) { | |
| 287 | -			$message_t = $this->l->t('Can’t increase permissions of %s', [$share->getNode()->getPath()]); | |
| 288 | - throw new GenericShareException($message_t, $message_t, 404); | |
| 289 | - } | |
| 290 | - | |
| 291 | - | |
| 292 | - // Check that read permissions are always set | |
| 293 | - // Link shares are allowed to have no read permissions to allow upload to hidden folders | |
| 294 | - $noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK | |
| 295 | - || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL; | |
| 296 | - if (!$noReadPermissionRequired && | |
| 297 | -			($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) { | |
| 298 | -			throw new \InvalidArgumentException('Shares need at least read permissions'); | |
| 299 | - } | |
| 300 | - | |
| 301 | -		if ($share->getNode() instanceof \OCP\Files\File) { | |
| 302 | -			if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) { | |
| 303 | -				$message_t = $this->l->t('Files can’t be shared with delete permissions'); | |
| 304 | - throw new GenericShareException($message_t); | |
| 305 | - } | |
| 306 | -			if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) { | |
| 307 | -				$message_t = $this->l->t('Files can’t be shared with create permissions'); | |
| 308 | - throw new GenericShareException($message_t); | |
| 309 | - } | |
| 310 | - } | |
| 311 | - } | |
| 312 | - | |
| 313 | - /** | |
| 314 | - * Validate if the expiration date fits the system settings | |
| 315 | - * | |
| 316 | - * @param \OCP\Share\IShare $share The share to validate the expiration date of | |
| 317 | - * @return \OCP\Share\IShare The modified share object | |
| 318 | - * @throws GenericShareException | |
| 319 | - * @throws \InvalidArgumentException | |
| 320 | - * @throws \Exception | |
| 321 | - */ | |
| 322 | -	protected function validateExpirationDate(\OCP\Share\IShare $share) { | |
| 323 | - | |
| 324 | - $expirationDate = $share->getExpirationDate(); | |
| 325 | - | |
| 326 | -		if ($expirationDate !== null) { | |
| 327 | - //Make sure the expiration date is a date | |
| 328 | - $expirationDate->setTime(0, 0, 0); | |
| 329 | - | |
| 330 | - $date = new \DateTime(); | |
| 331 | - $date->setTime(0, 0, 0); | |
| 332 | -			if ($date >= $expirationDate) { | |
| 333 | -				$message = $this->l->t('Expiration date is in the past'); | |
| 334 | - throw new GenericShareException($message, $message, 404); | |
| 335 | - } | |
| 336 | - } | |
| 337 | - | |
| 338 | - // If expiredate is empty set a default one if there is a default | |
| 339 | - $fullId = null; | |
| 340 | -		try { | |
| 341 | - $fullId = $share->getFullId(); | |
| 342 | -		} catch (\UnexpectedValueException $e) { | |
| 343 | - // This is a new share | |
| 344 | - } | |
| 345 | - | |
| 346 | -		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) { | |
| 347 | - $expirationDate = new \DateTime(); | |
| 348 | - $expirationDate->setTime(0,0,0); | |
| 349 | -			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D')); | |
| 350 | - } | |
| 351 | - | |
| 352 | - // If we enforce the expiration date check that is does not exceed | |
| 353 | -		if ($this->shareApiLinkDefaultExpireDateEnforced()) { | |
| 354 | -			if ($expirationDate === null) { | |
| 355 | -				throw new \InvalidArgumentException('Expiration date is enforced'); | |
| 356 | - } | |
| 357 | - | |
| 358 | - $date = new \DateTime(); | |
| 359 | - $date->setTime(0, 0, 0); | |
| 360 | -			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D')); | |
| 361 | -			if ($date < $expirationDate) { | |
| 362 | -				$message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]); | |
| 363 | - throw new GenericShareException($message, $message, 404); | |
| 364 | - } | |
| 365 | - } | |
| 366 | - | |
| 367 | - $accepted = true; | |
| 368 | - $message = ''; | |
| 369 | -		\OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [ | |
| 370 | - 'expirationDate' => &$expirationDate, | |
| 371 | - 'accepted' => &$accepted, | |
| 372 | - 'message' => &$message, | |
| 373 | - 'passwordSet' => $share->getPassword() !== null, | |
| 374 | - ]); | |
| 375 | - | |
| 376 | -		if (!$accepted) { | |
| 377 | - throw new \Exception($message); | |
| 378 | - } | |
| 379 | - | |
| 380 | - $share->setExpirationDate($expirationDate); | |
| 381 | - | |
| 382 | - return $share; | |
| 383 | - } | |
| 384 | - | |
| 385 | - /** | |
| 386 | - * Check for pre share requirements for user shares | |
| 387 | - * | |
| 388 | - * @param \OCP\Share\IShare $share | |
| 389 | - * @throws \Exception | |
| 390 | - */ | |
| 391 | -	protected function userCreateChecks(\OCP\Share\IShare $share) { | |
| 392 | - // Check if we can share with group members only | |
| 393 | -		if ($this->shareWithGroupMembersOnly()) { | |
| 394 | - $sharedBy = $this->userManager->get($share->getSharedBy()); | |
| 395 | - $sharedWith = $this->userManager->get($share->getSharedWith()); | |
| 396 | - // Verify we can share with this user | |
| 397 | - $groups = array_intersect( | |
| 398 | - $this->groupManager->getUserGroupIds($sharedBy), | |
| 399 | - $this->groupManager->getUserGroupIds($sharedWith) | |
| 400 | - ); | |
| 401 | -			if (empty($groups)) { | |
| 402 | -				throw new \Exception('Sharing is only allowed with group members'); | |
| 403 | - } | |
| 404 | - } | |
| 405 | - | |
| 406 | - /* | |
| 279 | + $permissions = $share->getNode()->getPermissions(); | |
| 280 | + $mount = $share->getNode()->getMountPoint(); | |
| 281 | +        if (!($mount instanceof MoveableMount)) { | |
| 282 | + $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE; | |
| 283 | + } | |
| 284 | + | |
| 285 | + // Check that we do not share with more permissions than we have | |
| 286 | +        if ($share->getPermissions() & ~$permissions) { | |
| 287 | +            $message_t = $this->l->t('Can’t increase permissions of %s', [$share->getNode()->getPath()]); | |
| 288 | + throw new GenericShareException($message_t, $message_t, 404); | |
| 289 | + } | |
| 290 | + | |
| 291 | + | |
| 292 | + // Check that read permissions are always set | |
| 293 | + // Link shares are allowed to have no read permissions to allow upload to hidden folders | |
| 294 | + $noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK | |
| 295 | + || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL; | |
| 296 | + if (!$noReadPermissionRequired && | |
| 297 | +            ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) { | |
| 298 | +            throw new \InvalidArgumentException('Shares need at least read permissions'); | |
| 299 | + } | |
| 300 | + | |
| 301 | +        if ($share->getNode() instanceof \OCP\Files\File) { | |
| 302 | +            if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) { | |
| 303 | +                $message_t = $this->l->t('Files can’t be shared with delete permissions'); | |
| 304 | + throw new GenericShareException($message_t); | |
| 305 | + } | |
| 306 | +            if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) { | |
| 307 | +                $message_t = $this->l->t('Files can’t be shared with create permissions'); | |
| 308 | + throw new GenericShareException($message_t); | |
| 309 | + } | |
| 310 | + } | |
| 311 | + } | |
| 312 | + | |
| 313 | + /** | |
| 314 | + * Validate if the expiration date fits the system settings | |
| 315 | + * | |
| 316 | + * @param \OCP\Share\IShare $share The share to validate the expiration date of | |
| 317 | + * @return \OCP\Share\IShare The modified share object | |
| 318 | + * @throws GenericShareException | |
| 319 | + * @throws \InvalidArgumentException | |
| 320 | + * @throws \Exception | |
| 321 | + */ | |
| 322 | +    protected function validateExpirationDate(\OCP\Share\IShare $share) { | |
| 323 | + | |
| 324 | + $expirationDate = $share->getExpirationDate(); | |
| 325 | + | |
| 326 | +        if ($expirationDate !== null) { | |
| 327 | + //Make sure the expiration date is a date | |
| 328 | + $expirationDate->setTime(0, 0, 0); | |
| 329 | + | |
| 330 | + $date = new \DateTime(); | |
| 331 | + $date->setTime(0, 0, 0); | |
| 332 | +            if ($date >= $expirationDate) { | |
| 333 | +                $message = $this->l->t('Expiration date is in the past'); | |
| 334 | + throw new GenericShareException($message, $message, 404); | |
| 335 | + } | |
| 336 | + } | |
| 337 | + | |
| 338 | + // If expiredate is empty set a default one if there is a default | |
| 339 | + $fullId = null; | |
| 340 | +        try { | |
| 341 | + $fullId = $share->getFullId(); | |
| 342 | +        } catch (\UnexpectedValueException $e) { | |
| 343 | + // This is a new share | |
| 344 | + } | |
| 345 | + | |
| 346 | +        if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) { | |
| 347 | + $expirationDate = new \DateTime(); | |
| 348 | + $expirationDate->setTime(0,0,0); | |
| 349 | +            $expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D')); | |
| 350 | + } | |
| 351 | + | |
| 352 | + // If we enforce the expiration date check that is does not exceed | |
| 353 | +        if ($this->shareApiLinkDefaultExpireDateEnforced()) { | |
| 354 | +            if ($expirationDate === null) { | |
| 355 | +                throw new \InvalidArgumentException('Expiration date is enforced'); | |
| 356 | + } | |
| 357 | + | |
| 358 | + $date = new \DateTime(); | |
| 359 | + $date->setTime(0, 0, 0); | |
| 360 | +            $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D')); | |
| 361 | +            if ($date < $expirationDate) { | |
| 362 | +                $message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]); | |
| 363 | + throw new GenericShareException($message, $message, 404); | |
| 364 | + } | |
| 365 | + } | |
| 366 | + | |
| 367 | + $accepted = true; | |
| 368 | + $message = ''; | |
| 369 | +        \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [ | |
| 370 | + 'expirationDate' => &$expirationDate, | |
| 371 | + 'accepted' => &$accepted, | |
| 372 | + 'message' => &$message, | |
| 373 | + 'passwordSet' => $share->getPassword() !== null, | |
| 374 | + ]); | |
| 375 | + | |
| 376 | +        if (!$accepted) { | |
| 377 | + throw new \Exception($message); | |
| 378 | + } | |
| 379 | + | |
| 380 | + $share->setExpirationDate($expirationDate); | |
| 381 | + | |
| 382 | + return $share; | |
| 383 | + } | |
| 384 | + | |
| 385 | + /** | |
| 386 | + * Check for pre share requirements for user shares | |
| 387 | + * | |
| 388 | + * @param \OCP\Share\IShare $share | |
| 389 | + * @throws \Exception | |
| 390 | + */ | |
| 391 | +    protected function userCreateChecks(\OCP\Share\IShare $share) { | |
| 392 | + // Check if we can share with group members only | |
| 393 | +        if ($this->shareWithGroupMembersOnly()) { | |
| 394 | + $sharedBy = $this->userManager->get($share->getSharedBy()); | |
| 395 | + $sharedWith = $this->userManager->get($share->getSharedWith()); | |
| 396 | + // Verify we can share with this user | |
| 397 | + $groups = array_intersect( | |
| 398 | + $this->groupManager->getUserGroupIds($sharedBy), | |
| 399 | + $this->groupManager->getUserGroupIds($sharedWith) | |
| 400 | + ); | |
| 401 | +            if (empty($groups)) { | |
| 402 | +                throw new \Exception('Sharing is only allowed with group members'); | |
| 403 | + } | |
| 404 | + } | |
| 405 | + | |
| 406 | + /* | |
| 407 | 407 | * TODO: Could be costly, fix | 
| 408 | 408 | * | 
| 409 | 409 | * Also this is not what we want in the future.. then we want to squash identical shares. | 
| 410 | 410 | */ | 
| 411 | - $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER); | |
| 412 | - $existingShares = $provider->getSharesByPath($share->getNode()); | |
| 413 | -		foreach($existingShares as $existingShare) { | |
| 414 | - // Ignore if it is the same share | |
| 415 | -			try { | |
| 416 | -				if ($existingShare->getFullId() === $share->getFullId()) { | |
| 417 | - continue; | |
| 418 | - } | |
| 419 | -			} catch (\UnexpectedValueException $e) { | |
| 420 | - //Shares are not identical | |
| 421 | - } | |
| 422 | - | |
| 423 | - // Identical share already existst | |
| 424 | -			if ($existingShare->getSharedWith() === $share->getSharedWith()) { | |
| 425 | -				throw new \Exception('Path is already shared with this user'); | |
| 426 | - } | |
| 427 | - | |
| 428 | - // The share is already shared with this user via a group share | |
| 429 | -			if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) { | |
| 430 | - $group = $this->groupManager->get($existingShare->getSharedWith()); | |
| 431 | -				if (!is_null($group)) { | |
| 432 | - $user = $this->userManager->get($share->getSharedWith()); | |
| 433 | - | |
| 434 | -					if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) { | |
| 435 | -						throw new \Exception('Path is already shared with this user'); | |
| 436 | - } | |
| 437 | - } | |
| 438 | - } | |
| 439 | - } | |
| 440 | - } | |
| 441 | - | |
| 442 | - /** | |
| 443 | - * Check for pre share requirements for group shares | |
| 444 | - * | |
| 445 | - * @param \OCP\Share\IShare $share | |
| 446 | - * @throws \Exception | |
| 447 | - */ | |
| 448 | -	protected function groupCreateChecks(\OCP\Share\IShare $share) { | |
| 449 | - // Verify group shares are allowed | |
| 450 | -		if (!$this->allowGroupSharing()) { | |
| 451 | -			throw new \Exception('Group sharing is now allowed'); | |
| 452 | - } | |
| 453 | - | |
| 454 | - // Verify if the user can share with this group | |
| 455 | -		if ($this->shareWithGroupMembersOnly()) { | |
| 456 | - $sharedBy = $this->userManager->get($share->getSharedBy()); | |
| 457 | - $sharedWith = $this->groupManager->get($share->getSharedWith()); | |
| 458 | -			if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) { | |
| 459 | -				throw new \Exception('Sharing is only allowed within your own groups'); | |
| 460 | - } | |
| 461 | - } | |
| 462 | - | |
| 463 | - /* | |
| 411 | + $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER); | |
| 412 | + $existingShares = $provider->getSharesByPath($share->getNode()); | |
| 413 | +        foreach($existingShares as $existingShare) { | |
| 414 | + // Ignore if it is the same share | |
| 415 | +            try { | |
| 416 | +                if ($existingShare->getFullId() === $share->getFullId()) { | |
| 417 | + continue; | |
| 418 | + } | |
| 419 | +            } catch (\UnexpectedValueException $e) { | |
| 420 | + //Shares are not identical | |
| 421 | + } | |
| 422 | + | |
| 423 | + // Identical share already existst | |
| 424 | +            if ($existingShare->getSharedWith() === $share->getSharedWith()) { | |
| 425 | +                throw new \Exception('Path is already shared with this user'); | |
| 426 | + } | |
| 427 | + | |
| 428 | + // The share is already shared with this user via a group share | |
| 429 | +            if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) { | |
| 430 | + $group = $this->groupManager->get($existingShare->getSharedWith()); | |
| 431 | +                if (!is_null($group)) { | |
| 432 | + $user = $this->userManager->get($share->getSharedWith()); | |
| 433 | + | |
| 434 | +                    if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) { | |
| 435 | +                        throw new \Exception('Path is already shared with this user'); | |
| 436 | + } | |
| 437 | + } | |
| 438 | + } | |
| 439 | + } | |
| 440 | + } | |
| 441 | + | |
| 442 | + /** | |
| 443 | + * Check for pre share requirements for group shares | |
| 444 | + * | |
| 445 | + * @param \OCP\Share\IShare $share | |
| 446 | + * @throws \Exception | |
| 447 | + */ | |
| 448 | +    protected function groupCreateChecks(\OCP\Share\IShare $share) { | |
| 449 | + // Verify group shares are allowed | |
| 450 | +        if (!$this->allowGroupSharing()) { | |
| 451 | +            throw new \Exception('Group sharing is now allowed'); | |
| 452 | + } | |
| 453 | + | |
| 454 | + // Verify if the user can share with this group | |
| 455 | +        if ($this->shareWithGroupMembersOnly()) { | |
| 456 | + $sharedBy = $this->userManager->get($share->getSharedBy()); | |
| 457 | + $sharedWith = $this->groupManager->get($share->getSharedWith()); | |
| 458 | +            if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) { | |
| 459 | +                throw new \Exception('Sharing is only allowed within your own groups'); | |
| 460 | + } | |
| 461 | + } | |
| 462 | + | |
| 463 | + /* | |
| 464 | 464 | * TODO: Could be costly, fix | 
| 465 | 465 | * | 
| 466 | 466 | * Also this is not what we want in the future.. then we want to squash identical shares. | 
| 467 | 467 | */ | 
| 468 | - $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP); | |
| 469 | - $existingShares = $provider->getSharesByPath($share->getNode()); | |
| 470 | -		foreach($existingShares as $existingShare) { | |
| 471 | -			try { | |
| 472 | -				if ($existingShare->getFullId() === $share->getFullId()) { | |
| 473 | - continue; | |
| 474 | - } | |
| 475 | -			} catch (\UnexpectedValueException $e) { | |
| 476 | - //It is a new share so just continue | |
| 477 | - } | |
| 478 | - | |
| 479 | -			if ($existingShare->getSharedWith() === $share->getSharedWith()) { | |
| 480 | -				throw new \Exception('Path is already shared with this group'); | |
| 481 | - } | |
| 482 | - } | |
| 483 | - } | |
| 484 | - | |
| 485 | - /** | |
| 486 | - * Check for pre share requirements for link shares | |
| 487 | - * | |
| 488 | - * @param \OCP\Share\IShare $share | |
| 489 | - * @throws \Exception | |
| 490 | - */ | |
| 491 | -	protected function linkCreateChecks(\OCP\Share\IShare $share) { | |
| 492 | - // Are link shares allowed? | |
| 493 | -		if (!$this->shareApiAllowLinks()) { | |
| 494 | -			throw new \Exception('Link sharing is not allowed'); | |
| 495 | - } | |
| 496 | - | |
| 497 | - // Link shares by definition can't have share permissions | |
| 498 | -		if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) { | |
| 499 | -			throw new \InvalidArgumentException('Link shares can’t have reshare permissions'); | |
| 500 | - } | |
| 501 | - | |
| 502 | - // Check if public upload is allowed | |
| 503 | - if (!$this->shareApiLinkAllowPublicUpload() && | |
| 504 | -			($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) { | |
| 505 | -			throw new \InvalidArgumentException('Public upload is not allowed'); | |
| 506 | - } | |
| 507 | - } | |
| 508 | - | |
| 509 | - /** | |
| 510 | - * To make sure we don't get invisible link shares we set the parent | |
| 511 | - * of a link if it is a reshare. This is a quick word around | |
| 512 | - * until we can properly display multiple link shares in the UI | |
| 513 | - * | |
| 514 | - * See: https://github.com/owncloud/core/issues/22295 | |
| 515 | - * | |
| 516 | - * FIXME: Remove once multiple link shares can be properly displayed | |
| 517 | - * | |
| 518 | - * @param \OCP\Share\IShare $share | |
| 519 | - */ | |
| 520 | -	protected function setLinkParent(\OCP\Share\IShare $share) { | |
| 521 | - | |
| 522 | - // No sense in checking if the method is not there. | |
| 523 | -		if (method_exists($share, 'setParent')) { | |
| 524 | - $storage = $share->getNode()->getStorage(); | |
| 525 | -			if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) { | |
| 526 | - /** @var \OCA\Files_Sharing\SharedStorage $storage */ | |
| 527 | - $share->setParent($storage->getShareId()); | |
| 528 | - } | |
| 529 | - }; | |
| 530 | - } | |
| 531 | - | |
| 532 | - /** | |
| 533 | - * @param File|Folder $path | |
| 534 | - */ | |
| 535 | -	protected function pathCreateChecks($path) { | |
| 536 | - // Make sure that we do not share a path that contains a shared mountpoint | |
| 537 | -		if ($path instanceof \OCP\Files\Folder) { | |
| 538 | - $mounts = $this->mountManager->findIn($path->getPath()); | |
| 539 | -			foreach($mounts as $mount) { | |
| 540 | -				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) { | |
| 541 | -					throw new \InvalidArgumentException('Path contains files shared with you'); | |
| 542 | - } | |
| 543 | - } | |
| 544 | - } | |
| 545 | - } | |
| 546 | - | |
| 547 | - /** | |
| 548 | - * Check if the user that is sharing can actually share | |
| 549 | - * | |
| 550 | - * @param \OCP\Share\IShare $share | |
| 551 | - * @throws \Exception | |
| 552 | - */ | |
| 553 | -	protected function canShare(\OCP\Share\IShare $share) { | |
| 554 | -		if (!$this->shareApiEnabled()) { | |
| 555 | -			throw new \Exception('Sharing is disabled'); | |
| 556 | - } | |
| 557 | - | |
| 558 | -		if ($this->sharingDisabledForUser($share->getSharedBy())) { | |
| 559 | -			throw new \Exception('Sharing is disabled for you'); | |
| 560 | - } | |
| 561 | - } | |
| 562 | - | |
| 563 | - /** | |
| 564 | - * Share a path | |
| 565 | - * | |
| 566 | - * @param \OCP\Share\IShare $share | |
| 567 | - * @return Share The share object | |
| 568 | - * @throws \Exception | |
| 569 | - * | |
| 570 | - * TODO: handle link share permissions or check them | |
| 571 | - */ | |
| 572 | -	public function createShare(\OCP\Share\IShare $share) { | |
| 573 | - $this->canShare($share); | |
| 574 | - | |
| 575 | - $this->generalCreateChecks($share); | |
| 576 | - | |
| 577 | - // Verify if there are any issues with the path | |
| 578 | - $this->pathCreateChecks($share->getNode()); | |
| 579 | - | |
| 580 | - /* | |
| 468 | + $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP); | |
| 469 | + $existingShares = $provider->getSharesByPath($share->getNode()); | |
| 470 | +        foreach($existingShares as $existingShare) { | |
| 471 | +            try { | |
| 472 | +                if ($existingShare->getFullId() === $share->getFullId()) { | |
| 473 | + continue; | |
| 474 | + } | |
| 475 | +            } catch (\UnexpectedValueException $e) { | |
| 476 | + //It is a new share so just continue | |
| 477 | + } | |
| 478 | + | |
| 479 | +            if ($existingShare->getSharedWith() === $share->getSharedWith()) { | |
| 480 | +                throw new \Exception('Path is already shared with this group'); | |
| 481 | + } | |
| 482 | + } | |
| 483 | + } | |
| 484 | + | |
| 485 | + /** | |
| 486 | + * Check for pre share requirements for link shares | |
| 487 | + * | |
| 488 | + * @param \OCP\Share\IShare $share | |
| 489 | + * @throws \Exception | |
| 490 | + */ | |
| 491 | +    protected function linkCreateChecks(\OCP\Share\IShare $share) { | |
| 492 | + // Are link shares allowed? | |
| 493 | +        if (!$this->shareApiAllowLinks()) { | |
| 494 | +            throw new \Exception('Link sharing is not allowed'); | |
| 495 | + } | |
| 496 | + | |
| 497 | + // Link shares by definition can't have share permissions | |
| 498 | +        if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) { | |
| 499 | +            throw new \InvalidArgumentException('Link shares can’t have reshare permissions'); | |
| 500 | + } | |
| 501 | + | |
| 502 | + // Check if public upload is allowed | |
| 503 | + if (!$this->shareApiLinkAllowPublicUpload() && | |
| 504 | +            ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) { | |
| 505 | +            throw new \InvalidArgumentException('Public upload is not allowed'); | |
| 506 | + } | |
| 507 | + } | |
| 508 | + | |
| 509 | + /** | |
| 510 | + * To make sure we don't get invisible link shares we set the parent | |
| 511 | + * of a link if it is a reshare. This is a quick word around | |
| 512 | + * until we can properly display multiple link shares in the UI | |
| 513 | + * | |
| 514 | + * See: https://github.com/owncloud/core/issues/22295 | |
| 515 | + * | |
| 516 | + * FIXME: Remove once multiple link shares can be properly displayed | |
| 517 | + * | |
| 518 | + * @param \OCP\Share\IShare $share | |
| 519 | + */ | |
| 520 | +    protected function setLinkParent(\OCP\Share\IShare $share) { | |
| 521 | + | |
| 522 | + // No sense in checking if the method is not there. | |
| 523 | +        if (method_exists($share, 'setParent')) { | |
| 524 | + $storage = $share->getNode()->getStorage(); | |
| 525 | +            if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) { | |
| 526 | + /** @var \OCA\Files_Sharing\SharedStorage $storage */ | |
| 527 | + $share->setParent($storage->getShareId()); | |
| 528 | + } | |
| 529 | + }; | |
| 530 | + } | |
| 531 | + | |
| 532 | + /** | |
| 533 | + * @param File|Folder $path | |
| 534 | + */ | |
| 535 | +    protected function pathCreateChecks($path) { | |
| 536 | + // Make sure that we do not share a path that contains a shared mountpoint | |
| 537 | +        if ($path instanceof \OCP\Files\Folder) { | |
| 538 | + $mounts = $this->mountManager->findIn($path->getPath()); | |
| 539 | +            foreach($mounts as $mount) { | |
| 540 | +                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) { | |
| 541 | +                    throw new \InvalidArgumentException('Path contains files shared with you'); | |
| 542 | + } | |
| 543 | + } | |
| 544 | + } | |
| 545 | + } | |
| 546 | + | |
| 547 | + /** | |
| 548 | + * Check if the user that is sharing can actually share | |
| 549 | + * | |
| 550 | + * @param \OCP\Share\IShare $share | |
| 551 | + * @throws \Exception | |
| 552 | + */ | |
| 553 | +    protected function canShare(\OCP\Share\IShare $share) { | |
| 554 | +        if (!$this->shareApiEnabled()) { | |
| 555 | +            throw new \Exception('Sharing is disabled'); | |
| 556 | + } | |
| 557 | + | |
| 558 | +        if ($this->sharingDisabledForUser($share->getSharedBy())) { | |
| 559 | +            throw new \Exception('Sharing is disabled for you'); | |
| 560 | + } | |
| 561 | + } | |
| 562 | + | |
| 563 | + /** | |
| 564 | + * Share a path | |
| 565 | + * | |
| 566 | + * @param \OCP\Share\IShare $share | |
| 567 | + * @return Share The share object | |
| 568 | + * @throws \Exception | |
| 569 | + * | |
| 570 | + * TODO: handle link share permissions or check them | |
| 571 | + */ | |
| 572 | +    public function createShare(\OCP\Share\IShare $share) { | |
| 573 | + $this->canShare($share); | |
| 574 | + | |
| 575 | + $this->generalCreateChecks($share); | |
| 576 | + | |
| 577 | + // Verify if there are any issues with the path | |
| 578 | + $this->pathCreateChecks($share->getNode()); | |
| 579 | + | |
| 580 | + /* | |
| 581 | 581 | * On creation of a share the owner is always the owner of the path | 
| 582 | 582 | * Except for mounted federated shares. | 
| 583 | 583 | */ | 
| 584 | - $storage = $share->getNode()->getStorage(); | |
| 585 | -		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) { | |
| 586 | - $parent = $share->getNode()->getParent(); | |
| 587 | -			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) { | |
| 588 | - $parent = $parent->getParent(); | |
| 589 | - } | |
| 590 | - $share->setShareOwner($parent->getOwner()->getUID()); | |
| 591 | -		} else { | |
| 592 | - $share->setShareOwner($share->getNode()->getOwner()->getUID()); | |
| 593 | - } | |
| 594 | - | |
| 595 | - //Verify share type | |
| 596 | -		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) { | |
| 597 | - $this->userCreateChecks($share); | |
| 598 | -		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) { | |
| 599 | - $this->groupCreateChecks($share); | |
| 600 | -		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) { | |
| 601 | - $this->linkCreateChecks($share); | |
| 602 | - $this->setLinkParent($share); | |
| 603 | - | |
| 604 | - /* | |
| 584 | + $storage = $share->getNode()->getStorage(); | |
| 585 | +        if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) { | |
| 586 | + $parent = $share->getNode()->getParent(); | |
| 587 | +            while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) { | |
| 588 | + $parent = $parent->getParent(); | |
| 589 | + } | |
| 590 | + $share->setShareOwner($parent->getOwner()->getUID()); | |
| 591 | +        } else { | |
| 592 | + $share->setShareOwner($share->getNode()->getOwner()->getUID()); | |
| 593 | + } | |
| 594 | + | |
| 595 | + //Verify share type | |
| 596 | +        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) { | |
| 597 | + $this->userCreateChecks($share); | |
| 598 | +        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) { | |
| 599 | + $this->groupCreateChecks($share); | |
| 600 | +        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) { | |
| 601 | + $this->linkCreateChecks($share); | |
| 602 | + $this->setLinkParent($share); | |
| 603 | + | |
| 604 | + /* | |
| 605 | 605 | * For now ignore a set token. | 
| 606 | 606 | */ | 
| 607 | - $share->setToken( | |
| 608 | - $this->secureRandom->generate( | |
| 609 | - \OC\Share\Constants::TOKEN_LENGTH, | |
| 610 | - \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE | |
| 611 | - ) | |
| 612 | - ); | |
| 613 | - | |
| 614 | - //Verify the expiration date | |
| 615 | - $this->validateExpirationDate($share); | |
| 616 | - | |
| 617 | - //Verify the password | |
| 618 | - $this->verifyPassword($share->getPassword()); | |
| 619 | - | |
| 620 | - // If a password is set. Hash it! | |
| 621 | -			if ($share->getPassword() !== null) { | |
| 622 | - $share->setPassword($this->hasher->hash($share->getPassword())); | |
| 623 | - } | |
| 624 | -		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) { | |
| 625 | - $share->setToken( | |
| 626 | - $this->secureRandom->generate( | |
| 627 | - \OC\Share\Constants::TOKEN_LENGTH, | |
| 628 | - \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE | |
| 629 | - ) | |
| 630 | - ); | |
| 631 | - } | |
| 632 | - | |
| 633 | - // Cannot share with the owner | |
| 634 | - if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && | |
| 635 | -			$share->getSharedWith() === $share->getShareOwner()) { | |
| 636 | -			throw new \InvalidArgumentException('Can’t share with the share owner'); | |
| 637 | - } | |
| 638 | - | |
| 639 | - // Generate the target | |
| 640 | -		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName(); | |
| 641 | - $target = \OC\Files\Filesystem::normalizePath($target); | |
| 642 | - $share->setTarget($target); | |
| 643 | - | |
| 644 | - // Pre share event | |
| 645 | - $event = new GenericEvent($share); | |
| 646 | -		$a = $this->eventDispatcher->dispatch('OCP\Share::preShare', $event); | |
| 647 | -		if ($event->isPropagationStopped() && $event->hasArgument('error')) { | |
| 648 | -			throw new \Exception($event->getArgument('error')); | |
| 649 | - } | |
| 650 | - | |
| 651 | - $oldShare = $share; | |
| 652 | - $provider = $this->factory->getProviderForType($share->getShareType()); | |
| 653 | - $share = $provider->create($share); | |
| 654 | - //reuse the node we already have | |
| 655 | - $share->setNode($oldShare->getNode()); | |
| 656 | - | |
| 657 | - // Post share event | |
| 658 | - $event = new GenericEvent($share); | |
| 659 | -		$this->eventDispatcher->dispatch('OCP\Share::postShare', $event); | |
| 660 | - | |
| 661 | -		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) { | |
| 662 | - $user = $this->userManager->get($share->getSharedWith()); | |
| 663 | -			if ($user !== null) { | |
| 664 | - $emailAddress = $user->getEMailAddress(); | |
| 665 | -				if ($emailAddress !== null && $emailAddress !== '') { | |
| 666 | - $userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null); | |
| 667 | -					$l = $this->l10nFactory->get('lib', $userLang); | |
| 668 | - $this->sendMailNotification( | |
| 669 | - $l, | |
| 670 | - $share->getNode()->getName(), | |
| 671 | -						$this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', [ 'fileid' => $share->getNode()->getId() ]), | |
| 672 | - $share->getSharedBy(), | |
| 673 | - $emailAddress, | |
| 674 | - $share->getExpirationDate() | |
| 675 | - ); | |
| 676 | -					$this->logger->debug('Send share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']); | |
| 677 | -				} else { | |
| 678 | -					$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']); | |
| 679 | - } | |
| 680 | -			} else { | |
| 681 | -				$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']); | |
| 682 | - } | |
| 683 | - } | |
| 684 | - | |
| 685 | - return $share; | |
| 686 | - } | |
| 687 | - | |
| 688 | - /** | |
| 689 | - * @param IL10N $l Language of the recipient | |
| 690 | - * @param string $filename file/folder name | |
| 691 | - * @param string $link link to the file/folder | |
| 692 | - * @param string $initiator user ID of share sender | |
| 693 | - * @param string $shareWith email address of share receiver | |
| 694 | - * @param \DateTime|null $expiration | |
| 695 | - * @throws \Exception If mail couldn't be sent | |
| 696 | - */ | |
| 697 | - protected function sendMailNotification(IL10N $l, | |
| 698 | - $filename, | |
| 699 | - $link, | |
| 700 | - $initiator, | |
| 701 | - $shareWith, | |
| 702 | -											\DateTime $expiration = null) { | |
| 703 | - $initiatorUser = $this->userManager->get($initiator); | |
| 704 | - $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator; | |
| 705 | - | |
| 706 | - $message = $this->mailer->createMessage(); | |
| 707 | - | |
| 708 | -		$emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [ | |
| 709 | - 'filename' => $filename, | |
| 710 | - 'link' => $link, | |
| 711 | - 'initiator' => $initiatorDisplayName, | |
| 712 | - 'expiration' => $expiration, | |
| 713 | - 'shareWith' => $shareWith, | |
| 714 | - ]); | |
| 715 | - | |
| 716 | -		$emailTemplate->setSubject($l->t('%s shared »%s« with you', array($initiatorDisplayName, $filename))); | |
| 717 | - $emailTemplate->addHeader(); | |
| 718 | -		$emailTemplate->addHeading($l->t('%s shared »%s« with you', [$initiatorDisplayName, $filename]), false); | |
| 719 | -		$text = $l->t('%s shared »%s« with you.', [$initiatorDisplayName, $filename]); | |
| 720 | - | |
| 721 | - $emailTemplate->addBodyText( | |
| 722 | -			$text . ' ' . $l->t('Click the button below to open it.'), | |
| 723 | - $text | |
| 724 | - ); | |
| 725 | - $emailTemplate->addBodyButton( | |
| 726 | -			$l->t('Open »%s«', [$filename]), | |
| 727 | - $link | |
| 728 | - ); | |
| 729 | - | |
| 730 | - $message->setTo([$shareWith]); | |
| 731 | - | |
| 732 | - // The "From" contains the sharers name | |
| 733 | - $instanceName = $this->defaults->getName(); | |
| 734 | - $senderName = $l->t( | |
| 735 | - '%s via %s', | |
| 736 | - [ | |
| 737 | - $initiatorDisplayName, | |
| 738 | - $instanceName | |
| 739 | - ] | |
| 740 | - ); | |
| 741 | - $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]); | |
| 742 | - | |
| 743 | - // The "Reply-To" is set to the sharer if an mail address is configured | |
| 744 | - // also the default footer contains a "Do not reply" which needs to be adjusted. | |
| 745 | - $initiatorEmail = $initiatorUser->getEMailAddress(); | |
| 746 | -		if($initiatorEmail !== null) { | |
| 747 | - $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]); | |
| 748 | - $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')); | |
| 749 | -		} else { | |
| 750 | - $emailTemplate->addFooter(); | |
| 751 | - } | |
| 752 | - | |
| 753 | - $message->useTemplate($emailTemplate); | |
| 754 | - $this->mailer->send($message); | |
| 755 | - } | |
| 756 | - | |
| 757 | - /** | |
| 758 | - * Update a share | |
| 759 | - * | |
| 760 | - * @param \OCP\Share\IShare $share | |
| 761 | - * @return \OCP\Share\IShare The share object | |
| 762 | - * @throws \InvalidArgumentException | |
| 763 | - */ | |
| 764 | -	public function updateShare(\OCP\Share\IShare $share) { | |
| 765 | - $expirationDateUpdated = false; | |
| 766 | - | |
| 767 | - $this->canShare($share); | |
| 768 | - | |
| 769 | -		try { | |
| 770 | - $originalShare = $this->getShareById($share->getFullId()); | |
| 771 | -		} catch (\UnexpectedValueException $e) { | |
| 772 | -			throw new \InvalidArgumentException('Share does not have a full id'); | |
| 773 | - } | |
| 774 | - | |
| 775 | - // We can't change the share type! | |
| 776 | -		if ($share->getShareType() !== $originalShare->getShareType()) { | |
| 777 | -			throw new \InvalidArgumentException('Can’t change share type'); | |
| 778 | - } | |
| 779 | - | |
| 780 | - // We can only change the recipient on user shares | |
| 781 | - if ($share->getSharedWith() !== $originalShare->getSharedWith() && | |
| 782 | -		    $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) { | |
| 783 | -			throw new \InvalidArgumentException('Can only update recipient on user shares'); | |
| 784 | - } | |
| 785 | - | |
| 786 | - // Cannot share with the owner | |
| 787 | - if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && | |
| 788 | -			$share->getSharedWith() === $share->getShareOwner()) { | |
| 789 | -			throw new \InvalidArgumentException('Can’t share with the share owner'); | |
| 790 | - } | |
| 791 | - | |
| 792 | - $this->generalCreateChecks($share); | |
| 793 | - | |
| 794 | -		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) { | |
| 795 | - $this->userCreateChecks($share); | |
| 796 | -		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) { | |
| 797 | - $this->groupCreateChecks($share); | |
| 798 | -		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) { | |
| 799 | - $this->linkCreateChecks($share); | |
| 800 | - | |
| 801 | - $this->updateSharePasswordIfNeeded($share, $originalShare); | |
| 802 | - | |
| 803 | -			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) { | |
| 804 | - //Verify the expiration date | |
| 805 | - $this->validateExpirationDate($share); | |
| 806 | - $expirationDateUpdated = true; | |
| 807 | - } | |
| 808 | -		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) { | |
| 809 | - $plainTextPassword = $share->getPassword(); | |
| 810 | -			if (!$this->updateSharePasswordIfNeeded($share, $originalShare)) { | |
| 811 | - $plainTextPassword = null; | |
| 812 | - } | |
| 813 | - } | |
| 814 | - | |
| 815 | - $this->pathCreateChecks($share->getNode()); | |
| 816 | - | |
| 817 | - // Now update the share! | |
| 818 | - $provider = $this->factory->getProviderForType($share->getShareType()); | |
| 819 | -		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) { | |
| 820 | - $share = $provider->update($share, $plainTextPassword); | |
| 821 | -		} else { | |
| 822 | - $share = $provider->update($share); | |
| 823 | - } | |
| 824 | - | |
| 825 | -		if ($expirationDateUpdated === true) { | |
| 826 | -			\OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [ | |
| 827 | - 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder', | |
| 828 | - 'itemSource' => $share->getNode()->getId(), | |
| 829 | - 'date' => $share->getExpirationDate(), | |
| 830 | - 'uidOwner' => $share->getSharedBy(), | |
| 831 | - ]); | |
| 832 | - } | |
| 833 | - | |
| 834 | -		if ($share->getPassword() !== $originalShare->getPassword()) { | |
| 835 | -			\OC_Hook::emit('OCP\Share', 'post_update_password', [ | |
| 836 | - 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder', | |
| 837 | - 'itemSource' => $share->getNode()->getId(), | |
| 838 | - 'uidOwner' => $share->getSharedBy(), | |
| 839 | - 'token' => $share->getToken(), | |
| 840 | - 'disabled' => is_null($share->getPassword()), | |
| 841 | - ]); | |
| 842 | - } | |
| 843 | - | |
| 844 | -		if ($share->getPermissions() !== $originalShare->getPermissions()) { | |
| 845 | -			if ($this->userManager->userExists($share->getShareOwner())) { | |
| 846 | - $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner()); | |
| 847 | -			} else { | |
| 848 | - $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy()); | |
| 849 | - } | |
| 850 | -			\OC_Hook::emit('OCP\Share', 'post_update_permissions', array( | |
| 851 | - 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder', | |
| 852 | - 'itemSource' => $share->getNode()->getId(), | |
| 853 | - 'shareType' => $share->getShareType(), | |
| 854 | - 'shareWith' => $share->getSharedWith(), | |
| 855 | - 'uidOwner' => $share->getSharedBy(), | |
| 856 | - 'permissions' => $share->getPermissions(), | |
| 857 | - 'path' => $userFolder->getRelativePath($share->getNode()->getPath()), | |
| 858 | - )); | |
| 859 | - } | |
| 860 | - | |
| 861 | - return $share; | |
| 862 | - } | |
| 863 | - | |
| 864 | - /** | |
| 865 | - * Updates the password of the given share if it is not the same as the | |
| 866 | - * password of the original share. | |
| 867 | - * | |
| 868 | - * @param \OCP\Share\IShare $share the share to update its password. | |
| 869 | - * @param \OCP\Share\IShare $originalShare the original share to compare its | |
| 870 | - * password with. | |
| 871 | - * @return boolean whether the password was updated or not. | |
| 872 | - */ | |
| 873 | -	private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) { | |
| 874 | - // Password updated. | |
| 875 | -		if ($share->getPassword() !== $originalShare->getPassword()) { | |
| 876 | - //Verify the password | |
| 877 | - $this->verifyPassword($share->getPassword()); | |
| 878 | - | |
| 879 | - // If a password is set. Hash it! | |
| 880 | -			if ($share->getPassword() !== null) { | |
| 881 | - $share->setPassword($this->hasher->hash($share->getPassword())); | |
| 882 | - | |
| 883 | - return true; | |
| 884 | - } | |
| 885 | - } | |
| 886 | - | |
| 887 | - return false; | |
| 888 | - } | |
| 889 | - | |
| 890 | - /** | |
| 891 | - * Delete all the children of this share | |
| 892 | - * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in | |
| 893 | - * | |
| 894 | - * @param \OCP\Share\IShare $share | |
| 895 | - * @return \OCP\Share\IShare[] List of deleted shares | |
| 896 | - */ | |
| 897 | -	protected function deleteChildren(\OCP\Share\IShare $share) { | |
| 898 | - $deletedShares = []; | |
| 899 | - | |
| 900 | - $provider = $this->factory->getProviderForType($share->getShareType()); | |
| 901 | - | |
| 902 | -		foreach ($provider->getChildren($share) as $child) { | |
| 903 | - $deletedChildren = $this->deleteChildren($child); | |
| 904 | - $deletedShares = array_merge($deletedShares, $deletedChildren); | |
| 905 | - | |
| 906 | - $provider->delete($child); | |
| 907 | - $deletedShares[] = $child; | |
| 908 | - } | |
| 909 | - | |
| 910 | - return $deletedShares; | |
| 911 | - } | |
| 912 | - | |
| 913 | - /** | |
| 914 | - * Delete a share | |
| 915 | - * | |
| 916 | - * @param \OCP\Share\IShare $share | |
| 917 | - * @throws ShareNotFound | |
| 918 | - * @throws \InvalidArgumentException | |
| 919 | - */ | |
| 920 | -	public function deleteShare(\OCP\Share\IShare $share) { | |
| 921 | - | |
| 922 | -		try { | |
| 923 | - $share->getFullId(); | |
| 924 | -		} catch (\UnexpectedValueException $e) { | |
| 925 | -			throw new \InvalidArgumentException('Share does not have a full id'); | |
| 926 | - } | |
| 927 | - | |
| 928 | - $event = new GenericEvent($share); | |
| 929 | -		$this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event); | |
| 930 | - | |
| 931 | - // Get all children and delete them as well | |
| 932 | - $deletedShares = $this->deleteChildren($share); | |
| 933 | - | |
| 934 | - // Do the actual delete | |
| 935 | - $provider = $this->factory->getProviderForType($share->getShareType()); | |
| 936 | - $provider->delete($share); | |
| 937 | - | |
| 938 | - // All the deleted shares caused by this delete | |
| 939 | - $deletedShares[] = $share; | |
| 940 | - | |
| 941 | - // Emit post hook | |
| 942 | -		$event->setArgument('deletedShares', $deletedShares); | |
| 943 | -		$this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event); | |
| 944 | - } | |
| 945 | - | |
| 946 | - | |
| 947 | - /** | |
| 948 | - * Unshare a file as the recipient. | |
| 949 | - * This can be different from a regular delete for example when one of | |
| 950 | - * the users in a groups deletes that share. But the provider should | |
| 951 | - * handle this. | |
| 952 | - * | |
| 953 | - * @param \OCP\Share\IShare $share | |
| 954 | - * @param string $recipientId | |
| 955 | - */ | |
| 956 | -	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) { | |
| 957 | - list($providerId, ) = $this->splitFullId($share->getFullId()); | |
| 958 | - $provider = $this->factory->getProvider($providerId); | |
| 959 | - | |
| 960 | - $provider->deleteFromSelf($share, $recipientId); | |
| 961 | - $event = new GenericEvent($share); | |
| 962 | -		$this->eventDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event); | |
| 963 | - } | |
| 964 | - | |
| 965 | - /** | |
| 966 | - * @inheritdoc | |
| 967 | - */ | |
| 968 | -	public function moveShare(\OCP\Share\IShare $share, $recipientId) { | |
| 969 | -		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) { | |
| 970 | -			throw new \InvalidArgumentException('Can’t change target of link share'); | |
| 971 | - } | |
| 972 | - | |
| 973 | -		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) { | |
| 974 | -			throw new \InvalidArgumentException('Invalid recipient'); | |
| 975 | - } | |
| 976 | - | |
| 977 | -		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) { | |
| 978 | - $sharedWith = $this->groupManager->get($share->getSharedWith()); | |
| 979 | -			if (is_null($sharedWith)) { | |
| 980 | -				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist'); | |
| 981 | - } | |
| 982 | - $recipient = $this->userManager->get($recipientId); | |
| 983 | -			if (!$sharedWith->inGroup($recipient)) { | |
| 984 | -				throw new \InvalidArgumentException('Invalid recipient'); | |
| 985 | - } | |
| 986 | - } | |
| 987 | - | |
| 988 | - list($providerId, ) = $this->splitFullId($share->getFullId()); | |
| 989 | - $provider = $this->factory->getProvider($providerId); | |
| 990 | - | |
| 991 | - $provider->move($share, $recipientId); | |
| 992 | - } | |
| 993 | - | |
| 994 | -	public function getSharesInFolder($userId, Folder $node, $reshares = false) { | |
| 995 | - $providers = $this->factory->getAllProviders(); | |
| 996 | - | |
| 997 | -		return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) { | |
| 998 | - $newShares = $provider->getSharesInFolder($userId, $node, $reshares); | |
| 999 | -			foreach ($newShares as $fid => $data) { | |
| 1000 | -				if (!isset($shares[$fid])) { | |
| 1001 | - $shares[$fid] = []; | |
| 1002 | - } | |
| 1003 | - | |
| 1004 | - $shares[$fid] = array_merge($shares[$fid], $data); | |
| 1005 | - } | |
| 1006 | - return $shares; | |
| 1007 | - }, []); | |
| 1008 | - } | |
| 1009 | - | |
| 1010 | - /** | |
| 1011 | - * @inheritdoc | |
| 1012 | - */ | |
| 1013 | -	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) { | |
| 1014 | - if ($path !== null && | |
| 1015 | - !($path instanceof \OCP\Files\File) && | |
| 1016 | -				!($path instanceof \OCP\Files\Folder)) { | |
| 1017 | -			throw new \InvalidArgumentException('invalid path'); | |
| 1018 | - } | |
| 1019 | - | |
| 1020 | -		try { | |
| 1021 | - $provider = $this->factory->getProviderForType($shareType); | |
| 1022 | -		} catch (ProviderException $e) { | |
| 1023 | - return []; | |
| 1024 | - } | |
| 1025 | - | |
| 1026 | - $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset); | |
| 1027 | - | |
| 1028 | - /* | |
| 607 | + $share->setToken( | |
| 608 | + $this->secureRandom->generate( | |
| 609 | + \OC\Share\Constants::TOKEN_LENGTH, | |
| 610 | + \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE | |
| 611 | + ) | |
| 612 | + ); | |
| 613 | + | |
| 614 | + //Verify the expiration date | |
| 615 | + $this->validateExpirationDate($share); | |
| 616 | + | |
| 617 | + //Verify the password | |
| 618 | + $this->verifyPassword($share->getPassword()); | |
| 619 | + | |
| 620 | + // If a password is set. Hash it! | |
| 621 | +            if ($share->getPassword() !== null) { | |
| 622 | + $share->setPassword($this->hasher->hash($share->getPassword())); | |
| 623 | + } | |
| 624 | +        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) { | |
| 625 | + $share->setToken( | |
| 626 | + $this->secureRandom->generate( | |
| 627 | + \OC\Share\Constants::TOKEN_LENGTH, | |
| 628 | + \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE | |
| 629 | + ) | |
| 630 | + ); | |
| 631 | + } | |
| 632 | + | |
| 633 | + // Cannot share with the owner | |
| 634 | + if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && | |
| 635 | +            $share->getSharedWith() === $share->getShareOwner()) { | |
| 636 | +            throw new \InvalidArgumentException('Can’t share with the share owner'); | |
| 637 | + } | |
| 638 | + | |
| 639 | + // Generate the target | |
| 640 | +        $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName(); | |
| 641 | + $target = \OC\Files\Filesystem::normalizePath($target); | |
| 642 | + $share->setTarget($target); | |
| 643 | + | |
| 644 | + // Pre share event | |
| 645 | + $event = new GenericEvent($share); | |
| 646 | +        $a = $this->eventDispatcher->dispatch('OCP\Share::preShare', $event); | |
| 647 | +        if ($event->isPropagationStopped() && $event->hasArgument('error')) { | |
| 648 | +            throw new \Exception($event->getArgument('error')); | |
| 649 | + } | |
| 650 | + | |
| 651 | + $oldShare = $share; | |
| 652 | + $provider = $this->factory->getProviderForType($share->getShareType()); | |
| 653 | + $share = $provider->create($share); | |
| 654 | + //reuse the node we already have | |
| 655 | + $share->setNode($oldShare->getNode()); | |
| 656 | + | |
| 657 | + // Post share event | |
| 658 | + $event = new GenericEvent($share); | |
| 659 | +        $this->eventDispatcher->dispatch('OCP\Share::postShare', $event); | |
| 660 | + | |
| 661 | +        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) { | |
| 662 | + $user = $this->userManager->get($share->getSharedWith()); | |
| 663 | +            if ($user !== null) { | |
| 664 | + $emailAddress = $user->getEMailAddress(); | |
| 665 | +                if ($emailAddress !== null && $emailAddress !== '') { | |
| 666 | + $userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null); | |
| 667 | +                    $l = $this->l10nFactory->get('lib', $userLang); | |
| 668 | + $this->sendMailNotification( | |
| 669 | + $l, | |
| 670 | + $share->getNode()->getName(), | |
| 671 | +                        $this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', [ 'fileid' => $share->getNode()->getId() ]), | |
| 672 | + $share->getSharedBy(), | |
| 673 | + $emailAddress, | |
| 674 | + $share->getExpirationDate() | |
| 675 | + ); | |
| 676 | +                    $this->logger->debug('Send share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']); | |
| 677 | +                } else { | |
| 678 | +                    $this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']); | |
| 679 | + } | |
| 680 | +            } else { | |
| 681 | +                $this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']); | |
| 682 | + } | |
| 683 | + } | |
| 684 | + | |
| 685 | + return $share; | |
| 686 | + } | |
| 687 | + | |
| 688 | + /** | |
| 689 | + * @param IL10N $l Language of the recipient | |
| 690 | + * @param string $filename file/folder name | |
| 691 | + * @param string $link link to the file/folder | |
| 692 | + * @param string $initiator user ID of share sender | |
| 693 | + * @param string $shareWith email address of share receiver | |
| 694 | + * @param \DateTime|null $expiration | |
| 695 | + * @throws \Exception If mail couldn't be sent | |
| 696 | + */ | |
| 697 | + protected function sendMailNotification(IL10N $l, | |
| 698 | + $filename, | |
| 699 | + $link, | |
| 700 | + $initiator, | |
| 701 | + $shareWith, | |
| 702 | +                                            \DateTime $expiration = null) { | |
| 703 | + $initiatorUser = $this->userManager->get($initiator); | |
| 704 | + $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator; | |
| 705 | + | |
| 706 | + $message = $this->mailer->createMessage(); | |
| 707 | + | |
| 708 | +        $emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [ | |
| 709 | + 'filename' => $filename, | |
| 710 | + 'link' => $link, | |
| 711 | + 'initiator' => $initiatorDisplayName, | |
| 712 | + 'expiration' => $expiration, | |
| 713 | + 'shareWith' => $shareWith, | |
| 714 | + ]); | |
| 715 | + | |
| 716 | +        $emailTemplate->setSubject($l->t('%s shared »%s« with you', array($initiatorDisplayName, $filename))); | |
| 717 | + $emailTemplate->addHeader(); | |
| 718 | +        $emailTemplate->addHeading($l->t('%s shared »%s« with you', [$initiatorDisplayName, $filename]), false); | |
| 719 | +        $text = $l->t('%s shared »%s« with you.', [$initiatorDisplayName, $filename]); | |
| 720 | + | |
| 721 | + $emailTemplate->addBodyText( | |
| 722 | +            $text . ' ' . $l->t('Click the button below to open it.'), | |
| 723 | + $text | |
| 724 | + ); | |
| 725 | + $emailTemplate->addBodyButton( | |
| 726 | +            $l->t('Open »%s«', [$filename]), | |
| 727 | + $link | |
| 728 | + ); | |
| 729 | + | |
| 730 | + $message->setTo([$shareWith]); | |
| 731 | + | |
| 732 | + // The "From" contains the sharers name | |
| 733 | + $instanceName = $this->defaults->getName(); | |
| 734 | + $senderName = $l->t( | |
| 735 | + '%s via %s', | |
| 736 | + [ | |
| 737 | + $initiatorDisplayName, | |
| 738 | + $instanceName | |
| 739 | + ] | |
| 740 | + ); | |
| 741 | + $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]); | |
| 742 | + | |
| 743 | + // The "Reply-To" is set to the sharer if an mail address is configured | |
| 744 | + // also the default footer contains a "Do not reply" which needs to be adjusted. | |
| 745 | + $initiatorEmail = $initiatorUser->getEMailAddress(); | |
| 746 | +        if($initiatorEmail !== null) { | |
| 747 | + $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]); | |
| 748 | + $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')); | |
| 749 | +        } else { | |
| 750 | + $emailTemplate->addFooter(); | |
| 751 | + } | |
| 752 | + | |
| 753 | + $message->useTemplate($emailTemplate); | |
| 754 | + $this->mailer->send($message); | |
| 755 | + } | |
| 756 | + | |
| 757 | + /** | |
| 758 | + * Update a share | |
| 759 | + * | |
| 760 | + * @param \OCP\Share\IShare $share | |
| 761 | + * @return \OCP\Share\IShare The share object | |
| 762 | + * @throws \InvalidArgumentException | |
| 763 | + */ | |
| 764 | +    public function updateShare(\OCP\Share\IShare $share) { | |
| 765 | + $expirationDateUpdated = false; | |
| 766 | + | |
| 767 | + $this->canShare($share); | |
| 768 | + | |
| 769 | +        try { | |
| 770 | + $originalShare = $this->getShareById($share->getFullId()); | |
| 771 | +        } catch (\UnexpectedValueException $e) { | |
| 772 | +            throw new \InvalidArgumentException('Share does not have a full id'); | |
| 773 | + } | |
| 774 | + | |
| 775 | + // We can't change the share type! | |
| 776 | +        if ($share->getShareType() !== $originalShare->getShareType()) { | |
| 777 | +            throw new \InvalidArgumentException('Can’t change share type'); | |
| 778 | + } | |
| 779 | + | |
| 780 | + // We can only change the recipient on user shares | |
| 781 | + if ($share->getSharedWith() !== $originalShare->getSharedWith() && | |
| 782 | +            $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) { | |
| 783 | +            throw new \InvalidArgumentException('Can only update recipient on user shares'); | |
| 784 | + } | |
| 785 | + | |
| 786 | + // Cannot share with the owner | |
| 787 | + if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && | |
| 788 | +            $share->getSharedWith() === $share->getShareOwner()) { | |
| 789 | +            throw new \InvalidArgumentException('Can’t share with the share owner'); | |
| 790 | + } | |
| 791 | + | |
| 792 | + $this->generalCreateChecks($share); | |
| 793 | + | |
| 794 | +        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) { | |
| 795 | + $this->userCreateChecks($share); | |
| 796 | +        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) { | |
| 797 | + $this->groupCreateChecks($share); | |
| 798 | +        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) { | |
| 799 | + $this->linkCreateChecks($share); | |
| 800 | + | |
| 801 | + $this->updateSharePasswordIfNeeded($share, $originalShare); | |
| 802 | + | |
| 803 | +            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) { | |
| 804 | + //Verify the expiration date | |
| 805 | + $this->validateExpirationDate($share); | |
| 806 | + $expirationDateUpdated = true; | |
| 807 | + } | |
| 808 | +        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) { | |
| 809 | + $plainTextPassword = $share->getPassword(); | |
| 810 | +            if (!$this->updateSharePasswordIfNeeded($share, $originalShare)) { | |
| 811 | + $plainTextPassword = null; | |
| 812 | + } | |
| 813 | + } | |
| 814 | + | |
| 815 | + $this->pathCreateChecks($share->getNode()); | |
| 816 | + | |
| 817 | + // Now update the share! | |
| 818 | + $provider = $this->factory->getProviderForType($share->getShareType()); | |
| 819 | +        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) { | |
| 820 | + $share = $provider->update($share, $plainTextPassword); | |
| 821 | +        } else { | |
| 822 | + $share = $provider->update($share); | |
| 823 | + } | |
| 824 | + | |
| 825 | +        if ($expirationDateUpdated === true) { | |
| 826 | +            \OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [ | |
| 827 | + 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder', | |
| 828 | + 'itemSource' => $share->getNode()->getId(), | |
| 829 | + 'date' => $share->getExpirationDate(), | |
| 830 | + 'uidOwner' => $share->getSharedBy(), | |
| 831 | + ]); | |
| 832 | + } | |
| 833 | + | |
| 834 | +        if ($share->getPassword() !== $originalShare->getPassword()) { | |
| 835 | +            \OC_Hook::emit('OCP\Share', 'post_update_password', [ | |
| 836 | + 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder', | |
| 837 | + 'itemSource' => $share->getNode()->getId(), | |
| 838 | + 'uidOwner' => $share->getSharedBy(), | |
| 839 | + 'token' => $share->getToken(), | |
| 840 | + 'disabled' => is_null($share->getPassword()), | |
| 841 | + ]); | |
| 842 | + } | |
| 843 | + | |
| 844 | +        if ($share->getPermissions() !== $originalShare->getPermissions()) { | |
| 845 | +            if ($this->userManager->userExists($share->getShareOwner())) { | |
| 846 | + $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner()); | |
| 847 | +            } else { | |
| 848 | + $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy()); | |
| 849 | + } | |
| 850 | +            \OC_Hook::emit('OCP\Share', 'post_update_permissions', array( | |
| 851 | + 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder', | |
| 852 | + 'itemSource' => $share->getNode()->getId(), | |
| 853 | + 'shareType' => $share->getShareType(), | |
| 854 | + 'shareWith' => $share->getSharedWith(), | |
| 855 | + 'uidOwner' => $share->getSharedBy(), | |
| 856 | + 'permissions' => $share->getPermissions(), | |
| 857 | + 'path' => $userFolder->getRelativePath($share->getNode()->getPath()), | |
| 858 | + )); | |
| 859 | + } | |
| 860 | + | |
| 861 | + return $share; | |
| 862 | + } | |
| 863 | + | |
| 864 | + /** | |
| 865 | + * Updates the password of the given share if it is not the same as the | |
| 866 | + * password of the original share. | |
| 867 | + * | |
| 868 | + * @param \OCP\Share\IShare $share the share to update its password. | |
| 869 | + * @param \OCP\Share\IShare $originalShare the original share to compare its | |
| 870 | + * password with. | |
| 871 | + * @return boolean whether the password was updated or not. | |
| 872 | + */ | |
| 873 | +    private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) { | |
| 874 | + // Password updated. | |
| 875 | +        if ($share->getPassword() !== $originalShare->getPassword()) { | |
| 876 | + //Verify the password | |
| 877 | + $this->verifyPassword($share->getPassword()); | |
| 878 | + | |
| 879 | + // If a password is set. Hash it! | |
| 880 | +            if ($share->getPassword() !== null) { | |
| 881 | + $share->setPassword($this->hasher->hash($share->getPassword())); | |
| 882 | + | |
| 883 | + return true; | |
| 884 | + } | |
| 885 | + } | |
| 886 | + | |
| 887 | + return false; | |
| 888 | + } | |
| 889 | + | |
| 890 | + /** | |
| 891 | + * Delete all the children of this share | |
| 892 | + * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in | |
| 893 | + * | |
| 894 | + * @param \OCP\Share\IShare $share | |
| 895 | + * @return \OCP\Share\IShare[] List of deleted shares | |
| 896 | + */ | |
| 897 | +    protected function deleteChildren(\OCP\Share\IShare $share) { | |
| 898 | + $deletedShares = []; | |
| 899 | + | |
| 900 | + $provider = $this->factory->getProviderForType($share->getShareType()); | |
| 901 | + | |
| 902 | +        foreach ($provider->getChildren($share) as $child) { | |
| 903 | + $deletedChildren = $this->deleteChildren($child); | |
| 904 | + $deletedShares = array_merge($deletedShares, $deletedChildren); | |
| 905 | + | |
| 906 | + $provider->delete($child); | |
| 907 | + $deletedShares[] = $child; | |
| 908 | + } | |
| 909 | + | |
| 910 | + return $deletedShares; | |
| 911 | + } | |
| 912 | + | |
| 913 | + /** | |
| 914 | + * Delete a share | |
| 915 | + * | |
| 916 | + * @param \OCP\Share\IShare $share | |
| 917 | + * @throws ShareNotFound | |
| 918 | + * @throws \InvalidArgumentException | |
| 919 | + */ | |
| 920 | +    public function deleteShare(\OCP\Share\IShare $share) { | |
| 921 | + | |
| 922 | +        try { | |
| 923 | + $share->getFullId(); | |
| 924 | +        } catch (\UnexpectedValueException $e) { | |
| 925 | +            throw new \InvalidArgumentException('Share does not have a full id'); | |
| 926 | + } | |
| 927 | + | |
| 928 | + $event = new GenericEvent($share); | |
| 929 | +        $this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event); | |
| 930 | + | |
| 931 | + // Get all children and delete them as well | |
| 932 | + $deletedShares = $this->deleteChildren($share); | |
| 933 | + | |
| 934 | + // Do the actual delete | |
| 935 | + $provider = $this->factory->getProviderForType($share->getShareType()); | |
| 936 | + $provider->delete($share); | |
| 937 | + | |
| 938 | + // All the deleted shares caused by this delete | |
| 939 | + $deletedShares[] = $share; | |
| 940 | + | |
| 941 | + // Emit post hook | |
| 942 | +        $event->setArgument('deletedShares', $deletedShares); | |
| 943 | +        $this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event); | |
| 944 | + } | |
| 945 | + | |
| 946 | + | |
| 947 | + /** | |
| 948 | + * Unshare a file as the recipient. | |
| 949 | + * This can be different from a regular delete for example when one of | |
| 950 | + * the users in a groups deletes that share. But the provider should | |
| 951 | + * handle this. | |
| 952 | + * | |
| 953 | + * @param \OCP\Share\IShare $share | |
| 954 | + * @param string $recipientId | |
| 955 | + */ | |
| 956 | +    public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) { | |
| 957 | + list($providerId, ) = $this->splitFullId($share->getFullId()); | |
| 958 | + $provider = $this->factory->getProvider($providerId); | |
| 959 | + | |
| 960 | + $provider->deleteFromSelf($share, $recipientId); | |
| 961 | + $event = new GenericEvent($share); | |
| 962 | +        $this->eventDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event); | |
| 963 | + } | |
| 964 | + | |
| 965 | + /** | |
| 966 | + * @inheritdoc | |
| 967 | + */ | |
| 968 | +    public function moveShare(\OCP\Share\IShare $share, $recipientId) { | |
| 969 | +        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) { | |
| 970 | +            throw new \InvalidArgumentException('Can’t change target of link share'); | |
| 971 | + } | |
| 972 | + | |
| 973 | +        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) { | |
| 974 | +            throw new \InvalidArgumentException('Invalid recipient'); | |
| 975 | + } | |
| 976 | + | |
| 977 | +        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) { | |
| 978 | + $sharedWith = $this->groupManager->get($share->getSharedWith()); | |
| 979 | +            if (is_null($sharedWith)) { | |
| 980 | +                throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist'); | |
| 981 | + } | |
| 982 | + $recipient = $this->userManager->get($recipientId); | |
| 983 | +            if (!$sharedWith->inGroup($recipient)) { | |
| 984 | +                throw new \InvalidArgumentException('Invalid recipient'); | |
| 985 | + } | |
| 986 | + } | |
| 987 | + | |
| 988 | + list($providerId, ) = $this->splitFullId($share->getFullId()); | |
| 989 | + $provider = $this->factory->getProvider($providerId); | |
| 990 | + | |
| 991 | + $provider->move($share, $recipientId); | |
| 992 | + } | |
| 993 | + | |
| 994 | +    public function getSharesInFolder($userId, Folder $node, $reshares = false) { | |
| 995 | + $providers = $this->factory->getAllProviders(); | |
| 996 | + | |
| 997 | +        return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) { | |
| 998 | + $newShares = $provider->getSharesInFolder($userId, $node, $reshares); | |
| 999 | +            foreach ($newShares as $fid => $data) { | |
| 1000 | +                if (!isset($shares[$fid])) { | |
| 1001 | + $shares[$fid] = []; | |
| 1002 | + } | |
| 1003 | + | |
| 1004 | + $shares[$fid] = array_merge($shares[$fid], $data); | |
| 1005 | + } | |
| 1006 | + return $shares; | |
| 1007 | + }, []); | |
| 1008 | + } | |
| 1009 | + | |
| 1010 | + /** | |
| 1011 | + * @inheritdoc | |
| 1012 | + */ | |
| 1013 | +    public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) { | |
| 1014 | + if ($path !== null && | |
| 1015 | + !($path instanceof \OCP\Files\File) && | |
| 1016 | +                !($path instanceof \OCP\Files\Folder)) { | |
| 1017 | +            throw new \InvalidArgumentException('invalid path'); | |
| 1018 | + } | |
| 1019 | + | |
| 1020 | +        try { | |
| 1021 | + $provider = $this->factory->getProviderForType($shareType); | |
| 1022 | +        } catch (ProviderException $e) { | |
| 1023 | + return []; | |
| 1024 | + } | |
| 1025 | + | |
| 1026 | + $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset); | |
| 1027 | + | |
| 1028 | + /* | |
| 1029 | 1029 | * Work around so we don't return expired shares but still follow | 
| 1030 | 1030 | * proper pagination. | 
| 1031 | 1031 | */ | 
| 1032 | 1032 | |
| 1033 | - $shares2 = []; | |
| 1034 | - | |
| 1035 | -		while(true) { | |
| 1036 | - $added = 0; | |
| 1037 | -			foreach ($shares as $share) { | |
| 1038 | - | |
| 1039 | -				try { | |
| 1040 | - $this->checkExpireDate($share); | |
| 1041 | -				} catch (ShareNotFound $e) { | |
| 1042 | - //Ignore since this basically means the share is deleted | |
| 1043 | - continue; | |
| 1044 | - } | |
| 1045 | - | |
| 1046 | - $added++; | |
| 1047 | - $shares2[] = $share; | |
| 1048 | - | |
| 1049 | -				if (count($shares2) === $limit) { | |
| 1050 | - break; | |
| 1051 | - } | |
| 1052 | - } | |
| 1053 | - | |
| 1054 | - // If we did not fetch more shares than the limit then there are no more shares | |
| 1055 | -			if (count($shares) < $limit) { | |
| 1056 | - break; | |
| 1057 | - } | |
| 1058 | - | |
| 1059 | -			if (count($shares2) === $limit) { | |
| 1060 | - break; | |
| 1061 | - } | |
| 1062 | - | |
| 1063 | - // If there was no limit on the select we are done | |
| 1064 | -			if ($limit === -1) { | |
| 1065 | - break; | |
| 1066 | - } | |
| 1067 | - | |
| 1068 | - $offset += $added; | |
| 1069 | - | |
| 1070 | - // Fetch again $limit shares | |
| 1071 | - $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset); | |
| 1072 | - | |
| 1073 | - // No more shares means we are done | |
| 1074 | -			if (empty($shares)) { | |
| 1075 | - break; | |
| 1076 | - } | |
| 1077 | - } | |
| 1078 | - | |
| 1079 | - $shares = $shares2; | |
| 1080 | - | |
| 1081 | - return $shares; | |
| 1082 | - } | |
| 1083 | - | |
| 1084 | - /** | |
| 1085 | - * @inheritdoc | |
| 1086 | - */ | |
| 1087 | -	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) { | |
| 1088 | -		try { | |
| 1089 | - $provider = $this->factory->getProviderForType($shareType); | |
| 1090 | -		} catch (ProviderException $e) { | |
| 1091 | - return []; | |
| 1092 | - } | |
| 1093 | - | |
| 1094 | - $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset); | |
| 1095 | - | |
| 1096 | - // remove all shares which are already expired | |
| 1097 | -		foreach ($shares as $key => $share) { | |
| 1098 | -			try { | |
| 1099 | - $this->checkExpireDate($share); | |
| 1100 | -			} catch (ShareNotFound $e) { | |
| 1101 | - unset($shares[$key]); | |
| 1102 | - } | |
| 1103 | - } | |
| 1104 | - | |
| 1105 | - return $shares; | |
| 1106 | - } | |
| 1107 | - | |
| 1108 | - /** | |
| 1109 | - * @inheritdoc | |
| 1110 | - */ | |
| 1111 | -	public function getShareById($id, $recipient = null) { | |
| 1112 | -		if ($id === null) { | |
| 1113 | - throw new ShareNotFound(); | |
| 1114 | - } | |
| 1115 | - | |
| 1116 | - list($providerId, $id) = $this->splitFullId($id); | |
| 1117 | - | |
| 1118 | -		try { | |
| 1119 | - $provider = $this->factory->getProvider($providerId); | |
| 1120 | -		} catch (ProviderException $e) { | |
| 1121 | - throw new ShareNotFound(); | |
| 1122 | - } | |
| 1123 | - | |
| 1124 | - $share = $provider->getShareById($id, $recipient); | |
| 1125 | - | |
| 1126 | - $this->checkExpireDate($share); | |
| 1127 | - | |
| 1128 | - return $share; | |
| 1129 | - } | |
| 1130 | - | |
| 1131 | - /** | |
| 1132 | - * Get all the shares for a given path | |
| 1133 | - * | |
| 1134 | - * @param \OCP\Files\Node $path | |
| 1135 | - * @param int $page | |
| 1136 | - * @param int $perPage | |
| 1137 | - * | |
| 1138 | - * @return Share[] | |
| 1139 | - */ | |
| 1140 | -	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) { | |
| 1141 | - return []; | |
| 1142 | - } | |
| 1143 | - | |
| 1144 | - /** | |
| 1145 | - * Get the share by token possible with password | |
| 1146 | - * | |
| 1147 | - * @param string $token | |
| 1148 | - * @return Share | |
| 1149 | - * | |
| 1150 | - * @throws ShareNotFound | |
| 1151 | - */ | |
| 1152 | -	public function getShareByToken($token) { | |
| 1153 | - $share = null; | |
| 1154 | -		try { | |
| 1155 | -			if($this->shareApiAllowLinks()) { | |
| 1156 | - $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK); | |
| 1157 | - $share = $provider->getShareByToken($token); | |
| 1158 | - } | |
| 1159 | -		} catch (ProviderException $e) { | |
| 1160 | -		} catch (ShareNotFound $e) { | |
| 1161 | - } | |
| 1162 | - | |
| 1163 | - | |
| 1164 | - // If it is not a link share try to fetch a federated share by token | |
| 1165 | -		if ($share === null) { | |
| 1166 | -			try { | |
| 1167 | - $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE); | |
| 1168 | - $share = $provider->getShareByToken($token); | |
| 1169 | -			} catch (ProviderException $e) { | |
| 1170 | -			} catch (ShareNotFound $e) { | |
| 1171 | - } | |
| 1172 | - } | |
| 1173 | - | |
| 1174 | - // If it is not a link share try to fetch a mail share by token | |
| 1175 | -		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) { | |
| 1176 | -			try { | |
| 1177 | - $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL); | |
| 1178 | - $share = $provider->getShareByToken($token); | |
| 1179 | -			} catch (ProviderException $e) { | |
| 1180 | -			} catch (ShareNotFound $e) { | |
| 1181 | - } | |
| 1182 | - } | |
| 1183 | - | |
| 1184 | -		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) { | |
| 1185 | -			try { | |
| 1186 | - $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE); | |
| 1187 | - $share = $provider->getShareByToken($token); | |
| 1188 | -			} catch (ProviderException $e) { | |
| 1189 | -			} catch (ShareNotFound $e) { | |
| 1190 | - } | |
| 1191 | - } | |
| 1192 | - | |
| 1193 | -		if ($share === null) { | |
| 1194 | -			throw new ShareNotFound($this->l->t('The requested share does not exist anymore')); | |
| 1195 | - } | |
| 1196 | - | |
| 1197 | - $this->checkExpireDate($share); | |
| 1198 | - | |
| 1199 | - /* | |
| 1033 | + $shares2 = []; | |
| 1034 | + | |
| 1035 | +        while(true) { | |
| 1036 | + $added = 0; | |
| 1037 | +            foreach ($shares as $share) { | |
| 1038 | + | |
| 1039 | +                try { | |
| 1040 | + $this->checkExpireDate($share); | |
| 1041 | +                } catch (ShareNotFound $e) { | |
| 1042 | + //Ignore since this basically means the share is deleted | |
| 1043 | + continue; | |
| 1044 | + } | |
| 1045 | + | |
| 1046 | + $added++; | |
| 1047 | + $shares2[] = $share; | |
| 1048 | + | |
| 1049 | +                if (count($shares2) === $limit) { | |
| 1050 | + break; | |
| 1051 | + } | |
| 1052 | + } | |
| 1053 | + | |
| 1054 | + // If we did not fetch more shares than the limit then there are no more shares | |
| 1055 | +            if (count($shares) < $limit) { | |
| 1056 | + break; | |
| 1057 | + } | |
| 1058 | + | |
| 1059 | +            if (count($shares2) === $limit) { | |
| 1060 | + break; | |
| 1061 | + } | |
| 1062 | + | |
| 1063 | + // If there was no limit on the select we are done | |
| 1064 | +            if ($limit === -1) { | |
| 1065 | + break; | |
| 1066 | + } | |
| 1067 | + | |
| 1068 | + $offset += $added; | |
| 1069 | + | |
| 1070 | + // Fetch again $limit shares | |
| 1071 | + $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset); | |
| 1072 | + | |
| 1073 | + // No more shares means we are done | |
| 1074 | +            if (empty($shares)) { | |
| 1075 | + break; | |
| 1076 | + } | |
| 1077 | + } | |
| 1078 | + | |
| 1079 | + $shares = $shares2; | |
| 1080 | + | |
| 1081 | + return $shares; | |
| 1082 | + } | |
| 1083 | + | |
| 1084 | + /** | |
| 1085 | + * @inheritdoc | |
| 1086 | + */ | |
| 1087 | +    public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) { | |
| 1088 | +        try { | |
| 1089 | + $provider = $this->factory->getProviderForType($shareType); | |
| 1090 | +        } catch (ProviderException $e) { | |
| 1091 | + return []; | |
| 1092 | + } | |
| 1093 | + | |
| 1094 | + $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset); | |
| 1095 | + | |
| 1096 | + // remove all shares which are already expired | |
| 1097 | +        foreach ($shares as $key => $share) { | |
| 1098 | +            try { | |
| 1099 | + $this->checkExpireDate($share); | |
| 1100 | +            } catch (ShareNotFound $e) { | |
| 1101 | + unset($shares[$key]); | |
| 1102 | + } | |
| 1103 | + } | |
| 1104 | + | |
| 1105 | + return $shares; | |
| 1106 | + } | |
| 1107 | + | |
| 1108 | + /** | |
| 1109 | + * @inheritdoc | |
| 1110 | + */ | |
| 1111 | +    public function getShareById($id, $recipient = null) { | |
| 1112 | +        if ($id === null) { | |
| 1113 | + throw new ShareNotFound(); | |
| 1114 | + } | |
| 1115 | + | |
| 1116 | + list($providerId, $id) = $this->splitFullId($id); | |
| 1117 | + | |
| 1118 | +        try { | |
| 1119 | + $provider = $this->factory->getProvider($providerId); | |
| 1120 | +        } catch (ProviderException $e) { | |
| 1121 | + throw new ShareNotFound(); | |
| 1122 | + } | |
| 1123 | + | |
| 1124 | + $share = $provider->getShareById($id, $recipient); | |
| 1125 | + | |
| 1126 | + $this->checkExpireDate($share); | |
| 1127 | + | |
| 1128 | + return $share; | |
| 1129 | + } | |
| 1130 | + | |
| 1131 | + /** | |
| 1132 | + * Get all the shares for a given path | |
| 1133 | + * | |
| 1134 | + * @param \OCP\Files\Node $path | |
| 1135 | + * @param int $page | |
| 1136 | + * @param int $perPage | |
| 1137 | + * | |
| 1138 | + * @return Share[] | |
| 1139 | + */ | |
| 1140 | +    public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) { | |
| 1141 | + return []; | |
| 1142 | + } | |
| 1143 | + | |
| 1144 | + /** | |
| 1145 | + * Get the share by token possible with password | |
| 1146 | + * | |
| 1147 | + * @param string $token | |
| 1148 | + * @return Share | |
| 1149 | + * | |
| 1150 | + * @throws ShareNotFound | |
| 1151 | + */ | |
| 1152 | +    public function getShareByToken($token) { | |
| 1153 | + $share = null; | |
| 1154 | +        try { | |
| 1155 | +            if($this->shareApiAllowLinks()) { | |
| 1156 | + $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK); | |
| 1157 | + $share = $provider->getShareByToken($token); | |
| 1158 | + } | |
| 1159 | +        } catch (ProviderException $e) { | |
| 1160 | +        } catch (ShareNotFound $e) { | |
| 1161 | + } | |
| 1162 | + | |
| 1163 | + | |
| 1164 | + // If it is not a link share try to fetch a federated share by token | |
| 1165 | +        if ($share === null) { | |
| 1166 | +            try { | |
| 1167 | + $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE); | |
| 1168 | + $share = $provider->getShareByToken($token); | |
| 1169 | +            } catch (ProviderException $e) { | |
| 1170 | +            } catch (ShareNotFound $e) { | |
| 1171 | + } | |
| 1172 | + } | |
| 1173 | + | |
| 1174 | + // If it is not a link share try to fetch a mail share by token | |
| 1175 | +        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) { | |
| 1176 | +            try { | |
| 1177 | + $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL); | |
| 1178 | + $share = $provider->getShareByToken($token); | |
| 1179 | +            } catch (ProviderException $e) { | |
| 1180 | +            } catch (ShareNotFound $e) { | |
| 1181 | + } | |
| 1182 | + } | |
| 1183 | + | |
| 1184 | +        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) { | |
| 1185 | +            try { | |
| 1186 | + $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE); | |
| 1187 | + $share = $provider->getShareByToken($token); | |
| 1188 | +            } catch (ProviderException $e) { | |
| 1189 | +            } catch (ShareNotFound $e) { | |
| 1190 | + } | |
| 1191 | + } | |
| 1192 | + | |
| 1193 | +        if ($share === null) { | |
| 1194 | +            throw new ShareNotFound($this->l->t('The requested share does not exist anymore')); | |
| 1195 | + } | |
| 1196 | + | |
| 1197 | + $this->checkExpireDate($share); | |
| 1198 | + | |
| 1199 | + /* | |
| 1200 | 1200 | * Reduce the permissions for link shares if public upload is not enabled | 
| 1201 | 1201 | */ | 
| 1202 | - if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK && | |
| 1203 | -			!$this->shareApiLinkAllowPublicUpload()) { | |
| 1204 | - $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE)); | |
| 1205 | - } | |
| 1206 | - | |
| 1207 | - return $share; | |
| 1208 | - } | |
| 1209 | - | |
| 1210 | -	protected function checkExpireDate($share) { | |
| 1211 | - if ($share->getExpirationDate() !== null && | |
| 1212 | -			$share->getExpirationDate() <= new \DateTime()) { | |
| 1213 | - $this->deleteShare($share); | |
| 1214 | -			throw new ShareNotFound($this->l->t('The requested share does not exist anymore')); | |
| 1215 | - } | |
| 1216 | - | |
| 1217 | - } | |
| 1218 | - | |
| 1219 | - /** | |
| 1220 | - * Verify the password of a public share | |
| 1221 | - * | |
| 1222 | - * @param \OCP\Share\IShare $share | |
| 1223 | - * @param string $password | |
| 1224 | - * @return bool | |
| 1225 | - */ | |
| 1226 | -	public function checkPassword(\OCP\Share\IShare $share, $password) { | |
| 1227 | - $passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK | |
| 1228 | - || $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL; | |
| 1229 | -		if (!$passwordProtected) { | |
| 1230 | - //TODO maybe exception? | |
| 1231 | - return false; | |
| 1232 | - } | |
| 1233 | - | |
| 1234 | -		if ($password === null || $share->getPassword() === null) { | |
| 1235 | - return false; | |
| 1236 | - } | |
| 1237 | - | |
| 1238 | - $newHash = ''; | |
| 1239 | -		if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) { | |
| 1240 | - return false; | |
| 1241 | - } | |
| 1242 | - | |
| 1243 | -		if (!empty($newHash)) { | |
| 1244 | - $share->setPassword($newHash); | |
| 1245 | - $provider = $this->factory->getProviderForType($share->getShareType()); | |
| 1246 | - $provider->update($share); | |
| 1247 | - } | |
| 1248 | - | |
| 1249 | - return true; | |
| 1250 | - } | |
| 1251 | - | |
| 1252 | - /** | |
| 1253 | - * @inheritdoc | |
| 1254 | - */ | |
| 1255 | -	public function userDeleted($uid) { | |
| 1256 | - $types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE, \OCP\Share::SHARE_TYPE_EMAIL]; | |
| 1257 | - | |
| 1258 | -		foreach ($types as $type) { | |
| 1259 | -			try { | |
| 1260 | - $provider = $this->factory->getProviderForType($type); | |
| 1261 | -			} catch (ProviderException $e) { | |
| 1262 | - continue; | |
| 1263 | - } | |
| 1264 | - $provider->userDeleted($uid, $type); | |
| 1265 | - } | |
| 1266 | - } | |
| 1267 | - | |
| 1268 | - /** | |
| 1269 | - * @inheritdoc | |
| 1270 | - */ | |
| 1271 | -	public function groupDeleted($gid) { | |
| 1272 | - $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP); | |
| 1273 | - $provider->groupDeleted($gid); | |
| 1274 | - } | |
| 1275 | - | |
| 1276 | - /** | |
| 1277 | - * @inheritdoc | |
| 1278 | - */ | |
| 1279 | -	public function userDeletedFromGroup($uid, $gid) { | |
| 1280 | - $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP); | |
| 1281 | - $provider->userDeletedFromGroup($uid, $gid); | |
| 1282 | - } | |
| 1283 | - | |
| 1284 | - /** | |
| 1285 | - * Get access list to a path. This means | |
| 1286 | - * all the users that can access a given path. | |
| 1287 | - * | |
| 1288 | - * Consider: | |
| 1289 | - * -root | |
| 1290 | - * |-folder1 (23) | |
| 1291 | - * |-folder2 (32) | |
| 1292 | - * |-fileA (42) | |
| 1293 | - * | |
| 1294 | - * fileA is shared with user1 and user1@server1 | |
| 1295 | - * folder2 is shared with group2 (user4 is a member of group2) | |
| 1296 | - * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2 | |
| 1297 | - * | |
| 1298 | - * Then the access list to '/folder1/folder2/fileA' with $currentAccess is: | |
| 1299 | - * [ | |
| 1300 | - * users => [ | |
| 1301 | - * 'user1' => ['node_id' => 42, 'node_path' => '/fileA'], | |
| 1302 | - * 'user4' => ['node_id' => 32, 'node_path' => '/folder2'], | |
| 1303 | - * 'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'], | |
| 1304 | - * ], | |
| 1305 | - * remote => [ | |
| 1306 | - * 'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'], | |
| 1307 | - * 'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'], | |
| 1308 | - * ], | |
| 1309 | - * public => bool | |
| 1310 | - * mail => bool | |
| 1311 | - * ] | |
| 1312 | - * | |
| 1313 | - * The access list to '/folder1/folder2/fileA' **without** $currentAccess is: | |
| 1314 | - * [ | |
| 1315 | - * users => ['user1', 'user2', 'user4'], | |
| 1316 | - * remote => bool, | |
| 1317 | - * public => bool | |
| 1318 | - * mail => bool | |
| 1319 | - * ] | |
| 1320 | - * | |
| 1321 | - * This is required for encryption/activity | |
| 1322 | - * | |
| 1323 | - * @param \OCP\Files\Node $path | |
| 1324 | - * @param bool $recursive Should we check all parent folders as well | |
| 1325 | - * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it) | |
| 1326 | - * @return array | |
| 1327 | - */ | |
| 1328 | -	public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) { | |
| 1329 | - $owner = $path->getOwner()->getUID(); | |
| 1330 | - | |
| 1331 | -		if ($currentAccess) { | |
| 1332 | - $al = ['users' => [], 'remote' => [], 'public' => false]; | |
| 1333 | -		} else { | |
| 1334 | - $al = ['users' => [], 'remote' => false, 'public' => false]; | |
| 1335 | - } | |
| 1336 | -		if (!$this->userManager->userExists($owner)) { | |
| 1337 | - return $al; | |
| 1338 | - } | |
| 1339 | - | |
| 1340 | - //Get node for the owner | |
| 1341 | - $userFolder = $this->rootFolder->getUserFolder($owner); | |
| 1342 | -		if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) { | |
| 1343 | - $path = $userFolder->getById($path->getId())[0]; | |
| 1344 | - } | |
| 1345 | - | |
| 1346 | - $providers = $this->factory->getAllProviders(); | |
| 1347 | - | |
| 1348 | - /** @var Node[] $nodes */ | |
| 1349 | - $nodes = []; | |
| 1350 | - | |
| 1351 | - | |
| 1352 | -		if ($currentAccess) { | |
| 1353 | - $ownerPath = $path->getPath(); | |
| 1354 | -			$ownerPath = explode('/', $ownerPath, 4); | |
| 1355 | -			if (count($ownerPath) < 4) { | |
| 1356 | - $ownerPath = ''; | |
| 1357 | -			} else { | |
| 1358 | - $ownerPath = $ownerPath[3]; | |
| 1359 | - } | |
| 1360 | - $al['users'][$owner] = [ | |
| 1361 | - 'node_id' => $path->getId(), | |
| 1362 | - 'node_path' => '/' . $ownerPath, | |
| 1363 | - ]; | |
| 1364 | -		} else { | |
| 1365 | - $al['users'][] = $owner; | |
| 1366 | - } | |
| 1367 | - | |
| 1368 | - // Collect all the shares | |
| 1369 | -		while ($path->getPath() !== $userFolder->getPath()) { | |
| 1370 | - $nodes[] = $path; | |
| 1371 | -			if (!$recursive) { | |
| 1372 | - break; | |
| 1373 | - } | |
| 1374 | - $path = $path->getParent(); | |
| 1375 | - } | |
| 1376 | - | |
| 1377 | -		foreach ($providers as $provider) { | |
| 1378 | - $tmp = $provider->getAccessList($nodes, $currentAccess); | |
| 1379 | - | |
| 1380 | -			foreach ($tmp as $k => $v) { | |
| 1381 | -				if (isset($al[$k])) { | |
| 1382 | -					if (is_array($al[$k])) { | |
| 1383 | - $al[$k] = array_merge($al[$k], $v); | |
| 1384 | -					} else { | |
| 1385 | - $al[$k] = $al[$k] || $v; | |
| 1386 | - } | |
| 1387 | -				} else { | |
| 1388 | - $al[$k] = $v; | |
| 1389 | - } | |
| 1390 | - } | |
| 1391 | - } | |
| 1392 | - | |
| 1393 | - return $al; | |
| 1394 | - } | |
| 1395 | - | |
| 1396 | - /** | |
| 1397 | - * Create a new share | |
| 1398 | - * @return \OCP\Share\IShare | |
| 1399 | - */ | |
| 1400 | -	public function newShare() { | |
| 1401 | - return new \OC\Share20\Share($this->rootFolder, $this->userManager); | |
| 1402 | - } | |
| 1403 | - | |
| 1404 | - /** | |
| 1405 | - * Is the share API enabled | |
| 1406 | - * | |
| 1407 | - * @return bool | |
| 1408 | - */ | |
| 1409 | -	public function shareApiEnabled() { | |
| 1410 | -		return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes'; | |
| 1411 | - } | |
| 1412 | - | |
| 1413 | - /** | |
| 1414 | - * Is public link sharing enabled | |
| 1415 | - * | |
| 1416 | - * @return bool | |
| 1417 | - */ | |
| 1418 | -	public function shareApiAllowLinks() { | |
| 1419 | -		return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes'; | |
| 1420 | - } | |
| 1421 | - | |
| 1422 | - /** | |
| 1423 | - * Is password on public link requires | |
| 1424 | - * | |
| 1425 | - * @return bool | |
| 1426 | - */ | |
| 1427 | -	public function shareApiLinkEnforcePassword() { | |
| 1428 | -		return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes'; | |
| 1429 | - } | |
| 1430 | - | |
| 1431 | - /** | |
| 1432 | - * Is default expire date enabled | |
| 1433 | - * | |
| 1434 | - * @return bool | |
| 1435 | - */ | |
| 1436 | -	public function shareApiLinkDefaultExpireDate() { | |
| 1437 | -		return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes'; | |
| 1438 | - } | |
| 1439 | - | |
| 1440 | - /** | |
| 1441 | - * Is default expire date enforced | |
| 1442 | - *` | |
| 1443 | - * @return bool | |
| 1444 | - */ | |
| 1445 | -	public function shareApiLinkDefaultExpireDateEnforced() { | |
| 1446 | - return $this->shareApiLinkDefaultExpireDate() && | |
| 1447 | -			$this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes'; | |
| 1448 | - } | |
| 1449 | - | |
| 1450 | - /** | |
| 1451 | - * Number of default expire days | |
| 1452 | - *shareApiLinkAllowPublicUpload | |
| 1453 | - * @return int | |
| 1454 | - */ | |
| 1455 | -	public function shareApiLinkDefaultExpireDays() { | |
| 1456 | -		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7'); | |
| 1457 | - } | |
| 1458 | - | |
| 1459 | - /** | |
| 1460 | - * Allow public upload on link shares | |
| 1461 | - * | |
| 1462 | - * @return bool | |
| 1463 | - */ | |
| 1464 | -	public function shareApiLinkAllowPublicUpload() { | |
| 1465 | -		return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes'; | |
| 1466 | - } | |
| 1467 | - | |
| 1468 | - /** | |
| 1469 | - * check if user can only share with group members | |
| 1470 | - * @return bool | |
| 1471 | - */ | |
| 1472 | -	public function shareWithGroupMembersOnly() { | |
| 1473 | -		return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes'; | |
| 1474 | - } | |
| 1475 | - | |
| 1476 | - /** | |
| 1477 | - * Check if users can share with groups | |
| 1478 | - * @return bool | |
| 1479 | - */ | |
| 1480 | -	public function allowGroupSharing() { | |
| 1481 | -		return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes'; | |
| 1482 | - } | |
| 1483 | - | |
| 1484 | - /** | |
| 1485 | - * Copied from \OC_Util::isSharingDisabledForUser | |
| 1486 | - * | |
| 1487 | - * TODO: Deprecate fuction from OC_Util | |
| 1488 | - * | |
| 1489 | - * @param string $userId | |
| 1490 | - * @return bool | |
| 1491 | - */ | |
| 1492 | -	public function sharingDisabledForUser($userId) { | |
| 1493 | -		if ($userId === null) { | |
| 1494 | - return false; | |
| 1495 | - } | |
| 1496 | - | |
| 1497 | -		if (isset($this->sharingDisabledForUsersCache[$userId])) { | |
| 1498 | - return $this->sharingDisabledForUsersCache[$userId]; | |
| 1499 | - } | |
| 1500 | - | |
| 1501 | -		if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') { | |
| 1502 | -			$groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', ''); | |
| 1503 | - $excludedGroups = json_decode($groupsList); | |
| 1504 | -			if (is_null($excludedGroups)) { | |
| 1505 | -				$excludedGroups = explode(',', $groupsList); | |
| 1506 | - $newValue = json_encode($excludedGroups); | |
| 1507 | -				$this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue); | |
| 1508 | - } | |
| 1509 | - $user = $this->userManager->get($userId); | |
| 1510 | - $usersGroups = $this->groupManager->getUserGroupIds($user); | |
| 1511 | -			if (!empty($usersGroups)) { | |
| 1512 | - $remainingGroups = array_diff($usersGroups, $excludedGroups); | |
| 1513 | - // if the user is only in groups which are disabled for sharing then | |
| 1514 | - // sharing is also disabled for the user | |
| 1515 | -				if (empty($remainingGroups)) { | |
| 1516 | - $this->sharingDisabledForUsersCache[$userId] = true; | |
| 1517 | - return true; | |
| 1518 | - } | |
| 1519 | - } | |
| 1520 | - } | |
| 1521 | - | |
| 1522 | - $this->sharingDisabledForUsersCache[$userId] = false; | |
| 1523 | - return false; | |
| 1524 | - } | |
| 1525 | - | |
| 1526 | - /** | |
| 1527 | - * @inheritdoc | |
| 1528 | - */ | |
| 1529 | -	public function outgoingServer2ServerSharesAllowed() { | |
| 1530 | -		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes'; | |
| 1531 | - } | |
| 1532 | - | |
| 1533 | - /** | |
| 1534 | - * @inheritdoc | |
| 1535 | - */ | |
| 1536 | -	public function shareProviderExists($shareType) { | |
| 1537 | -		try { | |
| 1538 | - $this->factory->getProviderForType($shareType); | |
| 1539 | -		} catch (ProviderException $e) { | |
| 1540 | - return false; | |
| 1541 | - } | |
| 1542 | - | |
| 1543 | - return true; | |
| 1544 | - } | |
| 1202 | + if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK && | |
| 1203 | +            !$this->shareApiLinkAllowPublicUpload()) { | |
| 1204 | + $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE)); | |
| 1205 | + } | |
| 1206 | + | |
| 1207 | + return $share; | |
| 1208 | + } | |
| 1209 | + | |
| 1210 | +    protected function checkExpireDate($share) { | |
| 1211 | + if ($share->getExpirationDate() !== null && | |
| 1212 | +            $share->getExpirationDate() <= new \DateTime()) { | |
| 1213 | + $this->deleteShare($share); | |
| 1214 | +            throw new ShareNotFound($this->l->t('The requested share does not exist anymore')); | |
| 1215 | + } | |
| 1216 | + | |
| 1217 | + } | |
| 1218 | + | |
| 1219 | + /** | |
| 1220 | + * Verify the password of a public share | |
| 1221 | + * | |
| 1222 | + * @param \OCP\Share\IShare $share | |
| 1223 | + * @param string $password | |
| 1224 | + * @return bool | |
| 1225 | + */ | |
| 1226 | +    public function checkPassword(\OCP\Share\IShare $share, $password) { | |
| 1227 | + $passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK | |
| 1228 | + || $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL; | |
| 1229 | +        if (!$passwordProtected) { | |
| 1230 | + //TODO maybe exception? | |
| 1231 | + return false; | |
| 1232 | + } | |
| 1233 | + | |
| 1234 | +        if ($password === null || $share->getPassword() === null) { | |
| 1235 | + return false; | |
| 1236 | + } | |
| 1237 | + | |
| 1238 | + $newHash = ''; | |
| 1239 | +        if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) { | |
| 1240 | + return false; | |
| 1241 | + } | |
| 1242 | + | |
| 1243 | +        if (!empty($newHash)) { | |
| 1244 | + $share->setPassword($newHash); | |
| 1245 | + $provider = $this->factory->getProviderForType($share->getShareType()); | |
| 1246 | + $provider->update($share); | |
| 1247 | + } | |
| 1248 | + | |
| 1249 | + return true; | |
| 1250 | + } | |
| 1251 | + | |
| 1252 | + /** | |
| 1253 | + * @inheritdoc | |
| 1254 | + */ | |
| 1255 | +    public function userDeleted($uid) { | |
| 1256 | + $types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE, \OCP\Share::SHARE_TYPE_EMAIL]; | |
| 1257 | + | |
| 1258 | +        foreach ($types as $type) { | |
| 1259 | +            try { | |
| 1260 | + $provider = $this->factory->getProviderForType($type); | |
| 1261 | +            } catch (ProviderException $e) { | |
| 1262 | + continue; | |
| 1263 | + } | |
| 1264 | + $provider->userDeleted($uid, $type); | |
| 1265 | + } | |
| 1266 | + } | |
| 1267 | + | |
| 1268 | + /** | |
| 1269 | + * @inheritdoc | |
| 1270 | + */ | |
| 1271 | +    public function groupDeleted($gid) { | |
| 1272 | + $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP); | |
| 1273 | + $provider->groupDeleted($gid); | |
| 1274 | + } | |
| 1275 | + | |
| 1276 | + /** | |
| 1277 | + * @inheritdoc | |
| 1278 | + */ | |
| 1279 | +    public function userDeletedFromGroup($uid, $gid) { | |
| 1280 | + $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP); | |
| 1281 | + $provider->userDeletedFromGroup($uid, $gid); | |
| 1282 | + } | |
| 1283 | + | |
| 1284 | + /** | |
| 1285 | + * Get access list to a path. This means | |
| 1286 | + * all the users that can access a given path. | |
| 1287 | + * | |
| 1288 | + * Consider: | |
| 1289 | + * -root | |
| 1290 | + * |-folder1 (23) | |
| 1291 | + * |-folder2 (32) | |
| 1292 | + * |-fileA (42) | |
| 1293 | + * | |
| 1294 | + * fileA is shared with user1 and user1@server1 | |
| 1295 | + * folder2 is shared with group2 (user4 is a member of group2) | |
| 1296 | + * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2 | |
| 1297 | + * | |
| 1298 | + * Then the access list to '/folder1/folder2/fileA' with $currentAccess is: | |
| 1299 | + * [ | |
| 1300 | + * users => [ | |
| 1301 | + * 'user1' => ['node_id' => 42, 'node_path' => '/fileA'], | |
| 1302 | + * 'user4' => ['node_id' => 32, 'node_path' => '/folder2'], | |
| 1303 | + * 'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'], | |
| 1304 | + * ], | |
| 1305 | + * remote => [ | |
| 1306 | + * 'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'], | |
| 1307 | + * 'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'], | |
| 1308 | + * ], | |
| 1309 | + * public => bool | |
| 1310 | + * mail => bool | |
| 1311 | + * ] | |
| 1312 | + * | |
| 1313 | + * The access list to '/folder1/folder2/fileA' **without** $currentAccess is: | |
| 1314 | + * [ | |
| 1315 | + * users => ['user1', 'user2', 'user4'], | |
| 1316 | + * remote => bool, | |
| 1317 | + * public => bool | |
| 1318 | + * mail => bool | |
| 1319 | + * ] | |
| 1320 | + * | |
| 1321 | + * This is required for encryption/activity | |
| 1322 | + * | |
| 1323 | + * @param \OCP\Files\Node $path | |
| 1324 | + * @param bool $recursive Should we check all parent folders as well | |
| 1325 | + * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it) | |
| 1326 | + * @return array | |
| 1327 | + */ | |
| 1328 | +    public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) { | |
| 1329 | + $owner = $path->getOwner()->getUID(); | |
| 1330 | + | |
| 1331 | +        if ($currentAccess) { | |
| 1332 | + $al = ['users' => [], 'remote' => [], 'public' => false]; | |
| 1333 | +        } else { | |
| 1334 | + $al = ['users' => [], 'remote' => false, 'public' => false]; | |
| 1335 | + } | |
| 1336 | +        if (!$this->userManager->userExists($owner)) { | |
| 1337 | + return $al; | |
| 1338 | + } | |
| 1339 | + | |
| 1340 | + //Get node for the owner | |
| 1341 | + $userFolder = $this->rootFolder->getUserFolder($owner); | |
| 1342 | +        if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) { | |
| 1343 | + $path = $userFolder->getById($path->getId())[0]; | |
| 1344 | + } | |
| 1345 | + | |
| 1346 | + $providers = $this->factory->getAllProviders(); | |
| 1347 | + | |
| 1348 | + /** @var Node[] $nodes */ | |
| 1349 | + $nodes = []; | |
| 1350 | + | |
| 1351 | + | |
| 1352 | +        if ($currentAccess) { | |
| 1353 | + $ownerPath = $path->getPath(); | |
| 1354 | +            $ownerPath = explode('/', $ownerPath, 4); | |
| 1355 | +            if (count($ownerPath) < 4) { | |
| 1356 | + $ownerPath = ''; | |
| 1357 | +            } else { | |
| 1358 | + $ownerPath = $ownerPath[3]; | |
| 1359 | + } | |
| 1360 | + $al['users'][$owner] = [ | |
| 1361 | + 'node_id' => $path->getId(), | |
| 1362 | + 'node_path' => '/' . $ownerPath, | |
| 1363 | + ]; | |
| 1364 | +        } else { | |
| 1365 | + $al['users'][] = $owner; | |
| 1366 | + } | |
| 1367 | + | |
| 1368 | + // Collect all the shares | |
| 1369 | +        while ($path->getPath() !== $userFolder->getPath()) { | |
| 1370 | + $nodes[] = $path; | |
| 1371 | +            if (!$recursive) { | |
| 1372 | + break; | |
| 1373 | + } | |
| 1374 | + $path = $path->getParent(); | |
| 1375 | + } | |
| 1376 | + | |
| 1377 | +        foreach ($providers as $provider) { | |
| 1378 | + $tmp = $provider->getAccessList($nodes, $currentAccess); | |
| 1379 | + | |
| 1380 | +            foreach ($tmp as $k => $v) { | |
| 1381 | +                if (isset($al[$k])) { | |
| 1382 | +                    if (is_array($al[$k])) { | |
| 1383 | + $al[$k] = array_merge($al[$k], $v); | |
| 1384 | +                    } else { | |
| 1385 | + $al[$k] = $al[$k] || $v; | |
| 1386 | + } | |
| 1387 | +                } else { | |
| 1388 | + $al[$k] = $v; | |
| 1389 | + } | |
| 1390 | + } | |
| 1391 | + } | |
| 1392 | + | |
| 1393 | + return $al; | |
| 1394 | + } | |
| 1395 | + | |
| 1396 | + /** | |
| 1397 | + * Create a new share | |
| 1398 | + * @return \OCP\Share\IShare | |
| 1399 | + */ | |
| 1400 | +    public function newShare() { | |
| 1401 | + return new \OC\Share20\Share($this->rootFolder, $this->userManager); | |
| 1402 | + } | |
| 1403 | + | |
| 1404 | + /** | |
| 1405 | + * Is the share API enabled | |
| 1406 | + * | |
| 1407 | + * @return bool | |
| 1408 | + */ | |
| 1409 | +    public function shareApiEnabled() { | |
| 1410 | +        return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes'; | |
| 1411 | + } | |
| 1412 | + | |
| 1413 | + /** | |
| 1414 | + * Is public link sharing enabled | |
| 1415 | + * | |
| 1416 | + * @return bool | |
| 1417 | + */ | |
| 1418 | +    public function shareApiAllowLinks() { | |
| 1419 | +        return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes'; | |
| 1420 | + } | |
| 1421 | + | |
| 1422 | + /** | |
| 1423 | + * Is password on public link requires | |
| 1424 | + * | |
| 1425 | + * @return bool | |
| 1426 | + */ | |
| 1427 | +    public function shareApiLinkEnforcePassword() { | |
| 1428 | +        return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes'; | |
| 1429 | + } | |
| 1430 | + | |
| 1431 | + /** | |
| 1432 | + * Is default expire date enabled | |
| 1433 | + * | |
| 1434 | + * @return bool | |
| 1435 | + */ | |
| 1436 | +    public function shareApiLinkDefaultExpireDate() { | |
| 1437 | +        return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes'; | |
| 1438 | + } | |
| 1439 | + | |
| 1440 | + /** | |
| 1441 | + * Is default expire date enforced | |
| 1442 | + *` | |
| 1443 | + * @return bool | |
| 1444 | + */ | |
| 1445 | +    public function shareApiLinkDefaultExpireDateEnforced() { | |
| 1446 | + return $this->shareApiLinkDefaultExpireDate() && | |
| 1447 | +            $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes'; | |
| 1448 | + } | |
| 1449 | + | |
| 1450 | + /** | |
| 1451 | + * Number of default expire days | |
| 1452 | + *shareApiLinkAllowPublicUpload | |
| 1453 | + * @return int | |
| 1454 | + */ | |
| 1455 | +    public function shareApiLinkDefaultExpireDays() { | |
| 1456 | +        return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7'); | |
| 1457 | + } | |
| 1458 | + | |
| 1459 | + /** | |
| 1460 | + * Allow public upload on link shares | |
| 1461 | + * | |
| 1462 | + * @return bool | |
| 1463 | + */ | |
| 1464 | +    public function shareApiLinkAllowPublicUpload() { | |
| 1465 | +        return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes'; | |
| 1466 | + } | |
| 1467 | + | |
| 1468 | + /** | |
| 1469 | + * check if user can only share with group members | |
| 1470 | + * @return bool | |
| 1471 | + */ | |
| 1472 | +    public function shareWithGroupMembersOnly() { | |
| 1473 | +        return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes'; | |
| 1474 | + } | |
| 1475 | + | |
| 1476 | + /** | |
| 1477 | + * Check if users can share with groups | |
| 1478 | + * @return bool | |
| 1479 | + */ | |
| 1480 | +    public function allowGroupSharing() { | |
| 1481 | +        return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes'; | |
| 1482 | + } | |
| 1483 | + | |
| 1484 | + /** | |
| 1485 | + * Copied from \OC_Util::isSharingDisabledForUser | |
| 1486 | + * | |
| 1487 | + * TODO: Deprecate fuction from OC_Util | |
| 1488 | + * | |
| 1489 | + * @param string $userId | |
| 1490 | + * @return bool | |
| 1491 | + */ | |
| 1492 | +    public function sharingDisabledForUser($userId) { | |
| 1493 | +        if ($userId === null) { | |
| 1494 | + return false; | |
| 1495 | + } | |
| 1496 | + | |
| 1497 | +        if (isset($this->sharingDisabledForUsersCache[$userId])) { | |
| 1498 | + return $this->sharingDisabledForUsersCache[$userId]; | |
| 1499 | + } | |
| 1500 | + | |
| 1501 | +        if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') { | |
| 1502 | +            $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', ''); | |
| 1503 | + $excludedGroups = json_decode($groupsList); | |
| 1504 | +            if (is_null($excludedGroups)) { | |
| 1505 | +                $excludedGroups = explode(',', $groupsList); | |
| 1506 | + $newValue = json_encode($excludedGroups); | |
| 1507 | +                $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue); | |
| 1508 | + } | |
| 1509 | + $user = $this->userManager->get($userId); | |
| 1510 | + $usersGroups = $this->groupManager->getUserGroupIds($user); | |
| 1511 | +            if (!empty($usersGroups)) { | |
| 1512 | + $remainingGroups = array_diff($usersGroups, $excludedGroups); | |
| 1513 | + // if the user is only in groups which are disabled for sharing then | |
| 1514 | + // sharing is also disabled for the user | |
| 1515 | +                if (empty($remainingGroups)) { | |
| 1516 | + $this->sharingDisabledForUsersCache[$userId] = true; | |
| 1517 | + return true; | |
| 1518 | + } | |
| 1519 | + } | |
| 1520 | + } | |
| 1521 | + | |
| 1522 | + $this->sharingDisabledForUsersCache[$userId] = false; | |
| 1523 | + return false; | |
| 1524 | + } | |
| 1525 | + | |
| 1526 | + /** | |
| 1527 | + * @inheritdoc | |
| 1528 | + */ | |
| 1529 | +    public function outgoingServer2ServerSharesAllowed() { | |
| 1530 | +        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes'; | |
| 1531 | + } | |
| 1532 | + | |
| 1533 | + /** | |
| 1534 | + * @inheritdoc | |
| 1535 | + */ | |
| 1536 | +    public function shareProviderExists($shareType) { | |
| 1537 | +        try { | |
| 1538 | + $this->factory->getProviderForType($shareType); | |
| 1539 | +        } catch (ProviderException $e) { | |
| 1540 | + return false; | |
| 1541 | + } | |
| 1542 | + | |
| 1543 | + return true; | |
| 1544 | + } | |
| 1545 | 1545 | |
| 1546 | 1546 | } | 
| @@ -61,1196 +61,1196 @@ | ||
| 61 | 61 | * upgrading and removing apps. | 
| 62 | 62 | */ | 
| 63 | 63 |  class OC_App { | 
| 64 | - static private $appVersion = []; | |
| 65 | - static private $adminForms = array(); | |
| 66 | - static private $personalForms = array(); | |
| 67 | - static private $appInfo = array(); | |
| 68 | - static private $appTypes = array(); | |
| 69 | - static private $loadedApps = array(); | |
| 70 | - static private $altLogin = array(); | |
| 71 | - static private $alreadyRegistered = []; | |
| 72 | - const officialApp = 200; | |
| 73 | - | |
| 74 | - /** | |
| 75 | - * clean the appId | |
| 76 | - * | |
| 77 | - * @param string|boolean $app AppId that needs to be cleaned | |
| 78 | - * @return string | |
| 79 | - */ | |
| 80 | -	public static function cleanAppId($app) { | |
| 81 | -		return str_replace(array('\0', '/', '\\', '..'), '', $app); | |
| 82 | - } | |
| 83 | - | |
| 84 | - /** | |
| 85 | - * Check if an app is loaded | |
| 86 | - * | |
| 87 | - * @param string $app | |
| 88 | - * @return bool | |
| 89 | - */ | |
| 90 | -	public static function isAppLoaded($app) { | |
| 91 | - return in_array($app, self::$loadedApps, true); | |
| 92 | - } | |
| 93 | - | |
| 94 | - /** | |
| 95 | - * loads all apps | |
| 96 | - * | |
| 97 | - * @param string[] | string | null $types | |
| 98 | - * @return bool | |
| 99 | - * | |
| 100 | - * This function walks through the ownCloud directory and loads all apps | |
| 101 | - * it can find. A directory contains an app if the file /appinfo/info.xml | |
| 102 | - * exists. | |
| 103 | - * | |
| 104 | - * if $types is set, only apps of those types will be loaded | |
| 105 | - */ | |
| 106 | -	public static function loadApps($types = null) { | |
| 107 | -		if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) { | |
| 108 | - return false; | |
| 109 | - } | |
| 110 | - // Load the enabled apps here | |
| 111 | - $apps = self::getEnabledApps(); | |
| 112 | - | |
| 113 | - // Add each apps' folder as allowed class path | |
| 114 | -		foreach($apps as $app) { | |
| 115 | - $path = self::getAppPath($app); | |
| 116 | -			if($path !== false) { | |
| 117 | - self::registerAutoloading($app, $path); | |
| 118 | - } | |
| 119 | - } | |
| 120 | - | |
| 121 | - // prevent app.php from printing output | |
| 122 | - ob_start(); | |
| 123 | -		foreach ($apps as $app) { | |
| 124 | -			if ((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) { | |
| 125 | - self::loadApp($app); | |
| 126 | - } | |
| 127 | - } | |
| 128 | - ob_end_clean(); | |
| 129 | - | |
| 130 | - return true; | |
| 131 | - } | |
| 132 | - | |
| 133 | - /** | |
| 134 | - * load a single app | |
| 135 | - * | |
| 136 | - * @param string $app | |
| 137 | - */ | |
| 138 | -	public static function loadApp($app) { | |
| 139 | - self::$loadedApps[] = $app; | |
| 140 | - $appPath = self::getAppPath($app); | |
| 141 | -		if($appPath === false) { | |
| 142 | - return; | |
| 143 | - } | |
| 144 | - | |
| 145 | - // in case someone calls loadApp() directly | |
| 146 | - self::registerAutoloading($app, $appPath); | |
| 147 | - | |
| 148 | -		if (is_file($appPath . '/appinfo/app.php')) { | |
| 149 | -			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app); | |
| 150 | - self::requireAppFile($app); | |
| 151 | -			if (self::isType($app, array('authentication'))) { | |
| 152 | - // since authentication apps affect the "is app enabled for group" check, | |
| 153 | - // the enabled apps cache needs to be cleared to make sure that the | |
| 154 | - // next time getEnableApps() is called it will also include apps that were | |
| 155 | - // enabled for groups | |
| 156 | - self::$enabledAppsCache = array(); | |
| 157 | - } | |
| 158 | -			\OC::$server->getEventLogger()->end('load_app_' . $app); | |
| 159 | - } | |
| 160 | - | |
| 161 | - $info = self::getAppInfo($app); | |
| 162 | -		if (!empty($info['activity']['filters'])) { | |
| 163 | -			foreach ($info['activity']['filters'] as $filter) { | |
| 164 | - \OC::$server->getActivityManager()->registerFilter($filter); | |
| 165 | - } | |
| 166 | - } | |
| 167 | -		if (!empty($info['activity']['settings'])) { | |
| 168 | -			foreach ($info['activity']['settings'] as $setting) { | |
| 169 | - \OC::$server->getActivityManager()->registerSetting($setting); | |
| 170 | - } | |
| 171 | - } | |
| 172 | -		if (!empty($info['activity']['providers'])) { | |
| 173 | -			foreach ($info['activity']['providers'] as $provider) { | |
| 174 | - \OC::$server->getActivityManager()->registerProvider($provider); | |
| 175 | - } | |
| 176 | - } | |
| 177 | -		if (!empty($info['collaboration']['plugins'])) { | |
| 178 | - // deal with one or many plugin entries | |
| 179 | - $plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ? | |
| 180 | - [$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin']; | |
| 181 | -			foreach ($plugins as $plugin) { | |
| 182 | -				if($plugin['@attributes']['type'] === 'collaborator-search') { | |
| 183 | - $pluginInfo = [ | |
| 184 | - 'shareType' => $plugin['@attributes']['share-type'], | |
| 185 | - 'class' => $plugin['@value'], | |
| 186 | - ]; | |
| 187 | - \OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo); | |
| 188 | -				} else if ($plugin['@attributes']['type'] === 'autocomplete-sort') { | |
| 189 | - \OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']); | |
| 190 | - } | |
| 191 | - } | |
| 192 | - } | |
| 193 | - } | |
| 194 | - | |
| 195 | - /** | |
| 196 | - * @internal | |
| 197 | - * @param string $app | |
| 198 | - * @param string $path | |
| 199 | - */ | |
| 200 | -	public static function registerAutoloading($app, $path) { | |
| 201 | - $key = $app . '-' . $path; | |
| 202 | -		if(isset(self::$alreadyRegistered[$key])) { | |
| 203 | - return; | |
| 204 | - } | |
| 205 | - | |
| 206 | - self::$alreadyRegistered[$key] = true; | |
| 207 | - | |
| 208 | - // Register on PSR-4 composer autoloader | |
| 209 | - $appNamespace = \OC\AppFramework\App::buildAppNamespace($app); | |
| 210 | - \OC::$server->registerNamespace($app, $appNamespace); | |
| 211 | - | |
| 212 | -		if (file_exists($path . '/composer/autoload.php')) { | |
| 213 | - require_once $path . '/composer/autoload.php'; | |
| 214 | -		} else { | |
| 215 | - \OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true); | |
| 216 | - // Register on legacy autoloader | |
| 217 | - \OC::$loader->addValidRoot($path); | |
| 218 | - } | |
| 219 | - | |
| 220 | - // Register Test namespace only when testing | |
| 221 | -		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) { | |
| 222 | - \OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true); | |
| 223 | - } | |
| 224 | - } | |
| 225 | - | |
| 226 | - /** | |
| 227 | - * Load app.php from the given app | |
| 228 | - * | |
| 229 | - * @param string $app app name | |
| 230 | - */ | |
| 231 | -	private static function requireAppFile($app) { | |
| 232 | -		try { | |
| 233 | - // encapsulated here to avoid variable scope conflicts | |
| 234 | - require_once $app . '/appinfo/app.php'; | |
| 235 | -		} catch (Error $ex) { | |
| 236 | - \OC::$server->getLogger()->logException($ex); | |
| 237 | - $blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps(); | |
| 238 | -			if (!in_array($app, $blacklist)) { | |
| 239 | - self::disable($app); | |
| 240 | - } | |
| 241 | - } | |
| 242 | - } | |
| 243 | - | |
| 244 | - /** | |
| 245 | - * check if an app is of a specific type | |
| 246 | - * | |
| 247 | - * @param string $app | |
| 248 | - * @param string|array $types | |
| 249 | - * @return bool | |
| 250 | - */ | |
| 251 | -	public static function isType($app, $types) { | |
| 252 | -		if (is_string($types)) { | |
| 253 | - $types = array($types); | |
| 254 | - } | |
| 255 | - $appTypes = self::getAppTypes($app); | |
| 256 | -		foreach ($types as $type) { | |
| 257 | -			if (array_search($type, $appTypes) !== false) { | |
| 258 | - return true; | |
| 259 | - } | |
| 260 | - } | |
| 261 | - return false; | |
| 262 | - } | |
| 263 | - | |
| 264 | - /** | |
| 265 | - * get the types of an app | |
| 266 | - * | |
| 267 | - * @param string $app | |
| 268 | - * @return array | |
| 269 | - */ | |
| 270 | -	private static function getAppTypes($app) { | |
| 271 | - //load the cache | |
| 272 | -		if (count(self::$appTypes) == 0) { | |
| 273 | - self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types'); | |
| 274 | - } | |
| 275 | - | |
| 276 | -		if (isset(self::$appTypes[$app])) { | |
| 277 | -			return explode(',', self::$appTypes[$app]); | |
| 278 | -		} else { | |
| 279 | - return array(); | |
| 280 | - } | |
| 281 | - } | |
| 282 | - | |
| 283 | - /** | |
| 284 | - * read app types from info.xml and cache them in the database | |
| 285 | - */ | |
| 286 | -	public static function setAppTypes($app) { | |
| 287 | - $appData = self::getAppInfo($app); | |
| 288 | -		if(!is_array($appData)) { | |
| 289 | - return; | |
| 290 | - } | |
| 291 | - | |
| 292 | -		if (isset($appData['types'])) { | |
| 293 | -			$appTypes = implode(',', $appData['types']); | |
| 294 | -		} else { | |
| 295 | - $appTypes = ''; | |
| 296 | - $appData['types'] = []; | |
| 297 | - } | |
| 298 | - | |
| 299 | - \OC::$server->getAppConfig()->setValue($app, 'types', $appTypes); | |
| 300 | - | |
| 301 | -		if (\OC::$server->getAppManager()->hasProtectedAppType($appData['types'])) { | |
| 302 | - $enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'yes'); | |
| 303 | -			if ($enabled !== 'yes' && $enabled !== 'no') { | |
| 304 | - \OC::$server->getAppConfig()->setValue($app, 'enabled', 'yes'); | |
| 305 | - } | |
| 306 | - } | |
| 307 | - } | |
| 308 | - | |
| 309 | - /** | |
| 310 | - * get all enabled apps | |
| 311 | - */ | |
| 312 | - protected static $enabledAppsCache = array(); | |
| 313 | - | |
| 314 | - /** | |
| 315 | - * Returns apps enabled for the current user. | |
| 316 | - * | |
| 317 | - * @param bool $forceRefresh whether to refresh the cache | |
| 318 | - * @param bool $all whether to return apps for all users, not only the | |
| 319 | - * currently logged in one | |
| 320 | - * @return string[] | |
| 321 | - */ | |
| 322 | -	public static function getEnabledApps($forceRefresh = false, $all = false) { | |
| 323 | -		if (!\OC::$server->getSystemConfig()->getValue('installed', false)) { | |
| 324 | - return array(); | |
| 325 | - } | |
| 326 | - // in incognito mode or when logged out, $user will be false, | |
| 327 | - // which is also the case during an upgrade | |
| 328 | - $appManager = \OC::$server->getAppManager(); | |
| 329 | -		if ($all) { | |
| 330 | - $user = null; | |
| 331 | -		} else { | |
| 332 | - $user = \OC::$server->getUserSession()->getUser(); | |
| 333 | - } | |
| 334 | - | |
| 335 | -		if (is_null($user)) { | |
| 336 | - $apps = $appManager->getInstalledApps(); | |
| 337 | -		} else { | |
| 338 | - $apps = $appManager->getEnabledAppsForUser($user); | |
| 339 | - } | |
| 340 | -		$apps = array_filter($apps, function ($app) { | |
| 341 | - return $app !== 'files';//we add this manually | |
| 342 | - }); | |
| 343 | - sort($apps); | |
| 344 | - array_unshift($apps, 'files'); | |
| 345 | - return $apps; | |
| 346 | - } | |
| 347 | - | |
| 348 | - /** | |
| 349 | - * checks whether or not an app is enabled | |
| 350 | - * | |
| 351 | - * @param string $app app | |
| 352 | - * @return bool | |
| 353 | - * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId) | |
| 354 | - * | |
| 355 | - * This function checks whether or not an app is enabled. | |
| 356 | - */ | |
| 357 | -	public static function isEnabled($app) { | |
| 358 | - return \OC::$server->getAppManager()->isEnabledForUser($app); | |
| 359 | - } | |
| 360 | - | |
| 361 | - /** | |
| 362 | - * enables an app | |
| 363 | - * | |
| 364 | - * @param string $appId | |
| 365 | - * @param array $groups (optional) when set, only these groups will have access to the app | |
| 366 | - * @throws \Exception | |
| 367 | - * @return void | |
| 368 | - * | |
| 369 | - * This function set an app as enabled in appconfig. | |
| 370 | - */ | |
| 371 | - public function enable($appId, | |
| 372 | -						   $groups = null) { | |
| 373 | - self::$enabledAppsCache = []; // flush | |
| 374 | - | |
| 375 | - // Check if app is already downloaded | |
| 376 | - $installer = new Installer( | |
| 377 | - \OC::$server->getAppFetcher(), | |
| 378 | - \OC::$server->getHTTPClientService(), | |
| 379 | - \OC::$server->getTempManager(), | |
| 380 | - \OC::$server->getLogger(), | |
| 381 | - \OC::$server->getConfig() | |
| 382 | - ); | |
| 383 | - $isDownloaded = $installer->isDownloaded($appId); | |
| 384 | - | |
| 385 | -		if(!$isDownloaded) { | |
| 386 | - $installer->downloadApp($appId); | |
| 387 | - } | |
| 388 | - | |
| 389 | - $installer->installApp($appId); | |
| 390 | - | |
| 391 | - $appManager = \OC::$server->getAppManager(); | |
| 392 | -		if (!is_null($groups)) { | |
| 393 | - $groupManager = \OC::$server->getGroupManager(); | |
| 394 | - $groupsList = []; | |
| 395 | -			foreach ($groups as $group) { | |
| 396 | - $groupItem = $groupManager->get($group); | |
| 397 | -				if ($groupItem instanceof \OCP\IGroup) { | |
| 398 | - $groupsList[] = $groupManager->get($group); | |
| 399 | - } | |
| 400 | - } | |
| 401 | - $appManager->enableAppForGroups($appId, $groupsList); | |
| 402 | -		} else { | |
| 403 | - $appManager->enableApp($appId); | |
| 404 | - } | |
| 405 | - } | |
| 406 | - | |
| 407 | - /** | |
| 408 | - * @param string $app | |
| 409 | - * @return bool | |
| 410 | - */ | |
| 411 | -	public static function removeApp($app) { | |
| 412 | -		if (\OC::$server->getAppManager()->isShipped($app)) { | |
| 413 | - return false; | |
| 414 | - } | |
| 415 | - | |
| 416 | - $installer = new Installer( | |
| 417 | - \OC::$server->getAppFetcher(), | |
| 418 | - \OC::$server->getHTTPClientService(), | |
| 419 | - \OC::$server->getTempManager(), | |
| 420 | - \OC::$server->getLogger(), | |
| 421 | - \OC::$server->getConfig() | |
| 422 | - ); | |
| 423 | - return $installer->removeApp($app); | |
| 424 | - } | |
| 425 | - | |
| 426 | - /** | |
| 427 | - * This function set an app as disabled in appconfig. | |
| 428 | - * | |
| 429 | - * @param string $app app | |
| 430 | - * @throws Exception | |
| 431 | - */ | |
| 432 | -	public static function disable($app) { | |
| 433 | - // flush | |
| 434 | - self::$enabledAppsCache = array(); | |
| 435 | - | |
| 436 | - // run uninstall steps | |
| 437 | - $appData = OC_App::getAppInfo($app); | |
| 438 | -		if (!is_null($appData)) { | |
| 439 | - OC_App::executeRepairSteps($app, $appData['repair-steps']['uninstall']); | |
| 440 | - } | |
| 441 | - | |
| 442 | - // emit disable hook - needed anymore ? | |
| 443 | -		\OC_Hook::emit('OC_App', 'pre_disable', array('app' => $app)); | |
| 444 | - | |
| 445 | - // finally disable it | |
| 446 | - $appManager = \OC::$server->getAppManager(); | |
| 447 | - $appManager->disableApp($app); | |
| 448 | - } | |
| 449 | - | |
| 450 | - // This is private as well. It simply works, so don't ask for more details | |
| 451 | -	private static function proceedNavigation($list) { | |
| 452 | -		usort($list, function($a, $b) { | |
| 453 | -			if (isset($a['order']) && isset($b['order'])) { | |
| 454 | - return ($a['order'] < $b['order']) ? -1 : 1; | |
| 455 | -			} else if (isset($a['order']) || isset($b['order'])) { | |
| 456 | - return isset($a['order']) ? -1 : 1; | |
| 457 | -			} else { | |
| 458 | - return ($a['name'] < $b['name']) ? -1 : 1; | |
| 459 | - } | |
| 460 | - }); | |
| 461 | - | |
| 462 | - $activeApp = OC::$server->getNavigationManager()->getActiveEntry(); | |
| 463 | -		foreach ($list as $index => &$navEntry) { | |
| 464 | -			if ($navEntry['id'] == $activeApp) { | |
| 465 | - $navEntry['active'] = true; | |
| 466 | -			} else { | |
| 467 | - $navEntry['active'] = false; | |
| 468 | - } | |
| 469 | - } | |
| 470 | - unset($navEntry); | |
| 471 | - | |
| 472 | - return $list; | |
| 473 | - } | |
| 474 | - | |
| 475 | - /** | |
| 476 | - * Get the path where to install apps | |
| 477 | - * | |
| 478 | - * @return string|false | |
| 479 | - */ | |
| 480 | -	public static function getInstallPath() { | |
| 481 | -		if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) { | |
| 482 | - return false; | |
| 483 | - } | |
| 484 | - | |
| 485 | -		foreach (OC::$APPSROOTS as $dir) { | |
| 486 | -			if (isset($dir['writable']) && $dir['writable'] === true) { | |
| 487 | - return $dir['path']; | |
| 488 | - } | |
| 489 | - } | |
| 490 | - | |
| 491 | -		\OCP\Util::writeLog('core', 'No application directories are marked as writable.', \OCP\Util::ERROR); | |
| 492 | - return null; | |
| 493 | - } | |
| 494 | - | |
| 495 | - | |
| 496 | - /** | |
| 497 | - * search for an app in all app-directories | |
| 498 | - * | |
| 499 | - * @param string $appId | |
| 500 | - * @return false|string | |
| 501 | - */ | |
| 502 | -	public static function findAppInDirectories($appId) { | |
| 503 | - $sanitizedAppId = self::cleanAppId($appId); | |
| 504 | -		if($sanitizedAppId !== $appId) { | |
| 505 | - return false; | |
| 506 | - } | |
| 507 | - static $app_dir = array(); | |
| 508 | - | |
| 509 | -		if (isset($app_dir[$appId])) { | |
| 510 | - return $app_dir[$appId]; | |
| 511 | - } | |
| 512 | - | |
| 513 | - $possibleApps = array(); | |
| 514 | -		foreach (OC::$APPSROOTS as $dir) { | |
| 515 | -			if (file_exists($dir['path'] . '/' . $appId)) { | |
| 516 | - $possibleApps[] = $dir; | |
| 517 | - } | |
| 518 | - } | |
| 519 | - | |
| 520 | -		if (empty($possibleApps)) { | |
| 521 | - return false; | |
| 522 | -		} elseif (count($possibleApps) === 1) { | |
| 523 | - $dir = array_shift($possibleApps); | |
| 524 | - $app_dir[$appId] = $dir; | |
| 525 | - return $dir; | |
| 526 | -		} else { | |
| 527 | - $versionToLoad = array(); | |
| 528 | -			foreach ($possibleApps as $possibleApp) { | |
| 529 | - $version = self::getAppVersionByPath($possibleApp['path']); | |
| 530 | -				if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) { | |
| 531 | - $versionToLoad = array( | |
| 532 | - 'dir' => $possibleApp, | |
| 533 | - 'version' => $version, | |
| 534 | - ); | |
| 535 | - } | |
| 536 | - } | |
| 537 | - $app_dir[$appId] = $versionToLoad['dir']; | |
| 538 | - return $versionToLoad['dir']; | |
| 539 | - //TODO - write test | |
| 540 | - } | |
| 541 | - } | |
| 542 | - | |
| 543 | - /** | |
| 544 | - * Get the directory for the given app. | |
| 545 | - * If the app is defined in multiple directories, the first one is taken. (false if not found) | |
| 546 | - * | |
| 547 | - * @param string $appId | |
| 548 | - * @return string|false | |
| 549 | - */ | |
| 550 | -	public static function getAppPath($appId) { | |
| 551 | -		if ($appId === null || trim($appId) === '') { | |
| 552 | - return false; | |
| 553 | - } | |
| 554 | - | |
| 555 | -		if (($dir = self::findAppInDirectories($appId)) != false) { | |
| 556 | - return $dir['path'] . '/' . $appId; | |
| 557 | - } | |
| 558 | - return false; | |
| 559 | - } | |
| 560 | - | |
| 561 | - /** | |
| 562 | - * Get the path for the given app on the access | |
| 563 | - * If the app is defined in multiple directories, the first one is taken. (false if not found) | |
| 564 | - * | |
| 565 | - * @param string $appId | |
| 566 | - * @return string|false | |
| 567 | - */ | |
| 568 | -	public static function getAppWebPath($appId) { | |
| 569 | -		if (($dir = self::findAppInDirectories($appId)) != false) { | |
| 570 | - return OC::$WEBROOT . $dir['url'] . '/' . $appId; | |
| 571 | - } | |
| 572 | - return false; | |
| 573 | - } | |
| 574 | - | |
| 575 | - /** | |
| 576 | - * get the last version of the app from appinfo/info.xml | |
| 577 | - * | |
| 578 | - * @param string $appId | |
| 579 | - * @param bool $useCache | |
| 580 | - * @return string | |
| 581 | - */ | |
| 582 | -	public static function getAppVersion($appId, $useCache = true) { | |
| 583 | -		if($useCache && isset(self::$appVersion[$appId])) { | |
| 584 | - return self::$appVersion[$appId]; | |
| 585 | - } | |
| 586 | - | |
| 587 | - $file = self::getAppPath($appId); | |
| 588 | - self::$appVersion[$appId] = ($file !== false) ? self::getAppVersionByPath($file) : '0'; | |
| 589 | - return self::$appVersion[$appId]; | |
| 590 | - } | |
| 591 | - | |
| 592 | - /** | |
| 593 | - * get app's version based on it's path | |
| 594 | - * | |
| 595 | - * @param string $path | |
| 596 | - * @return string | |
| 597 | - */ | |
| 598 | -	public static function getAppVersionByPath($path) { | |
| 599 | - $infoFile = $path . '/appinfo/info.xml'; | |
| 600 | - $appData = self::getAppInfo($infoFile, true); | |
| 601 | - return isset($appData['version']) ? $appData['version'] : ''; | |
| 602 | - } | |
| 603 | - | |
| 604 | - | |
| 605 | - /** | |
| 606 | - * Read all app metadata from the info.xml file | |
| 607 | - * | |
| 608 | - * @param string $appId id of the app or the path of the info.xml file | |
| 609 | - * @param bool $path | |
| 610 | - * @param string $lang | |
| 611 | - * @return array|null | |
| 612 | - * @note all data is read from info.xml, not just pre-defined fields | |
| 613 | - */ | |
| 614 | -	public static function getAppInfo($appId, $path = false, $lang = null) { | |
| 615 | -		if ($path) { | |
| 616 | - $file = $appId; | |
| 617 | -		} else { | |
| 618 | -			if ($lang === null && isset(self::$appInfo[$appId])) { | |
| 619 | - return self::$appInfo[$appId]; | |
| 620 | - } | |
| 621 | - $appPath = self::getAppPath($appId); | |
| 622 | -			if($appPath === false) { | |
| 623 | - return null; | |
| 624 | - } | |
| 625 | - $file = $appPath . '/appinfo/info.xml'; | |
| 626 | - } | |
| 627 | - | |
| 628 | -		$parser = new InfoParser(\OC::$server->getMemCacheFactory()->createLocal('core.appinfo')); | |
| 629 | - $data = $parser->parse($file); | |
| 630 | - | |
| 631 | -		if (is_array($data)) { | |
| 632 | - $data = OC_App::parseAppInfo($data, $lang); | |
| 633 | - } | |
| 634 | -		if(isset($data['ocsid'])) { | |
| 635 | - $storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid'); | |
| 636 | -			if($storedId !== '' && $storedId !== $data['ocsid']) { | |
| 637 | - $data['ocsid'] = $storedId; | |
| 638 | - } | |
| 639 | - } | |
| 640 | - | |
| 641 | -		if ($lang === null) { | |
| 642 | - self::$appInfo[$appId] = $data; | |
| 643 | - } | |
| 644 | - | |
| 645 | - return $data; | |
| 646 | - } | |
| 647 | - | |
| 648 | - /** | |
| 649 | - * Returns the navigation | |
| 650 | - * | |
| 651 | - * @return array | |
| 652 | - * | |
| 653 | - * This function returns an array containing all entries added. The | |
| 654 | - * entries are sorted by the key 'order' ascending. Additional to the keys | |
| 655 | - * given for each app the following keys exist: | |
| 656 | - * - active: boolean, signals if the user is on this navigation entry | |
| 657 | - */ | |
| 658 | -	public static function getNavigation() { | |
| 659 | - $entries = OC::$server->getNavigationManager()->getAll(); | |
| 660 | - return self::proceedNavigation($entries); | |
| 661 | - } | |
| 662 | - | |
| 663 | - /** | |
| 664 | - * Returns the Settings Navigation | |
| 665 | - * | |
| 666 | - * @return string[] | |
| 667 | - * | |
| 668 | - * This function returns an array containing all settings pages added. The | |
| 669 | - * entries are sorted by the key 'order' ascending. | |
| 670 | - */ | |
| 671 | -	public static function getSettingsNavigation() { | |
| 672 | -		$entries = OC::$server->getNavigationManager()->getAll('settings'); | |
| 673 | - return self::proceedNavigation($entries); | |
| 674 | - } | |
| 675 | - | |
| 676 | - /** | |
| 677 | - * get the id of loaded app | |
| 678 | - * | |
| 679 | - * @return string | |
| 680 | - */ | |
| 681 | -	public static function getCurrentApp() { | |
| 682 | - $request = \OC::$server->getRequest(); | |
| 683 | - $script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1); | |
| 684 | - $topFolder = substr($script, 0, strpos($script, '/')); | |
| 685 | -		if (empty($topFolder)) { | |
| 686 | - $path_info = $request->getPathInfo(); | |
| 687 | -			if ($path_info) { | |
| 688 | - $topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1); | |
| 689 | - } | |
| 690 | - } | |
| 691 | -		if ($topFolder == 'apps') { | |
| 692 | - $length = strlen($topFolder); | |
| 693 | - return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1); | |
| 694 | -		} else { | |
| 695 | - return $topFolder; | |
| 696 | - } | |
| 697 | - } | |
| 698 | - | |
| 699 | - /** | |
| 700 | - * @param string $type | |
| 701 | - * @return array | |
| 702 | - */ | |
| 703 | -	public static function getForms($type) { | |
| 704 | - $forms = array(); | |
| 705 | -		switch ($type) { | |
| 706 | - case 'admin': | |
| 707 | - $source = self::$adminForms; | |
| 708 | - break; | |
| 709 | - case 'personal': | |
| 710 | - $source = self::$personalForms; | |
| 711 | - break; | |
| 712 | - default: | |
| 713 | - return array(); | |
| 714 | - } | |
| 715 | -		foreach ($source as $form) { | |
| 716 | - $forms[] = include $form; | |
| 717 | - } | |
| 718 | - return $forms; | |
| 719 | - } | |
| 720 | - | |
| 721 | - /** | |
| 722 | - * register an admin form to be shown | |
| 723 | - * | |
| 724 | - * @param string $app | |
| 725 | - * @param string $page | |
| 726 | - */ | |
| 727 | -	public static function registerAdmin($app, $page) { | |
| 728 | - self::$adminForms[] = $app . '/' . $page . '.php'; | |
| 729 | - } | |
| 730 | - | |
| 731 | - /** | |
| 732 | - * register a personal form to be shown | |
| 733 | - * @param string $app | |
| 734 | - * @param string $page | |
| 735 | - */ | |
| 736 | -	public static function registerPersonal($app, $page) { | |
| 737 | - self::$personalForms[] = $app . '/' . $page . '.php'; | |
| 738 | - } | |
| 739 | - | |
| 740 | - /** | |
| 741 | - * @param array $entry | |
| 742 | - */ | |
| 743 | -	public static function registerLogIn(array $entry) { | |
| 744 | - self::$altLogin[] = $entry; | |
| 745 | - } | |
| 746 | - | |
| 747 | - /** | |
| 748 | - * @return array | |
| 749 | - */ | |
| 750 | -	public static function getAlternativeLogIns() { | |
| 751 | - return self::$altLogin; | |
| 752 | - } | |
| 753 | - | |
| 754 | - /** | |
| 755 | - * get a list of all apps in the apps folder | |
| 756 | - * | |
| 757 | - * @return array an array of app names (string IDs) | |
| 758 | - * @todo: change the name of this method to getInstalledApps, which is more accurate | |
| 759 | - */ | |
| 760 | -	public static function getAllApps() { | |
| 761 | - | |
| 762 | - $apps = array(); | |
| 763 | - | |
| 764 | -		foreach (OC::$APPSROOTS as $apps_dir) { | |
| 765 | -			if (!is_readable($apps_dir['path'])) { | |
| 766 | -				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN); | |
| 767 | - continue; | |
| 768 | - } | |
| 769 | - $dh = opendir($apps_dir['path']); | |
| 770 | - | |
| 771 | -			if (is_resource($dh)) { | |
| 772 | -				while (($file = readdir($dh)) !== false) { | |
| 773 | - | |
| 774 | -					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) { | |
| 775 | - | |
| 776 | - $apps[] = $file; | |
| 777 | - } | |
| 778 | - } | |
| 779 | - } | |
| 780 | - } | |
| 781 | - | |
| 782 | - $apps = array_unique($apps); | |
| 783 | - | |
| 784 | - return $apps; | |
| 785 | - } | |
| 786 | - | |
| 787 | - /** | |
| 788 | - * List all apps, this is used in apps.php | |
| 789 | - * | |
| 790 | - * @return array | |
| 791 | - */ | |
| 792 | -	public function listAllApps() { | |
| 793 | - $installedApps = OC_App::getAllApps(); | |
| 794 | - | |
| 795 | - $appManager = \OC::$server->getAppManager(); | |
| 796 | - //we don't want to show configuration for these | |
| 797 | - $blacklist = $appManager->getAlwaysEnabledApps(); | |
| 798 | - $appList = array(); | |
| 799 | -		$langCode = \OC::$server->getL10N('core')->getLanguageCode(); | |
| 800 | - $urlGenerator = \OC::$server->getURLGenerator(); | |
| 801 | - | |
| 802 | -		foreach ($installedApps as $app) { | |
| 803 | -			if (array_search($app, $blacklist) === false) { | |
| 804 | - | |
| 805 | - $info = OC_App::getAppInfo($app, false, $langCode); | |
| 806 | -				if (!is_array($info)) { | |
| 807 | -					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR); | |
| 808 | - continue; | |
| 809 | - } | |
| 810 | - | |
| 811 | -				if (!isset($info['name'])) { | |
| 812 | -					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR); | |
| 813 | - continue; | |
| 814 | - } | |
| 815 | - | |
| 816 | - $enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'no'); | |
| 817 | - $info['groups'] = null; | |
| 818 | -				if ($enabled === 'yes') { | |
| 819 | - $active = true; | |
| 820 | -				} else if ($enabled === 'no') { | |
| 821 | - $active = false; | |
| 822 | -				} else { | |
| 823 | - $active = true; | |
| 824 | - $info['groups'] = $enabled; | |
| 825 | - } | |
| 826 | - | |
| 827 | - $info['active'] = $active; | |
| 828 | - | |
| 829 | -				if ($appManager->isShipped($app)) { | |
| 830 | - $info['internal'] = true; | |
| 831 | - $info['level'] = self::officialApp; | |
| 832 | - $info['removable'] = false; | |
| 833 | -				} else { | |
| 834 | - $info['internal'] = false; | |
| 835 | - $info['removable'] = true; | |
| 836 | - } | |
| 837 | - | |
| 838 | - $appPath = self::getAppPath($app); | |
| 839 | -				if($appPath !== false) { | |
| 840 | - $appIcon = $appPath . '/img/' . $app . '.svg'; | |
| 841 | -					if (file_exists($appIcon)) { | |
| 842 | - $info['preview'] = $urlGenerator->imagePath($app, $app . '.svg'); | |
| 843 | - $info['previewAsIcon'] = true; | |
| 844 | -					} else { | |
| 845 | - $appIcon = $appPath . '/img/app.svg'; | |
| 846 | -						if (file_exists($appIcon)) { | |
| 847 | - $info['preview'] = $urlGenerator->imagePath($app, 'app.svg'); | |
| 848 | - $info['previewAsIcon'] = true; | |
| 849 | - } | |
| 850 | - } | |
| 851 | - } | |
| 852 | - // fix documentation | |
| 853 | -				if (isset($info['documentation']) && is_array($info['documentation'])) { | |
| 854 | -					foreach ($info['documentation'] as $key => $url) { | |
| 855 | - // If it is not an absolute URL we assume it is a key | |
| 856 | - // i.e. admin-ldap will get converted to go.php?to=admin-ldap | |
| 857 | -						if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) { | |
| 858 | - $url = $urlGenerator->linkToDocs($url); | |
| 859 | - } | |
| 860 | - | |
| 861 | - $info['documentation'][$key] = $url; | |
| 862 | - } | |
| 863 | - } | |
| 864 | - | |
| 865 | - $info['version'] = OC_App::getAppVersion($app); | |
| 866 | - $appList[] = $info; | |
| 867 | - } | |
| 868 | - } | |
| 869 | - | |
| 870 | - return $appList; | |
| 871 | - } | |
| 872 | - | |
| 873 | -	public static function shouldUpgrade($app) { | |
| 874 | - $versions = self::getAppVersions(); | |
| 875 | - $currentVersion = OC_App::getAppVersion($app); | |
| 876 | -		if ($currentVersion && isset($versions[$app])) { | |
| 877 | - $installedVersion = $versions[$app]; | |
| 878 | -			if (!version_compare($currentVersion, $installedVersion, '=')) { | |
| 879 | - return true; | |
| 880 | - } | |
| 881 | - } | |
| 882 | - return false; | |
| 883 | - } | |
| 884 | - | |
| 885 | - /** | |
| 886 | - * Adjust the number of version parts of $version1 to match | |
| 887 | - * the number of version parts of $version2. | |
| 888 | - * | |
| 889 | - * @param string $version1 version to adjust | |
| 890 | - * @param string $version2 version to take the number of parts from | |
| 891 | - * @return string shortened $version1 | |
| 892 | - */ | |
| 893 | -	private static function adjustVersionParts($version1, $version2) { | |
| 894 | -		$version1 = explode('.', $version1); | |
| 895 | -		$version2 = explode('.', $version2); | |
| 896 | - // reduce $version1 to match the number of parts in $version2 | |
| 897 | -		while (count($version1) > count($version2)) { | |
| 898 | - array_pop($version1); | |
| 899 | - } | |
| 900 | - // if $version1 does not have enough parts, add some | |
| 901 | -		while (count($version1) < count($version2)) { | |
| 902 | - $version1[] = '0'; | |
| 903 | - } | |
| 904 | -		return implode('.', $version1); | |
| 905 | - } | |
| 906 | - | |
| 907 | - /** | |
| 908 | - * Check whether the current ownCloud version matches the given | |
| 909 | - * application's version requirements. | |
| 910 | - * | |
| 911 | - * The comparison is made based on the number of parts that the | |
| 912 | - * app info version has. For example for ownCloud 6.0.3 if the | |
| 913 | - * app info version is expecting version 6.0, the comparison is | |
| 914 | - * made on the first two parts of the ownCloud version. | |
| 915 | - * This means that it's possible to specify "requiremin" => 6 | |
| 916 | - * and "requiremax" => 6 and it will still match ownCloud 6.0.3. | |
| 917 | - * | |
| 918 | - * @param string $ocVersion ownCloud version to check against | |
| 919 | - * @param array $appInfo app info (from xml) | |
| 920 | - * | |
| 921 | - * @return boolean true if compatible, otherwise false | |
| 922 | - */ | |
| 923 | -	public static function isAppCompatible($ocVersion, $appInfo) { | |
| 924 | - $requireMin = ''; | |
| 925 | - $requireMax = ''; | |
| 926 | -		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) { | |
| 927 | - $requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version']; | |
| 928 | -		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) { | |
| 929 | - $requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version']; | |
| 930 | -		} else if (isset($appInfo['requiremin'])) { | |
| 931 | - $requireMin = $appInfo['requiremin']; | |
| 932 | -		} else if (isset($appInfo['require'])) { | |
| 933 | - $requireMin = $appInfo['require']; | |
| 934 | - } | |
| 935 | - | |
| 936 | -		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) { | |
| 937 | - $requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version']; | |
| 938 | -		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) { | |
| 939 | - $requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version']; | |
| 940 | -		} else if (isset($appInfo['requiremax'])) { | |
| 941 | - $requireMax = $appInfo['requiremax']; | |
| 942 | - } | |
| 943 | - | |
| 944 | -		if (is_array($ocVersion)) { | |
| 945 | -			$ocVersion = implode('.', $ocVersion); | |
| 946 | - } | |
| 947 | - | |
| 948 | - if (!empty($requireMin) | |
| 949 | - && version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<') | |
| 950 | -		) { | |
| 951 | - | |
| 952 | - return false; | |
| 953 | - } | |
| 954 | - | |
| 955 | - if (!empty($requireMax) | |
| 956 | - && version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>') | |
| 957 | -		) { | |
| 958 | - return false; | |
| 959 | - } | |
| 960 | - | |
| 961 | - return true; | |
| 962 | - } | |
| 963 | - | |
| 964 | - /** | |
| 965 | - * get the installed version of all apps | |
| 966 | - */ | |
| 967 | -	public static function getAppVersions() { | |
| 968 | - static $versions; | |
| 969 | - | |
| 970 | -		if(!$versions) { | |
| 971 | - $appConfig = \OC::$server->getAppConfig(); | |
| 972 | - $versions = $appConfig->getValues(false, 'installed_version'); | |
| 973 | - } | |
| 974 | - return $versions; | |
| 975 | - } | |
| 976 | - | |
| 977 | - /** | |
| 978 | - * @param string $app | |
| 979 | - * @param \OCP\IConfig $config | |
| 980 | - * @param \OCP\IL10N $l | |
| 981 | - * @return bool | |
| 982 | - * | |
| 983 | - * @throws Exception if app is not compatible with this version of ownCloud | |
| 984 | - * @throws Exception if no app-name was specified | |
| 985 | - */ | |
| 986 | - public function installApp($app, | |
| 987 | - \OCP\IConfig $config, | |
| 988 | -							   \OCP\IL10N $l) { | |
| 989 | -		if ($app !== false) { | |
| 990 | - // check if the app is compatible with this version of ownCloud | |
| 991 | - $info = self::getAppInfo($app); | |
| 992 | -			if(!is_array($info)) { | |
| 993 | - throw new \Exception( | |
| 994 | -					$l->t('App "%s" cannot be installed because appinfo file cannot be read.', | |
| 995 | - [$info['name']] | |
| 996 | - ) | |
| 997 | - ); | |
| 998 | - } | |
| 999 | - | |
| 1000 | - $version = \OCP\Util::getVersion(); | |
| 1001 | -			if (!self::isAppCompatible($version, $info)) { | |
| 1002 | - throw new \Exception( | |
| 1003 | -					$l->t('App "%s" cannot be installed because it is not compatible with this version of the server.', | |
| 1004 | - array($info['name']) | |
| 1005 | - ) | |
| 1006 | - ); | |
| 1007 | - } | |
| 1008 | - | |
| 1009 | - // check for required dependencies | |
| 1010 | - self::checkAppDependencies($config, $l, $info); | |
| 1011 | - | |
| 1012 | - $config->setAppValue($app, 'enabled', 'yes'); | |
| 1013 | -			if (isset($appData['id'])) { | |
| 1014 | - $config->setAppValue($app, 'ocsid', $appData['id']); | |
| 1015 | - } | |
| 1016 | - | |
| 1017 | -			if(isset($info['settings']) && is_array($info['settings'])) { | |
| 1018 | - $appPath = self::getAppPath($app); | |
| 1019 | - self::registerAutoloading($app, $appPath); | |
| 1020 | - \OC::$server->getSettingsManager()->setupSettings($info['settings']); | |
| 1021 | - } | |
| 1022 | - | |
| 1023 | -			\OC_Hook::emit('OC_App', 'post_enable', array('app' => $app)); | |
| 1024 | -		} else { | |
| 1025 | -			if(empty($appName) ) { | |
| 1026 | -				throw new \Exception($l->t("No app name specified")); | |
| 1027 | -			} else { | |
| 1028 | -				throw new \Exception($l->t("App '%s' could not be installed!", $appName)); | |
| 1029 | - } | |
| 1030 | - } | |
| 1031 | - | |
| 1032 | - return $app; | |
| 1033 | - } | |
| 1034 | - | |
| 1035 | - /** | |
| 1036 | - * update the database for the app and call the update script | |
| 1037 | - * | |
| 1038 | - * @param string $appId | |
| 1039 | - * @return bool | |
| 1040 | - */ | |
| 1041 | -	public static function updateApp($appId) { | |
| 1042 | - $appPath = self::getAppPath($appId); | |
| 1043 | -		if($appPath === false) { | |
| 1044 | - return false; | |
| 1045 | - } | |
| 1046 | - self::registerAutoloading($appId, $appPath); | |
| 1047 | - | |
| 1048 | - $appData = self::getAppInfo($appId); | |
| 1049 | - self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']); | |
| 1050 | - | |
| 1051 | -		if (file_exists($appPath . '/appinfo/database.xml')) { | |
| 1052 | - OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml'); | |
| 1053 | -		} else { | |
| 1054 | - $ms = new MigrationService($appId, \OC::$server->getDatabaseConnection()); | |
| 1055 | - $ms->migrate(); | |
| 1056 | - } | |
| 1057 | - | |
| 1058 | - self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']); | |
| 1059 | - self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']); | |
| 1060 | - unset(self::$appVersion[$appId]); | |
| 1061 | - | |
| 1062 | - // run upgrade code | |
| 1063 | -		if (file_exists($appPath . '/appinfo/update.php')) { | |
| 1064 | - self::loadApp($appId); | |
| 1065 | - include $appPath . '/appinfo/update.php'; | |
| 1066 | - } | |
| 1067 | - self::setupBackgroundJobs($appData['background-jobs']); | |
| 1068 | -		if(isset($appData['settings']) && is_array($appData['settings'])) { | |
| 1069 | - \OC::$server->getSettingsManager()->setupSettings($appData['settings']); | |
| 1070 | - } | |
| 1071 | - | |
| 1072 | - //set remote/public handlers | |
| 1073 | -		if (array_key_exists('ocsid', $appData)) { | |
| 1074 | - \OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']); | |
| 1075 | -		} elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) { | |
| 1076 | - \OC::$server->getConfig()->deleteAppValue($appId, 'ocsid'); | |
| 1077 | - } | |
| 1078 | -		foreach ($appData['remote'] as $name => $path) { | |
| 1079 | -			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path); | |
| 1080 | - } | |
| 1081 | -		foreach ($appData['public'] as $name => $path) { | |
| 1082 | -			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path); | |
| 1083 | - } | |
| 1084 | - | |
| 1085 | - self::setAppTypes($appId); | |
| 1086 | - | |
| 1087 | - $version = \OC_App::getAppVersion($appId); | |
| 1088 | - \OC::$server->getAppConfig()->setValue($appId, 'installed_version', $version); | |
| 1089 | - | |
| 1090 | - \OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent( | |
| 1091 | - ManagerEvent::EVENT_APP_UPDATE, $appId | |
| 1092 | - )); | |
| 1093 | - | |
| 1094 | - return true; | |
| 1095 | - } | |
| 1096 | - | |
| 1097 | - /** | |
| 1098 | - * @param string $appId | |
| 1099 | - * @param string[] $steps | |
| 1100 | - * @throws \OC\NeedsUpdateException | |
| 1101 | - */ | |
| 1102 | -	public static function executeRepairSteps($appId, array $steps) { | |
| 1103 | -		if (empty($steps)) { | |
| 1104 | - return; | |
| 1105 | - } | |
| 1106 | - // load the app | |
| 1107 | - self::loadApp($appId); | |
| 1108 | - | |
| 1109 | - $dispatcher = OC::$server->getEventDispatcher(); | |
| 1110 | - | |
| 1111 | - // load the steps | |
| 1112 | - $r = new Repair([], $dispatcher); | |
| 1113 | -		foreach ($steps as $step) { | |
| 1114 | -			try { | |
| 1115 | - $r->addStep($step); | |
| 1116 | -			} catch (Exception $ex) { | |
| 1117 | -				$r->emit('\OC\Repair', 'error', [$ex->getMessage()]); | |
| 1118 | - \OC::$server->getLogger()->logException($ex); | |
| 1119 | - } | |
| 1120 | - } | |
| 1121 | - // run the steps | |
| 1122 | - $r->run(); | |
| 1123 | - } | |
| 1124 | - | |
| 1125 | -	public static function setupBackgroundJobs(array $jobs) { | |
| 1126 | - $queue = \OC::$server->getJobList(); | |
| 1127 | -		foreach ($jobs as $job) { | |
| 1128 | - $queue->add($job); | |
| 1129 | - } | |
| 1130 | - } | |
| 1131 | - | |
| 1132 | - /** | |
| 1133 | - * @param string $appId | |
| 1134 | - * @param string[] $steps | |
| 1135 | - */ | |
| 1136 | -	private static function setupLiveMigrations($appId, array $steps) { | |
| 1137 | - $queue = \OC::$server->getJobList(); | |
| 1138 | -		foreach ($steps as $step) { | |
| 1139 | -			$queue->add('OC\Migration\BackgroundRepair', [ | |
| 1140 | - 'app' => $appId, | |
| 1141 | - 'step' => $step]); | |
| 1142 | - } | |
| 1143 | - } | |
| 1144 | - | |
| 1145 | - /** | |
| 1146 | - * @param string $appId | |
| 1147 | - * @return \OC\Files\View|false | |
| 1148 | - */ | |
| 1149 | -	public static function getStorage($appId) { | |
| 1150 | -		if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check | |
| 1151 | -			if (\OC::$server->getUserSession()->isLoggedIn()) { | |
| 1152 | -				$view = new \OC\Files\View('/' . OC_User::getUser()); | |
| 1153 | -				if (!$view->file_exists($appId)) { | |
| 1154 | - $view->mkdir($appId); | |
| 1155 | - } | |
| 1156 | -				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId); | |
| 1157 | -			} else { | |
| 1158 | -				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR); | |
| 1159 | - return false; | |
| 1160 | - } | |
| 1161 | -		} else { | |
| 1162 | -			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR); | |
| 1163 | - return false; | |
| 1164 | - } | |
| 1165 | - } | |
| 1166 | - | |
| 1167 | -	protected static function findBestL10NOption($options, $lang) { | |
| 1168 | - $fallback = $similarLangFallback = $englishFallback = false; | |
| 1169 | - | |
| 1170 | - $lang = strtolower($lang); | |
| 1171 | - $similarLang = $lang; | |
| 1172 | -		if (strpos($similarLang, '_')) { | |
| 1173 | - // For "de_DE" we want to find "de" and the other way around | |
| 1174 | - $similarLang = substr($lang, 0, strpos($lang, '_')); | |
| 1175 | - } | |
| 1176 | - | |
| 1177 | -		foreach ($options as $option) { | |
| 1178 | -			if (is_array($option)) { | |
| 1179 | -				if ($fallback === false) { | |
| 1180 | - $fallback = $option['@value']; | |
| 1181 | - } | |
| 1182 | - | |
| 1183 | -				if (!isset($option['@attributes']['lang'])) { | |
| 1184 | - continue; | |
| 1185 | - } | |
| 1186 | - | |
| 1187 | - $attributeLang = strtolower($option['@attributes']['lang']); | |
| 1188 | -				if ($attributeLang === $lang) { | |
| 1189 | - return $option['@value']; | |
| 1190 | - } | |
| 1191 | - | |
| 1192 | -				if ($attributeLang === $similarLang) { | |
| 1193 | - $similarLangFallback = $option['@value']; | |
| 1194 | -				} else if (strpos($attributeLang, $similarLang . '_') === 0) { | |
| 1195 | -					if ($similarLangFallback === false) { | |
| 1196 | - $similarLangFallback = $option['@value']; | |
| 1197 | - } | |
| 1198 | - } | |
| 1199 | -			} else { | |
| 1200 | - $englishFallback = $option; | |
| 1201 | - } | |
| 1202 | - } | |
| 1203 | - | |
| 1204 | -		if ($similarLangFallback !== false) { | |
| 1205 | - return $similarLangFallback; | |
| 1206 | -		} else if ($englishFallback !== false) { | |
| 1207 | - return $englishFallback; | |
| 1208 | - } | |
| 1209 | - return (string) $fallback; | |
| 1210 | - } | |
| 1211 | - | |
| 1212 | - /** | |
| 1213 | - * parses the app data array and enhanced the 'description' value | |
| 1214 | - * | |
| 1215 | - * @param array $data the app data | |
| 1216 | - * @param string $lang | |
| 1217 | - * @return array improved app data | |
| 1218 | - */ | |
| 1219 | -	public static function parseAppInfo(array $data, $lang = null) { | |
| 1220 | - | |
| 1221 | -		if ($lang && isset($data['name']) && is_array($data['name'])) { | |
| 1222 | - $data['name'] = self::findBestL10NOption($data['name'], $lang); | |
| 1223 | - } | |
| 1224 | -		if ($lang && isset($data['summary']) && is_array($data['summary'])) { | |
| 1225 | - $data['summary'] = self::findBestL10NOption($data['summary'], $lang); | |
| 1226 | - } | |
| 1227 | -		if ($lang && isset($data['description']) && is_array($data['description'])) { | |
| 1228 | - $data['description'] = trim(self::findBestL10NOption($data['description'], $lang)); | |
| 1229 | -		} else if (isset($data['description']) && is_string($data['description'])) { | |
| 1230 | - $data['description'] = trim($data['description']); | |
| 1231 | -		} else  { | |
| 1232 | - $data['description'] = ''; | |
| 1233 | - } | |
| 1234 | - | |
| 1235 | - return $data; | |
| 1236 | - } | |
| 1237 | - | |
| 1238 | - /** | |
| 1239 | - * @param \OCP\IConfig $config | |
| 1240 | - * @param \OCP\IL10N $l | |
| 1241 | - * @param array $info | |
| 1242 | - * @throws \Exception | |
| 1243 | - */ | |
| 1244 | -	public static function checkAppDependencies($config, $l, $info) { | |
| 1245 | - $dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l); | |
| 1246 | - $missing = $dependencyAnalyzer->analyze($info); | |
| 1247 | -		if (!empty($missing)) { | |
| 1248 | - $missingMsg = implode(PHP_EOL, $missing); | |
| 1249 | - throw new \Exception( | |
| 1250 | -				$l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s', | |
| 1251 | - [$info['name'], $missingMsg] | |
| 1252 | - ) | |
| 1253 | - ); | |
| 1254 | - } | |
| 1255 | - } | |
| 64 | + static private $appVersion = []; | |
| 65 | + static private $adminForms = array(); | |
| 66 | + static private $personalForms = array(); | |
| 67 | + static private $appInfo = array(); | |
| 68 | + static private $appTypes = array(); | |
| 69 | + static private $loadedApps = array(); | |
| 70 | + static private $altLogin = array(); | |
| 71 | + static private $alreadyRegistered = []; | |
| 72 | + const officialApp = 200; | |
| 73 | + | |
| 74 | + /** | |
| 75 | + * clean the appId | |
| 76 | + * | |
| 77 | + * @param string|boolean $app AppId that needs to be cleaned | |
| 78 | + * @return string | |
| 79 | + */ | |
| 80 | +    public static function cleanAppId($app) { | |
| 81 | +        return str_replace(array('\0', '/', '\\', '..'), '', $app); | |
| 82 | + } | |
| 83 | + | |
| 84 | + /** | |
| 85 | + * Check if an app is loaded | |
| 86 | + * | |
| 87 | + * @param string $app | |
| 88 | + * @return bool | |
| 89 | + */ | |
| 90 | +    public static function isAppLoaded($app) { | |
| 91 | + return in_array($app, self::$loadedApps, true); | |
| 92 | + } | |
| 93 | + | |
| 94 | + /** | |
| 95 | + * loads all apps | |
| 96 | + * | |
| 97 | + * @param string[] | string | null $types | |
| 98 | + * @return bool | |
| 99 | + * | |
| 100 | + * This function walks through the ownCloud directory and loads all apps | |
| 101 | + * it can find. A directory contains an app if the file /appinfo/info.xml | |
| 102 | + * exists. | |
| 103 | + * | |
| 104 | + * if $types is set, only apps of those types will be loaded | |
| 105 | + */ | |
| 106 | +    public static function loadApps($types = null) { | |
| 107 | +        if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) { | |
| 108 | + return false; | |
| 109 | + } | |
| 110 | + // Load the enabled apps here | |
| 111 | + $apps = self::getEnabledApps(); | |
| 112 | + | |
| 113 | + // Add each apps' folder as allowed class path | |
| 114 | +        foreach($apps as $app) { | |
| 115 | + $path = self::getAppPath($app); | |
| 116 | +            if($path !== false) { | |
| 117 | + self::registerAutoloading($app, $path); | |
| 118 | + } | |
| 119 | + } | |
| 120 | + | |
| 121 | + // prevent app.php from printing output | |
| 122 | + ob_start(); | |
| 123 | +        foreach ($apps as $app) { | |
| 124 | +            if ((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) { | |
| 125 | + self::loadApp($app); | |
| 126 | + } | |
| 127 | + } | |
| 128 | + ob_end_clean(); | |
| 129 | + | |
| 130 | + return true; | |
| 131 | + } | |
| 132 | + | |
| 133 | + /** | |
| 134 | + * load a single app | |
| 135 | + * | |
| 136 | + * @param string $app | |
| 137 | + */ | |
| 138 | +    public static function loadApp($app) { | |
| 139 | + self::$loadedApps[] = $app; | |
| 140 | + $appPath = self::getAppPath($app); | |
| 141 | +        if($appPath === false) { | |
| 142 | + return; | |
| 143 | + } | |
| 144 | + | |
| 145 | + // in case someone calls loadApp() directly | |
| 146 | + self::registerAutoloading($app, $appPath); | |
| 147 | + | |
| 148 | +        if (is_file($appPath . '/appinfo/app.php')) { | |
| 149 | +            \OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app); | |
| 150 | + self::requireAppFile($app); | |
| 151 | +            if (self::isType($app, array('authentication'))) { | |
| 152 | + // since authentication apps affect the "is app enabled for group" check, | |
| 153 | + // the enabled apps cache needs to be cleared to make sure that the | |
| 154 | + // next time getEnableApps() is called it will also include apps that were | |
| 155 | + // enabled for groups | |
| 156 | + self::$enabledAppsCache = array(); | |
| 157 | + } | |
| 158 | +            \OC::$server->getEventLogger()->end('load_app_' . $app); | |
| 159 | + } | |
| 160 | + | |
| 161 | + $info = self::getAppInfo($app); | |
| 162 | +        if (!empty($info['activity']['filters'])) { | |
| 163 | +            foreach ($info['activity']['filters'] as $filter) { | |
| 164 | + \OC::$server->getActivityManager()->registerFilter($filter); | |
| 165 | + } | |
| 166 | + } | |
| 167 | +        if (!empty($info['activity']['settings'])) { | |
| 168 | +            foreach ($info['activity']['settings'] as $setting) { | |
| 169 | + \OC::$server->getActivityManager()->registerSetting($setting); | |
| 170 | + } | |
| 171 | + } | |
| 172 | +        if (!empty($info['activity']['providers'])) { | |
| 173 | +            foreach ($info['activity']['providers'] as $provider) { | |
| 174 | + \OC::$server->getActivityManager()->registerProvider($provider); | |
| 175 | + } | |
| 176 | + } | |
| 177 | +        if (!empty($info['collaboration']['plugins'])) { | |
| 178 | + // deal with one or many plugin entries | |
| 179 | + $plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ? | |
| 180 | + [$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin']; | |
| 181 | +            foreach ($plugins as $plugin) { | |
| 182 | +                if($plugin['@attributes']['type'] === 'collaborator-search') { | |
| 183 | + $pluginInfo = [ | |
| 184 | + 'shareType' => $plugin['@attributes']['share-type'], | |
| 185 | + 'class' => $plugin['@value'], | |
| 186 | + ]; | |
| 187 | + \OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo); | |
| 188 | +                } else if ($plugin['@attributes']['type'] === 'autocomplete-sort') { | |
| 189 | + \OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']); | |
| 190 | + } | |
| 191 | + } | |
| 192 | + } | |
| 193 | + } | |
| 194 | + | |
| 195 | + /** | |
| 196 | + * @internal | |
| 197 | + * @param string $app | |
| 198 | + * @param string $path | |
| 199 | + */ | |
| 200 | +    public static function registerAutoloading($app, $path) { | |
| 201 | + $key = $app . '-' . $path; | |
| 202 | +        if(isset(self::$alreadyRegistered[$key])) { | |
| 203 | + return; | |
| 204 | + } | |
| 205 | + | |
| 206 | + self::$alreadyRegistered[$key] = true; | |
| 207 | + | |
| 208 | + // Register on PSR-4 composer autoloader | |
| 209 | + $appNamespace = \OC\AppFramework\App::buildAppNamespace($app); | |
| 210 | + \OC::$server->registerNamespace($app, $appNamespace); | |
| 211 | + | |
| 212 | +        if (file_exists($path . '/composer/autoload.php')) { | |
| 213 | + require_once $path . '/composer/autoload.php'; | |
| 214 | +        } else { | |
| 215 | + \OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true); | |
| 216 | + // Register on legacy autoloader | |
| 217 | + \OC::$loader->addValidRoot($path); | |
| 218 | + } | |
| 219 | + | |
| 220 | + // Register Test namespace only when testing | |
| 221 | +        if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) { | |
| 222 | + \OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true); | |
| 223 | + } | |
| 224 | + } | |
| 225 | + | |
| 226 | + /** | |
| 227 | + * Load app.php from the given app | |
| 228 | + * | |
| 229 | + * @param string $app app name | |
| 230 | + */ | |
| 231 | +    private static function requireAppFile($app) { | |
| 232 | +        try { | |
| 233 | + // encapsulated here to avoid variable scope conflicts | |
| 234 | + require_once $app . '/appinfo/app.php'; | |
| 235 | +        } catch (Error $ex) { | |
| 236 | + \OC::$server->getLogger()->logException($ex); | |
| 237 | + $blacklist = \OC::$server->getAppManager()->getAlwaysEnabledApps(); | |
| 238 | +            if (!in_array($app, $blacklist)) { | |
| 239 | + self::disable($app); | |
| 240 | + } | |
| 241 | + } | |
| 242 | + } | |
| 243 | + | |
| 244 | + /** | |
| 245 | + * check if an app is of a specific type | |
| 246 | + * | |
| 247 | + * @param string $app | |
| 248 | + * @param string|array $types | |
| 249 | + * @return bool | |
| 250 | + */ | |
| 251 | +    public static function isType($app, $types) { | |
| 252 | +        if (is_string($types)) { | |
| 253 | + $types = array($types); | |
| 254 | + } | |
| 255 | + $appTypes = self::getAppTypes($app); | |
| 256 | +        foreach ($types as $type) { | |
| 257 | +            if (array_search($type, $appTypes) !== false) { | |
| 258 | + return true; | |
| 259 | + } | |
| 260 | + } | |
| 261 | + return false; | |
| 262 | + } | |
| 263 | + | |
| 264 | + /** | |
| 265 | + * get the types of an app | |
| 266 | + * | |
| 267 | + * @param string $app | |
| 268 | + * @return array | |
| 269 | + */ | |
| 270 | +    private static function getAppTypes($app) { | |
| 271 | + //load the cache | |
| 272 | +        if (count(self::$appTypes) == 0) { | |
| 273 | + self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types'); | |
| 274 | + } | |
| 275 | + | |
| 276 | +        if (isset(self::$appTypes[$app])) { | |
| 277 | +            return explode(',', self::$appTypes[$app]); | |
| 278 | +        } else { | |
| 279 | + return array(); | |
| 280 | + } | |
| 281 | + } | |
| 282 | + | |
| 283 | + /** | |
| 284 | + * read app types from info.xml and cache them in the database | |
| 285 | + */ | |
| 286 | +    public static function setAppTypes($app) { | |
| 287 | + $appData = self::getAppInfo($app); | |
| 288 | +        if(!is_array($appData)) { | |
| 289 | + return; | |
| 290 | + } | |
| 291 | + | |
| 292 | +        if (isset($appData['types'])) { | |
| 293 | +            $appTypes = implode(',', $appData['types']); | |
| 294 | +        } else { | |
| 295 | + $appTypes = ''; | |
| 296 | + $appData['types'] = []; | |
| 297 | + } | |
| 298 | + | |
| 299 | + \OC::$server->getAppConfig()->setValue($app, 'types', $appTypes); | |
| 300 | + | |
| 301 | +        if (\OC::$server->getAppManager()->hasProtectedAppType($appData['types'])) { | |
| 302 | + $enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'yes'); | |
| 303 | +            if ($enabled !== 'yes' && $enabled !== 'no') { | |
| 304 | + \OC::$server->getAppConfig()->setValue($app, 'enabled', 'yes'); | |
| 305 | + } | |
| 306 | + } | |
| 307 | + } | |
| 308 | + | |
| 309 | + /** | |
| 310 | + * get all enabled apps | |
| 311 | + */ | |
| 312 | + protected static $enabledAppsCache = array(); | |
| 313 | + | |
| 314 | + /** | |
| 315 | + * Returns apps enabled for the current user. | |
| 316 | + * | |
| 317 | + * @param bool $forceRefresh whether to refresh the cache | |
| 318 | + * @param bool $all whether to return apps for all users, not only the | |
| 319 | + * currently logged in one | |
| 320 | + * @return string[] | |
| 321 | + */ | |
| 322 | +    public static function getEnabledApps($forceRefresh = false, $all = false) { | |
| 323 | +        if (!\OC::$server->getSystemConfig()->getValue('installed', false)) { | |
| 324 | + return array(); | |
| 325 | + } | |
| 326 | + // in incognito mode or when logged out, $user will be false, | |
| 327 | + // which is also the case during an upgrade | |
| 328 | + $appManager = \OC::$server->getAppManager(); | |
| 329 | +        if ($all) { | |
| 330 | + $user = null; | |
| 331 | +        } else { | |
| 332 | + $user = \OC::$server->getUserSession()->getUser(); | |
| 333 | + } | |
| 334 | + | |
| 335 | +        if (is_null($user)) { | |
| 336 | + $apps = $appManager->getInstalledApps(); | |
| 337 | +        } else { | |
| 338 | + $apps = $appManager->getEnabledAppsForUser($user); | |
| 339 | + } | |
| 340 | +        $apps = array_filter($apps, function ($app) { | |
| 341 | + return $app !== 'files';//we add this manually | |
| 342 | + }); | |
| 343 | + sort($apps); | |
| 344 | + array_unshift($apps, 'files'); | |
| 345 | + return $apps; | |
| 346 | + } | |
| 347 | + | |
| 348 | + /** | |
| 349 | + * checks whether or not an app is enabled | |
| 350 | + * | |
| 351 | + * @param string $app app | |
| 352 | + * @return bool | |
| 353 | + * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId) | |
| 354 | + * | |
| 355 | + * This function checks whether or not an app is enabled. | |
| 356 | + */ | |
| 357 | +    public static function isEnabled($app) { | |
| 358 | + return \OC::$server->getAppManager()->isEnabledForUser($app); | |
| 359 | + } | |
| 360 | + | |
| 361 | + /** | |
| 362 | + * enables an app | |
| 363 | + * | |
| 364 | + * @param string $appId | |
| 365 | + * @param array $groups (optional) when set, only these groups will have access to the app | |
| 366 | + * @throws \Exception | |
| 367 | + * @return void | |
| 368 | + * | |
| 369 | + * This function set an app as enabled in appconfig. | |
| 370 | + */ | |
| 371 | + public function enable($appId, | |
| 372 | +                            $groups = null) { | |
| 373 | + self::$enabledAppsCache = []; // flush | |
| 374 | + | |
| 375 | + // Check if app is already downloaded | |
| 376 | + $installer = new Installer( | |
| 377 | + \OC::$server->getAppFetcher(), | |
| 378 | + \OC::$server->getHTTPClientService(), | |
| 379 | + \OC::$server->getTempManager(), | |
| 380 | + \OC::$server->getLogger(), | |
| 381 | + \OC::$server->getConfig() | |
| 382 | + ); | |
| 383 | + $isDownloaded = $installer->isDownloaded($appId); | |
| 384 | + | |
| 385 | +        if(!$isDownloaded) { | |
| 386 | + $installer->downloadApp($appId); | |
| 387 | + } | |
| 388 | + | |
| 389 | + $installer->installApp($appId); | |
| 390 | + | |
| 391 | + $appManager = \OC::$server->getAppManager(); | |
| 392 | +        if (!is_null($groups)) { | |
| 393 | + $groupManager = \OC::$server->getGroupManager(); | |
| 394 | + $groupsList = []; | |
| 395 | +            foreach ($groups as $group) { | |
| 396 | + $groupItem = $groupManager->get($group); | |
| 397 | +                if ($groupItem instanceof \OCP\IGroup) { | |
| 398 | + $groupsList[] = $groupManager->get($group); | |
| 399 | + } | |
| 400 | + } | |
| 401 | + $appManager->enableAppForGroups($appId, $groupsList); | |
| 402 | +        } else { | |
| 403 | + $appManager->enableApp($appId); | |
| 404 | + } | |
| 405 | + } | |
| 406 | + | |
| 407 | + /** | |
| 408 | + * @param string $app | |
| 409 | + * @return bool | |
| 410 | + */ | |
| 411 | +    public static function removeApp($app) { | |
| 412 | +        if (\OC::$server->getAppManager()->isShipped($app)) { | |
| 413 | + return false; | |
| 414 | + } | |
| 415 | + | |
| 416 | + $installer = new Installer( | |
| 417 | + \OC::$server->getAppFetcher(), | |
| 418 | + \OC::$server->getHTTPClientService(), | |
| 419 | + \OC::$server->getTempManager(), | |
| 420 | + \OC::$server->getLogger(), | |
| 421 | + \OC::$server->getConfig() | |
| 422 | + ); | |
| 423 | + return $installer->removeApp($app); | |
| 424 | + } | |
| 425 | + | |
| 426 | + /** | |
| 427 | + * This function set an app as disabled in appconfig. | |
| 428 | + * | |
| 429 | + * @param string $app app | |
| 430 | + * @throws Exception | |
| 431 | + */ | |
| 432 | +    public static function disable($app) { | |
| 433 | + // flush | |
| 434 | + self::$enabledAppsCache = array(); | |
| 435 | + | |
| 436 | + // run uninstall steps | |
| 437 | + $appData = OC_App::getAppInfo($app); | |
| 438 | +        if (!is_null($appData)) { | |
| 439 | + OC_App::executeRepairSteps($app, $appData['repair-steps']['uninstall']); | |
| 440 | + } | |
| 441 | + | |
| 442 | + // emit disable hook - needed anymore ? | |
| 443 | +        \OC_Hook::emit('OC_App', 'pre_disable', array('app' => $app)); | |
| 444 | + | |
| 445 | + // finally disable it | |
| 446 | + $appManager = \OC::$server->getAppManager(); | |
| 447 | + $appManager->disableApp($app); | |
| 448 | + } | |
| 449 | + | |
| 450 | + // This is private as well. It simply works, so don't ask for more details | |
| 451 | +    private static function proceedNavigation($list) { | |
| 452 | +        usort($list, function($a, $b) { | |
| 453 | +            if (isset($a['order']) && isset($b['order'])) { | |
| 454 | + return ($a['order'] < $b['order']) ? -1 : 1; | |
| 455 | +            } else if (isset($a['order']) || isset($b['order'])) { | |
| 456 | + return isset($a['order']) ? -1 : 1; | |
| 457 | +            } else { | |
| 458 | + return ($a['name'] < $b['name']) ? -1 : 1; | |
| 459 | + } | |
| 460 | + }); | |
| 461 | + | |
| 462 | + $activeApp = OC::$server->getNavigationManager()->getActiveEntry(); | |
| 463 | +        foreach ($list as $index => &$navEntry) { | |
| 464 | +            if ($navEntry['id'] == $activeApp) { | |
| 465 | + $navEntry['active'] = true; | |
| 466 | +            } else { | |
| 467 | + $navEntry['active'] = false; | |
| 468 | + } | |
| 469 | + } | |
| 470 | + unset($navEntry); | |
| 471 | + | |
| 472 | + return $list; | |
| 473 | + } | |
| 474 | + | |
| 475 | + /** | |
| 476 | + * Get the path where to install apps | |
| 477 | + * | |
| 478 | + * @return string|false | |
| 479 | + */ | |
| 480 | +    public static function getInstallPath() { | |
| 481 | +        if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) { | |
| 482 | + return false; | |
| 483 | + } | |
| 484 | + | |
| 485 | +        foreach (OC::$APPSROOTS as $dir) { | |
| 486 | +            if (isset($dir['writable']) && $dir['writable'] === true) { | |
| 487 | + return $dir['path']; | |
| 488 | + } | |
| 489 | + } | |
| 490 | + | |
| 491 | +        \OCP\Util::writeLog('core', 'No application directories are marked as writable.', \OCP\Util::ERROR); | |
| 492 | + return null; | |
| 493 | + } | |
| 494 | + | |
| 495 | + | |
| 496 | + /** | |
| 497 | + * search for an app in all app-directories | |
| 498 | + * | |
| 499 | + * @param string $appId | |
| 500 | + * @return false|string | |
| 501 | + */ | |
| 502 | +    public static function findAppInDirectories($appId) { | |
| 503 | + $sanitizedAppId = self::cleanAppId($appId); | |
| 504 | +        if($sanitizedAppId !== $appId) { | |
| 505 | + return false; | |
| 506 | + } | |
| 507 | + static $app_dir = array(); | |
| 508 | + | |
| 509 | +        if (isset($app_dir[$appId])) { | |
| 510 | + return $app_dir[$appId]; | |
| 511 | + } | |
| 512 | + | |
| 513 | + $possibleApps = array(); | |
| 514 | +        foreach (OC::$APPSROOTS as $dir) { | |
| 515 | +            if (file_exists($dir['path'] . '/' . $appId)) { | |
| 516 | + $possibleApps[] = $dir; | |
| 517 | + } | |
| 518 | + } | |
| 519 | + | |
| 520 | +        if (empty($possibleApps)) { | |
| 521 | + return false; | |
| 522 | +        } elseif (count($possibleApps) === 1) { | |
| 523 | + $dir = array_shift($possibleApps); | |
| 524 | + $app_dir[$appId] = $dir; | |
| 525 | + return $dir; | |
| 526 | +        } else { | |
| 527 | + $versionToLoad = array(); | |
| 528 | +            foreach ($possibleApps as $possibleApp) { | |
| 529 | + $version = self::getAppVersionByPath($possibleApp['path']); | |
| 530 | +                if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) { | |
| 531 | + $versionToLoad = array( | |
| 532 | + 'dir' => $possibleApp, | |
| 533 | + 'version' => $version, | |
| 534 | + ); | |
| 535 | + } | |
| 536 | + } | |
| 537 | + $app_dir[$appId] = $versionToLoad['dir']; | |
| 538 | + return $versionToLoad['dir']; | |
| 539 | + //TODO - write test | |
| 540 | + } | |
| 541 | + } | |
| 542 | + | |
| 543 | + /** | |
| 544 | + * Get the directory for the given app. | |
| 545 | + * If the app is defined in multiple directories, the first one is taken. (false if not found) | |
| 546 | + * | |
| 547 | + * @param string $appId | |
| 548 | + * @return string|false | |
| 549 | + */ | |
| 550 | +    public static function getAppPath($appId) { | |
| 551 | +        if ($appId === null || trim($appId) === '') { | |
| 552 | + return false; | |
| 553 | + } | |
| 554 | + | |
| 555 | +        if (($dir = self::findAppInDirectories($appId)) != false) { | |
| 556 | + return $dir['path'] . '/' . $appId; | |
| 557 | + } | |
| 558 | + return false; | |
| 559 | + } | |
| 560 | + | |
| 561 | + /** | |
| 562 | + * Get the path for the given app on the access | |
| 563 | + * If the app is defined in multiple directories, the first one is taken. (false if not found) | |
| 564 | + * | |
| 565 | + * @param string $appId | |
| 566 | + * @return string|false | |
| 567 | + */ | |
| 568 | +    public static function getAppWebPath($appId) { | |
| 569 | +        if (($dir = self::findAppInDirectories($appId)) != false) { | |
| 570 | + return OC::$WEBROOT . $dir['url'] . '/' . $appId; | |
| 571 | + } | |
| 572 | + return false; | |
| 573 | + } | |
| 574 | + | |
| 575 | + /** | |
| 576 | + * get the last version of the app from appinfo/info.xml | |
| 577 | + * | |
| 578 | + * @param string $appId | |
| 579 | + * @param bool $useCache | |
| 580 | + * @return string | |
| 581 | + */ | |
| 582 | +    public static function getAppVersion($appId, $useCache = true) { | |
| 583 | +        if($useCache && isset(self::$appVersion[$appId])) { | |
| 584 | + return self::$appVersion[$appId]; | |
| 585 | + } | |
| 586 | + | |
| 587 | + $file = self::getAppPath($appId); | |
| 588 | + self::$appVersion[$appId] = ($file !== false) ? self::getAppVersionByPath($file) : '0'; | |
| 589 | + return self::$appVersion[$appId]; | |
| 590 | + } | |
| 591 | + | |
| 592 | + /** | |
| 593 | + * get app's version based on it's path | |
| 594 | + * | |
| 595 | + * @param string $path | |
| 596 | + * @return string | |
| 597 | + */ | |
| 598 | +    public static function getAppVersionByPath($path) { | |
| 599 | + $infoFile = $path . '/appinfo/info.xml'; | |
| 600 | + $appData = self::getAppInfo($infoFile, true); | |
| 601 | + return isset($appData['version']) ? $appData['version'] : ''; | |
| 602 | + } | |
| 603 | + | |
| 604 | + | |
| 605 | + /** | |
| 606 | + * Read all app metadata from the info.xml file | |
| 607 | + * | |
| 608 | + * @param string $appId id of the app or the path of the info.xml file | |
| 609 | + * @param bool $path | |
| 610 | + * @param string $lang | |
| 611 | + * @return array|null | |
| 612 | + * @note all data is read from info.xml, not just pre-defined fields | |
| 613 | + */ | |
| 614 | +    public static function getAppInfo($appId, $path = false, $lang = null) { | |
| 615 | +        if ($path) { | |
| 616 | + $file = $appId; | |
| 617 | +        } else { | |
| 618 | +            if ($lang === null && isset(self::$appInfo[$appId])) { | |
| 619 | + return self::$appInfo[$appId]; | |
| 620 | + } | |
| 621 | + $appPath = self::getAppPath($appId); | |
| 622 | +            if($appPath === false) { | |
| 623 | + return null; | |
| 624 | + } | |
| 625 | + $file = $appPath . '/appinfo/info.xml'; | |
| 626 | + } | |
| 627 | + | |
| 628 | +        $parser = new InfoParser(\OC::$server->getMemCacheFactory()->createLocal('core.appinfo')); | |
| 629 | + $data = $parser->parse($file); | |
| 630 | + | |
| 631 | +        if (is_array($data)) { | |
| 632 | + $data = OC_App::parseAppInfo($data, $lang); | |
| 633 | + } | |
| 634 | +        if(isset($data['ocsid'])) { | |
| 635 | + $storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid'); | |
| 636 | +            if($storedId !== '' && $storedId !== $data['ocsid']) { | |
| 637 | + $data['ocsid'] = $storedId; | |
| 638 | + } | |
| 639 | + } | |
| 640 | + | |
| 641 | +        if ($lang === null) { | |
| 642 | + self::$appInfo[$appId] = $data; | |
| 643 | + } | |
| 644 | + | |
| 645 | + return $data; | |
| 646 | + } | |
| 647 | + | |
| 648 | + /** | |
| 649 | + * Returns the navigation | |
| 650 | + * | |
| 651 | + * @return array | |
| 652 | + * | |
| 653 | + * This function returns an array containing all entries added. The | |
| 654 | + * entries are sorted by the key 'order' ascending. Additional to the keys | |
| 655 | + * given for each app the following keys exist: | |
| 656 | + * - active: boolean, signals if the user is on this navigation entry | |
| 657 | + */ | |
| 658 | +    public static function getNavigation() { | |
| 659 | + $entries = OC::$server->getNavigationManager()->getAll(); | |
| 660 | + return self::proceedNavigation($entries); | |
| 661 | + } | |
| 662 | + | |
| 663 | + /** | |
| 664 | + * Returns the Settings Navigation | |
| 665 | + * | |
| 666 | + * @return string[] | |
| 667 | + * | |
| 668 | + * This function returns an array containing all settings pages added. The | |
| 669 | + * entries are sorted by the key 'order' ascending. | |
| 670 | + */ | |
| 671 | +    public static function getSettingsNavigation() { | |
| 672 | +        $entries = OC::$server->getNavigationManager()->getAll('settings'); | |
| 673 | + return self::proceedNavigation($entries); | |
| 674 | + } | |
| 675 | + | |
| 676 | + /** | |
| 677 | + * get the id of loaded app | |
| 678 | + * | |
| 679 | + * @return string | |
| 680 | + */ | |
| 681 | +    public static function getCurrentApp() { | |
| 682 | + $request = \OC::$server->getRequest(); | |
| 683 | + $script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1); | |
| 684 | + $topFolder = substr($script, 0, strpos($script, '/')); | |
| 685 | +        if (empty($topFolder)) { | |
| 686 | + $path_info = $request->getPathInfo(); | |
| 687 | +            if ($path_info) { | |
| 688 | + $topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1); | |
| 689 | + } | |
| 690 | + } | |
| 691 | +        if ($topFolder == 'apps') { | |
| 692 | + $length = strlen($topFolder); | |
| 693 | + return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1); | |
| 694 | +        } else { | |
| 695 | + return $topFolder; | |
| 696 | + } | |
| 697 | + } | |
| 698 | + | |
| 699 | + /** | |
| 700 | + * @param string $type | |
| 701 | + * @return array | |
| 702 | + */ | |
| 703 | +    public static function getForms($type) { | |
| 704 | + $forms = array(); | |
| 705 | +        switch ($type) { | |
| 706 | + case 'admin': | |
| 707 | + $source = self::$adminForms; | |
| 708 | + break; | |
| 709 | + case 'personal': | |
| 710 | + $source = self::$personalForms; | |
| 711 | + break; | |
| 712 | + default: | |
| 713 | + return array(); | |
| 714 | + } | |
| 715 | +        foreach ($source as $form) { | |
| 716 | + $forms[] = include $form; | |
| 717 | + } | |
| 718 | + return $forms; | |
| 719 | + } | |
| 720 | + | |
| 721 | + /** | |
| 722 | + * register an admin form to be shown | |
| 723 | + * | |
| 724 | + * @param string $app | |
| 725 | + * @param string $page | |
| 726 | + */ | |
| 727 | +    public static function registerAdmin($app, $page) { | |
| 728 | + self::$adminForms[] = $app . '/' . $page . '.php'; | |
| 729 | + } | |
| 730 | + | |
| 731 | + /** | |
| 732 | + * register a personal form to be shown | |
| 733 | + * @param string $app | |
| 734 | + * @param string $page | |
| 735 | + */ | |
| 736 | +    public static function registerPersonal($app, $page) { | |
| 737 | + self::$personalForms[] = $app . '/' . $page . '.php'; | |
| 738 | + } | |
| 739 | + | |
| 740 | + /** | |
| 741 | + * @param array $entry | |
| 742 | + */ | |
| 743 | +    public static function registerLogIn(array $entry) { | |
| 744 | + self::$altLogin[] = $entry; | |
| 745 | + } | |
| 746 | + | |
| 747 | + /** | |
| 748 | + * @return array | |
| 749 | + */ | |
| 750 | +    public static function getAlternativeLogIns() { | |
| 751 | + return self::$altLogin; | |
| 752 | + } | |
| 753 | + | |
| 754 | + /** | |
| 755 | + * get a list of all apps in the apps folder | |
| 756 | + * | |
| 757 | + * @return array an array of app names (string IDs) | |
| 758 | + * @todo: change the name of this method to getInstalledApps, which is more accurate | |
| 759 | + */ | |
| 760 | +    public static function getAllApps() { | |
| 761 | + | |
| 762 | + $apps = array(); | |
| 763 | + | |
| 764 | +        foreach (OC::$APPSROOTS as $apps_dir) { | |
| 765 | +            if (!is_readable($apps_dir['path'])) { | |
| 766 | +                \OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN); | |
| 767 | + continue; | |
| 768 | + } | |
| 769 | + $dh = opendir($apps_dir['path']); | |
| 770 | + | |
| 771 | +            if (is_resource($dh)) { | |
| 772 | +                while (($file = readdir($dh)) !== false) { | |
| 773 | + | |
| 774 | +                    if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) { | |
| 775 | + | |
| 776 | + $apps[] = $file; | |
| 777 | + } | |
| 778 | + } | |
| 779 | + } | |
| 780 | + } | |
| 781 | + | |
| 782 | + $apps = array_unique($apps); | |
| 783 | + | |
| 784 | + return $apps; | |
| 785 | + } | |
| 786 | + | |
| 787 | + /** | |
| 788 | + * List all apps, this is used in apps.php | |
| 789 | + * | |
| 790 | + * @return array | |
| 791 | + */ | |
| 792 | +    public function listAllApps() { | |
| 793 | + $installedApps = OC_App::getAllApps(); | |
| 794 | + | |
| 795 | + $appManager = \OC::$server->getAppManager(); | |
| 796 | + //we don't want to show configuration for these | |
| 797 | + $blacklist = $appManager->getAlwaysEnabledApps(); | |
| 798 | + $appList = array(); | |
| 799 | +        $langCode = \OC::$server->getL10N('core')->getLanguageCode(); | |
| 800 | + $urlGenerator = \OC::$server->getURLGenerator(); | |
| 801 | + | |
| 802 | +        foreach ($installedApps as $app) { | |
| 803 | +            if (array_search($app, $blacklist) === false) { | |
| 804 | + | |
| 805 | + $info = OC_App::getAppInfo($app, false, $langCode); | |
| 806 | +                if (!is_array($info)) { | |
| 807 | +                    \OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR); | |
| 808 | + continue; | |
| 809 | + } | |
| 810 | + | |
| 811 | +                if (!isset($info['name'])) { | |
| 812 | +                    \OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR); | |
| 813 | + continue; | |
| 814 | + } | |
| 815 | + | |
| 816 | + $enabled = \OC::$server->getAppConfig()->getValue($app, 'enabled', 'no'); | |
| 817 | + $info['groups'] = null; | |
| 818 | +                if ($enabled === 'yes') { | |
| 819 | + $active = true; | |
| 820 | +                } else if ($enabled === 'no') { | |
| 821 | + $active = false; | |
| 822 | +                } else { | |
| 823 | + $active = true; | |
| 824 | + $info['groups'] = $enabled; | |
| 825 | + } | |
| 826 | + | |
| 827 | + $info['active'] = $active; | |
| 828 | + | |
| 829 | +                if ($appManager->isShipped($app)) { | |
| 830 | + $info['internal'] = true; | |
| 831 | + $info['level'] = self::officialApp; | |
| 832 | + $info['removable'] = false; | |
| 833 | +                } else { | |
| 834 | + $info['internal'] = false; | |
| 835 | + $info['removable'] = true; | |
| 836 | + } | |
| 837 | + | |
| 838 | + $appPath = self::getAppPath($app); | |
| 839 | +                if($appPath !== false) { | |
| 840 | + $appIcon = $appPath . '/img/' . $app . '.svg'; | |
| 841 | +                    if (file_exists($appIcon)) { | |
| 842 | + $info['preview'] = $urlGenerator->imagePath($app, $app . '.svg'); | |
| 843 | + $info['previewAsIcon'] = true; | |
| 844 | +                    } else { | |
| 845 | + $appIcon = $appPath . '/img/app.svg'; | |
| 846 | +                        if (file_exists($appIcon)) { | |
| 847 | + $info['preview'] = $urlGenerator->imagePath($app, 'app.svg'); | |
| 848 | + $info['previewAsIcon'] = true; | |
| 849 | + } | |
| 850 | + } | |
| 851 | + } | |
| 852 | + // fix documentation | |
| 853 | +                if (isset($info['documentation']) && is_array($info['documentation'])) { | |
| 854 | +                    foreach ($info['documentation'] as $key => $url) { | |
| 855 | + // If it is not an absolute URL we assume it is a key | |
| 856 | + // i.e. admin-ldap will get converted to go.php?to=admin-ldap | |
| 857 | +                        if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) { | |
| 858 | + $url = $urlGenerator->linkToDocs($url); | |
| 859 | + } | |
| 860 | + | |
| 861 | + $info['documentation'][$key] = $url; | |
| 862 | + } | |
| 863 | + } | |
| 864 | + | |
| 865 | + $info['version'] = OC_App::getAppVersion($app); | |
| 866 | + $appList[] = $info; | |
| 867 | + } | |
| 868 | + } | |
| 869 | + | |
| 870 | + return $appList; | |
| 871 | + } | |
| 872 | + | |
| 873 | +    public static function shouldUpgrade($app) { | |
| 874 | + $versions = self::getAppVersions(); | |
| 875 | + $currentVersion = OC_App::getAppVersion($app); | |
| 876 | +        if ($currentVersion && isset($versions[$app])) { | |
| 877 | + $installedVersion = $versions[$app]; | |
| 878 | +            if (!version_compare($currentVersion, $installedVersion, '=')) { | |
| 879 | + return true; | |
| 880 | + } | |
| 881 | + } | |
| 882 | + return false; | |
| 883 | + } | |
| 884 | + | |
| 885 | + /** | |
| 886 | + * Adjust the number of version parts of $version1 to match | |
| 887 | + * the number of version parts of $version2. | |
| 888 | + * | |
| 889 | + * @param string $version1 version to adjust | |
| 890 | + * @param string $version2 version to take the number of parts from | |
| 891 | + * @return string shortened $version1 | |
| 892 | + */ | |
| 893 | +    private static function adjustVersionParts($version1, $version2) { | |
| 894 | +        $version1 = explode('.', $version1); | |
| 895 | +        $version2 = explode('.', $version2); | |
| 896 | + // reduce $version1 to match the number of parts in $version2 | |
| 897 | +        while (count($version1) > count($version2)) { | |
| 898 | + array_pop($version1); | |
| 899 | + } | |
| 900 | + // if $version1 does not have enough parts, add some | |
| 901 | +        while (count($version1) < count($version2)) { | |
| 902 | + $version1[] = '0'; | |
| 903 | + } | |
| 904 | +        return implode('.', $version1); | |
| 905 | + } | |
| 906 | + | |
| 907 | + /** | |
| 908 | + * Check whether the current ownCloud version matches the given | |
| 909 | + * application's version requirements. | |
| 910 | + * | |
| 911 | + * The comparison is made based on the number of parts that the | |
| 912 | + * app info version has. For example for ownCloud 6.0.3 if the | |
| 913 | + * app info version is expecting version 6.0, the comparison is | |
| 914 | + * made on the first two parts of the ownCloud version. | |
| 915 | + * This means that it's possible to specify "requiremin" => 6 | |
| 916 | + * and "requiremax" => 6 and it will still match ownCloud 6.0.3. | |
| 917 | + * | |
| 918 | + * @param string $ocVersion ownCloud version to check against | |
| 919 | + * @param array $appInfo app info (from xml) | |
| 920 | + * | |
| 921 | + * @return boolean true if compatible, otherwise false | |
| 922 | + */ | |
| 923 | +    public static function isAppCompatible($ocVersion, $appInfo) { | |
| 924 | + $requireMin = ''; | |
| 925 | + $requireMax = ''; | |
| 926 | +        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) { | |
| 927 | + $requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version']; | |
| 928 | +        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) { | |
| 929 | + $requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version']; | |
| 930 | +        } else if (isset($appInfo['requiremin'])) { | |
| 931 | + $requireMin = $appInfo['requiremin']; | |
| 932 | +        } else if (isset($appInfo['require'])) { | |
| 933 | + $requireMin = $appInfo['require']; | |
| 934 | + } | |
| 935 | + | |
| 936 | +        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) { | |
| 937 | + $requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version']; | |
| 938 | +        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) { | |
| 939 | + $requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version']; | |
| 940 | +        } else if (isset($appInfo['requiremax'])) { | |
| 941 | + $requireMax = $appInfo['requiremax']; | |
| 942 | + } | |
| 943 | + | |
| 944 | +        if (is_array($ocVersion)) { | |
| 945 | +            $ocVersion = implode('.', $ocVersion); | |
| 946 | + } | |
| 947 | + | |
| 948 | + if (!empty($requireMin) | |
| 949 | + && version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<') | |
| 950 | +        ) { | |
| 951 | + | |
| 952 | + return false; | |
| 953 | + } | |
| 954 | + | |
| 955 | + if (!empty($requireMax) | |
| 956 | + && version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>') | |
| 957 | +        ) { | |
| 958 | + return false; | |
| 959 | + } | |
| 960 | + | |
| 961 | + return true; | |
| 962 | + } | |
| 963 | + | |
| 964 | + /** | |
| 965 | + * get the installed version of all apps | |
| 966 | + */ | |
| 967 | +    public static function getAppVersions() { | |
| 968 | + static $versions; | |
| 969 | + | |
| 970 | +        if(!$versions) { | |
| 971 | + $appConfig = \OC::$server->getAppConfig(); | |
| 972 | + $versions = $appConfig->getValues(false, 'installed_version'); | |
| 973 | + } | |
| 974 | + return $versions; | |
| 975 | + } | |
| 976 | + | |
| 977 | + /** | |
| 978 | + * @param string $app | |
| 979 | + * @param \OCP\IConfig $config | |
| 980 | + * @param \OCP\IL10N $l | |
| 981 | + * @return bool | |
| 982 | + * | |
| 983 | + * @throws Exception if app is not compatible with this version of ownCloud | |
| 984 | + * @throws Exception if no app-name was specified | |
| 985 | + */ | |
| 986 | + public function installApp($app, | |
| 987 | + \OCP\IConfig $config, | |
| 988 | +                                \OCP\IL10N $l) { | |
| 989 | +        if ($app !== false) { | |
| 990 | + // check if the app is compatible with this version of ownCloud | |
| 991 | + $info = self::getAppInfo($app); | |
| 992 | +            if(!is_array($info)) { | |
| 993 | + throw new \Exception( | |
| 994 | +                    $l->t('App "%s" cannot be installed because appinfo file cannot be read.', | |
| 995 | + [$info['name']] | |
| 996 | + ) | |
| 997 | + ); | |
| 998 | + } | |
| 999 | + | |
| 1000 | + $version = \OCP\Util::getVersion(); | |
| 1001 | +            if (!self::isAppCompatible($version, $info)) { | |
| 1002 | + throw new \Exception( | |
| 1003 | +                    $l->t('App "%s" cannot be installed because it is not compatible with this version of the server.', | |
| 1004 | + array($info['name']) | |
| 1005 | + ) | |
| 1006 | + ); | |
| 1007 | + } | |
| 1008 | + | |
| 1009 | + // check for required dependencies | |
| 1010 | + self::checkAppDependencies($config, $l, $info); | |
| 1011 | + | |
| 1012 | + $config->setAppValue($app, 'enabled', 'yes'); | |
| 1013 | +            if (isset($appData['id'])) { | |
| 1014 | + $config->setAppValue($app, 'ocsid', $appData['id']); | |
| 1015 | + } | |
| 1016 | + | |
| 1017 | +            if(isset($info['settings']) && is_array($info['settings'])) { | |
| 1018 | + $appPath = self::getAppPath($app); | |
| 1019 | + self::registerAutoloading($app, $appPath); | |
| 1020 | + \OC::$server->getSettingsManager()->setupSettings($info['settings']); | |
| 1021 | + } | |
| 1022 | + | |
| 1023 | +            \OC_Hook::emit('OC_App', 'post_enable', array('app' => $app)); | |
| 1024 | +        } else { | |
| 1025 | +            if(empty($appName) ) { | |
| 1026 | +                throw new \Exception($l->t("No app name specified")); | |
| 1027 | +            } else { | |
| 1028 | +                throw new \Exception($l->t("App '%s' could not be installed!", $appName)); | |
| 1029 | + } | |
| 1030 | + } | |
| 1031 | + | |
| 1032 | + return $app; | |
| 1033 | + } | |
| 1034 | + | |
| 1035 | + /** | |
| 1036 | + * update the database for the app and call the update script | |
| 1037 | + * | |
| 1038 | + * @param string $appId | |
| 1039 | + * @return bool | |
| 1040 | + */ | |
| 1041 | +    public static function updateApp($appId) { | |
| 1042 | + $appPath = self::getAppPath($appId); | |
| 1043 | +        if($appPath === false) { | |
| 1044 | + return false; | |
| 1045 | + } | |
| 1046 | + self::registerAutoloading($appId, $appPath); | |
| 1047 | + | |
| 1048 | + $appData = self::getAppInfo($appId); | |
| 1049 | + self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']); | |
| 1050 | + | |
| 1051 | +        if (file_exists($appPath . '/appinfo/database.xml')) { | |
| 1052 | + OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml'); | |
| 1053 | +        } else { | |
| 1054 | + $ms = new MigrationService($appId, \OC::$server->getDatabaseConnection()); | |
| 1055 | + $ms->migrate(); | |
| 1056 | + } | |
| 1057 | + | |
| 1058 | + self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']); | |
| 1059 | + self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']); | |
| 1060 | + unset(self::$appVersion[$appId]); | |
| 1061 | + | |
| 1062 | + // run upgrade code | |
| 1063 | +        if (file_exists($appPath . '/appinfo/update.php')) { | |
| 1064 | + self::loadApp($appId); | |
| 1065 | + include $appPath . '/appinfo/update.php'; | |
| 1066 | + } | |
| 1067 | + self::setupBackgroundJobs($appData['background-jobs']); | |
| 1068 | +        if(isset($appData['settings']) && is_array($appData['settings'])) { | |
| 1069 | + \OC::$server->getSettingsManager()->setupSettings($appData['settings']); | |
| 1070 | + } | |
| 1071 | + | |
| 1072 | + //set remote/public handlers | |
| 1073 | +        if (array_key_exists('ocsid', $appData)) { | |
| 1074 | + \OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']); | |
| 1075 | +        } elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) { | |
| 1076 | + \OC::$server->getConfig()->deleteAppValue($appId, 'ocsid'); | |
| 1077 | + } | |
| 1078 | +        foreach ($appData['remote'] as $name => $path) { | |
| 1079 | +            \OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path); | |
| 1080 | + } | |
| 1081 | +        foreach ($appData['public'] as $name => $path) { | |
| 1082 | +            \OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path); | |
| 1083 | + } | |
| 1084 | + | |
| 1085 | + self::setAppTypes($appId); | |
| 1086 | + | |
| 1087 | + $version = \OC_App::getAppVersion($appId); | |
| 1088 | + \OC::$server->getAppConfig()->setValue($appId, 'installed_version', $version); | |
| 1089 | + | |
| 1090 | + \OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent( | |
| 1091 | + ManagerEvent::EVENT_APP_UPDATE, $appId | |
| 1092 | + )); | |
| 1093 | + | |
| 1094 | + return true; | |
| 1095 | + } | |
| 1096 | + | |
| 1097 | + /** | |
| 1098 | + * @param string $appId | |
| 1099 | + * @param string[] $steps | |
| 1100 | + * @throws \OC\NeedsUpdateException | |
| 1101 | + */ | |
| 1102 | +    public static function executeRepairSteps($appId, array $steps) { | |
| 1103 | +        if (empty($steps)) { | |
| 1104 | + return; | |
| 1105 | + } | |
| 1106 | + // load the app | |
| 1107 | + self::loadApp($appId); | |
| 1108 | + | |
| 1109 | + $dispatcher = OC::$server->getEventDispatcher(); | |
| 1110 | + | |
| 1111 | + // load the steps | |
| 1112 | + $r = new Repair([], $dispatcher); | |
| 1113 | +        foreach ($steps as $step) { | |
| 1114 | +            try { | |
| 1115 | + $r->addStep($step); | |
| 1116 | +            } catch (Exception $ex) { | |
| 1117 | +                $r->emit('\OC\Repair', 'error', [$ex->getMessage()]); | |
| 1118 | + \OC::$server->getLogger()->logException($ex); | |
| 1119 | + } | |
| 1120 | + } | |
| 1121 | + // run the steps | |
| 1122 | + $r->run(); | |
| 1123 | + } | |
| 1124 | + | |
| 1125 | +    public static function setupBackgroundJobs(array $jobs) { | |
| 1126 | + $queue = \OC::$server->getJobList(); | |
| 1127 | +        foreach ($jobs as $job) { | |
| 1128 | + $queue->add($job); | |
| 1129 | + } | |
| 1130 | + } | |
| 1131 | + | |
| 1132 | + /** | |
| 1133 | + * @param string $appId | |
| 1134 | + * @param string[] $steps | |
| 1135 | + */ | |
| 1136 | +    private static function setupLiveMigrations($appId, array $steps) { | |
| 1137 | + $queue = \OC::$server->getJobList(); | |
| 1138 | +        foreach ($steps as $step) { | |
| 1139 | +            $queue->add('OC\Migration\BackgroundRepair', [ | |
| 1140 | + 'app' => $appId, | |
| 1141 | + 'step' => $step]); | |
| 1142 | + } | |
| 1143 | + } | |
| 1144 | + | |
| 1145 | + /** | |
| 1146 | + * @param string $appId | |
| 1147 | + * @return \OC\Files\View|false | |
| 1148 | + */ | |
| 1149 | +    public static function getStorage($appId) { | |
| 1150 | +        if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check | |
| 1151 | +            if (\OC::$server->getUserSession()->isLoggedIn()) { | |
| 1152 | +                $view = new \OC\Files\View('/' . OC_User::getUser()); | |
| 1153 | +                if (!$view->file_exists($appId)) { | |
| 1154 | + $view->mkdir($appId); | |
| 1155 | + } | |
| 1156 | +                return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId); | |
| 1157 | +            } else { | |
| 1158 | +                \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR); | |
| 1159 | + return false; | |
| 1160 | + } | |
| 1161 | +        } else { | |
| 1162 | +            \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR); | |
| 1163 | + return false; | |
| 1164 | + } | |
| 1165 | + } | |
| 1166 | + | |
| 1167 | +    protected static function findBestL10NOption($options, $lang) { | |
| 1168 | + $fallback = $similarLangFallback = $englishFallback = false; | |
| 1169 | + | |
| 1170 | + $lang = strtolower($lang); | |
| 1171 | + $similarLang = $lang; | |
| 1172 | +        if (strpos($similarLang, '_')) { | |
| 1173 | + // For "de_DE" we want to find "de" and the other way around | |
| 1174 | + $similarLang = substr($lang, 0, strpos($lang, '_')); | |
| 1175 | + } | |
| 1176 | + | |
| 1177 | +        foreach ($options as $option) { | |
| 1178 | +            if (is_array($option)) { | |
| 1179 | +                if ($fallback === false) { | |
| 1180 | + $fallback = $option['@value']; | |
| 1181 | + } | |
| 1182 | + | |
| 1183 | +                if (!isset($option['@attributes']['lang'])) { | |
| 1184 | + continue; | |
| 1185 | + } | |
| 1186 | + | |
| 1187 | + $attributeLang = strtolower($option['@attributes']['lang']); | |
| 1188 | +                if ($attributeLang === $lang) { | |
| 1189 | + return $option['@value']; | |
| 1190 | + } | |
| 1191 | + | |
| 1192 | +                if ($attributeLang === $similarLang) { | |
| 1193 | + $similarLangFallback = $option['@value']; | |
| 1194 | +                } else if (strpos($attributeLang, $similarLang . '_') === 0) { | |
| 1195 | +                    if ($similarLangFallback === false) { | |
| 1196 | + $similarLangFallback = $option['@value']; | |
| 1197 | + } | |
| 1198 | + } | |
| 1199 | +            } else { | |
| 1200 | + $englishFallback = $option; | |
| 1201 | + } | |
| 1202 | + } | |
| 1203 | + | |
| 1204 | +        if ($similarLangFallback !== false) { | |
| 1205 | + return $similarLangFallback; | |
| 1206 | +        } else if ($englishFallback !== false) { | |
| 1207 | + return $englishFallback; | |
| 1208 | + } | |
| 1209 | + return (string) $fallback; | |
| 1210 | + } | |
| 1211 | + | |
| 1212 | + /** | |
| 1213 | + * parses the app data array and enhanced the 'description' value | |
| 1214 | + * | |
| 1215 | + * @param array $data the app data | |
| 1216 | + * @param string $lang | |
| 1217 | + * @return array improved app data | |
| 1218 | + */ | |
| 1219 | +    public static function parseAppInfo(array $data, $lang = null) { | |
| 1220 | + | |
| 1221 | +        if ($lang && isset($data['name']) && is_array($data['name'])) { | |
| 1222 | + $data['name'] = self::findBestL10NOption($data['name'], $lang); | |
| 1223 | + } | |
| 1224 | +        if ($lang && isset($data['summary']) && is_array($data['summary'])) { | |
| 1225 | + $data['summary'] = self::findBestL10NOption($data['summary'], $lang); | |
| 1226 | + } | |
| 1227 | +        if ($lang && isset($data['description']) && is_array($data['description'])) { | |
| 1228 | + $data['description'] = trim(self::findBestL10NOption($data['description'], $lang)); | |
| 1229 | +        } else if (isset($data['description']) && is_string($data['description'])) { | |
| 1230 | + $data['description'] = trim($data['description']); | |
| 1231 | +        } else  { | |
| 1232 | + $data['description'] = ''; | |
| 1233 | + } | |
| 1234 | + | |
| 1235 | + return $data; | |
| 1236 | + } | |
| 1237 | + | |
| 1238 | + /** | |
| 1239 | + * @param \OCP\IConfig $config | |
| 1240 | + * @param \OCP\IL10N $l | |
| 1241 | + * @param array $info | |
| 1242 | + * @throws \Exception | |
| 1243 | + */ | |
| 1244 | +    public static function checkAppDependencies($config, $l, $info) { | |
| 1245 | + $dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l); | |
| 1246 | + $missing = $dependencyAnalyzer->analyze($info); | |
| 1247 | +        if (!empty($missing)) { | |
| 1248 | + $missingMsg = implode(PHP_EOL, $missing); | |
| 1249 | + throw new \Exception( | |
| 1250 | +                $l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s', | |
| 1251 | + [$info['name'], $missingMsg] | |
| 1252 | + ) | |
| 1253 | + ); | |
| 1254 | + } | |
| 1255 | + } | |
| 1256 | 1256 | } | 
| @@ -28,54 +28,54 @@ | ||
| 28 | 28 | use OCP\IServerContainer; | 
| 29 | 29 | |
| 30 | 30 |  class Manager implements IManager { | 
| 31 | - /** @var string[] */ | |
| 32 | - protected $sorters =[]; | |
| 31 | + /** @var string[] */ | |
| 32 | + protected $sorters =[]; | |
| 33 | 33 | |
| 34 | - /** @var ISorter[] */ | |
| 35 | - protected $sorterInstances = []; | |
| 36 | - /** @var IServerContainer */ | |
| 37 | - private $c; | |
| 34 | + /** @var ISorter[] */ | |
| 35 | + protected $sorterInstances = []; | |
| 36 | + /** @var IServerContainer */ | |
| 37 | + private $c; | |
| 38 | 38 | |
| 39 | -	public function __construct(IServerContainer $container) { | |
| 40 | - $this->c = $container; | |
| 41 | - } | |
| 39 | +    public function __construct(IServerContainer $container) { | |
| 40 | + $this->c = $container; | |
| 41 | + } | |
| 42 | 42 | |
| 43 | -	public function runSorters(array $sorters, array &$sortArray, array $context) { | |
| 44 | - $sorterInstances = $this->getSorters(); | |
| 45 | -		while($sorter = array_shift($sorters)) { | |
| 46 | -			if(isset($sorterInstances[$sorter])) { | |
| 47 | - $sorterInstances[$sorter]->sort($sortArray, $context); | |
| 48 | -			} else { | |
| 49 | -				$this->c->getLogger()->warning('No sorter for ID "{id}", skipping', [ | |
| 50 | - 'app' => 'core', 'id' => $sorter | |
| 51 | - ]); | |
| 52 | - } | |
| 53 | - } | |
| 54 | - } | |
| 43 | +    public function runSorters(array $sorters, array &$sortArray, array $context) { | |
| 44 | + $sorterInstances = $this->getSorters(); | |
| 45 | +        while($sorter = array_shift($sorters)) { | |
| 46 | +            if(isset($sorterInstances[$sorter])) { | |
| 47 | + $sorterInstances[$sorter]->sort($sortArray, $context); | |
| 48 | +            } else { | |
| 49 | +                $this->c->getLogger()->warning('No sorter for ID "{id}", skipping', [ | |
| 50 | + 'app' => 'core', 'id' => $sorter | |
| 51 | + ]); | |
| 52 | + } | |
| 53 | + } | |
| 54 | + } | |
| 55 | 55 | |
| 56 | -	public function registerSorter($className) { | |
| 57 | - $this->sorters[] = $className; | |
| 58 | - } | |
| 56 | +    public function registerSorter($className) { | |
| 57 | + $this->sorters[] = $className; | |
| 58 | + } | |
| 59 | 59 | |
| 60 | -	protected function getSorters() { | |
| 61 | -		if(count($this->sorterInstances) === 0) { | |
| 62 | -			foreach ($this->sorters as $sorter) { | |
| 63 | - /** @var ISorter $instance */ | |
| 64 | - $instance = $this->c->resolve($sorter); | |
| 65 | -				if(!$instance instanceof ISorter) { | |
| 66 | -					$this->c->getLogger()->notice('Skipping sorter which is not an instance of ISorter. Class name: {class}', | |
| 67 | - ['app' => 'core', 'class' => $sorter]); | |
| 68 | - continue; | |
| 69 | - } | |
| 70 | - $sorterId = trim($instance->getId()); | |
| 71 | -				if(trim($sorterId) === '') { | |
| 72 | -					$this->c->getLogger()->notice('Skipping sorter with empty ID. Class name: {class}', | |
| 73 | - ['app' => 'core', 'class' => $sorter]); | |
| 74 | - continue; | |
| 75 | - } | |
| 76 | - $this->sorterInstances[$sorterId] = $instance; | |
| 77 | - } | |
| 78 | - } | |
| 79 | - return $this->sorterInstances; | |
| 80 | - } | |
| 60 | +    protected function getSorters() { | |
| 61 | +        if(count($this->sorterInstances) === 0) { | |
| 62 | +            foreach ($this->sorters as $sorter) { | |
| 63 | + /** @var ISorter $instance */ | |
| 64 | + $instance = $this->c->resolve($sorter); | |
| 65 | +                if(!$instance instanceof ISorter) { | |
| 66 | +                    $this->c->getLogger()->notice('Skipping sorter which is not an instance of ISorter. Class name: {class}', | |
| 67 | + ['app' => 'core', 'class' => $sorter]); | |
| 68 | + continue; | |
| 69 | + } | |
| 70 | + $sorterId = trim($instance->getId()); | |
| 71 | +                if(trim($sorterId) === '') { | |
| 72 | +                    $this->c->getLogger()->notice('Skipping sorter with empty ID. Class name: {class}', | |
| 73 | + ['app' => 'core', 'class' => $sorter]); | |
| 74 | + continue; | |
| 75 | + } | |
| 76 | + $this->sorterInstances[$sorterId] = $instance; | |
| 77 | + } | |
| 78 | + } | |
| 79 | + return $this->sorterInstances; | |
| 80 | + } | |
| 81 | 81 | } |