| @@ -93,7 +93,7 @@ | ||
| 93 | 93 | /** | 
| 94 | 94 | * returns a list of all possible property names | 
| 95 | 95 | * | 
| 96 | - * @return array | |
| 96 | + * @return string[] | |
| 97 | 97 | */ | 
| 98 | 98 |  	static public function getPropertyNames() { | 
| 99 | 99 | return [ | 
| @@ -36,270 +36,270 @@ | ||
| 36 | 36 | use Sabre\DAV\PropPatch; | 
| 37 | 37 | |
| 38 | 38 |  class CommentNode implements \Sabre\DAV\INode, \Sabre\DAV\IProperties { | 
| 39 | - const NS_OWNCLOUD = 'http://owncloud.org/ns'; | |
| 39 | + const NS_OWNCLOUD = 'http://owncloud.org/ns'; | |
| 40 | 40 | |
| 41 | -	const PROPERTY_NAME_UNREAD = '{http://owncloud.org/ns}isUnread'; | |
| 42 | -	const PROPERTY_NAME_MESSAGE = '{http://owncloud.org/ns}message'; | |
| 43 | -	const PROPERTY_NAME_ACTOR_DISPLAYNAME = '{http://owncloud.org/ns}actorDisplayName'; | |
| 44 | -	const PROPERTY_NAME_MENTIONS = '{http://owncloud.org/ns}mentions'; | |
| 45 | -	const PROPERTY_NAME_MENTION = '{http://owncloud.org/ns}mention'; | |
| 46 | -	const PROPERTY_NAME_MENTION_TYPE = '{http://owncloud.org/ns}mentionType'; | |
| 47 | -	const PROPERTY_NAME_MENTION_ID = '{http://owncloud.org/ns}mentionId'; | |
| 48 | -	const PROPERTY_NAME_MENTION_DISPLAYNAME = '{http://owncloud.org/ns}mentionDisplayName'; | |
| 41 | +    const PROPERTY_NAME_UNREAD = '{http://owncloud.org/ns}isUnread'; | |
| 42 | +    const PROPERTY_NAME_MESSAGE = '{http://owncloud.org/ns}message'; | |
| 43 | +    const PROPERTY_NAME_ACTOR_DISPLAYNAME = '{http://owncloud.org/ns}actorDisplayName'; | |
| 44 | +    const PROPERTY_NAME_MENTIONS = '{http://owncloud.org/ns}mentions'; | |
| 45 | +    const PROPERTY_NAME_MENTION = '{http://owncloud.org/ns}mention'; | |
| 46 | +    const PROPERTY_NAME_MENTION_TYPE = '{http://owncloud.org/ns}mentionType'; | |
| 47 | +    const PROPERTY_NAME_MENTION_ID = '{http://owncloud.org/ns}mentionId'; | |
| 48 | +    const PROPERTY_NAME_MENTION_DISPLAYNAME = '{http://owncloud.org/ns}mentionDisplayName'; | |
| 49 | 49 | |
| 50 | - /** @var IComment */ | |
| 51 | - public $comment; | |
| 50 | + /** @var IComment */ | |
| 51 | + public $comment; | |
| 52 | 52 | |
| 53 | - /** @var ICommentsManager */ | |
| 54 | - protected $commentsManager; | |
| 53 | + /** @var ICommentsManager */ | |
| 54 | + protected $commentsManager; | |
| 55 | 55 | |
| 56 | - /** @var ILogger */ | |
| 57 | - protected $logger; | |
| 56 | + /** @var ILogger */ | |
| 57 | + protected $logger; | |
| 58 | 58 | |
| 59 | - /** @var array list of properties with key being their name and value their setter */ | |
| 60 | - protected $properties = []; | |
| 59 | + /** @var array list of properties with key being their name and value their setter */ | |
| 60 | + protected $properties = []; | |
| 61 | 61 | |
| 62 | - /** @var IUserManager */ | |
| 63 | - protected $userManager; | |
| 62 | + /** @var IUserManager */ | |
| 63 | + protected $userManager; | |
| 64 | 64 | |
| 65 | - /** @var IUserSession */ | |
| 66 | - protected $userSession; | |
| 65 | + /** @var IUserSession */ | |
| 66 | + protected $userSession; | |
| 67 | 67 | |
| 68 | - /** | |
| 69 | - * CommentNode constructor. | |
| 70 | - * | |
| 71 | - * @param ICommentsManager $commentsManager | |
| 72 | - * @param IComment $comment | |
| 73 | - * @param IUserManager $userManager | |
| 74 | - * @param IUserSession $userSession | |
| 75 | - * @param ILogger $logger | |
| 76 | - */ | |
| 77 | - public function __construct( | |
| 78 | - ICommentsManager $commentsManager, | |
| 79 | - IComment $comment, | |
| 80 | - IUserManager $userManager, | |
| 81 | - IUserSession $userSession, | |
| 82 | - ILogger $logger | |
| 83 | -	) { | |
| 84 | - $this->commentsManager = $commentsManager; | |
| 85 | - $this->comment = $comment; | |
| 86 | - $this->logger = $logger; | |
| 68 | + /** | |
| 69 | + * CommentNode constructor. | |
| 70 | + * | |
| 71 | + * @param ICommentsManager $commentsManager | |
| 72 | + * @param IComment $comment | |
| 73 | + * @param IUserManager $userManager | |
| 74 | + * @param IUserSession $userSession | |
| 75 | + * @param ILogger $logger | |
| 76 | + */ | |
| 77 | + public function __construct( | |
| 78 | + ICommentsManager $commentsManager, | |
| 79 | + IComment $comment, | |
| 80 | + IUserManager $userManager, | |
| 81 | + IUserSession $userSession, | |
| 82 | + ILogger $logger | |
| 83 | +    ) { | |
| 84 | + $this->commentsManager = $commentsManager; | |
| 85 | + $this->comment = $comment; | |
| 86 | + $this->logger = $logger; | |
| 87 | 87 | |
| 88 | - $methods = get_class_methods($this->comment); | |
| 89 | -		$methods = array_filter($methods, function($name){ | |
| 90 | - return strpos($name, 'get') === 0; | |
| 91 | - }); | |
| 92 | -		foreach($methods as $getter) { | |
| 93 | -			if($getter === 'getMentions') { | |
| 94 | - continue; // special treatment | |
| 95 | - } | |
| 96 | -			$name = '{'.self::NS_OWNCLOUD.'}' . lcfirst(substr($getter, 3)); | |
| 97 | - $this->properties[$name] = $getter; | |
| 98 | - } | |
| 99 | - $this->userManager = $userManager; | |
| 100 | - $this->userSession = $userSession; | |
| 101 | - } | |
| 88 | + $methods = get_class_methods($this->comment); | |
| 89 | +        $methods = array_filter($methods, function($name){ | |
| 90 | + return strpos($name, 'get') === 0; | |
| 91 | + }); | |
| 92 | +        foreach($methods as $getter) { | |
| 93 | +            if($getter === 'getMentions') { | |
| 94 | + continue; // special treatment | |
| 95 | + } | |
| 96 | +            $name = '{'.self::NS_OWNCLOUD.'}' . lcfirst(substr($getter, 3)); | |
| 97 | + $this->properties[$name] = $getter; | |
| 98 | + } | |
| 99 | + $this->userManager = $userManager; | |
| 100 | + $this->userSession = $userSession; | |
| 101 | + } | |
| 102 | 102 | |
| 103 | - /** | |
| 104 | - * returns a list of all possible property names | |
| 105 | - * | |
| 106 | - * @return array | |
| 107 | - */ | |
| 108 | -	static public function getPropertyNames() { | |
| 109 | - return [ | |
| 110 | -			'{http://owncloud.org/ns}id', | |
| 111 | -			'{http://owncloud.org/ns}parentId', | |
| 112 | -			'{http://owncloud.org/ns}topmostParentId', | |
| 113 | -			'{http://owncloud.org/ns}childrenCount', | |
| 114 | -			'{http://owncloud.org/ns}verb', | |
| 115 | -			'{http://owncloud.org/ns}actorType', | |
| 116 | -			'{http://owncloud.org/ns}actorId', | |
| 117 | -			'{http://owncloud.org/ns}creationDateTime', | |
| 118 | -			'{http://owncloud.org/ns}latestChildDateTime', | |
| 119 | -			'{http://owncloud.org/ns}objectType', | |
| 120 | -			'{http://owncloud.org/ns}objectId', | |
| 121 | - // re-used property names are defined as constants | |
| 122 | - self::PROPERTY_NAME_MESSAGE, | |
| 123 | - self::PROPERTY_NAME_ACTOR_DISPLAYNAME, | |
| 124 | - self::PROPERTY_NAME_UNREAD, | |
| 125 | - self::PROPERTY_NAME_MENTIONS, | |
| 126 | - self::PROPERTY_NAME_MENTION, | |
| 127 | - self::PROPERTY_NAME_MENTION_TYPE, | |
| 128 | - self::PROPERTY_NAME_MENTION_ID, | |
| 129 | - self::PROPERTY_NAME_MENTION_DISPLAYNAME, | |
| 130 | - ]; | |
| 131 | - } | |
| 103 | + /** | |
| 104 | + * returns a list of all possible property names | |
| 105 | + * | |
| 106 | + * @return array | |
| 107 | + */ | |
| 108 | +    static public function getPropertyNames() { | |
| 109 | + return [ | |
| 110 | +            '{http://owncloud.org/ns}id', | |
| 111 | +            '{http://owncloud.org/ns}parentId', | |
| 112 | +            '{http://owncloud.org/ns}topmostParentId', | |
| 113 | +            '{http://owncloud.org/ns}childrenCount', | |
| 114 | +            '{http://owncloud.org/ns}verb', | |
| 115 | +            '{http://owncloud.org/ns}actorType', | |
| 116 | +            '{http://owncloud.org/ns}actorId', | |
| 117 | +            '{http://owncloud.org/ns}creationDateTime', | |
| 118 | +            '{http://owncloud.org/ns}latestChildDateTime', | |
| 119 | +            '{http://owncloud.org/ns}objectType', | |
| 120 | +            '{http://owncloud.org/ns}objectId', | |
| 121 | + // re-used property names are defined as constants | |
| 122 | + self::PROPERTY_NAME_MESSAGE, | |
| 123 | + self::PROPERTY_NAME_ACTOR_DISPLAYNAME, | |
| 124 | + self::PROPERTY_NAME_UNREAD, | |
| 125 | + self::PROPERTY_NAME_MENTIONS, | |
| 126 | + self::PROPERTY_NAME_MENTION, | |
| 127 | + self::PROPERTY_NAME_MENTION_TYPE, | |
| 128 | + self::PROPERTY_NAME_MENTION_ID, | |
| 129 | + self::PROPERTY_NAME_MENTION_DISPLAYNAME, | |
| 130 | + ]; | |
| 131 | + } | |
| 132 | 132 | |
| 133 | -	protected function checkWriteAccessOnComment() { | |
| 134 | - $user = $this->userSession->getUser(); | |
| 135 | - if( $this->comment->getActorType() !== 'users' | |
| 136 | - || is_null($user) | |
| 137 | - || $this->comment->getActorId() !== $user->getUID() | |
| 138 | -		) { | |
| 139 | -			throw new Forbidden('Only authors are allowed to edit their comment.'); | |
| 140 | - } | |
| 141 | - } | |
| 133 | +    protected function checkWriteAccessOnComment() { | |
| 134 | + $user = $this->userSession->getUser(); | |
| 135 | + if( $this->comment->getActorType() !== 'users' | |
| 136 | + || is_null($user) | |
| 137 | + || $this->comment->getActorId() !== $user->getUID() | |
| 138 | +        ) { | |
| 139 | +            throw new Forbidden('Only authors are allowed to edit their comment.'); | |
| 140 | + } | |
| 141 | + } | |
| 142 | 142 | |
| 143 | - /** | |
| 144 | - * Deleted the current node | |
| 145 | - * | |
| 146 | - * @return void | |
| 147 | - */ | |
| 148 | -	function delete() { | |
| 149 | - $this->checkWriteAccessOnComment(); | |
| 150 | - $this->commentsManager->delete($this->comment->getId()); | |
| 151 | - } | |
| 143 | + /** | |
| 144 | + * Deleted the current node | |
| 145 | + * | |
| 146 | + * @return void | |
| 147 | + */ | |
| 148 | +    function delete() { | |
| 149 | + $this->checkWriteAccessOnComment(); | |
| 150 | + $this->commentsManager->delete($this->comment->getId()); | |
| 151 | + } | |
| 152 | 152 | |
| 153 | - /** | |
| 154 | - * Returns the name of the node. | |
| 155 | - * | |
| 156 | - * This is used to generate the url. | |
| 157 | - * | |
| 158 | - * @return string | |
| 159 | - */ | |
| 160 | -	function getName() { | |
| 161 | - return $this->comment->getId(); | |
| 162 | - } | |
| 153 | + /** | |
| 154 | + * Returns the name of the node. | |
| 155 | + * | |
| 156 | + * This is used to generate the url. | |
| 157 | + * | |
| 158 | + * @return string | |
| 159 | + */ | |
| 160 | +    function getName() { | |
| 161 | + return $this->comment->getId(); | |
| 162 | + } | |
| 163 | 163 | |
| 164 | - /** | |
| 165 | - * Renames the node | |
| 166 | - * | |
| 167 | - * @param string $name The new name | |
| 168 | - * @throws MethodNotAllowed | |
| 169 | - */ | |
| 170 | -	function setName($name) { | |
| 171 | - throw new MethodNotAllowed(); | |
| 172 | - } | |
| 164 | + /** | |
| 165 | + * Renames the node | |
| 166 | + * | |
| 167 | + * @param string $name The new name | |
| 168 | + * @throws MethodNotAllowed | |
| 169 | + */ | |
| 170 | +    function setName($name) { | |
| 171 | + throw new MethodNotAllowed(); | |
| 172 | + } | |
| 173 | 173 | |
| 174 | - /** | |
| 175 | - * Returns the last modification time, as a unix timestamp | |
| 176 | - * | |
| 177 | - * @return int | |
| 178 | - */ | |
| 179 | -	function getLastModified() { | |
| 180 | - return null; | |
| 181 | - } | |
| 174 | + /** | |
| 175 | + * Returns the last modification time, as a unix timestamp | |
| 176 | + * | |
| 177 | + * @return int | |
| 178 | + */ | |
| 179 | +    function getLastModified() { | |
| 180 | + return null; | |
| 181 | + } | |
| 182 | 182 | |
| 183 | - /** | |
| 184 | - * update the comment's message | |
| 185 | - * | |
| 186 | - * @param $propertyValue | |
| 187 | - * @return bool | |
| 188 | - * @throws BadRequest | |
| 189 | - * @throws \Exception | |
| 190 | - */ | |
| 191 | -	public function updateComment($propertyValue) { | |
| 192 | - $this->checkWriteAccessOnComment(); | |
| 193 | -		try { | |
| 194 | - $this->comment->setMessage($propertyValue); | |
| 195 | - $this->commentsManager->save($this->comment); | |
| 196 | - return true; | |
| 197 | -		} catch (\Exception $e) { | |
| 198 | - $this->logger->logException($e, ['app' => 'dav/comments']); | |
| 199 | -			if($e instanceof MessageTooLongException) { | |
| 200 | - $msg = 'Message exceeds allowed character limit of '; | |
| 201 | - throw new BadRequest($msg . IComment::MAX_MESSAGE_LENGTH, 0, $e); | |
| 202 | - } | |
| 203 | - throw $e; | |
| 204 | - } | |
| 205 | - } | |
| 183 | + /** | |
| 184 | + * update the comment's message | |
| 185 | + * | |
| 186 | + * @param $propertyValue | |
| 187 | + * @return bool | |
| 188 | + * @throws BadRequest | |
| 189 | + * @throws \Exception | |
| 190 | + */ | |
| 191 | +    public function updateComment($propertyValue) { | |
| 192 | + $this->checkWriteAccessOnComment(); | |
| 193 | +        try { | |
| 194 | + $this->comment->setMessage($propertyValue); | |
| 195 | + $this->commentsManager->save($this->comment); | |
| 196 | + return true; | |
| 197 | +        } catch (\Exception $e) { | |
| 198 | + $this->logger->logException($e, ['app' => 'dav/comments']); | |
| 199 | +            if($e instanceof MessageTooLongException) { | |
| 200 | + $msg = 'Message exceeds allowed character limit of '; | |
| 201 | + throw new BadRequest($msg . IComment::MAX_MESSAGE_LENGTH, 0, $e); | |
| 202 | + } | |
| 203 | + throw $e; | |
| 204 | + } | |
| 205 | + } | |
| 206 | 206 | |
| 207 | - /** | |
| 208 | - * Updates properties on this node. | |
| 209 | - * | |
| 210 | - * This method received a PropPatch object, which contains all the | |
| 211 | - * information about the update. | |
| 212 | - * | |
| 213 | - * To update specific properties, call the 'handle' method on this object. | |
| 214 | - * Read the PropPatch documentation for more information. | |
| 215 | - * | |
| 216 | - * @param PropPatch $propPatch | |
| 217 | - * @return void | |
| 218 | - */ | |
| 219 | -	function propPatch(PropPatch $propPatch) { | |
| 220 | - // other properties than 'message' are read only | |
| 221 | - $propPatch->handle(self::PROPERTY_NAME_MESSAGE, [$this, 'updateComment']); | |
| 222 | - } | |
| 207 | + /** | |
| 208 | + * Updates properties on this node. | |
| 209 | + * | |
| 210 | + * This method received a PropPatch object, which contains all the | |
| 211 | + * information about the update. | |
| 212 | + * | |
| 213 | + * To update specific properties, call the 'handle' method on this object. | |
| 214 | + * Read the PropPatch documentation for more information. | |
| 215 | + * | |
| 216 | + * @param PropPatch $propPatch | |
| 217 | + * @return void | |
| 218 | + */ | |
| 219 | +    function propPatch(PropPatch $propPatch) { | |
| 220 | + // other properties than 'message' are read only | |
| 221 | + $propPatch->handle(self::PROPERTY_NAME_MESSAGE, [$this, 'updateComment']); | |
| 222 | + } | |
| 223 | 223 | |
| 224 | - /** | |
| 225 | - * Returns a list of properties for this nodes. | |
| 226 | - * | |
| 227 | - * The properties list is a list of propertynames the client requested, | |
| 228 | -	 * encoded in clark-notation {xmlnamespace}tagname | |
| 229 | - * | |
| 230 | - * If the array is empty, it means 'all properties' were requested. | |
| 231 | - * | |
| 232 | - * Note that it's fine to liberally give properties back, instead of | |
| 233 | - * conforming to the list of requested properties. | |
| 234 | - * The Server class will filter out the extra. | |
| 235 | - * | |
| 236 | - * @param array $properties | |
| 237 | - * @return array | |
| 238 | - */ | |
| 239 | -	function getProperties($properties) { | |
| 240 | - $properties = array_keys($this->properties); | |
| 224 | + /** | |
| 225 | + * Returns a list of properties for this nodes. | |
| 226 | + * | |
| 227 | + * The properties list is a list of propertynames the client requested, | |
| 228 | +     * encoded in clark-notation {xmlnamespace}tagname | |
| 229 | + * | |
| 230 | + * If the array is empty, it means 'all properties' were requested. | |
| 231 | + * | |
| 232 | + * Note that it's fine to liberally give properties back, instead of | |
| 233 | + * conforming to the list of requested properties. | |
| 234 | + * The Server class will filter out the extra. | |
| 235 | + * | |
| 236 | + * @param array $properties | |
| 237 | + * @return array | |
| 238 | + */ | |
| 239 | +    function getProperties($properties) { | |
| 240 | + $properties = array_keys($this->properties); | |
| 241 | 241 | |
| 242 | - $result = []; | |
| 243 | -		foreach($properties as $property) { | |
| 244 | - $getter = $this->properties[$property]; | |
| 245 | -			if(method_exists($this->comment, $getter)) { | |
| 246 | - $result[$property] = $this->comment->$getter(); | |
| 247 | - } | |
| 248 | - } | |
| 242 | + $result = []; | |
| 243 | +        foreach($properties as $property) { | |
| 244 | + $getter = $this->properties[$property]; | |
| 245 | +            if(method_exists($this->comment, $getter)) { | |
| 246 | + $result[$property] = $this->comment->$getter(); | |
| 247 | + } | |
| 248 | + } | |
| 249 | 249 | |
| 250 | -		if($this->comment->getActorType() === 'users') { | |
| 251 | - $user = $this->userManager->get($this->comment->getActorId()); | |
| 252 | - $displayName = is_null($user) ? null : $user->getDisplayName(); | |
| 253 | - $result[self::PROPERTY_NAME_ACTOR_DISPLAYNAME] = $displayName; | |
| 254 | - } | |
| 250 | +        if($this->comment->getActorType() === 'users') { | |
| 251 | + $user = $this->userManager->get($this->comment->getActorId()); | |
| 252 | + $displayName = is_null($user) ? null : $user->getDisplayName(); | |
| 253 | + $result[self::PROPERTY_NAME_ACTOR_DISPLAYNAME] = $displayName; | |
| 254 | + } | |
| 255 | 255 | |
| 256 | - $result[self::PROPERTY_NAME_MENTIONS] = $this->composeMentionsPropertyValue(); | |
| 256 | + $result[self::PROPERTY_NAME_MENTIONS] = $this->composeMentionsPropertyValue(); | |
| 257 | 257 | |
| 258 | - $unread = null; | |
| 259 | - $user = $this->userSession->getUser(); | |
| 260 | -		if(!is_null($user)) { | |
| 261 | - $readUntil = $this->commentsManager->getReadMark( | |
| 262 | - $this->comment->getObjectType(), | |
| 263 | - $this->comment->getObjectId(), | |
| 264 | - $user | |
| 265 | - ); | |
| 266 | -			if(is_null($readUntil)) { | |
| 267 | - $unread = 'true'; | |
| 268 | -			} else { | |
| 269 | - $unread = $this->comment->getCreationDateTime() > $readUntil; | |
| 270 | - // re-format for output | |
| 271 | - $unread = $unread ? 'true' : 'false'; | |
| 272 | - } | |
| 273 | - } | |
| 274 | - $result[self::PROPERTY_NAME_UNREAD] = $unread; | |
| 258 | + $unread = null; | |
| 259 | + $user = $this->userSession->getUser(); | |
| 260 | +        if(!is_null($user)) { | |
| 261 | + $readUntil = $this->commentsManager->getReadMark( | |
| 262 | + $this->comment->getObjectType(), | |
| 263 | + $this->comment->getObjectId(), | |
| 264 | + $user | |
| 265 | + ); | |
| 266 | +            if(is_null($readUntil)) { | |
| 267 | + $unread = 'true'; | |
| 268 | +            } else { | |
| 269 | + $unread = $this->comment->getCreationDateTime() > $readUntil; | |
| 270 | + // re-format for output | |
| 271 | + $unread = $unread ? 'true' : 'false'; | |
| 272 | + } | |
| 273 | + } | |
| 274 | + $result[self::PROPERTY_NAME_UNREAD] = $unread; | |
| 275 | 275 | |
| 276 | - return $result; | |
| 277 | - } | |
| 276 | + return $result; | |
| 277 | + } | |
| 278 | 278 | |
| 279 | - /** | |
| 280 | - * transforms a mentions array as returned from IComment->getMentions to an | |
| 281 | - * array with DAV-compatible structure that can be assigned to the | |
| 282 | - * PROPERTY_NAME_MENTION property. | |
| 283 | - * | |
| 284 | - * @return array | |
| 285 | - */ | |
| 286 | -	protected function composeMentionsPropertyValue() { | |
| 287 | -		return array_map(function($mention) { | |
| 288 | -			try { | |
| 289 | - $displayName = $this->commentsManager->resolveDisplayName($mention['type'], $mention['id']); | |
| 290 | -			} catch (\OutOfBoundsException $e) { | |
| 291 | - $this->logger->logException($e); | |
| 292 | - // No displayname, upon client's discretion what to display. | |
| 293 | - $displayName = ''; | |
| 294 | - } | |
| 279 | + /** | |
| 280 | + * transforms a mentions array as returned from IComment->getMentions to an | |
| 281 | + * array with DAV-compatible structure that can be assigned to the | |
| 282 | + * PROPERTY_NAME_MENTION property. | |
| 283 | + * | |
| 284 | + * @return array | |
| 285 | + */ | |
| 286 | +    protected function composeMentionsPropertyValue() { | |
| 287 | +        return array_map(function($mention) { | |
| 288 | +            try { | |
| 289 | + $displayName = $this->commentsManager->resolveDisplayName($mention['type'], $mention['id']); | |
| 290 | +            } catch (\OutOfBoundsException $e) { | |
| 291 | + $this->logger->logException($e); | |
| 292 | + // No displayname, upon client's discretion what to display. | |
| 293 | + $displayName = ''; | |
| 294 | + } | |
| 295 | 295 | |
| 296 | - return [ | |
| 297 | - self::PROPERTY_NAME_MENTION => [ | |
| 298 | - self::PROPERTY_NAME_MENTION_TYPE => $mention['type'], | |
| 299 | - self::PROPERTY_NAME_MENTION_ID => $mention['id'], | |
| 300 | - self::PROPERTY_NAME_MENTION_DISPLAYNAME => $displayName, | |
| 301 | - ] | |
| 302 | - ]; | |
| 303 | - }, $this->comment->getMentions()); | |
| 304 | - } | |
| 296 | + return [ | |
| 297 | + self::PROPERTY_NAME_MENTION => [ | |
| 298 | + self::PROPERTY_NAME_MENTION_TYPE => $mention['type'], | |
| 299 | + self::PROPERTY_NAME_MENTION_ID => $mention['id'], | |
| 300 | + self::PROPERTY_NAME_MENTION_DISPLAYNAME => $displayName, | |
| 301 | + ] | |
| 302 | + ]; | |
| 303 | + }, $this->comment->getMentions()); | |
| 304 | + } | |
| 305 | 305 | } | 
| @@ -86,14 +86,14 @@ discard block | ||
| 86 | 86 | $this->logger = $logger; | 
| 87 | 87 | |
| 88 | 88 | $methods = get_class_methods($this->comment); | 
| 89 | -		$methods = array_filter($methods, function($name){ | |
| 89 | +		$methods = array_filter($methods, function($name) { | |
| 90 | 90 | return strpos($name, 'get') === 0; | 
| 91 | 91 | }); | 
| 92 | -		foreach($methods as $getter) { | |
| 93 | -			if($getter === 'getMentions') { | |
| 94 | - continue; // special treatment | |
| 92 | +		foreach ($methods as $getter) { | |
| 93 | +			if ($getter === 'getMentions') { | |
| 94 | + continue; // special treatment | |
| 95 | 95 | } | 
| 96 | -			$name = '{'.self::NS_OWNCLOUD.'}' . lcfirst(substr($getter, 3)); | |
| 96 | +			$name = '{'.self::NS_OWNCLOUD.'}'.lcfirst(substr($getter, 3)); | |
| 97 | 97 | $this->properties[$name] = $getter; | 
| 98 | 98 | } | 
| 99 | 99 | $this->userManager = $userManager; | 
| @@ -132,7 +132,7 @@ discard block | ||
| 132 | 132 | |
| 133 | 133 |  	protected function checkWriteAccessOnComment() { | 
| 134 | 134 | $user = $this->userSession->getUser(); | 
| 135 | - if( $this->comment->getActorType() !== 'users' | |
| 135 | + if ($this->comment->getActorType() !== 'users' | |
| 136 | 136 | || is_null($user) | 
| 137 | 137 | || $this->comment->getActorId() !== $user->getUID() | 
| 138 | 138 |  		) { | 
| @@ -196,9 +196,9 @@ discard block | ||
| 196 | 196 | return true; | 
| 197 | 197 |  		} catch (\Exception $e) { | 
| 198 | 198 | $this->logger->logException($e, ['app' => 'dav/comments']); | 
| 199 | -			if($e instanceof MessageTooLongException) { | |
| 199 | +			if ($e instanceof MessageTooLongException) { | |
| 200 | 200 | $msg = 'Message exceeds allowed character limit of '; | 
| 201 | - throw new BadRequest($msg . IComment::MAX_MESSAGE_LENGTH, 0, $e); | |
| 201 | + throw new BadRequest($msg.IComment::MAX_MESSAGE_LENGTH, 0, $e); | |
| 202 | 202 | } | 
| 203 | 203 | throw $e; | 
| 204 | 204 | } | 
| @@ -240,14 +240,14 @@ discard block | ||
| 240 | 240 | $properties = array_keys($this->properties); | 
| 241 | 241 | |
| 242 | 242 | $result = []; | 
| 243 | -		foreach($properties as $property) { | |
| 243 | +		foreach ($properties as $property) { | |
| 244 | 244 | $getter = $this->properties[$property]; | 
| 245 | -			if(method_exists($this->comment, $getter)) { | |
| 245 | +			if (method_exists($this->comment, $getter)) { | |
| 246 | 246 | $result[$property] = $this->comment->$getter(); | 
| 247 | 247 | } | 
| 248 | 248 | } | 
| 249 | 249 | |
| 250 | -		if($this->comment->getActorType() === 'users') { | |
| 250 | +		if ($this->comment->getActorType() === 'users') { | |
| 251 | 251 | $user = $this->userManager->get($this->comment->getActorId()); | 
| 252 | 252 | $displayName = is_null($user) ? null : $user->getDisplayName(); | 
| 253 | 253 | $result[self::PROPERTY_NAME_ACTOR_DISPLAYNAME] = $displayName; | 
| @@ -256,14 +256,14 @@ discard block | ||
| 256 | 256 | $result[self::PROPERTY_NAME_MENTIONS] = $this->composeMentionsPropertyValue(); | 
| 257 | 257 | |
| 258 | 258 | $unread = null; | 
| 259 | - $user = $this->userSession->getUser(); | |
| 260 | -		if(!is_null($user)) { | |
| 259 | + $user = $this->userSession->getUser(); | |
| 260 | +		if (!is_null($user)) { | |
| 261 | 261 | $readUntil = $this->commentsManager->getReadMark( | 
| 262 | 262 | $this->comment->getObjectType(), | 
| 263 | 263 | $this->comment->getObjectId(), | 
| 264 | 264 | $user | 
| 265 | 265 | ); | 
| 266 | -			if(is_null($readUntil)) { | |
| 266 | +			if (is_null($readUntil)) { | |
| 267 | 267 | $unread = 'true'; | 
| 268 | 268 |  			} else { | 
| 269 | 269 | $unread = $this->comment->getCreationDateTime() > $readUntil; | 
| @@ -138,7 +138,7 @@ | ||
| 138 | 138 |  	 * This will be used in the {DAV:}supported-report-set property. | 
| 139 | 139 | * | 
| 140 | 140 | * @param string $uri | 
| 141 | - * @return array | |
| 141 | + * @return string[] | |
| 142 | 142 | */ | 
| 143 | 143 |  	public function getSupportedReportSet($uri) { | 
| 144 | 144 | return [self::REPORT_NAME]; | 
| @@ -43,213 +43,213 @@ | ||
| 43 | 43 | * Sabre plugin to handle comments: | 
| 44 | 44 | */ | 
| 45 | 45 |  class CommentsPlugin extends ServerPlugin { | 
| 46 | - // namespace | |
| 47 | - const NS_OWNCLOUD = 'http://owncloud.org/ns'; | |
| 48 | - | |
| 49 | -	const REPORT_NAME            = '{http://owncloud.org/ns}filter-comments'; | |
| 50 | -	const REPORT_PARAM_LIMIT     = '{http://owncloud.org/ns}limit'; | |
| 51 | -	const REPORT_PARAM_OFFSET    = '{http://owncloud.org/ns}offset'; | |
| 52 | -	const REPORT_PARAM_TIMESTAMP = '{http://owncloud.org/ns}datetime'; | |
| 53 | - | |
| 54 | - /** @var ICommentsManager */ | |
| 55 | - protected $commentsManager; | |
| 56 | - | |
| 57 | - /** @var \Sabre\DAV\Server $server */ | |
| 58 | - private $server; | |
| 59 | - | |
| 60 | - /** @var \OCP\IUserSession */ | |
| 61 | - protected $userSession; | |
| 62 | - | |
| 63 | - /** | |
| 64 | - * Comments plugin | |
| 65 | - * | |
| 66 | - * @param ICommentsManager $commentsManager | |
| 67 | - * @param IUserSession $userSession | |
| 68 | - */ | |
| 69 | -	public function __construct(ICommentsManager $commentsManager, IUserSession $userSession) { | |
| 70 | - $this->commentsManager = $commentsManager; | |
| 71 | - $this->userSession = $userSession; | |
| 72 | - } | |
| 73 | - | |
| 74 | - /** | |
| 75 | - * This initializes the plugin. | |
| 76 | - * | |
| 77 | - * This function is called by Sabre\DAV\Server, after | |
| 78 | - * addPlugin is called. | |
| 79 | - * | |
| 80 | - * This method should set up the required event subscriptions. | |
| 81 | - * | |
| 82 | - * @param Server $server | |
| 83 | - * @return void | |
| 84 | - */ | |
| 85 | -	function initialize(Server $server) { | |
| 86 | - $this->server = $server; | |
| 87 | -		if(strpos($this->server->getRequestUri(), 'comments/') !== 0) { | |
| 88 | - return; | |
| 89 | - } | |
| 90 | - | |
| 91 | - $this->server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc'; | |
| 92 | - | |
| 93 | -		$this->server->xml->classMap['DateTime'] = function(Writer $writer, \DateTime $value) { | |
| 94 | - $writer->write(\Sabre\HTTP\toDate($value)); | |
| 95 | - }; | |
| 96 | - | |
| 97 | -		$this->server->on('report', [$this, 'onReport']); | |
| 98 | -		$this->server->on('method:POST', [$this, 'httpPost']); | |
| 99 | - } | |
| 100 | - | |
| 101 | - /** | |
| 102 | - * POST operation on Comments collections | |
| 103 | - * | |
| 104 | - * @param RequestInterface $request request object | |
| 105 | - * @param ResponseInterface $response response object | |
| 106 | - * @return null|false | |
| 107 | - */ | |
| 108 | -	public function httpPost(RequestInterface $request, ResponseInterface $response) { | |
| 109 | - $path = $request->getPath(); | |
| 110 | - $node = $this->server->tree->getNodeForPath($path); | |
| 111 | -		if (!$node instanceof EntityCollection) { | |
| 112 | - return null; | |
| 113 | - } | |
| 114 | - | |
| 115 | - $data = $request->getBodyAsString(); | |
| 116 | - $comment = $this->createComment( | |
| 117 | - $node->getName(), | |
| 118 | - $node->getId(), | |
| 119 | - $data, | |
| 120 | -			$request->getHeader('Content-Type') | |
| 121 | - ); | |
| 122 | - | |
| 123 | - // update read marker for the current user/poster to avoid | |
| 124 | - // having their own comments marked as unread | |
| 125 | - $node->setReadMarker(null); | |
| 126 | - | |
| 127 | - $url = rtrim($request->getUrl(), '/') . '/' . urlencode($comment->getId()); | |
| 128 | - | |
| 129 | -		$response->setHeader('Content-Location', $url); | |
| 130 | - | |
| 131 | - // created | |
| 132 | - $response->setStatus(201); | |
| 133 | - return false; | |
| 134 | - } | |
| 135 | - | |
| 136 | - /** | |
| 137 | - * Returns a list of reports this plugin supports. | |
| 138 | - * | |
| 139 | -	 * This will be used in the {DAV:}supported-report-set property. | |
| 140 | - * | |
| 141 | - * @param string $uri | |
| 142 | - * @return array | |
| 143 | - */ | |
| 144 | -	public function getSupportedReportSet($uri) { | |
| 145 | - return [self::REPORT_NAME]; | |
| 146 | - } | |
| 147 | - | |
| 148 | - /** | |
| 149 | - * REPORT operations to look for comments | |
| 150 | - * | |
| 151 | - * @param string $reportName | |
| 152 | - * @param array $report | |
| 153 | - * @param string $uri | |
| 154 | - * @return bool | |
| 155 | - * @throws NotFound | |
| 156 | - * @throws ReportNotSupported | |
| 157 | - */ | |
| 158 | -	public function onReport($reportName, $report, $uri) { | |
| 159 | - $node = $this->server->tree->getNodeForPath($uri); | |
| 160 | -		if(!$node instanceof EntityCollection || $reportName !== self::REPORT_NAME) { | |
| 161 | - throw new ReportNotSupported(); | |
| 162 | - } | |
| 163 | - $args = ['limit' => 0, 'offset' => 0, 'datetime' => null]; | |
| 164 | - $acceptableParameters = [ | |
| 165 | - $this::REPORT_PARAM_LIMIT, | |
| 166 | - $this::REPORT_PARAM_OFFSET, | |
| 167 | - $this::REPORT_PARAM_TIMESTAMP | |
| 168 | - ]; | |
| 169 | -		$ns = '{' . $this::NS_OWNCLOUD . '}'; | |
| 170 | -		foreach($report as $parameter) { | |
| 171 | -			if(!in_array($parameter['name'], $acceptableParameters) || empty($parameter['value'])) { | |
| 172 | - continue; | |
| 173 | - } | |
| 174 | - $args[str_replace($ns, '', $parameter['name'])] = $parameter['value']; | |
| 175 | - } | |
| 176 | - | |
| 177 | -		if(!is_null($args['datetime'])) { | |
| 178 | - $args['datetime'] = new \DateTime($args['datetime']); | |
| 179 | - } | |
| 180 | - | |
| 181 | - $results = $node->findChildren($args['limit'], $args['offset'], $args['datetime']); | |
| 182 | - | |
| 183 | - $responses = []; | |
| 184 | -		foreach($results as $node) { | |
| 185 | - $nodePath = $this->server->getRequestUri() . '/' . $node->comment->getId(); | |
| 186 | - $resultSet = $this->server->getPropertiesForPath($nodePath, CommentNode::getPropertyNames()); | |
| 187 | -			if(isset($resultSet[0]) && isset($resultSet[0][200])) { | |
| 188 | - $responses[] = new Response( | |
| 189 | - $this->server->getBaseUri() . $nodePath, | |
| 190 | - [200 => $resultSet[0][200]], | |
| 191 | - 200 | |
| 192 | - ); | |
| 193 | - } | |
| 194 | - | |
| 195 | - } | |
| 196 | - | |
| 197 | - $xml = $this->server->xml->write( | |
| 198 | -			'{DAV:}multistatus', | |
| 199 | - new MultiStatus($responses) | |
| 200 | - ); | |
| 201 | - | |
| 202 | - $this->server->httpResponse->setStatus(207); | |
| 203 | -		$this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); | |
| 204 | - $this->server->httpResponse->setBody($xml); | |
| 205 | - | |
| 206 | - return false; | |
| 207 | - } | |
| 208 | - | |
| 209 | - /** | |
| 210 | - * Creates a new comment | |
| 211 | - * | |
| 212 | - * @param string $objectType e.g. "files" | |
| 213 | - * @param string $objectId e.g. the file id | |
| 214 | - * @param string $data JSON encoded string containing the properties of the tag to create | |
| 215 | - * @param string $contentType content type of the data | |
| 216 | - * @return IComment newly created comment | |
| 217 | - * | |
| 218 | - * @throws BadRequest if a field was missing | |
| 219 | - * @throws UnsupportedMediaType if the content type is not supported | |
| 220 | - */ | |
| 221 | -	private function createComment($objectType, $objectId, $data, $contentType = 'application/json') { | |
| 222 | -		if (explode(';', $contentType)[0] === 'application/json') { | |
| 223 | - $data = json_decode($data, true); | |
| 224 | -		} else { | |
| 225 | - throw new UnsupportedMediaType(); | |
| 226 | - } | |
| 227 | - | |
| 228 | - $actorType = $data['actorType']; | |
| 229 | - $actorId = null; | |
| 230 | -		if($actorType === 'users') { | |
| 231 | - $user = $this->userSession->getUser(); | |
| 232 | -			if(!is_null($user)) { | |
| 233 | - $actorId = $user->getUID(); | |
| 234 | - } | |
| 235 | - } | |
| 236 | -		if(is_null($actorId)) { | |
| 237 | -			throw new BadRequest('Invalid actor "' .  $actorType .'"'); | |
| 238 | - } | |
| 239 | - | |
| 240 | -		try { | |
| 241 | - $comment = $this->commentsManager->create($actorType, $actorId, $objectType, $objectId); | |
| 242 | - $comment->setMessage($data['message']); | |
| 243 | - $comment->setVerb($data['verb']); | |
| 244 | - $this->commentsManager->save($comment); | |
| 245 | - return $comment; | |
| 246 | -		} catch (\InvalidArgumentException $e) { | |
| 247 | -			throw new BadRequest('Invalid input values', 0, $e); | |
| 248 | -		} catch (\OCP\Comments\MessageTooLongException $e) { | |
| 249 | - $msg = 'Message exceeds allowed character limit of '; | |
| 250 | - throw new BadRequest($msg . \OCP\Comments\IComment::MAX_MESSAGE_LENGTH, 0, $e); | |
| 251 | - } | |
| 252 | - } | |
| 46 | + // namespace | |
| 47 | + const NS_OWNCLOUD = 'http://owncloud.org/ns'; | |
| 48 | + | |
| 49 | +    const REPORT_NAME            = '{http://owncloud.org/ns}filter-comments'; | |
| 50 | +    const REPORT_PARAM_LIMIT     = '{http://owncloud.org/ns}limit'; | |
| 51 | +    const REPORT_PARAM_OFFSET    = '{http://owncloud.org/ns}offset'; | |
| 52 | +    const REPORT_PARAM_TIMESTAMP = '{http://owncloud.org/ns}datetime'; | |
| 53 | + | |
| 54 | + /** @var ICommentsManager */ | |
| 55 | + protected $commentsManager; | |
| 56 | + | |
| 57 | + /** @var \Sabre\DAV\Server $server */ | |
| 58 | + private $server; | |
| 59 | + | |
| 60 | + /** @var \OCP\IUserSession */ | |
| 61 | + protected $userSession; | |
| 62 | + | |
| 63 | + /** | |
| 64 | + * Comments plugin | |
| 65 | + * | |
| 66 | + * @param ICommentsManager $commentsManager | |
| 67 | + * @param IUserSession $userSession | |
| 68 | + */ | |
| 69 | +    public function __construct(ICommentsManager $commentsManager, IUserSession $userSession) { | |
| 70 | + $this->commentsManager = $commentsManager; | |
| 71 | + $this->userSession = $userSession; | |
| 72 | + } | |
| 73 | + | |
| 74 | + /** | |
| 75 | + * This initializes the plugin. | |
| 76 | + * | |
| 77 | + * This function is called by Sabre\DAV\Server, after | |
| 78 | + * addPlugin is called. | |
| 79 | + * | |
| 80 | + * This method should set up the required event subscriptions. | |
| 81 | + * | |
| 82 | + * @param Server $server | |
| 83 | + * @return void | |
| 84 | + */ | |
| 85 | +    function initialize(Server $server) { | |
| 86 | + $this->server = $server; | |
| 87 | +        if(strpos($this->server->getRequestUri(), 'comments/') !== 0) { | |
| 88 | + return; | |
| 89 | + } | |
| 90 | + | |
| 91 | + $this->server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc'; | |
| 92 | + | |
| 93 | +        $this->server->xml->classMap['DateTime'] = function(Writer $writer, \DateTime $value) { | |
| 94 | + $writer->write(\Sabre\HTTP\toDate($value)); | |
| 95 | + }; | |
| 96 | + | |
| 97 | +        $this->server->on('report', [$this, 'onReport']); | |
| 98 | +        $this->server->on('method:POST', [$this, 'httpPost']); | |
| 99 | + } | |
| 100 | + | |
| 101 | + /** | |
| 102 | + * POST operation on Comments collections | |
| 103 | + * | |
| 104 | + * @param RequestInterface $request request object | |
| 105 | + * @param ResponseInterface $response response object | |
| 106 | + * @return null|false | |
| 107 | + */ | |
| 108 | +    public function httpPost(RequestInterface $request, ResponseInterface $response) { | |
| 109 | + $path = $request->getPath(); | |
| 110 | + $node = $this->server->tree->getNodeForPath($path); | |
| 111 | +        if (!$node instanceof EntityCollection) { | |
| 112 | + return null; | |
| 113 | + } | |
| 114 | + | |
| 115 | + $data = $request->getBodyAsString(); | |
| 116 | + $comment = $this->createComment( | |
| 117 | + $node->getName(), | |
| 118 | + $node->getId(), | |
| 119 | + $data, | |
| 120 | +            $request->getHeader('Content-Type') | |
| 121 | + ); | |
| 122 | + | |
| 123 | + // update read marker for the current user/poster to avoid | |
| 124 | + // having their own comments marked as unread | |
| 125 | + $node->setReadMarker(null); | |
| 126 | + | |
| 127 | + $url = rtrim($request->getUrl(), '/') . '/' . urlencode($comment->getId()); | |
| 128 | + | |
| 129 | +        $response->setHeader('Content-Location', $url); | |
| 130 | + | |
| 131 | + // created | |
| 132 | + $response->setStatus(201); | |
| 133 | + return false; | |
| 134 | + } | |
| 135 | + | |
| 136 | + /** | |
| 137 | + * Returns a list of reports this plugin supports. | |
| 138 | + * | |
| 139 | +     * This will be used in the {DAV:}supported-report-set property. | |
| 140 | + * | |
| 141 | + * @param string $uri | |
| 142 | + * @return array | |
| 143 | + */ | |
| 144 | +    public function getSupportedReportSet($uri) { | |
| 145 | + return [self::REPORT_NAME]; | |
| 146 | + } | |
| 147 | + | |
| 148 | + /** | |
| 149 | + * REPORT operations to look for comments | |
| 150 | + * | |
| 151 | + * @param string $reportName | |
| 152 | + * @param array $report | |
| 153 | + * @param string $uri | |
| 154 | + * @return bool | |
| 155 | + * @throws NotFound | |
| 156 | + * @throws ReportNotSupported | |
| 157 | + */ | |
| 158 | +    public function onReport($reportName, $report, $uri) { | |
| 159 | + $node = $this->server->tree->getNodeForPath($uri); | |
| 160 | +        if(!$node instanceof EntityCollection || $reportName !== self::REPORT_NAME) { | |
| 161 | + throw new ReportNotSupported(); | |
| 162 | + } | |
| 163 | + $args = ['limit' => 0, 'offset' => 0, 'datetime' => null]; | |
| 164 | + $acceptableParameters = [ | |
| 165 | + $this::REPORT_PARAM_LIMIT, | |
| 166 | + $this::REPORT_PARAM_OFFSET, | |
| 167 | + $this::REPORT_PARAM_TIMESTAMP | |
| 168 | + ]; | |
| 169 | +        $ns = '{' . $this::NS_OWNCLOUD . '}'; | |
| 170 | +        foreach($report as $parameter) { | |
| 171 | +            if(!in_array($parameter['name'], $acceptableParameters) || empty($parameter['value'])) { | |
| 172 | + continue; | |
| 173 | + } | |
| 174 | + $args[str_replace($ns, '', $parameter['name'])] = $parameter['value']; | |
| 175 | + } | |
| 176 | + | |
| 177 | +        if(!is_null($args['datetime'])) { | |
| 178 | + $args['datetime'] = new \DateTime($args['datetime']); | |
| 179 | + } | |
| 180 | + | |
| 181 | + $results = $node->findChildren($args['limit'], $args['offset'], $args['datetime']); | |
| 182 | + | |
| 183 | + $responses = []; | |
| 184 | +        foreach($results as $node) { | |
| 185 | + $nodePath = $this->server->getRequestUri() . '/' . $node->comment->getId(); | |
| 186 | + $resultSet = $this->server->getPropertiesForPath($nodePath, CommentNode::getPropertyNames()); | |
| 187 | +            if(isset($resultSet[0]) && isset($resultSet[0][200])) { | |
| 188 | + $responses[] = new Response( | |
| 189 | + $this->server->getBaseUri() . $nodePath, | |
| 190 | + [200 => $resultSet[0][200]], | |
| 191 | + 200 | |
| 192 | + ); | |
| 193 | + } | |
| 194 | + | |
| 195 | + } | |
| 196 | + | |
| 197 | + $xml = $this->server->xml->write( | |
| 198 | +            '{DAV:}multistatus', | |
| 199 | + new MultiStatus($responses) | |
| 200 | + ); | |
| 201 | + | |
| 202 | + $this->server->httpResponse->setStatus(207); | |
| 203 | +        $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); | |
| 204 | + $this->server->httpResponse->setBody($xml); | |
| 205 | + | |
| 206 | + return false; | |
| 207 | + } | |
| 208 | + | |
| 209 | + /** | |
| 210 | + * Creates a new comment | |
| 211 | + * | |
| 212 | + * @param string $objectType e.g. "files" | |
| 213 | + * @param string $objectId e.g. the file id | |
| 214 | + * @param string $data JSON encoded string containing the properties of the tag to create | |
| 215 | + * @param string $contentType content type of the data | |
| 216 | + * @return IComment newly created comment | |
| 217 | + * | |
| 218 | + * @throws BadRequest if a field was missing | |
| 219 | + * @throws UnsupportedMediaType if the content type is not supported | |
| 220 | + */ | |
| 221 | +    private function createComment($objectType, $objectId, $data, $contentType = 'application/json') { | |
| 222 | +        if (explode(';', $contentType)[0] === 'application/json') { | |
| 223 | + $data = json_decode($data, true); | |
| 224 | +        } else { | |
| 225 | + throw new UnsupportedMediaType(); | |
| 226 | + } | |
| 227 | + | |
| 228 | + $actorType = $data['actorType']; | |
| 229 | + $actorId = null; | |
| 230 | +        if($actorType === 'users') { | |
| 231 | + $user = $this->userSession->getUser(); | |
| 232 | +            if(!is_null($user)) { | |
| 233 | + $actorId = $user->getUID(); | |
| 234 | + } | |
| 235 | + } | |
| 236 | +        if(is_null($actorId)) { | |
| 237 | +            throw new BadRequest('Invalid actor "' .  $actorType .'"'); | |
| 238 | + } | |
| 239 | + | |
| 240 | +        try { | |
| 241 | + $comment = $this->commentsManager->create($actorType, $actorId, $objectType, $objectId); | |
| 242 | + $comment->setMessage($data['message']); | |
| 243 | + $comment->setVerb($data['verb']); | |
| 244 | + $this->commentsManager->save($comment); | |
| 245 | + return $comment; | |
| 246 | +        } catch (\InvalidArgumentException $e) { | |
| 247 | +            throw new BadRequest('Invalid input values', 0, $e); | |
| 248 | +        } catch (\OCP\Comments\MessageTooLongException $e) { | |
| 249 | + $msg = 'Message exceeds allowed character limit of '; | |
| 250 | + throw new BadRequest($msg . \OCP\Comments\IComment::MAX_MESSAGE_LENGTH, 0, $e); | |
| 251 | + } | |
| 252 | + } | |
| 253 | 253 | |
| 254 | 254 | |
| 255 | 255 | |
| @@ -84,7 +84,7 @@ discard block | ||
| 84 | 84 | */ | 
| 85 | 85 |  	function initialize(Server $server) { | 
| 86 | 86 | $this->server = $server; | 
| 87 | -		if(strpos($this->server->getRequestUri(), 'comments/') !== 0) { | |
| 87 | +		if (strpos($this->server->getRequestUri(), 'comments/') !== 0) { | |
| 88 | 88 | return; | 
| 89 | 89 | } | 
| 90 | 90 | |
| @@ -124,7 +124,7 @@ discard block | ||
| 124 | 124 | // having their own comments marked as unread | 
| 125 | 125 | $node->setReadMarker(null); | 
| 126 | 126 | |
| 127 | - $url = rtrim($request->getUrl(), '/') . '/' . urlencode($comment->getId()); | |
| 127 | + $url = rtrim($request->getUrl(), '/').'/'.urlencode($comment->getId()); | |
| 128 | 128 | |
| 129 | 129 |  		$response->setHeader('Content-Location', $url); | 
| 130 | 130 | |
| @@ -157,7 +157,7 @@ discard block | ||
| 157 | 157 | */ | 
| 158 | 158 |  	public function onReport($reportName, $report, $uri) { | 
| 159 | 159 | $node = $this->server->tree->getNodeForPath($uri); | 
| 160 | -		if(!$node instanceof EntityCollection || $reportName !== self::REPORT_NAME) { | |
| 160 | +		if (!$node instanceof EntityCollection || $reportName !== self::REPORT_NAME) { | |
| 161 | 161 | throw new ReportNotSupported(); | 
| 162 | 162 | } | 
| 163 | 163 | $args = ['limit' => 0, 'offset' => 0, 'datetime' => null]; | 
| @@ -166,27 +166,27 @@ discard block | ||
| 166 | 166 | $this::REPORT_PARAM_OFFSET, | 
| 167 | 167 | $this::REPORT_PARAM_TIMESTAMP | 
| 168 | 168 | ]; | 
| 169 | -		$ns = '{' . $this::NS_OWNCLOUD . '}'; | |
| 170 | -		foreach($report as $parameter) { | |
| 171 | -			if(!in_array($parameter['name'], $acceptableParameters) || empty($parameter['value'])) { | |
| 169 | +		$ns = '{'.$this::NS_OWNCLOUD.'}'; | |
| 170 | +		foreach ($report as $parameter) { | |
| 171 | +			if (!in_array($parameter['name'], $acceptableParameters) || empty($parameter['value'])) { | |
| 172 | 172 | continue; | 
| 173 | 173 | } | 
| 174 | 174 | $args[str_replace($ns, '', $parameter['name'])] = $parameter['value']; | 
| 175 | 175 | } | 
| 176 | 176 | |
| 177 | -		if(!is_null($args['datetime'])) { | |
| 177 | +		if (!is_null($args['datetime'])) { | |
| 178 | 178 | $args['datetime'] = new \DateTime($args['datetime']); | 
| 179 | 179 | } | 
| 180 | 180 | |
| 181 | 181 | $results = $node->findChildren($args['limit'], $args['offset'], $args['datetime']); | 
| 182 | 182 | |
| 183 | 183 | $responses = []; | 
| 184 | -		foreach($results as $node) { | |
| 185 | - $nodePath = $this->server->getRequestUri() . '/' . $node->comment->getId(); | |
| 184 | +		foreach ($results as $node) { | |
| 185 | + $nodePath = $this->server->getRequestUri().'/'.$node->comment->getId(); | |
| 186 | 186 | $resultSet = $this->server->getPropertiesForPath($nodePath, CommentNode::getPropertyNames()); | 
| 187 | -			if(isset($resultSet[0]) && isset($resultSet[0][200])) { | |
| 187 | +			if (isset($resultSet[0]) && isset($resultSet[0][200])) { | |
| 188 | 188 | $responses[] = new Response( | 
| 189 | - $this->server->getBaseUri() . $nodePath, | |
| 189 | + $this->server->getBaseUri().$nodePath, | |
| 190 | 190 | [200 => $resultSet[0][200]], | 
| 191 | 191 | 200 | 
| 192 | 192 | ); | 
| @@ -227,14 +227,14 @@ discard block | ||
| 227 | 227 | |
| 228 | 228 | $actorType = $data['actorType']; | 
| 229 | 229 | $actorId = null; | 
| 230 | -		if($actorType === 'users') { | |
| 230 | +		if ($actorType === 'users') { | |
| 231 | 231 | $user = $this->userSession->getUser(); | 
| 232 | -			if(!is_null($user)) { | |
| 232 | +			if (!is_null($user)) { | |
| 233 | 233 | $actorId = $user->getUID(); | 
| 234 | 234 | } | 
| 235 | 235 | } | 
| 236 | -		if(is_null($actorId)) { | |
| 237 | -			throw new BadRequest('Invalid actor "' .  $actorType .'"'); | |
| 236 | +		if (is_null($actorId)) { | |
| 237 | +			throw new BadRequest('Invalid actor "'.$actorType.'"'); | |
| 238 | 238 | } | 
| 239 | 239 | |
| 240 | 240 |  		try { | 
| @@ -247,7 +247,7 @@ discard block | ||
| 247 | 247 |  			throw new BadRequest('Invalid input values', 0, $e); | 
| 248 | 248 |  		} catch (\OCP\Comments\MessageTooLongException $e) { | 
| 249 | 249 | $msg = 'Message exceeds allowed character limit of '; | 
| 250 | - throw new BadRequest($msg . \OCP\Comments\IComment::MAX_MESSAGE_LENGTH, 0, $e); | |
| 250 | + throw new BadRequest($msg.\OCP\Comments\IComment::MAX_MESSAGE_LENGTH, 0, $e); | |
| 251 | 251 | } | 
| 252 | 252 | } | 
| 253 | 253 | |
| @@ -115,7 +115,7 @@ | ||
| 115 | 115 | /** | 
| 116 | 116 | * Returns an array with all the child nodes | 
| 117 | 117 | * | 
| 118 | - * @return \Sabre\DAV\INode[] | |
| 118 | + * @return CommentNode[] | |
| 119 | 119 | */ | 
| 120 | 120 |  	function getChildren() { | 
| 121 | 121 | return $this->findChildren(); | 
| @@ -41,156 +41,156 @@ | ||
| 41 | 41 | * @package OCA\DAV\Comments | 
| 42 | 42 | */ | 
| 43 | 43 |  class EntityCollection extends RootCollection implements IProperties { | 
| 44 | -	const PROPERTY_NAME_READ_MARKER  = '{http://owncloud.org/ns}readMarker'; | |
| 44 | +    const PROPERTY_NAME_READ_MARKER  = '{http://owncloud.org/ns}readMarker'; | |
| 45 | 45 | |
| 46 | - /** @var string */ | |
| 47 | - protected $id; | |
| 46 | + /** @var string */ | |
| 47 | + protected $id; | |
| 48 | 48 | |
| 49 | - /** @var ILogger */ | |
| 50 | - protected $logger; | |
| 49 | + /** @var ILogger */ | |
| 50 | + protected $logger; | |
| 51 | 51 | |
| 52 | - /** | |
| 53 | - * @param string $id | |
| 54 | - * @param string $name | |
| 55 | - * @param ICommentsManager $commentsManager | |
| 56 | - * @param IUserManager $userManager | |
| 57 | - * @param IUserSession $userSession | |
| 58 | - * @param ILogger $logger | |
| 59 | - */ | |
| 60 | - public function __construct( | |
| 61 | - $id, | |
| 62 | - $name, | |
| 63 | - ICommentsManager $commentsManager, | |
| 64 | - IUserManager $userManager, | |
| 65 | - IUserSession $userSession, | |
| 66 | - ILogger $logger | |
| 67 | -	) { | |
| 68 | -		foreach(['id', 'name'] as $property) { | |
| 69 | - $$property = trim($$property); | |
| 70 | -			if(empty($$property) || !is_string($$property)) { | |
| 71 | -				throw new \InvalidArgumentException('"' . $property . '" parameter must be non-empty string'); | |
| 72 | - } | |
| 73 | - } | |
| 74 | - $this->id = $id; | |
| 75 | - $this->name = $name; | |
| 76 | - $this->commentsManager = $commentsManager; | |
| 77 | - $this->logger = $logger; | |
| 78 | - $this->userManager = $userManager; | |
| 79 | - $this->userSession = $userSession; | |
| 80 | - } | |
| 52 | + /** | |
| 53 | + * @param string $id | |
| 54 | + * @param string $name | |
| 55 | + * @param ICommentsManager $commentsManager | |
| 56 | + * @param IUserManager $userManager | |
| 57 | + * @param IUserSession $userSession | |
| 58 | + * @param ILogger $logger | |
| 59 | + */ | |
| 60 | + public function __construct( | |
| 61 | + $id, | |
| 62 | + $name, | |
| 63 | + ICommentsManager $commentsManager, | |
| 64 | + IUserManager $userManager, | |
| 65 | + IUserSession $userSession, | |
| 66 | + ILogger $logger | |
| 67 | +    ) { | |
| 68 | +        foreach(['id', 'name'] as $property) { | |
| 69 | + $$property = trim($$property); | |
| 70 | +            if(empty($$property) || !is_string($$property)) { | |
| 71 | +                throw new \InvalidArgumentException('"' . $property . '" parameter must be non-empty string'); | |
| 72 | + } | |
| 73 | + } | |
| 74 | + $this->id = $id; | |
| 75 | + $this->name = $name; | |
| 76 | + $this->commentsManager = $commentsManager; | |
| 77 | + $this->logger = $logger; | |
| 78 | + $this->userManager = $userManager; | |
| 79 | + $this->userSession = $userSession; | |
| 80 | + } | |
| 81 | 81 | |
| 82 | - /** | |
| 83 | - * returns the ID of this entity | |
| 84 | - * | |
| 85 | - * @return string | |
| 86 | - */ | |
| 87 | -	public function getId() { | |
| 88 | - return $this->id; | |
| 89 | - } | |
| 82 | + /** | |
| 83 | + * returns the ID of this entity | |
| 84 | + * | |
| 85 | + * @return string | |
| 86 | + */ | |
| 87 | +    public function getId() { | |
| 88 | + return $this->id; | |
| 89 | + } | |
| 90 | 90 | |
| 91 | - /** | |
| 92 | - * Returns a specific child node, referenced by its name | |
| 93 | - * | |
| 94 | - * This method must throw Sabre\DAV\Exception\NotFound if the node does not | |
| 95 | - * exist. | |
| 96 | - * | |
| 97 | - * @param string $name | |
| 98 | - * @return \Sabre\DAV\INode | |
| 99 | - * @throws NotFound | |
| 100 | - */ | |
| 101 | -	function getChild($name) { | |
| 102 | -		try { | |
| 103 | - $comment = $this->commentsManager->get($name); | |
| 104 | - return new CommentNode( | |
| 105 | - $this->commentsManager, | |
| 106 | - $comment, | |
| 107 | - $this->userManager, | |
| 108 | - $this->userSession, | |
| 109 | - $this->logger | |
| 110 | - ); | |
| 111 | -		} catch (NotFoundException $e) { | |
| 112 | - throw new NotFound(); | |
| 113 | - } | |
| 114 | - } | |
| 91 | + /** | |
| 92 | + * Returns a specific child node, referenced by its name | |
| 93 | + * | |
| 94 | + * This method must throw Sabre\DAV\Exception\NotFound if the node does not | |
| 95 | + * exist. | |
| 96 | + * | |
| 97 | + * @param string $name | |
| 98 | + * @return \Sabre\DAV\INode | |
| 99 | + * @throws NotFound | |
| 100 | + */ | |
| 101 | +    function getChild($name) { | |
| 102 | +        try { | |
| 103 | + $comment = $this->commentsManager->get($name); | |
| 104 | + return new CommentNode( | |
| 105 | + $this->commentsManager, | |
| 106 | + $comment, | |
| 107 | + $this->userManager, | |
| 108 | + $this->userSession, | |
| 109 | + $this->logger | |
| 110 | + ); | |
| 111 | +        } catch (NotFoundException $e) { | |
| 112 | + throw new NotFound(); | |
| 113 | + } | |
| 114 | + } | |
| 115 | 115 | |
| 116 | - /** | |
| 117 | - * Returns an array with all the child nodes | |
| 118 | - * | |
| 119 | - * @return \Sabre\DAV\INode[] | |
| 120 | - */ | |
| 121 | -	function getChildren() { | |
| 122 | - return $this->findChildren(); | |
| 123 | - } | |
| 116 | + /** | |
| 117 | + * Returns an array with all the child nodes | |
| 118 | + * | |
| 119 | + * @return \Sabre\DAV\INode[] | |
| 120 | + */ | |
| 121 | +    function getChildren() { | |
| 122 | + return $this->findChildren(); | |
| 123 | + } | |
| 124 | 124 | |
| 125 | - /** | |
| 126 | - * Returns an array of comment nodes. Result can be influenced by offset, | |
| 127 | - * limit and date time parameters. | |
| 128 | - * | |
| 129 | - * @param int $limit | |
| 130 | - * @param int $offset | |
| 131 | - * @param \DateTime|null $datetime | |
| 132 | - * @return CommentNode[] | |
| 133 | - */ | |
| 134 | -	function findChildren($limit = 0, $offset = 0, \DateTime $datetime = null) { | |
| 135 | - $comments = $this->commentsManager->getForObject($this->name, $this->id, $limit, $offset, $datetime); | |
| 136 | - $result = []; | |
| 137 | -		foreach($comments as $comment) { | |
| 138 | - $result[] = new CommentNode( | |
| 139 | - $this->commentsManager, | |
| 140 | - $comment, | |
| 141 | - $this->userManager, | |
| 142 | - $this->userSession, | |
| 143 | - $this->logger | |
| 144 | - ); | |
| 145 | - } | |
| 146 | - return $result; | |
| 147 | - } | |
| 125 | + /** | |
| 126 | + * Returns an array of comment nodes. Result can be influenced by offset, | |
| 127 | + * limit and date time parameters. | |
| 128 | + * | |
| 129 | + * @param int $limit | |
| 130 | + * @param int $offset | |
| 131 | + * @param \DateTime|null $datetime | |
| 132 | + * @return CommentNode[] | |
| 133 | + */ | |
| 134 | +    function findChildren($limit = 0, $offset = 0, \DateTime $datetime = null) { | |
| 135 | + $comments = $this->commentsManager->getForObject($this->name, $this->id, $limit, $offset, $datetime); | |
| 136 | + $result = []; | |
| 137 | +        foreach($comments as $comment) { | |
| 138 | + $result[] = new CommentNode( | |
| 139 | + $this->commentsManager, | |
| 140 | + $comment, | |
| 141 | + $this->userManager, | |
| 142 | + $this->userSession, | |
| 143 | + $this->logger | |
| 144 | + ); | |
| 145 | + } | |
| 146 | + return $result; | |
| 147 | + } | |
| 148 | 148 | |
| 149 | - /** | |
| 150 | - * Checks if a child-node with the specified name exists | |
| 151 | - * | |
| 152 | - * @param string $name | |
| 153 | - * @return bool | |
| 154 | - */ | |
| 155 | -	function childExists($name) { | |
| 156 | -		try { | |
| 157 | - $this->commentsManager->get($name); | |
| 158 | - return true; | |
| 159 | -		} catch (NotFoundException $e) { | |
| 160 | - return false; | |
| 161 | - } | |
| 162 | - } | |
| 149 | + /** | |
| 150 | + * Checks if a child-node with the specified name exists | |
| 151 | + * | |
| 152 | + * @param string $name | |
| 153 | + * @return bool | |
| 154 | + */ | |
| 155 | +    function childExists($name) { | |
| 156 | +        try { | |
| 157 | + $this->commentsManager->get($name); | |
| 158 | + return true; | |
| 159 | +        } catch (NotFoundException $e) { | |
| 160 | + return false; | |
| 161 | + } | |
| 162 | + } | |
| 163 | 163 | |
| 164 | - /** | |
| 165 | - * Sets the read marker to the specified date for the logged in user | |
| 166 | - * | |
| 167 | - * @param \DateTime $value | |
| 168 | - * @return bool | |
| 169 | - */ | |
| 170 | -	public function setReadMarker($value) { | |
| 171 | - $dateTime = new \DateTime($value); | |
| 172 | - $user = $this->userSession->getUser(); | |
| 173 | - $this->commentsManager->setReadMark($this->name, $this->id, $dateTime, $user); | |
| 174 | - return true; | |
| 175 | - } | |
| 164 | + /** | |
| 165 | + * Sets the read marker to the specified date for the logged in user | |
| 166 | + * | |
| 167 | + * @param \DateTime $value | |
| 168 | + * @return bool | |
| 169 | + */ | |
| 170 | +    public function setReadMarker($value) { | |
| 171 | + $dateTime = new \DateTime($value); | |
| 172 | + $user = $this->userSession->getUser(); | |
| 173 | + $this->commentsManager->setReadMark($this->name, $this->id, $dateTime, $user); | |
| 174 | + return true; | |
| 175 | + } | |
| 176 | 176 | |
| 177 | - /** | |
| 178 | - * @inheritdoc | |
| 179 | - */ | |
| 180 | -	function propPatch(PropPatch $propPatch) { | |
| 181 | - $propPatch->handle(self::PROPERTY_NAME_READ_MARKER, [$this, 'setReadMarker']); | |
| 182 | - } | |
| 177 | + /** | |
| 178 | + * @inheritdoc | |
| 179 | + */ | |
| 180 | +    function propPatch(PropPatch $propPatch) { | |
| 181 | + $propPatch->handle(self::PROPERTY_NAME_READ_MARKER, [$this, 'setReadMarker']); | |
| 182 | + } | |
| 183 | 183 | |
| 184 | - /** | |
| 185 | - * @inheritdoc | |
| 186 | - */ | |
| 187 | -	function getProperties($properties) { | |
| 188 | - $marker = null; | |
| 189 | - $user = $this->userSession->getUser(); | |
| 190 | -		if(!is_null($user)) { | |
| 191 | - $marker = $this->commentsManager->getReadMark($this->name, $this->id, $user); | |
| 192 | - } | |
| 193 | - return [self::PROPERTY_NAME_READ_MARKER => $marker]; | |
| 194 | - } | |
| 184 | + /** | |
| 185 | + * @inheritdoc | |
| 186 | + */ | |
| 187 | +    function getProperties($properties) { | |
| 188 | + $marker = null; | |
| 189 | + $user = $this->userSession->getUser(); | |
| 190 | +        if(!is_null($user)) { | |
| 191 | + $marker = $this->commentsManager->getReadMark($this->name, $this->id, $user); | |
| 192 | + } | |
| 193 | + return [self::PROPERTY_NAME_READ_MARKER => $marker]; | |
| 194 | + } | |
| 195 | 195 | } | 
| 196 | 196 | |
| @@ -41,7 +41,7 @@ discard block | ||
| 41 | 41 | * @package OCA\DAV\Comments | 
| 42 | 42 | */ | 
| 43 | 43 |  class EntityCollection extends RootCollection implements IProperties { | 
| 44 | -	const PROPERTY_NAME_READ_MARKER  = '{http://owncloud.org/ns}readMarker'; | |
| 44 | +	const PROPERTY_NAME_READ_MARKER = '{http://owncloud.org/ns}readMarker'; | |
| 45 | 45 | |
| 46 | 46 | /** @var string */ | 
| 47 | 47 | protected $id; | 
| @@ -65,10 +65,10 @@ discard block | ||
| 65 | 65 | IUserSession $userSession, | 
| 66 | 66 | ILogger $logger | 
| 67 | 67 |  	) { | 
| 68 | -		foreach(['id', 'name'] as $property) { | |
| 68 | +		foreach (['id', 'name'] as $property) { | |
| 69 | 69 | $$property = trim($$property); | 
| 70 | -			if(empty($$property) || !is_string($$property)) { | |
| 71 | -				throw new \InvalidArgumentException('"' . $property . '" parameter must be non-empty string'); | |
| 70 | +			if (empty($$property) || !is_string($$property)) { | |
| 71 | +				throw new \InvalidArgumentException('"'.$property.'" parameter must be non-empty string'); | |
| 72 | 72 | } | 
| 73 | 73 | } | 
| 74 | 74 | $this->id = $id; | 
| @@ -134,7 +134,7 @@ discard block | ||
| 134 | 134 |  	function findChildren($limit = 0, $offset = 0, \DateTime $datetime = null) { | 
| 135 | 135 | $comments = $this->commentsManager->getForObject($this->name, $this->id, $limit, $offset, $datetime); | 
| 136 | 136 | $result = []; | 
| 137 | -		foreach($comments as $comment) { | |
| 137 | +		foreach ($comments as $comment) { | |
| 138 | 138 | $result[] = new CommentNode( | 
| 139 | 139 | $this->commentsManager, | 
| 140 | 140 | $comment, | 
| @@ -187,7 +187,7 @@ discard block | ||
| 187 | 187 |  	function getProperties($properties) { | 
| 188 | 188 | $marker = null; | 
| 189 | 189 | $user = $this->userSession->getUser(); | 
| 190 | -		if(!is_null($user)) { | |
| 190 | +		if (!is_null($user)) { | |
| 191 | 191 | $marker = $this->commentsManager->getReadMark($this->name, $this->id, $user); | 
| 192 | 192 | } | 
| 193 | 193 | return [self::PROPERTY_NAME_READ_MARKER => $marker]; | 
| @@ -75,7 +75,7 @@ | ||
| 75 | 75 | private $cache = []; | 
| 76 | 76 | |
| 77 | 77 | /** | 
| 78 | - * @param Tree $tree node tree | |
| 78 | + * @param ObjectTree $tree node tree | |
| 79 | 79 | * @param IDBConnection $connection database connection | 
| 80 | 80 | * @param IUser $user owner of the tree and properties | 
| 81 | 81 | */ | 
| @@ -111,7 +111,7 @@ discard block | ||
| 111 | 111 | // we catch the exception to prevent breaking the whole list with a 404 | 
| 112 | 112 | // (soft fail) | 
| 113 | 113 | \OC::$server->getLogger()->warning( | 
| 114 | - 'Could not get node for path: \"' . $path . '\" : ' . $e->getMessage(), | |
| 114 | + 'Could not get node for path: \"'.$path.'\" : '.$e->getMessage(), | |
| 115 | 115 |  				array('app' => 'files') | 
| 116 | 116 | ); | 
| 117 | 117 | return; | 
| @@ -170,7 +170,7 @@ discard block | ||
| 170 | 170 | $statement = $this->connection->prepare( | 
| 171 | 171 | 'DELETE FROM `*PREFIX*properties` WHERE `userid` = ? AND `propertypath` = ?' | 
| 172 | 172 | ); | 
| 173 | - $statement->execute(array($this->user, '/' . $path)); | |
| 173 | + $statement->execute(array($this->user, '/'.$path)); | |
| 174 | 174 | $statement->closeCursor(); | 
| 175 | 175 | |
| 176 | 176 | unset($this->cache[$path]); | 
| @@ -186,10 +186,10 @@ discard block | ||
| 186 | 186 | */ | 
| 187 | 187 |  	public function move($source, $destination) { | 
| 188 | 188 | $statement = $this->connection->prepare( | 
| 189 | - 'UPDATE `*PREFIX*properties` SET `propertypath` = ?' . | |
| 189 | + 'UPDATE `*PREFIX*properties` SET `propertypath` = ?'. | |
| 190 | 190 | ' WHERE `userid` = ? AND `propertypath` = ?' | 
| 191 | 191 | ); | 
| 192 | -		$statement->execute(array('/' . $destination, $this->user, '/' . $source)); | |
| 192 | +		$statement->execute(array('/'.$destination, $this->user, '/'.$source)); | |
| 193 | 193 | $statement->closeCursor(); | 
| 194 | 194 | } | 
| 195 | 195 | |
| @@ -250,13 +250,13 @@ discard block | ||
| 250 | 250 |  	private function updateProperties($node, $properties) { | 
| 251 | 251 | $path = $node->getPath(); | 
| 252 | 252 | |
| 253 | - $deleteStatement = 'DELETE FROM `*PREFIX*properties`' . | |
| 253 | + $deleteStatement = 'DELETE FROM `*PREFIX*properties`'. | |
| 254 | 254 | ' WHERE `userid` = ? AND `propertypath` = ? AND `propertyname` = ?'; | 
| 255 | 255 | |
| 256 | - $insertStatement = 'INSERT INTO `*PREFIX*properties`' . | |
| 256 | + $insertStatement = 'INSERT INTO `*PREFIX*properties`'. | |
| 257 | 257 | ' (`userid`,`propertypath`,`propertyname`,`propertyvalue`) VALUES(?,?,?,?)'; | 
| 258 | 258 | |
| 259 | - $updateStatement = 'UPDATE `*PREFIX*properties` SET `propertyvalue` = ?' . | |
| 259 | + $updateStatement = 'UPDATE `*PREFIX*properties` SET `propertyvalue` = ?'. | |
| 260 | 260 | ' WHERE `userid` = ? AND `propertypath` = ? AND `propertyname` = ?'; | 
| 261 | 261 | |
| 262 | 262 | // TODO: use "insert or update" strategy ? | 
| @@ -329,7 +329,7 @@ discard block | ||
| 329 | 329 | |
| 330 | 330 | $result = $this->connection->executeQuery( | 
| 331 | 331 | $sql, | 
| 332 | - array($this->user, $this->connection->escapeLikeParameter(rtrim($path, '/')) . '/%', $requestedProperties), | |
| 332 | + array($this->user, $this->connection->escapeLikeParameter(rtrim($path, '/')).'/%', $requestedProperties), | |
| 333 | 333 | array(null, null, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY) | 
| 334 | 334 | ); | 
| 335 | 335 | |
| @@ -36,322 +36,322 @@ | ||
| 36 | 36 | |
| 37 | 37 |  class CustomPropertiesBackend implements BackendInterface { | 
| 38 | 38 | |
| 39 | - /** | |
| 40 | - * Ignored properties | |
| 41 | - * | |
| 42 | - * @var array | |
| 43 | - */ | |
| 44 | - private $ignoredProperties = array( | |
| 45 | -		'{DAV:}getcontentlength', | |
| 46 | -		'{DAV:}getcontenttype', | |
| 47 | -		'{DAV:}getetag', | |
| 48 | -		'{DAV:}quota-used-bytes', | |
| 49 | -		'{DAV:}quota-available-bytes', | |
| 50 | -		'{http://owncloud.org/ns}permissions', | |
| 51 | -		'{http://owncloud.org/ns}downloadURL', | |
| 52 | -		'{http://owncloud.org/ns}dDC', | |
| 53 | -		'{http://owncloud.org/ns}size', | |
| 54 | -		'{http://nextcloud.org/ns}is-encrypted', | |
| 55 | - ); | |
| 56 | - | |
| 57 | - /** | |
| 58 | - * @var Tree | |
| 59 | - */ | |
| 60 | - private $tree; | |
| 61 | - | |
| 62 | - /** | |
| 63 | - * @var IDBConnection | |
| 64 | - */ | |
| 65 | - private $connection; | |
| 66 | - | |
| 67 | - /** | |
| 68 | - * @var IUser | |
| 69 | - */ | |
| 70 | - private $user; | |
| 71 | - | |
| 72 | - /** | |
| 73 | - * Properties cache | |
| 74 | - * | |
| 75 | - * @var array | |
| 76 | - */ | |
| 77 | - private $cache = []; | |
| 78 | - | |
| 79 | - /** | |
| 80 | - * @param Tree $tree node tree | |
| 81 | - * @param IDBConnection $connection database connection | |
| 82 | - * @param IUser $user owner of the tree and properties | |
| 83 | - */ | |
| 84 | - public function __construct( | |
| 85 | - Tree $tree, | |
| 86 | - IDBConnection $connection, | |
| 87 | -		IUser $user) { | |
| 88 | - $this->tree = $tree; | |
| 89 | - $this->connection = $connection; | |
| 90 | - $this->user = $user->getUID(); | |
| 91 | - } | |
| 92 | - | |
| 93 | - /** | |
| 94 | - * Fetches properties for a path. | |
| 95 | - * | |
| 96 | - * @param string $path | |
| 97 | - * @param PropFind $propFind | |
| 98 | - * @return void | |
| 99 | - */ | |
| 100 | -	public function propFind($path, PropFind $propFind) { | |
| 101 | -		try { | |
| 102 | - $node = $this->tree->getNodeForPath($path); | |
| 103 | -			if (!($node instanceof Node)) { | |
| 104 | - return; | |
| 105 | - } | |
| 106 | -		} catch (ServiceUnavailable $e) { | |
| 107 | - // might happen for unavailable mount points, skip | |
| 108 | - return; | |
| 109 | -		} catch (NotFound $e) { | |
| 110 | - // in some rare (buggy) cases the node might not be found, | |
| 111 | - // we catch the exception to prevent breaking the whole list with a 404 | |
| 112 | - // (soft fail) | |
| 113 | - \OC::$server->getLogger()->warning( | |
| 114 | - 'Could not get node for path: \"' . $path . '\" : ' . $e->getMessage(), | |
| 115 | -				array('app' => 'files') | |
| 116 | - ); | |
| 117 | - return; | |
| 118 | - } | |
| 119 | - | |
| 120 | - $requestedProps = $propFind->get404Properties(); | |
| 121 | - | |
| 122 | - // these might appear | |
| 123 | - $requestedProps = array_diff( | |
| 124 | - $requestedProps, | |
| 125 | - $this->ignoredProperties | |
| 126 | - ); | |
| 127 | - | |
| 128 | -		if (empty($requestedProps)) { | |
| 129 | - return; | |
| 130 | - } | |
| 131 | - | |
| 132 | - if ($node instanceof Directory | |
| 133 | - && $propFind->getDepth() !== 0 | |
| 134 | -		) { | |
| 135 | - // note: pre-fetching only supported for depth <= 1 | |
| 136 | - $this->loadChildrenProperties($node, $requestedProps); | |
| 137 | - } | |
| 138 | - | |
| 139 | - $props = $this->getProperties($node, $requestedProps); | |
| 140 | -		foreach ($props as $propName => $propValue) { | |
| 141 | - $propFind->set($propName, $propValue); | |
| 142 | - } | |
| 143 | - } | |
| 144 | - | |
| 145 | - /** | |
| 146 | - * Updates properties for a path | |
| 147 | - * | |
| 148 | - * @param string $path | |
| 149 | - * @param PropPatch $propPatch | |
| 150 | - * | |
| 151 | - * @return void | |
| 152 | - */ | |
| 153 | -	public function propPatch($path, PropPatch $propPatch) { | |
| 154 | - $node = $this->tree->getNodeForPath($path); | |
| 155 | -		if (!($node instanceof Node)) { | |
| 156 | - return; | |
| 157 | - } | |
| 158 | - | |
| 159 | -		$propPatch->handleRemaining(function($changedProps) use ($node) { | |
| 160 | - return $this->updateProperties($node, $changedProps); | |
| 161 | - }); | |
| 162 | - } | |
| 163 | - | |
| 164 | - /** | |
| 165 | - * This method is called after a node is deleted. | |
| 166 | - * | |
| 167 | - * @param string $path path of node for which to delete properties | |
| 168 | - */ | |
| 169 | -	public function delete($path) { | |
| 170 | - $statement = $this->connection->prepare( | |
| 171 | - 'DELETE FROM `*PREFIX*properties` WHERE `userid` = ? AND `propertypath` = ?' | |
| 172 | - ); | |
| 173 | - $statement->execute(array($this->user, '/' . $path)); | |
| 174 | - $statement->closeCursor(); | |
| 175 | - | |
| 176 | - unset($this->cache[$path]); | |
| 177 | - } | |
| 178 | - | |
| 179 | - /** | |
| 180 | - * This method is called after a successful MOVE | |
| 181 | - * | |
| 182 | - * @param string $source | |
| 183 | - * @param string $destination | |
| 184 | - * | |
| 185 | - * @return void | |
| 186 | - */ | |
| 187 | -	public function move($source, $destination) { | |
| 188 | - $statement = $this->connection->prepare( | |
| 189 | - 'UPDATE `*PREFIX*properties` SET `propertypath` = ?' . | |
| 190 | - ' WHERE `userid` = ? AND `propertypath` = ?' | |
| 191 | - ); | |
| 192 | -		$statement->execute(array('/' . $destination, $this->user, '/' . $source)); | |
| 193 | - $statement->closeCursor(); | |
| 194 | - } | |
| 195 | - | |
| 196 | - /** | |
| 197 | - * Returns a list of properties for this nodes.; | |
| 198 | - * @param Node $node | |
| 199 | - * @param array $requestedProperties requested properties or empty array for "all" | |
| 200 | - * @return array | |
| 201 | - * @note The properties list is a list of propertynames the client | |
| 202 | - * requested, encoded as xmlnamespace#tagName, for example: | |
| 203 | - * http://www.example.org/namespace#author If the array is empty, all | |
| 204 | - * properties should be returned | |
| 205 | - */ | |
| 206 | -	private function getProperties(Node $node, array $requestedProperties) { | |
| 207 | - $path = $node->getPath(); | |
| 208 | -		if (isset($this->cache[$path])) { | |
| 209 | - return $this->cache[$path]; | |
| 210 | - } | |
| 211 | - | |
| 212 | - // TODO: chunking if more than 1000 properties | |
| 213 | - $sql = 'SELECT * FROM `*PREFIX*properties` WHERE `userid` = ? AND `propertypath` = ?'; | |
| 214 | - | |
| 215 | - $whereValues = array($this->user, $path); | |
| 216 | - $whereTypes = array(null, null); | |
| 217 | - | |
| 218 | -		if (!empty($requestedProperties)) { | |
| 219 | - // request only a subset | |
| 220 | - $sql .= ' AND `propertyname` in (?)'; | |
| 221 | - $whereValues[] = $requestedProperties; | |
| 222 | - $whereTypes[] = \Doctrine\DBAL\Connection::PARAM_STR_ARRAY; | |
| 223 | - } | |
| 224 | - | |
| 225 | - $result = $this->connection->executeQuery( | |
| 226 | - $sql, | |
| 227 | - $whereValues, | |
| 228 | - $whereTypes | |
| 229 | - ); | |
| 230 | - | |
| 231 | - $props = []; | |
| 232 | -		while ($row = $result->fetch()) { | |
| 233 | - $props[$row['propertyname']] = $row['propertyvalue']; | |
| 234 | - } | |
| 235 | - | |
| 236 | - $result->closeCursor(); | |
| 237 | - | |
| 238 | - $this->cache[$path] = $props; | |
| 239 | - return $props; | |
| 240 | - } | |
| 241 | - | |
| 242 | - /** | |
| 243 | - * Update properties | |
| 244 | - * | |
| 245 | - * @param Node $node node for which to update properties | |
| 246 | - * @param array $properties array of properties to update | |
| 247 | - * | |
| 248 | - * @return bool | |
| 249 | - */ | |
| 250 | -	private function updateProperties($node, $properties) { | |
| 251 | - $path = $node->getPath(); | |
| 252 | - | |
| 253 | - $deleteStatement = 'DELETE FROM `*PREFIX*properties`' . | |
| 254 | - ' WHERE `userid` = ? AND `propertypath` = ? AND `propertyname` = ?'; | |
| 255 | - | |
| 256 | - $insertStatement = 'INSERT INTO `*PREFIX*properties`' . | |
| 257 | - ' (`userid`,`propertypath`,`propertyname`,`propertyvalue`) VALUES(?,?,?,?)'; | |
| 258 | - | |
| 259 | - $updateStatement = 'UPDATE `*PREFIX*properties` SET `propertyvalue` = ?' . | |
| 260 | - ' WHERE `userid` = ? AND `propertypath` = ? AND `propertyname` = ?'; | |
| 261 | - | |
| 262 | - // TODO: use "insert or update" strategy ? | |
| 263 | - $existing = $this->getProperties($node, array()); | |
| 264 | - $this->connection->beginTransaction(); | |
| 265 | -		foreach ($properties as $propertyName => $propertyValue) { | |
| 266 | - // If it was null, we need to delete the property | |
| 267 | -			if (is_null($propertyValue)) { | |
| 268 | -				if (array_key_exists($propertyName, $existing)) { | |
| 269 | - $this->connection->executeUpdate($deleteStatement, | |
| 270 | - array( | |
| 271 | - $this->user, | |
| 272 | - $path, | |
| 273 | - $propertyName | |
| 274 | - ) | |
| 275 | - ); | |
| 276 | - } | |
| 277 | -			} else { | |
| 278 | -				if (!array_key_exists($propertyName, $existing)) { | |
| 279 | - $this->connection->executeUpdate($insertStatement, | |
| 280 | - array( | |
| 281 | - $this->user, | |
| 282 | - $path, | |
| 283 | - $propertyName, | |
| 284 | - $propertyValue | |
| 285 | - ) | |
| 286 | - ); | |
| 287 | -				} else { | |
| 288 | - $this->connection->executeUpdate($updateStatement, | |
| 289 | - array( | |
| 290 | - $propertyValue, | |
| 291 | - $this->user, | |
| 292 | - $path, | |
| 293 | - $propertyName | |
| 294 | - ) | |
| 295 | - ); | |
| 296 | - } | |
| 297 | - } | |
| 298 | - } | |
| 299 | - | |
| 300 | - $this->connection->commit(); | |
| 301 | - unset($this->cache[$path]); | |
| 302 | - | |
| 303 | - return true; | |
| 304 | - } | |
| 305 | - | |
| 306 | - /** | |
| 307 | - * Bulk load properties for directory children | |
| 308 | - * | |
| 309 | - * @param Directory $node | |
| 310 | - * @param array $requestedProperties requested properties | |
| 311 | - * | |
| 312 | - * @return void | |
| 313 | - */ | |
| 314 | -	private function loadChildrenProperties(Directory $node, $requestedProperties) { | |
| 315 | - $path = $node->getPath(); | |
| 316 | -		if (isset($this->cache[$path])) { | |
| 317 | - // we already loaded them at some point | |
| 318 | - return; | |
| 319 | - } | |
| 320 | - | |
| 321 | - $childNodes = $node->getChildren(); | |
| 322 | - // pre-fill cache | |
| 323 | -		foreach ($childNodes as $childNode) { | |
| 324 | - $this->cache[$childNode->getPath()] = []; | |
| 325 | - } | |
| 326 | - | |
| 327 | - $sql = 'SELECT * FROM `*PREFIX*properties` WHERE `userid` = ? AND `propertypath` LIKE ?'; | |
| 328 | - $sql .= ' AND `propertyname` in (?) ORDER BY `propertypath`, `propertyname`'; | |
| 329 | - | |
| 330 | - $result = $this->connection->executeQuery( | |
| 331 | - $sql, | |
| 332 | - array($this->user, $this->connection->escapeLikeParameter(rtrim($path, '/')) . '/%', $requestedProperties), | |
| 333 | - array(null, null, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY) | |
| 334 | - ); | |
| 335 | - | |
| 336 | - $oldPath = null; | |
| 337 | - $props = []; | |
| 338 | -		while ($row = $result->fetch()) { | |
| 339 | - $path = $row['propertypath']; | |
| 340 | -			if ($oldPath !== $path) { | |
| 341 | - // save previously gathered props | |
| 342 | - $this->cache[$oldPath] = $props; | |
| 343 | - $oldPath = $path; | |
| 344 | - // prepare props for next path | |
| 345 | - $props = []; | |
| 346 | - } | |
| 347 | - $props[$row['propertyname']] = $row['propertyvalue']; | |
| 348 | - } | |
| 349 | -		if (!is_null($oldPath)) { | |
| 350 | - // save props from last run | |
| 351 | - $this->cache[$oldPath] = $props; | |
| 352 | - } | |
| 353 | - | |
| 354 | - $result->closeCursor(); | |
| 355 | - } | |
| 39 | + /** | |
| 40 | + * Ignored properties | |
| 41 | + * | |
| 42 | + * @var array | |
| 43 | + */ | |
| 44 | + private $ignoredProperties = array( | |
| 45 | +        '{DAV:}getcontentlength', | |
| 46 | +        '{DAV:}getcontenttype', | |
| 47 | +        '{DAV:}getetag', | |
| 48 | +        '{DAV:}quota-used-bytes', | |
| 49 | +        '{DAV:}quota-available-bytes', | |
| 50 | +        '{http://owncloud.org/ns}permissions', | |
| 51 | +        '{http://owncloud.org/ns}downloadURL', | |
| 52 | +        '{http://owncloud.org/ns}dDC', | |
| 53 | +        '{http://owncloud.org/ns}size', | |
| 54 | +        '{http://nextcloud.org/ns}is-encrypted', | |
| 55 | + ); | |
| 56 | + | |
| 57 | + /** | |
| 58 | + * @var Tree | |
| 59 | + */ | |
| 60 | + private $tree; | |
| 61 | + | |
| 62 | + /** | |
| 63 | + * @var IDBConnection | |
| 64 | + */ | |
| 65 | + private $connection; | |
| 66 | + | |
| 67 | + /** | |
| 68 | + * @var IUser | |
| 69 | + */ | |
| 70 | + private $user; | |
| 71 | + | |
| 72 | + /** | |
| 73 | + * Properties cache | |
| 74 | + * | |
| 75 | + * @var array | |
| 76 | + */ | |
| 77 | + private $cache = []; | |
| 78 | + | |
| 79 | + /** | |
| 80 | + * @param Tree $tree node tree | |
| 81 | + * @param IDBConnection $connection database connection | |
| 82 | + * @param IUser $user owner of the tree and properties | |
| 83 | + */ | |
| 84 | + public function __construct( | |
| 85 | + Tree $tree, | |
| 86 | + IDBConnection $connection, | |
| 87 | +        IUser $user) { | |
| 88 | + $this->tree = $tree; | |
| 89 | + $this->connection = $connection; | |
| 90 | + $this->user = $user->getUID(); | |
| 91 | + } | |
| 92 | + | |
| 93 | + /** | |
| 94 | + * Fetches properties for a path. | |
| 95 | + * | |
| 96 | + * @param string $path | |
| 97 | + * @param PropFind $propFind | |
| 98 | + * @return void | |
| 99 | + */ | |
| 100 | +    public function propFind($path, PropFind $propFind) { | |
| 101 | +        try { | |
| 102 | + $node = $this->tree->getNodeForPath($path); | |
| 103 | +            if (!($node instanceof Node)) { | |
| 104 | + return; | |
| 105 | + } | |
| 106 | +        } catch (ServiceUnavailable $e) { | |
| 107 | + // might happen for unavailable mount points, skip | |
| 108 | + return; | |
| 109 | +        } catch (NotFound $e) { | |
| 110 | + // in some rare (buggy) cases the node might not be found, | |
| 111 | + // we catch the exception to prevent breaking the whole list with a 404 | |
| 112 | + // (soft fail) | |
| 113 | + \OC::$server->getLogger()->warning( | |
| 114 | + 'Could not get node for path: \"' . $path . '\" : ' . $e->getMessage(), | |
| 115 | +                array('app' => 'files') | |
| 116 | + ); | |
| 117 | + return; | |
| 118 | + } | |
| 119 | + | |
| 120 | + $requestedProps = $propFind->get404Properties(); | |
| 121 | + | |
| 122 | + // these might appear | |
| 123 | + $requestedProps = array_diff( | |
| 124 | + $requestedProps, | |
| 125 | + $this->ignoredProperties | |
| 126 | + ); | |
| 127 | + | |
| 128 | +        if (empty($requestedProps)) { | |
| 129 | + return; | |
| 130 | + } | |
| 131 | + | |
| 132 | + if ($node instanceof Directory | |
| 133 | + && $propFind->getDepth() !== 0 | |
| 134 | +        ) { | |
| 135 | + // note: pre-fetching only supported for depth <= 1 | |
| 136 | + $this->loadChildrenProperties($node, $requestedProps); | |
| 137 | + } | |
| 138 | + | |
| 139 | + $props = $this->getProperties($node, $requestedProps); | |
| 140 | +        foreach ($props as $propName => $propValue) { | |
| 141 | + $propFind->set($propName, $propValue); | |
| 142 | + } | |
| 143 | + } | |
| 144 | + | |
| 145 | + /** | |
| 146 | + * Updates properties for a path | |
| 147 | + * | |
| 148 | + * @param string $path | |
| 149 | + * @param PropPatch $propPatch | |
| 150 | + * | |
| 151 | + * @return void | |
| 152 | + */ | |
| 153 | +    public function propPatch($path, PropPatch $propPatch) { | |
| 154 | + $node = $this->tree->getNodeForPath($path); | |
| 155 | +        if (!($node instanceof Node)) { | |
| 156 | + return; | |
| 157 | + } | |
| 158 | + | |
| 159 | +        $propPatch->handleRemaining(function($changedProps) use ($node) { | |
| 160 | + return $this->updateProperties($node, $changedProps); | |
| 161 | + }); | |
| 162 | + } | |
| 163 | + | |
| 164 | + /** | |
| 165 | + * This method is called after a node is deleted. | |
| 166 | + * | |
| 167 | + * @param string $path path of node for which to delete properties | |
| 168 | + */ | |
| 169 | +    public function delete($path) { | |
| 170 | + $statement = $this->connection->prepare( | |
| 171 | + 'DELETE FROM `*PREFIX*properties` WHERE `userid` = ? AND `propertypath` = ?' | |
| 172 | + ); | |
| 173 | + $statement->execute(array($this->user, '/' . $path)); | |
| 174 | + $statement->closeCursor(); | |
| 175 | + | |
| 176 | + unset($this->cache[$path]); | |
| 177 | + } | |
| 178 | + | |
| 179 | + /** | |
| 180 | + * This method is called after a successful MOVE | |
| 181 | + * | |
| 182 | + * @param string $source | |
| 183 | + * @param string $destination | |
| 184 | + * | |
| 185 | + * @return void | |
| 186 | + */ | |
| 187 | +    public function move($source, $destination) { | |
| 188 | + $statement = $this->connection->prepare( | |
| 189 | + 'UPDATE `*PREFIX*properties` SET `propertypath` = ?' . | |
| 190 | + ' WHERE `userid` = ? AND `propertypath` = ?' | |
| 191 | + ); | |
| 192 | +        $statement->execute(array('/' . $destination, $this->user, '/' . $source)); | |
| 193 | + $statement->closeCursor(); | |
| 194 | + } | |
| 195 | + | |
| 196 | + /** | |
| 197 | + * Returns a list of properties for this nodes.; | |
| 198 | + * @param Node $node | |
| 199 | + * @param array $requestedProperties requested properties or empty array for "all" | |
| 200 | + * @return array | |
| 201 | + * @note The properties list is a list of propertynames the client | |
| 202 | + * requested, encoded as xmlnamespace#tagName, for example: | |
| 203 | + * http://www.example.org/namespace#author If the array is empty, all | |
| 204 | + * properties should be returned | |
| 205 | + */ | |
| 206 | +    private function getProperties(Node $node, array $requestedProperties) { | |
| 207 | + $path = $node->getPath(); | |
| 208 | +        if (isset($this->cache[$path])) { | |
| 209 | + return $this->cache[$path]; | |
| 210 | + } | |
| 211 | + | |
| 212 | + // TODO: chunking if more than 1000 properties | |
| 213 | + $sql = 'SELECT * FROM `*PREFIX*properties` WHERE `userid` = ? AND `propertypath` = ?'; | |
| 214 | + | |
| 215 | + $whereValues = array($this->user, $path); | |
| 216 | + $whereTypes = array(null, null); | |
| 217 | + | |
| 218 | +        if (!empty($requestedProperties)) { | |
| 219 | + // request only a subset | |
| 220 | + $sql .= ' AND `propertyname` in (?)'; | |
| 221 | + $whereValues[] = $requestedProperties; | |
| 222 | + $whereTypes[] = \Doctrine\DBAL\Connection::PARAM_STR_ARRAY; | |
| 223 | + } | |
| 224 | + | |
| 225 | + $result = $this->connection->executeQuery( | |
| 226 | + $sql, | |
| 227 | + $whereValues, | |
| 228 | + $whereTypes | |
| 229 | + ); | |
| 230 | + | |
| 231 | + $props = []; | |
| 232 | +        while ($row = $result->fetch()) { | |
| 233 | + $props[$row['propertyname']] = $row['propertyvalue']; | |
| 234 | + } | |
| 235 | + | |
| 236 | + $result->closeCursor(); | |
| 237 | + | |
| 238 | + $this->cache[$path] = $props; | |
| 239 | + return $props; | |
| 240 | + } | |
| 241 | + | |
| 242 | + /** | |
| 243 | + * Update properties | |
| 244 | + * | |
| 245 | + * @param Node $node node for which to update properties | |
| 246 | + * @param array $properties array of properties to update | |
| 247 | + * | |
| 248 | + * @return bool | |
| 249 | + */ | |
| 250 | +    private function updateProperties($node, $properties) { | |
| 251 | + $path = $node->getPath(); | |
| 252 | + | |
| 253 | + $deleteStatement = 'DELETE FROM `*PREFIX*properties`' . | |
| 254 | + ' WHERE `userid` = ? AND `propertypath` = ? AND `propertyname` = ?'; | |
| 255 | + | |
| 256 | + $insertStatement = 'INSERT INTO `*PREFIX*properties`' . | |
| 257 | + ' (`userid`,`propertypath`,`propertyname`,`propertyvalue`) VALUES(?,?,?,?)'; | |
| 258 | + | |
| 259 | + $updateStatement = 'UPDATE `*PREFIX*properties` SET `propertyvalue` = ?' . | |
| 260 | + ' WHERE `userid` = ? AND `propertypath` = ? AND `propertyname` = ?'; | |
| 261 | + | |
| 262 | + // TODO: use "insert or update" strategy ? | |
| 263 | + $existing = $this->getProperties($node, array()); | |
| 264 | + $this->connection->beginTransaction(); | |
| 265 | +        foreach ($properties as $propertyName => $propertyValue) { | |
| 266 | + // If it was null, we need to delete the property | |
| 267 | +            if (is_null($propertyValue)) { | |
| 268 | +                if (array_key_exists($propertyName, $existing)) { | |
| 269 | + $this->connection->executeUpdate($deleteStatement, | |
| 270 | + array( | |
| 271 | + $this->user, | |
| 272 | + $path, | |
| 273 | + $propertyName | |
| 274 | + ) | |
| 275 | + ); | |
| 276 | + } | |
| 277 | +            } else { | |
| 278 | +                if (!array_key_exists($propertyName, $existing)) { | |
| 279 | + $this->connection->executeUpdate($insertStatement, | |
| 280 | + array( | |
| 281 | + $this->user, | |
| 282 | + $path, | |
| 283 | + $propertyName, | |
| 284 | + $propertyValue | |
| 285 | + ) | |
| 286 | + ); | |
| 287 | +                } else { | |
| 288 | + $this->connection->executeUpdate($updateStatement, | |
| 289 | + array( | |
| 290 | + $propertyValue, | |
| 291 | + $this->user, | |
| 292 | + $path, | |
| 293 | + $propertyName | |
| 294 | + ) | |
| 295 | + ); | |
| 296 | + } | |
| 297 | + } | |
| 298 | + } | |
| 299 | + | |
| 300 | + $this->connection->commit(); | |
| 301 | + unset($this->cache[$path]); | |
| 302 | + | |
| 303 | + return true; | |
| 304 | + } | |
| 305 | + | |
| 306 | + /** | |
| 307 | + * Bulk load properties for directory children | |
| 308 | + * | |
| 309 | + * @param Directory $node | |
| 310 | + * @param array $requestedProperties requested properties | |
| 311 | + * | |
| 312 | + * @return void | |
| 313 | + */ | |
| 314 | +    private function loadChildrenProperties(Directory $node, $requestedProperties) { | |
| 315 | + $path = $node->getPath(); | |
| 316 | +        if (isset($this->cache[$path])) { | |
| 317 | + // we already loaded them at some point | |
| 318 | + return; | |
| 319 | + } | |
| 320 | + | |
| 321 | + $childNodes = $node->getChildren(); | |
| 322 | + // pre-fill cache | |
| 323 | +        foreach ($childNodes as $childNode) { | |
| 324 | + $this->cache[$childNode->getPath()] = []; | |
| 325 | + } | |
| 326 | + | |
| 327 | + $sql = 'SELECT * FROM `*PREFIX*properties` WHERE `userid` = ? AND `propertypath` LIKE ?'; | |
| 328 | + $sql .= ' AND `propertyname` in (?) ORDER BY `propertypath`, `propertyname`'; | |
| 329 | + | |
| 330 | + $result = $this->connection->executeQuery( | |
| 331 | + $sql, | |
| 332 | + array($this->user, $this->connection->escapeLikeParameter(rtrim($path, '/')) . '/%', $requestedProperties), | |
| 333 | + array(null, null, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY) | |
| 334 | + ); | |
| 335 | + | |
| 336 | + $oldPath = null; | |
| 337 | + $props = []; | |
| 338 | +        while ($row = $result->fetch()) { | |
| 339 | + $path = $row['propertypath']; | |
| 340 | +            if ($oldPath !== $path) { | |
| 341 | + // save previously gathered props | |
| 342 | + $this->cache[$oldPath] = $props; | |
| 343 | + $oldPath = $path; | |
| 344 | + // prepare props for next path | |
| 345 | + $props = []; | |
| 346 | + } | |
| 347 | + $props[$row['propertyname']] = $row['propertyvalue']; | |
| 348 | + } | |
| 349 | +        if (!is_null($oldPath)) { | |
| 350 | + // save props from last run | |
| 351 | + $this->cache[$oldPath] = $props; | |
| 352 | + } | |
| 353 | + | |
| 354 | + $result->closeCursor(); | |
| 355 | + } | |
| 356 | 356 | |
| 357 | 357 | } | 
| @@ -132,7 +132,7 @@ | ||
| 132 | 132 | * Returns the list of members for a group-principal | 
| 133 | 133 | * | 
| 134 | 134 | * @param string $principal | 
| 135 | - * @return array | |
| 135 | + * @return string[] | |
| 136 | 136 | */ | 
| 137 | 137 |  	function getGroupMemberSet($principal) { | 
| 138 | 138 | // TODO: for now the group principal has only one member, the user itself | 
| @@ -23,7 +23,6 @@ | ||
| 23 | 23 | namespace OCA\DAV\DAV; | 
| 24 | 24 | |
| 25 | 25 | use Sabre\DAVACL\PrincipalBackend\AbstractBackend; | 
| 26 | -use Sabre\HTTP\URLUtil; | |
| 27 | 26 | |
| 28 | 27 |  class SystemPrincipalBackend extends AbstractBackend { | 
| 29 | 28 | |
| @@ -27,165 +27,165 @@ | ||
| 27 | 27 | |
| 28 | 28 |  class SystemPrincipalBackend extends AbstractBackend { | 
| 29 | 29 | |
| 30 | - /** | |
| 31 | - * Returns a list of principals based on a prefix. | |
| 32 | - * | |
| 33 | - * This prefix will often contain something like 'principals'. You are only | |
| 34 | - * expected to return principals that are in this base path. | |
| 35 | - * | |
| 36 | - * You are expected to return at least a 'uri' for every user, you can | |
| 37 | - * return any additional properties if you wish so. Common properties are: | |
| 38 | -	 *   {DAV:}displayname | |
| 39 | -	 *   {http://sabredav.org/ns}email-address - This is a custom SabreDAV | |
| 40 | - * field that's actually injected in a number of other properties. If | |
| 41 | - * you have an email address, use this property. | |
| 42 | - * | |
| 43 | - * @param string $prefixPath | |
| 44 | - * @return array | |
| 45 | - */ | |
| 46 | -	function getPrincipalsByPrefix($prefixPath) { | |
| 47 | - $principals = []; | |
| 48 | - | |
| 49 | -		if ($prefixPath === 'principals/system') { | |
| 50 | - $principals[] = [ | |
| 51 | - 'uri' => 'principals/system/system', | |
| 52 | -				'{DAV:}displayname' => 'system', | |
| 53 | - ]; | |
| 54 | - $principals[] = [ | |
| 55 | - 'uri' => 'principals/system/public', | |
| 56 | -				'{DAV:}displayname' => 'public', | |
| 57 | - ]; | |
| 58 | - } | |
| 59 | - | |
| 60 | - return $principals; | |
| 61 | - } | |
| 62 | - | |
| 63 | - /** | |
| 64 | - * Returns a specific principal, specified by it's path. | |
| 65 | - * The returned structure should be the exact same as from | |
| 66 | - * getPrincipalsByPrefix. | |
| 67 | - * | |
| 68 | - * @param string $path | |
| 69 | - * @return array | |
| 70 | - */ | |
| 71 | -	function getPrincipalByPath($path) { | |
| 72 | - | |
| 73 | -		if ($path === 'principals/system/system') { | |
| 74 | - $principal = [ | |
| 75 | - 'uri' => 'principals/system/system', | |
| 76 | -				'{DAV:}displayname' => 'system', | |
| 77 | - ]; | |
| 78 | - return $principal; | |
| 79 | - } | |
| 80 | -		if ($path === 'principals/system/public') { | |
| 81 | - $principal = [ | |
| 82 | - 'uri' => 'principals/system/public', | |
| 83 | -				'{DAV:}displayname' => 'public', | |
| 84 | - ]; | |
| 85 | - return $principal; | |
| 86 | - } | |
| 87 | - | |
| 88 | - return null; | |
| 89 | - } | |
| 90 | - | |
| 91 | - /** | |
| 92 | - * Updates one ore more webdav properties on a principal. | |
| 93 | - * | |
| 94 | - * The list of mutations is stored in a Sabre\DAV\PropPatch object. | |
| 95 | - * To do the actual updates, you must tell this object which properties | |
| 96 | - * you're going to process with the handle() method. | |
| 97 | - * | |
| 98 | - * Calling the handle method is like telling the PropPatch object "I | |
| 99 | - * promise I can handle updating this property". | |
| 100 | - * | |
| 101 | - * Read the PropPatch documentation for more info and examples. | |
| 102 | - * | |
| 103 | - * @param string $path | |
| 104 | - * @param \Sabre\DAV\PropPatch $propPatch | |
| 105 | - * @return void | |
| 106 | - */ | |
| 107 | -	function updatePrincipal($path, \Sabre\DAV\PropPatch $propPatch) { | |
| 108 | - } | |
| 109 | - | |
| 110 | - /** | |
| 111 | - * This method is used to search for principals matching a set of | |
| 112 | - * properties. | |
| 113 | - * | |
| 114 | - * This search is specifically used by RFC3744's principal-property-search | |
| 115 | - * REPORT. | |
| 116 | - * | |
| 117 | - * The actual search should be a unicode-non-case-sensitive search. The | |
| 118 | - * keys in searchProperties are the WebDAV property names, while the values | |
| 119 | - * are the property values to search on. | |
| 120 | - * | |
| 121 | - * By default, if multiple properties are submitted to this method, the | |
| 122 | - * various properties should be combined with 'AND'. If $test is set to | |
| 123 | - * 'anyof', it should be combined using 'OR'. | |
| 124 | - * | |
| 125 | - * This method should simply return an array with full principal uri's. | |
| 126 | - * | |
| 127 | - * If somebody attempted to search on a property the backend does not | |
| 128 | - * support, you should simply return 0 results. | |
| 129 | - * | |
| 130 | - * You can also just return 0 results if you choose to not support | |
| 131 | - * searching at all, but keep in mind that this may stop certain features | |
| 132 | - * from working. | |
| 133 | - * | |
| 134 | - * @param string $prefixPath | |
| 135 | - * @param array $searchProperties | |
| 136 | - * @param string $test | |
| 137 | - * @return array | |
| 138 | - */ | |
| 139 | -	function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') { | |
| 140 | - return []; | |
| 141 | - } | |
| 142 | - | |
| 143 | - /** | |
| 144 | - * Returns the list of members for a group-principal | |
| 145 | - * | |
| 146 | - * @param string $principal | |
| 147 | - * @return array | |
| 148 | - */ | |
| 149 | -	function getGroupMemberSet($principal) { | |
| 150 | - // TODO: for now the group principal has only one member, the user itself | |
| 151 | - $principal = $this->getPrincipalByPath($principal); | |
| 152 | -		if (!$principal) { | |
| 153 | -			throw new \Sabre\DAV\Exception('Principal not found'); | |
| 154 | - } | |
| 155 | - | |
| 156 | - return [$principal['uri']]; | |
| 157 | - } | |
| 158 | - | |
| 159 | - /** | |
| 160 | - * Returns the list of groups a principal is a member of | |
| 161 | - * | |
| 162 | - * @param string $principal | |
| 163 | - * @return array | |
| 164 | - */ | |
| 165 | -	function getGroupMembership($principal) { | |
| 166 | - list($prefix, ) = \Sabre\Uri\split($principal); | |
| 167 | - | |
| 168 | -		if ($prefix === 'principals/system') { | |
| 169 | - $principal = $this->getPrincipalByPath($principal); | |
| 170 | -			if (!$principal) { | |
| 171 | -				throw new \Sabre\DAV\Exception('Principal not found'); | |
| 172 | - } | |
| 173 | - | |
| 174 | - return []; | |
| 175 | - } | |
| 176 | - return []; | |
| 177 | - } | |
| 178 | - | |
| 179 | - /** | |
| 180 | - * Updates the list of group members for a group principal. | |
| 181 | - * | |
| 182 | - * The principals should be passed as a list of uri's. | |
| 183 | - * | |
| 184 | - * @param string $principal | |
| 185 | - * @param array $members | |
| 186 | - * @return void | |
| 187 | - */ | |
| 188 | -	function setGroupMemberSet($principal, array $members) { | |
| 189 | -		throw new \Sabre\DAV\Exception('Setting members of the group is not supported yet'); | |
| 190 | - } | |
| 30 | + /** | |
| 31 | + * Returns a list of principals based on a prefix. | |
| 32 | + * | |
| 33 | + * This prefix will often contain something like 'principals'. You are only | |
| 34 | + * expected to return principals that are in this base path. | |
| 35 | + * | |
| 36 | + * You are expected to return at least a 'uri' for every user, you can | |
| 37 | + * return any additional properties if you wish so. Common properties are: | |
| 38 | +     *   {DAV:}displayname | |
| 39 | +     *   {http://sabredav.org/ns}email-address - This is a custom SabreDAV | |
| 40 | + * field that's actually injected in a number of other properties. If | |
| 41 | + * you have an email address, use this property. | |
| 42 | + * | |
| 43 | + * @param string $prefixPath | |
| 44 | + * @return array | |
| 45 | + */ | |
| 46 | +    function getPrincipalsByPrefix($prefixPath) { | |
| 47 | + $principals = []; | |
| 48 | + | |
| 49 | +        if ($prefixPath === 'principals/system') { | |
| 50 | + $principals[] = [ | |
| 51 | + 'uri' => 'principals/system/system', | |
| 52 | +                '{DAV:}displayname' => 'system', | |
| 53 | + ]; | |
| 54 | + $principals[] = [ | |
| 55 | + 'uri' => 'principals/system/public', | |
| 56 | +                '{DAV:}displayname' => 'public', | |
| 57 | + ]; | |
| 58 | + } | |
| 59 | + | |
| 60 | + return $principals; | |
| 61 | + } | |
| 62 | + | |
| 63 | + /** | |
| 64 | + * Returns a specific principal, specified by it's path. | |
| 65 | + * The returned structure should be the exact same as from | |
| 66 | + * getPrincipalsByPrefix. | |
| 67 | + * | |
| 68 | + * @param string $path | |
| 69 | + * @return array | |
| 70 | + */ | |
| 71 | +    function getPrincipalByPath($path) { | |
| 72 | + | |
| 73 | +        if ($path === 'principals/system/system') { | |
| 74 | + $principal = [ | |
| 75 | + 'uri' => 'principals/system/system', | |
| 76 | +                '{DAV:}displayname' => 'system', | |
| 77 | + ]; | |
| 78 | + return $principal; | |
| 79 | + } | |
| 80 | +        if ($path === 'principals/system/public') { | |
| 81 | + $principal = [ | |
| 82 | + 'uri' => 'principals/system/public', | |
| 83 | +                '{DAV:}displayname' => 'public', | |
| 84 | + ]; | |
| 85 | + return $principal; | |
| 86 | + } | |
| 87 | + | |
| 88 | + return null; | |
| 89 | + } | |
| 90 | + | |
| 91 | + /** | |
| 92 | + * Updates one ore more webdav properties on a principal. | |
| 93 | + * | |
| 94 | + * The list of mutations is stored in a Sabre\DAV\PropPatch object. | |
| 95 | + * To do the actual updates, you must tell this object which properties | |
| 96 | + * you're going to process with the handle() method. | |
| 97 | + * | |
| 98 | + * Calling the handle method is like telling the PropPatch object "I | |
| 99 | + * promise I can handle updating this property". | |
| 100 | + * | |
| 101 | + * Read the PropPatch documentation for more info and examples. | |
| 102 | + * | |
| 103 | + * @param string $path | |
| 104 | + * @param \Sabre\DAV\PropPatch $propPatch | |
| 105 | + * @return void | |
| 106 | + */ | |
| 107 | +    function updatePrincipal($path, \Sabre\DAV\PropPatch $propPatch) { | |
| 108 | + } | |
| 109 | + | |
| 110 | + /** | |
| 111 | + * This method is used to search for principals matching a set of | |
| 112 | + * properties. | |
| 113 | + * | |
| 114 | + * This search is specifically used by RFC3744's principal-property-search | |
| 115 | + * REPORT. | |
| 116 | + * | |
| 117 | + * The actual search should be a unicode-non-case-sensitive search. The | |
| 118 | + * keys in searchProperties are the WebDAV property names, while the values | |
| 119 | + * are the property values to search on. | |
| 120 | + * | |
| 121 | + * By default, if multiple properties are submitted to this method, the | |
| 122 | + * various properties should be combined with 'AND'. If $test is set to | |
| 123 | + * 'anyof', it should be combined using 'OR'. | |
| 124 | + * | |
| 125 | + * This method should simply return an array with full principal uri's. | |
| 126 | + * | |
| 127 | + * If somebody attempted to search on a property the backend does not | |
| 128 | + * support, you should simply return 0 results. | |
| 129 | + * | |
| 130 | + * You can also just return 0 results if you choose to not support | |
| 131 | + * searching at all, but keep in mind that this may stop certain features | |
| 132 | + * from working. | |
| 133 | + * | |
| 134 | + * @param string $prefixPath | |
| 135 | + * @param array $searchProperties | |
| 136 | + * @param string $test | |
| 137 | + * @return array | |
| 138 | + */ | |
| 139 | +    function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') { | |
| 140 | + return []; | |
| 141 | + } | |
| 142 | + | |
| 143 | + /** | |
| 144 | + * Returns the list of members for a group-principal | |
| 145 | + * | |
| 146 | + * @param string $principal | |
| 147 | + * @return array | |
| 148 | + */ | |
| 149 | +    function getGroupMemberSet($principal) { | |
| 150 | + // TODO: for now the group principal has only one member, the user itself | |
| 151 | + $principal = $this->getPrincipalByPath($principal); | |
| 152 | +        if (!$principal) { | |
| 153 | +            throw new \Sabre\DAV\Exception('Principal not found'); | |
| 154 | + } | |
| 155 | + | |
| 156 | + return [$principal['uri']]; | |
| 157 | + } | |
| 158 | + | |
| 159 | + /** | |
| 160 | + * Returns the list of groups a principal is a member of | |
| 161 | + * | |
| 162 | + * @param string $principal | |
| 163 | + * @return array | |
| 164 | + */ | |
| 165 | +    function getGroupMembership($principal) { | |
| 166 | + list($prefix, ) = \Sabre\Uri\split($principal); | |
| 167 | + | |
| 168 | +        if ($prefix === 'principals/system') { | |
| 169 | + $principal = $this->getPrincipalByPath($principal); | |
| 170 | +            if (!$principal) { | |
| 171 | +                throw new \Sabre\DAV\Exception('Principal not found'); | |
| 172 | + } | |
| 173 | + | |
| 174 | + return []; | |
| 175 | + } | |
| 176 | + return []; | |
| 177 | + } | |
| 178 | + | |
| 179 | + /** | |
| 180 | + * Updates the list of group members for a group principal. | |
| 181 | + * | |
| 182 | + * The principals should be passed as a list of uri's. | |
| 183 | + * | |
| 184 | + * @param string $principal | |
| 185 | + * @param array $members | |
| 186 | + * @return void | |
| 187 | + */ | |
| 188 | +    function setGroupMemberSet($principal, array $members) { | |
| 189 | +        throw new \Sabre\DAV\Exception('Setting members of the group is not supported yet'); | |
| 190 | + } | |
| 191 | 191 | } | 
| @@ -163,7 +163,7 @@ | ||
| 163 | 163 | * @return array | 
| 164 | 164 | */ | 
| 165 | 165 |  	function getGroupMembership($principal) { | 
| 166 | - list($prefix, ) = \Sabre\Uri\split($principal); | |
| 166 | + list($prefix,) = \Sabre\Uri\split($principal); | |
| 167 | 167 | |
| 168 | 168 |  		if ($prefix === 'principals/system') { | 
| 169 | 169 | $principal = $this->getPrincipalByPath($principal); | 
| @@ -369,7 +369,7 @@ | ||
| 369 | 369 | * @param string $path path to the file which should be updated | 
| 370 | 370 | * @param string $uid of the user who performs the operation | 
| 371 | 371 | * @param array $accessList who has access to the file contains the key 'users' and 'public' | 
| 372 | - * @return boolean | |
| 372 | + * @return null|boolean | |
| 373 | 373 | */ | 
| 374 | 374 |  	public function update($path, $uid, array $accessList) { | 
| 375 | 375 | |
| @@ -177,7 +177,7 @@ discard block | ||
| 177 | 177 | $this->isWriteOperation = false; | 
| 178 | 178 | $this->writeCache = ''; | 
| 179 | 179 | |
| 180 | -		if($this->session->isReady() === false) { | |
| 180 | +		if ($this->session->isReady() === false) { | |
| 181 | 181 | // if the master key is enabled we can initialize encryption | 
| 182 | 182 | // with a empty password and user name | 
| 183 | 183 |  			if ($this->util->isMasterKeyEnabled()) { | 
| @@ -198,7 +198,7 @@ discard block | ||
| 198 | 198 | // always use the version from the original file, also part files | 
| 199 | 199 | // need to have a correct version number if they get moved over to the | 
| 200 | 200 | // final location | 
| 201 | - $this->version = (int)$this->keyManager->getVersion($this->stripPartFileExtension($path), new View()); | |
| 201 | + $this->version = (int) $this->keyManager->getVersion($this->stripPartFileExtension($path), new View()); | |
| 202 | 202 | |
| 203 | 203 | if ( | 
| 204 | 204 | $mode === 'w' | 
| @@ -214,7 +214,7 @@ discard block | ||
| 214 | 214 | // if we read a part file we need to increase the version by 1 | 
| 215 | 215 | // because the version number was also increased by writing | 
| 216 | 216 | // the part file | 
| 217 | -			if(Scanner::isPartialFile($path)) { | |
| 217 | +			if (Scanner::isPartialFile($path)) { | |
| 218 | 218 | $this->version = $this->version + 1; | 
| 219 | 219 | } | 
| 220 | 220 | } | 
| @@ -300,7 +300,7 @@ discard block | ||
| 300 | 300 |  		if ($this->writeCache) { | 
| 301 | 301 | |
| 302 | 302 | // Concat writeCache to start of $data | 
| 303 | - $data = $this->writeCache . $data; | |
| 303 | + $data = $this->writeCache.$data; | |
| 304 | 304 | |
| 305 | 305 | // Clear the write cache, ready for reuse - it has been | 
| 306 | 306 | // flushed and its old contents processed | 
| @@ -402,7 +402,7 @@ discard block | ||
| 402 | 402 |  					try { | 
| 403 | 403 | $publicKeys[$user] = $this->keyManager->getPublicKey($user); | 
| 404 | 404 |  					} catch (PublicKeyMissingException $e) { | 
| 405 | -						$this->logger->warning('Could not encrypt file for ' . $user . ': ' . $e->getMessage()); | |
| 405 | +						$this->logger->warning('Could not encrypt file for '.$user.': '.$e->getMessage()); | |
| 406 | 406 | } | 
| 407 | 407 | } | 
| 408 | 408 | } | 
| @@ -489,8 +489,8 @@ discard block | ||
| 489 | 489 | // error message because in this case it means that the file was | 
| 490 | 490 | // shared with the user at a point where the user didn't had a | 
| 491 | 491 | // valid private/public key | 
| 492 | - $msg = 'Encryption module "' . $this->getDisplayName() . | |
| 493 | - '" is not able to read ' . $path; | |
| 492 | + $msg = 'Encryption module "'.$this->getDisplayName(). | |
| 493 | + '" is not able to read '.$path; | |
| 494 | 494 |  				$hint = $this->l->t('Can not read this file, probably this is a shared file. Please ask the file owner to reshare the file with you.'); | 
| 495 | 495 | $this->logger->warning($msg); | 
| 496 | 496 | throw new DecryptionFailedException($msg, $hint); | 
| @@ -532,7 +532,7 @@ discard block | ||
| 532 | 532 | $realPath = $path; | 
| 533 | 533 |  		$parts = explode('/', $path); | 
| 534 | 534 |  		if ($parts[2] === 'files_versions') { | 
| 535 | -			$realPath = '/' . $parts[1] . '/files/' . implode('/', array_slice($parts, 3)); | |
| 535 | +			$realPath = '/'.$parts[1].'/files/'.implode('/', array_slice($parts, 3)); | |
| 536 | 536 | $length = strrpos($realPath, '.'); | 
| 537 | 537 | $realPath = substr($realPath, 0, $length); | 
| 538 | 538 | } | 
| @@ -45,557 +45,557 @@ | ||
| 45 | 45 | |
| 46 | 46 |  class Encryption implements IEncryptionModule { | 
| 47 | 47 | |
| 48 | - const ID = 'OC_DEFAULT_MODULE'; | |
| 49 | - const DISPLAY_NAME = 'Default encryption module'; | |
| 50 | - | |
| 51 | - /** | |
| 52 | - * @var Crypt | |
| 53 | - */ | |
| 54 | - private $crypt; | |
| 55 | - | |
| 56 | - /** @var string */ | |
| 57 | - private $cipher; | |
| 58 | - | |
| 59 | - /** @var string */ | |
| 60 | - private $path; | |
| 61 | - | |
| 62 | - /** @var string */ | |
| 63 | - private $user; | |
| 64 | - | |
| 65 | - /** @var array */ | |
| 66 | - private $owner; | |
| 67 | - | |
| 68 | - /** @var string */ | |
| 69 | - private $fileKey; | |
| 70 | - | |
| 71 | - /** @var string */ | |
| 72 | - private $writeCache; | |
| 73 | - | |
| 74 | - /** @var KeyManager */ | |
| 75 | - private $keyManager; | |
| 76 | - | |
| 77 | - /** @var array */ | |
| 78 | - private $accessList; | |
| 79 | - | |
| 80 | - /** @var boolean */ | |
| 81 | - private $isWriteOperation; | |
| 82 | - | |
| 83 | - /** @var Util */ | |
| 84 | - private $util; | |
| 85 | - | |
| 86 | - /** @var Session */ | |
| 87 | - private $session; | |
| 88 | - | |
| 89 | - /** @var ILogger */ | |
| 90 | - private $logger; | |
| 91 | - | |
| 92 | - /** @var IL10N */ | |
| 93 | - private $l; | |
| 94 | - | |
| 95 | - /** @var EncryptAll */ | |
| 96 | - private $encryptAll; | |
| 97 | - | |
| 98 | - /** @var bool */ | |
| 99 | - private $useMasterPassword; | |
| 100 | - | |
| 101 | - /** @var DecryptAll */ | |
| 102 | - private $decryptAll; | |
| 103 | - | |
| 104 | - /** @var int unencrypted block size if block contains signature */ | |
| 105 | - private $unencryptedBlockSizeSigned = 6072; | |
| 106 | - | |
| 107 | - /** @var int unencrypted block size */ | |
| 108 | - private $unencryptedBlockSize = 6126; | |
| 109 | - | |
| 110 | - /** @var int Current version of the file */ | |
| 111 | - private $version = 0; | |
| 112 | - | |
| 113 | - /** @var array remember encryption signature version */ | |
| 114 | - private static $rememberVersion = []; | |
| 115 | - | |
| 116 | - | |
| 117 | - /** | |
| 118 | - * | |
| 119 | - * @param Crypt $crypt | |
| 120 | - * @param KeyManager $keyManager | |
| 121 | - * @param Util $util | |
| 122 | - * @param Session $session | |
| 123 | - * @param EncryptAll $encryptAll | |
| 124 | - * @param DecryptAll $decryptAll | |
| 125 | - * @param ILogger $logger | |
| 126 | - * @param IL10N $il10n | |
| 127 | - */ | |
| 128 | - public function __construct(Crypt $crypt, | |
| 129 | - KeyManager $keyManager, | |
| 130 | - Util $util, | |
| 131 | - Session $session, | |
| 132 | - EncryptAll $encryptAll, | |
| 133 | - DecryptAll $decryptAll, | |
| 134 | - ILogger $logger, | |
| 135 | -								IL10N $il10n) { | |
| 136 | - $this->crypt = $crypt; | |
| 137 | - $this->keyManager = $keyManager; | |
| 138 | - $this->util = $util; | |
| 139 | - $this->session = $session; | |
| 140 | - $this->encryptAll = $encryptAll; | |
| 141 | - $this->decryptAll = $decryptAll; | |
| 142 | - $this->logger = $logger; | |
| 143 | - $this->l = $il10n; | |
| 144 | - $this->owner = []; | |
| 145 | - $this->useMasterPassword = $util->isMasterKeyEnabled(); | |
| 146 | - } | |
| 147 | - | |
| 148 | - /** | |
| 149 | - * @return string defining the technical unique id | |
| 150 | - */ | |
| 151 | -	public function getId() { | |
| 152 | - return self::ID; | |
| 153 | - } | |
| 154 | - | |
| 155 | - /** | |
| 156 | - * In comparison to getKey() this function returns a human readable (maybe translated) name | |
| 157 | - * | |
| 158 | - * @return string | |
| 159 | - */ | |
| 160 | -	public function getDisplayName() { | |
| 161 | - return self::DISPLAY_NAME; | |
| 162 | - } | |
| 163 | - | |
| 164 | - /** | |
| 165 | - * start receiving chunks from a file. This is the place where you can | |
| 166 | - * perform some initial step before starting encrypting/decrypting the | |
| 167 | - * chunks | |
| 168 | - * | |
| 169 | - * @param string $path to the file | |
| 170 | - * @param string $user who read/write the file | |
| 171 | - * @param string $mode php stream open mode | |
| 172 | - * @param array $header contains the header data read from the file | |
| 173 | - * @param array $accessList who has access to the file contains the key 'users' and 'public' | |
| 174 | - * | |
| 175 | - * @return array $header contain data as key-value pairs which should be | |
| 176 | - * written to the header, in case of a write operation | |
| 177 | - * or if no additional data is needed return a empty array | |
| 178 | - */ | |
| 179 | -	public function begin($path, $user, $mode, array $header, array $accessList) { | |
| 180 | - $this->path = $this->getPathToRealFile($path); | |
| 181 | - $this->accessList = $accessList; | |
| 182 | - $this->user = $user; | |
| 183 | - $this->isWriteOperation = false; | |
| 184 | - $this->writeCache = ''; | |
| 185 | - | |
| 186 | -		if($this->session->isReady() === false) { | |
| 187 | - // if the master key is enabled we can initialize encryption | |
| 188 | - // with a empty password and user name | |
| 189 | -			if ($this->util->isMasterKeyEnabled()) { | |
| 190 | -				$this->keyManager->init('', ''); | |
| 191 | - } | |
| 192 | - } | |
| 193 | - | |
| 194 | -		if ($this->session->decryptAllModeActivated()) { | |
| 195 | - $encryptedFileKey = $this->keyManager->getEncryptedFileKey($this->path); | |
| 196 | - $shareKey = $this->keyManager->getShareKey($this->path, $this->session->getDecryptAllUid()); | |
| 197 | - $this->fileKey = $this->crypt->multiKeyDecrypt($encryptedFileKey, | |
| 198 | - $shareKey, | |
| 199 | - $this->session->getDecryptAllKey()); | |
| 200 | -		} else { | |
| 201 | - $this->fileKey = $this->keyManager->getFileKey($this->path, $this->user); | |
| 202 | - } | |
| 203 | - | |
| 204 | - // always use the version from the original file, also part files | |
| 205 | - // need to have a correct version number if they get moved over to the | |
| 206 | - // final location | |
| 207 | - $this->version = (int)$this->keyManager->getVersion($this->stripPartFileExtension($path), new View()); | |
| 208 | - | |
| 209 | - if ( | |
| 210 | - $mode === 'w' | |
| 211 | - || $mode === 'w+' | |
| 212 | - || $mode === 'wb' | |
| 213 | - || $mode === 'wb+' | |
| 214 | -		) { | |
| 215 | - $this->isWriteOperation = true; | |
| 216 | -			if (empty($this->fileKey)) { | |
| 217 | - $this->fileKey = $this->crypt->generateFileKey(); | |
| 218 | - } | |
| 219 | -		} else { | |
| 220 | - // if we read a part file we need to increase the version by 1 | |
| 221 | - // because the version number was also increased by writing | |
| 222 | - // the part file | |
| 223 | -			if(Scanner::isPartialFile($path)) { | |
| 224 | - $this->version = $this->version + 1; | |
| 225 | - } | |
| 226 | - } | |
| 227 | - | |
| 228 | -		if ($this->isWriteOperation) { | |
| 229 | - $this->cipher = $this->crypt->getCipher(); | |
| 230 | -		} elseif (isset($header['cipher'])) { | |
| 231 | - $this->cipher = $header['cipher']; | |
| 232 | -		} else { | |
| 233 | - // if we read a file without a header we fall-back to the legacy cipher | |
| 234 | - // which was used in <=oC6 | |
| 235 | - $this->cipher = $this->crypt->getLegacyCipher(); | |
| 236 | - } | |
| 237 | - | |
| 238 | -		return array('cipher' => $this->cipher, 'signed' => 'true'); | |
| 239 | - } | |
| 240 | - | |
| 241 | - /** | |
| 242 | - * last chunk received. This is the place where you can perform some final | |
| 243 | - * operation and return some remaining data if something is left in your | |
| 244 | - * buffer. | |
| 245 | - * | |
| 246 | - * @param string $path to the file | |
| 247 | - * @param int $position | |
| 248 | - * @return string remained data which should be written to the file in case | |
| 249 | - * of a write operation | |
| 250 | - * @throws PublicKeyMissingException | |
| 251 | - * @throws \Exception | |
| 252 | - * @throws \OCA\Encryption\Exceptions\MultiKeyEncryptException | |
| 253 | - */ | |
| 254 | -	public function end($path, $position = 0) { | |
| 255 | - $result = ''; | |
| 256 | -		if ($this->isWriteOperation) { | |
| 257 | - // in case of a part file we remember the new signature versions | |
| 258 | - // the version will be set later on update. | |
| 259 | - // This way we make sure that other apps listening to the pre-hooks | |
| 260 | - // still get the old version which should be the correct value for them | |
| 261 | -			if (Scanner::isPartialFile($path)) { | |
| 262 | - self::$rememberVersion[$this->stripPartFileExtension($path)] = $this->version + 1; | |
| 263 | - } | |
| 264 | -			if (!empty($this->writeCache)) { | |
| 265 | - $result = $this->crypt->symmetricEncryptFileContent($this->writeCache, $this->fileKey, $this->version + 1, $position); | |
| 266 | - $this->writeCache = ''; | |
| 267 | - } | |
| 268 | - $publicKeys = array(); | |
| 269 | -			if ($this->useMasterPassword === true) { | |
| 270 | - $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey(); | |
| 271 | -			} else { | |
| 272 | -				foreach ($this->accessList['users'] as $uid) { | |
| 273 | -					try { | |
| 274 | - $publicKeys[$uid] = $this->keyManager->getPublicKey($uid); | |
| 275 | -					} catch (PublicKeyMissingException $e) { | |
| 276 | - $this->logger->warning( | |
| 277 | -							'no public key found for user "{uid}", user will not be able to read the file', | |
| 278 | - ['app' => 'encryption', 'uid' => $uid] | |
| 279 | - ); | |
| 280 | - // if the public key of the owner is missing we should fail | |
| 281 | -						if ($uid === $this->user) { | |
| 282 | - throw $e; | |
| 283 | - } | |
| 284 | - } | |
| 285 | - } | |
| 286 | - } | |
| 287 | - | |
| 288 | - $publicKeys = $this->keyManager->addSystemKeys($this->accessList, $publicKeys, $this->getOwner($path)); | |
| 289 | - $encryptedKeyfiles = $this->crypt->multiKeyEncrypt($this->fileKey, $publicKeys); | |
| 290 | - $this->keyManager->setAllFileKeys($this->path, $encryptedKeyfiles); | |
| 291 | - } | |
| 292 | - return $result; | |
| 293 | - } | |
| 294 | - | |
| 295 | - | |
| 296 | - | |
| 297 | - /** | |
| 298 | - * encrypt data | |
| 299 | - * | |
| 300 | - * @param string $data you want to encrypt | |
| 301 | - * @param int $position | |
| 302 | - * @return string encrypted data | |
| 303 | - */ | |
| 304 | -	public function encrypt($data, $position = 0) { | |
| 305 | - // If extra data is left over from the last round, make sure it | |
| 306 | - // is integrated into the next block | |
| 307 | -		if ($this->writeCache) { | |
| 308 | - | |
| 309 | - // Concat writeCache to start of $data | |
| 310 | - $data = $this->writeCache . $data; | |
| 311 | - | |
| 312 | - // Clear the write cache, ready for reuse - it has been | |
| 313 | - // flushed and its old contents processed | |
| 314 | - $this->writeCache = ''; | |
| 315 | - | |
| 316 | - } | |
| 317 | - | |
| 318 | - $encrypted = ''; | |
| 319 | - // While there still remains some data to be processed & written | |
| 320 | -		while (strlen($data) > 0) { | |
| 321 | - | |
| 322 | - // Remaining length for this iteration, not of the | |
| 323 | - // entire file (may be greater than 8192 bytes) | |
| 324 | - $remainingLength = strlen($data); | |
| 325 | - | |
| 326 | - // If data remaining to be written is less than the | |
| 327 | - // size of 1 6126 byte block | |
| 328 | -			if ($remainingLength < $this->unencryptedBlockSizeSigned) { | |
| 329 | - | |
| 330 | - // Set writeCache to contents of $data | |
| 331 | - // The writeCache will be carried over to the | |
| 332 | - // next write round, and added to the start of | |
| 333 | - // $data to ensure that written blocks are | |
| 334 | - // always the correct length. If there is still | |
| 335 | - // data in writeCache after the writing round | |
| 336 | - // has finished, then the data will be written | |
| 337 | - // to disk by $this->flush(). | |
| 338 | - $this->writeCache = $data; | |
| 339 | - | |
| 340 | - // Clear $data ready for next round | |
| 341 | - $data = ''; | |
| 342 | - | |
| 343 | -			} else { | |
| 344 | - | |
| 345 | - // Read the chunk from the start of $data | |
| 346 | - $chunk = substr($data, 0, $this->unencryptedBlockSizeSigned); | |
| 347 | - | |
| 348 | - $encrypted .= $this->crypt->symmetricEncryptFileContent($chunk, $this->fileKey, $this->version + 1, $position); | |
| 349 | - | |
| 350 | - // Remove the chunk we just processed from | |
| 351 | - // $data, leaving only unprocessed data in $data | |
| 352 | - // var, for handling on the next round | |
| 353 | - $data = substr($data, $this->unencryptedBlockSizeSigned); | |
| 354 | - | |
| 355 | - } | |
| 356 | - | |
| 357 | - } | |
| 358 | - | |
| 359 | - return $encrypted; | |
| 360 | - } | |
| 361 | - | |
| 362 | - /** | |
| 363 | - * decrypt data | |
| 364 | - * | |
| 365 | - * @param string $data you want to decrypt | |
| 366 | - * @param int $position | |
| 367 | - * @return string decrypted data | |
| 368 | - * @throws DecryptionFailedException | |
| 369 | - */ | |
| 370 | -	public function decrypt($data, $position = 0) { | |
| 371 | -		if (empty($this->fileKey)) { | |
| 372 | - $msg = 'Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.'; | |
| 373 | -			$hint = $this->l->t('Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.'); | |
| 374 | - $this->logger->error($msg); | |
| 375 | - | |
| 376 | - throw new DecryptionFailedException($msg, $hint); | |
| 377 | - } | |
| 378 | - | |
| 379 | - return $this->crypt->symmetricDecryptFileContent($data, $this->fileKey, $this->cipher, $this->version, $position); | |
| 380 | - } | |
| 381 | - | |
| 382 | - /** | |
| 383 | - * update encrypted file, e.g. give additional users access to the file | |
| 384 | - * | |
| 385 | - * @param string $path path to the file which should be updated | |
| 386 | - * @param string $uid of the user who performs the operation | |
| 387 | - * @param array $accessList who has access to the file contains the key 'users' and 'public' | |
| 388 | - * @return boolean | |
| 389 | - */ | |
| 390 | -	public function update($path, $uid, array $accessList) { | |
| 391 | - | |
| 392 | -		if (empty($accessList)) { | |
| 393 | -			if (isset(self::$rememberVersion[$path])) { | |
| 394 | - $this->keyManager->setVersion($path, self::$rememberVersion[$path], new View()); | |
| 395 | - unset(self::$rememberVersion[$path]); | |
| 396 | - } | |
| 397 | - return; | |
| 398 | - } | |
| 399 | - | |
| 400 | - $fileKey = $this->keyManager->getFileKey($path, $uid); | |
| 401 | - | |
| 402 | -		if (!empty($fileKey)) { | |
| 403 | - | |
| 404 | - $publicKeys = array(); | |
| 405 | -			if ($this->useMasterPassword === true) { | |
| 406 | - $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey(); | |
| 407 | -			} else { | |
| 408 | -				foreach ($accessList['users'] as $user) { | |
| 409 | -					try { | |
| 410 | - $publicKeys[$user] = $this->keyManager->getPublicKey($user); | |
| 411 | -					} catch (PublicKeyMissingException $e) { | |
| 412 | -						$this->logger->warning('Could not encrypt file for ' . $user . ': ' . $e->getMessage()); | |
| 413 | - } | |
| 414 | - } | |
| 415 | - } | |
| 416 | - | |
| 417 | - $publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $this->getOwner($path)); | |
| 418 | - | |
| 419 | - $encryptedFileKey = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys); | |
| 420 | - | |
| 421 | - $this->keyManager->deleteAllFileKeys($path); | |
| 422 | - | |
| 423 | - $this->keyManager->setAllFileKeys($path, $encryptedFileKey); | |
| 424 | - | |
| 425 | -		} else { | |
| 426 | -			$this->logger->debug('no file key found, we assume that the file "{file}" is not encrypted', | |
| 427 | -				array('file' => $path, 'app' => 'encryption')); | |
| 428 | - | |
| 429 | - return false; | |
| 430 | - } | |
| 431 | - | |
| 432 | - return true; | |
| 433 | - } | |
| 434 | - | |
| 435 | - /** | |
| 436 | - * should the file be encrypted or not | |
| 437 | - * | |
| 438 | - * @param string $path | |
| 439 | - * @return boolean | |
| 440 | - */ | |
| 441 | -	public function shouldEncrypt($path) { | |
| 442 | -		if ($this->util->shouldEncryptHomeStorage() === false) { | |
| 443 | - $storage = $this->util->getStorage($path); | |
| 444 | -			if ($storage->instanceOfStorage('\OCP\Files\IHomeStorage')) { | |
| 445 | - return false; | |
| 446 | - } | |
| 447 | - } | |
| 448 | -		$parts = explode('/', $path); | |
| 449 | -		if (count($parts) < 4) { | |
| 450 | - return false; | |
| 451 | - } | |
| 452 | - | |
| 453 | -		if ($parts[2] === 'files') { | |
| 454 | - return true; | |
| 455 | - } | |
| 456 | -		if ($parts[2] === 'files_versions') { | |
| 457 | - return true; | |
| 458 | - } | |
| 459 | -		if ($parts[2] === 'files_trashbin') { | |
| 460 | - return true; | |
| 461 | - } | |
| 462 | - | |
| 463 | - return false; | |
| 464 | - } | |
| 465 | - | |
| 466 | - /** | |
| 467 | - * get size of the unencrypted payload per block. | |
| 468 | - * Nextcloud read/write files with a block size of 8192 byte | |
| 469 | - * | |
| 470 | - * @param bool $signed | |
| 471 | - * @return int | |
| 472 | - */ | |
| 473 | -	public function getUnencryptedBlockSize($signed = false) { | |
| 474 | -		if ($signed === false) { | |
| 475 | - return $this->unencryptedBlockSize; | |
| 476 | - } | |
| 477 | - | |
| 478 | - return $this->unencryptedBlockSizeSigned; | |
| 479 | - } | |
| 480 | - | |
| 481 | - /** | |
| 482 | - * check if the encryption module is able to read the file, | |
| 483 | - * e.g. if all encryption keys exists | |
| 484 | - * | |
| 485 | - * @param string $path | |
| 486 | - * @param string $uid user for whom we want to check if he can read the file | |
| 487 | - * @return bool | |
| 488 | - * @throws DecryptionFailedException | |
| 489 | - */ | |
| 490 | -	public function isReadable($path, $uid) { | |
| 491 | - $fileKey = $this->keyManager->getFileKey($path, $uid); | |
| 492 | -		if (empty($fileKey)) { | |
| 493 | - $owner = $this->util->getOwner($path); | |
| 494 | -			if ($owner !== $uid) { | |
| 495 | - // if it is a shared file we throw a exception with a useful | |
| 496 | - // error message because in this case it means that the file was | |
| 497 | - // shared with the user at a point where the user didn't had a | |
| 498 | - // valid private/public key | |
| 499 | - $msg = 'Encryption module "' . $this->getDisplayName() . | |
| 500 | - '" is not able to read ' . $path; | |
| 501 | -				$hint = $this->l->t('Can not read this file, probably this is a shared file. Please ask the file owner to reshare the file with you.'); | |
| 502 | - $this->logger->warning($msg); | |
| 503 | - throw new DecryptionFailedException($msg, $hint); | |
| 504 | - } | |
| 505 | - return false; | |
| 506 | - } | |
| 507 | - | |
| 508 | - return true; | |
| 509 | - } | |
| 510 | - | |
| 511 | - /** | |
| 512 | - * Initial encryption of all files | |
| 513 | - * | |
| 514 | - * @param InputInterface $input | |
| 515 | - * @param OutputInterface $output write some status information to the terminal during encryption | |
| 516 | - */ | |
| 517 | -	public function encryptAll(InputInterface $input, OutputInterface $output) { | |
| 518 | - $this->encryptAll->encryptAll($input, $output); | |
| 519 | - } | |
| 520 | - | |
| 521 | - /** | |
| 522 | - * prepare module to perform decrypt all operation | |
| 523 | - * | |
| 524 | - * @param InputInterface $input | |
| 525 | - * @param OutputInterface $output | |
| 526 | - * @param string $user | |
| 527 | - * @return bool | |
| 528 | - */ | |
| 529 | -	public function prepareDecryptAll(InputInterface $input, OutputInterface $output, $user = '') { | |
| 530 | - return $this->decryptAll->prepare($input, $output, $user); | |
| 531 | - } | |
| 532 | - | |
| 533 | - | |
| 534 | - /** | |
| 535 | - * @param string $path | |
| 536 | - * @return string | |
| 537 | - */ | |
| 538 | -	protected function getPathToRealFile($path) { | |
| 539 | - $realPath = $path; | |
| 540 | -		$parts = explode('/', $path); | |
| 541 | -		if ($parts[2] === 'files_versions') { | |
| 542 | -			$realPath = '/' . $parts[1] . '/files/' . implode('/', array_slice($parts, 3)); | |
| 543 | - $length = strrpos($realPath, '.'); | |
| 544 | - $realPath = substr($realPath, 0, $length); | |
| 545 | - } | |
| 546 | - | |
| 547 | - return $realPath; | |
| 548 | - } | |
| 549 | - | |
| 550 | - /** | |
| 551 | - * remove .part file extension and the ocTransferId from the file to get the | |
| 552 | - * original file name | |
| 553 | - * | |
| 554 | - * @param string $path | |
| 555 | - * @return string | |
| 556 | - */ | |
| 557 | -	protected function stripPartFileExtension($path) { | |
| 558 | -		if (pathinfo($path, PATHINFO_EXTENSION) === 'part') { | |
| 559 | - $pos = strrpos($path, '.', -6); | |
| 560 | - $path = substr($path, 0, $pos); | |
| 561 | - } | |
| 562 | - | |
| 563 | - return $path; | |
| 564 | - } | |
| 565 | - | |
| 566 | - /** | |
| 567 | - * get owner of a file | |
| 568 | - * | |
| 569 | - * @param string $path | |
| 570 | - * @return string | |
| 571 | - */ | |
| 572 | -	protected function getOwner($path) { | |
| 573 | -		if (!isset($this->owner[$path])) { | |
| 574 | - $this->owner[$path] = $this->util->getOwner($path); | |
| 575 | - } | |
| 576 | - return $this->owner[$path]; | |
| 577 | - } | |
| 578 | - | |
| 579 | - /** | |
| 580 | - * Check if the module is ready to be used by that specific user. | |
| 581 | - * In case a module is not ready - because e.g. key pairs have not been generated | |
| 582 | - * upon login this method can return false before any operation starts and might | |
| 583 | - * cause issues during operations. | |
| 584 | - * | |
| 585 | - * @param string $user | |
| 586 | - * @return boolean | |
| 587 | - * @since 9.1.0 | |
| 588 | - */ | |
| 589 | -	public function isReadyForUser($user) { | |
| 590 | - return $this->keyManager->userHasKeys($user); | |
| 591 | - } | |
| 592 | - | |
| 593 | - /** | |
| 594 | - * We only need a detailed access list if the master key is not enabled | |
| 595 | - * | |
| 596 | - * @return bool | |
| 597 | - */ | |
| 598 | -	public function needDetailedAccessList() { | |
| 599 | - return !$this->util->isMasterKeyEnabled(); | |
| 600 | - } | |
| 48 | + const ID = 'OC_DEFAULT_MODULE'; | |
| 49 | + const DISPLAY_NAME = 'Default encryption module'; | |
| 50 | + | |
| 51 | + /** | |
| 52 | + * @var Crypt | |
| 53 | + */ | |
| 54 | + private $crypt; | |
| 55 | + | |
| 56 | + /** @var string */ | |
| 57 | + private $cipher; | |
| 58 | + | |
| 59 | + /** @var string */ | |
| 60 | + private $path; | |
| 61 | + | |
| 62 | + /** @var string */ | |
| 63 | + private $user; | |
| 64 | + | |
| 65 | + /** @var array */ | |
| 66 | + private $owner; | |
| 67 | + | |
| 68 | + /** @var string */ | |
| 69 | + private $fileKey; | |
| 70 | + | |
| 71 | + /** @var string */ | |
| 72 | + private $writeCache; | |
| 73 | + | |
| 74 | + /** @var KeyManager */ | |
| 75 | + private $keyManager; | |
| 76 | + | |
| 77 | + /** @var array */ | |
| 78 | + private $accessList; | |
| 79 | + | |
| 80 | + /** @var boolean */ | |
| 81 | + private $isWriteOperation; | |
| 82 | + | |
| 83 | + /** @var Util */ | |
| 84 | + private $util; | |
| 85 | + | |
| 86 | + /** @var Session */ | |
| 87 | + private $session; | |
| 88 | + | |
| 89 | + /** @var ILogger */ | |
| 90 | + private $logger; | |
| 91 | + | |
| 92 | + /** @var IL10N */ | |
| 93 | + private $l; | |
| 94 | + | |
| 95 | + /** @var EncryptAll */ | |
| 96 | + private $encryptAll; | |
| 97 | + | |
| 98 | + /** @var bool */ | |
| 99 | + private $useMasterPassword; | |
| 100 | + | |
| 101 | + /** @var DecryptAll */ | |
| 102 | + private $decryptAll; | |
| 103 | + | |
| 104 | + /** @var int unencrypted block size if block contains signature */ | |
| 105 | + private $unencryptedBlockSizeSigned = 6072; | |
| 106 | + | |
| 107 | + /** @var int unencrypted block size */ | |
| 108 | + private $unencryptedBlockSize = 6126; | |
| 109 | + | |
| 110 | + /** @var int Current version of the file */ | |
| 111 | + private $version = 0; | |
| 112 | + | |
| 113 | + /** @var array remember encryption signature version */ | |
| 114 | + private static $rememberVersion = []; | |
| 115 | + | |
| 116 | + | |
| 117 | + /** | |
| 118 | + * | |
| 119 | + * @param Crypt $crypt | |
| 120 | + * @param KeyManager $keyManager | |
| 121 | + * @param Util $util | |
| 122 | + * @param Session $session | |
| 123 | + * @param EncryptAll $encryptAll | |
| 124 | + * @param DecryptAll $decryptAll | |
| 125 | + * @param ILogger $logger | |
| 126 | + * @param IL10N $il10n | |
| 127 | + */ | |
| 128 | + public function __construct(Crypt $crypt, | |
| 129 | + KeyManager $keyManager, | |
| 130 | + Util $util, | |
| 131 | + Session $session, | |
| 132 | + EncryptAll $encryptAll, | |
| 133 | + DecryptAll $decryptAll, | |
| 134 | + ILogger $logger, | |
| 135 | +                                IL10N $il10n) { | |
| 136 | + $this->crypt = $crypt; | |
| 137 | + $this->keyManager = $keyManager; | |
| 138 | + $this->util = $util; | |
| 139 | + $this->session = $session; | |
| 140 | + $this->encryptAll = $encryptAll; | |
| 141 | + $this->decryptAll = $decryptAll; | |
| 142 | + $this->logger = $logger; | |
| 143 | + $this->l = $il10n; | |
| 144 | + $this->owner = []; | |
| 145 | + $this->useMasterPassword = $util->isMasterKeyEnabled(); | |
| 146 | + } | |
| 147 | + | |
| 148 | + /** | |
| 149 | + * @return string defining the technical unique id | |
| 150 | + */ | |
| 151 | +    public function getId() { | |
| 152 | + return self::ID; | |
| 153 | + } | |
| 154 | + | |
| 155 | + /** | |
| 156 | + * In comparison to getKey() this function returns a human readable (maybe translated) name | |
| 157 | + * | |
| 158 | + * @return string | |
| 159 | + */ | |
| 160 | +    public function getDisplayName() { | |
| 161 | + return self::DISPLAY_NAME; | |
| 162 | + } | |
| 163 | + | |
| 164 | + /** | |
| 165 | + * start receiving chunks from a file. This is the place where you can | |
| 166 | + * perform some initial step before starting encrypting/decrypting the | |
| 167 | + * chunks | |
| 168 | + * | |
| 169 | + * @param string $path to the file | |
| 170 | + * @param string $user who read/write the file | |
| 171 | + * @param string $mode php stream open mode | |
| 172 | + * @param array $header contains the header data read from the file | |
| 173 | + * @param array $accessList who has access to the file contains the key 'users' and 'public' | |
| 174 | + * | |
| 175 | + * @return array $header contain data as key-value pairs which should be | |
| 176 | + * written to the header, in case of a write operation | |
| 177 | + * or if no additional data is needed return a empty array | |
| 178 | + */ | |
| 179 | +    public function begin($path, $user, $mode, array $header, array $accessList) { | |
| 180 | + $this->path = $this->getPathToRealFile($path); | |
| 181 | + $this->accessList = $accessList; | |
| 182 | + $this->user = $user; | |
| 183 | + $this->isWriteOperation = false; | |
| 184 | + $this->writeCache = ''; | |
| 185 | + | |
| 186 | +        if($this->session->isReady() === false) { | |
| 187 | + // if the master key is enabled we can initialize encryption | |
| 188 | + // with a empty password and user name | |
| 189 | +            if ($this->util->isMasterKeyEnabled()) { | |
| 190 | +                $this->keyManager->init('', ''); | |
| 191 | + } | |
| 192 | + } | |
| 193 | + | |
| 194 | +        if ($this->session->decryptAllModeActivated()) { | |
| 195 | + $encryptedFileKey = $this->keyManager->getEncryptedFileKey($this->path); | |
| 196 | + $shareKey = $this->keyManager->getShareKey($this->path, $this->session->getDecryptAllUid()); | |
| 197 | + $this->fileKey = $this->crypt->multiKeyDecrypt($encryptedFileKey, | |
| 198 | + $shareKey, | |
| 199 | + $this->session->getDecryptAllKey()); | |
| 200 | +        } else { | |
| 201 | + $this->fileKey = $this->keyManager->getFileKey($this->path, $this->user); | |
| 202 | + } | |
| 203 | + | |
| 204 | + // always use the version from the original file, also part files | |
| 205 | + // need to have a correct version number if they get moved over to the | |
| 206 | + // final location | |
| 207 | + $this->version = (int)$this->keyManager->getVersion($this->stripPartFileExtension($path), new View()); | |
| 208 | + | |
| 209 | + if ( | |
| 210 | + $mode === 'w' | |
| 211 | + || $mode === 'w+' | |
| 212 | + || $mode === 'wb' | |
| 213 | + || $mode === 'wb+' | |
| 214 | +        ) { | |
| 215 | + $this->isWriteOperation = true; | |
| 216 | +            if (empty($this->fileKey)) { | |
| 217 | + $this->fileKey = $this->crypt->generateFileKey(); | |
| 218 | + } | |
| 219 | +        } else { | |
| 220 | + // if we read a part file we need to increase the version by 1 | |
| 221 | + // because the version number was also increased by writing | |
| 222 | + // the part file | |
| 223 | +            if(Scanner::isPartialFile($path)) { | |
| 224 | + $this->version = $this->version + 1; | |
| 225 | + } | |
| 226 | + } | |
| 227 | + | |
| 228 | +        if ($this->isWriteOperation) { | |
| 229 | + $this->cipher = $this->crypt->getCipher(); | |
| 230 | +        } elseif (isset($header['cipher'])) { | |
| 231 | + $this->cipher = $header['cipher']; | |
| 232 | +        } else { | |
| 233 | + // if we read a file without a header we fall-back to the legacy cipher | |
| 234 | + // which was used in <=oC6 | |
| 235 | + $this->cipher = $this->crypt->getLegacyCipher(); | |
| 236 | + } | |
| 237 | + | |
| 238 | +        return array('cipher' => $this->cipher, 'signed' => 'true'); | |
| 239 | + } | |
| 240 | + | |
| 241 | + /** | |
| 242 | + * last chunk received. This is the place where you can perform some final | |
| 243 | + * operation and return some remaining data if something is left in your | |
| 244 | + * buffer. | |
| 245 | + * | |
| 246 | + * @param string $path to the file | |
| 247 | + * @param int $position | |
| 248 | + * @return string remained data which should be written to the file in case | |
| 249 | + * of a write operation | |
| 250 | + * @throws PublicKeyMissingException | |
| 251 | + * @throws \Exception | |
| 252 | + * @throws \OCA\Encryption\Exceptions\MultiKeyEncryptException | |
| 253 | + */ | |
| 254 | +    public function end($path, $position = 0) { | |
| 255 | + $result = ''; | |
| 256 | +        if ($this->isWriteOperation) { | |
| 257 | + // in case of a part file we remember the new signature versions | |
| 258 | + // the version will be set later on update. | |
| 259 | + // This way we make sure that other apps listening to the pre-hooks | |
| 260 | + // still get the old version which should be the correct value for them | |
| 261 | +            if (Scanner::isPartialFile($path)) { | |
| 262 | + self::$rememberVersion[$this->stripPartFileExtension($path)] = $this->version + 1; | |
| 263 | + } | |
| 264 | +            if (!empty($this->writeCache)) { | |
| 265 | + $result = $this->crypt->symmetricEncryptFileContent($this->writeCache, $this->fileKey, $this->version + 1, $position); | |
| 266 | + $this->writeCache = ''; | |
| 267 | + } | |
| 268 | + $publicKeys = array(); | |
| 269 | +            if ($this->useMasterPassword === true) { | |
| 270 | + $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey(); | |
| 271 | +            } else { | |
| 272 | +                foreach ($this->accessList['users'] as $uid) { | |
| 273 | +                    try { | |
| 274 | + $publicKeys[$uid] = $this->keyManager->getPublicKey($uid); | |
| 275 | +                    } catch (PublicKeyMissingException $e) { | |
| 276 | + $this->logger->warning( | |
| 277 | +                            'no public key found for user "{uid}", user will not be able to read the file', | |
| 278 | + ['app' => 'encryption', 'uid' => $uid] | |
| 279 | + ); | |
| 280 | + // if the public key of the owner is missing we should fail | |
| 281 | +                        if ($uid === $this->user) { | |
| 282 | + throw $e; | |
| 283 | + } | |
| 284 | + } | |
| 285 | + } | |
| 286 | + } | |
| 287 | + | |
| 288 | + $publicKeys = $this->keyManager->addSystemKeys($this->accessList, $publicKeys, $this->getOwner($path)); | |
| 289 | + $encryptedKeyfiles = $this->crypt->multiKeyEncrypt($this->fileKey, $publicKeys); | |
| 290 | + $this->keyManager->setAllFileKeys($this->path, $encryptedKeyfiles); | |
| 291 | + } | |
| 292 | + return $result; | |
| 293 | + } | |
| 294 | + | |
| 295 | + | |
| 296 | + | |
| 297 | + /** | |
| 298 | + * encrypt data | |
| 299 | + * | |
| 300 | + * @param string $data you want to encrypt | |
| 301 | + * @param int $position | |
| 302 | + * @return string encrypted data | |
| 303 | + */ | |
| 304 | +    public function encrypt($data, $position = 0) { | |
| 305 | + // If extra data is left over from the last round, make sure it | |
| 306 | + // is integrated into the next block | |
| 307 | +        if ($this->writeCache) { | |
| 308 | + | |
| 309 | + // Concat writeCache to start of $data | |
| 310 | + $data = $this->writeCache . $data; | |
| 311 | + | |
| 312 | + // Clear the write cache, ready for reuse - it has been | |
| 313 | + // flushed and its old contents processed | |
| 314 | + $this->writeCache = ''; | |
| 315 | + | |
| 316 | + } | |
| 317 | + | |
| 318 | + $encrypted = ''; | |
| 319 | + // While there still remains some data to be processed & written | |
| 320 | +        while (strlen($data) > 0) { | |
| 321 | + | |
| 322 | + // Remaining length for this iteration, not of the | |
| 323 | + // entire file (may be greater than 8192 bytes) | |
| 324 | + $remainingLength = strlen($data); | |
| 325 | + | |
| 326 | + // If data remaining to be written is less than the | |
| 327 | + // size of 1 6126 byte block | |
| 328 | +            if ($remainingLength < $this->unencryptedBlockSizeSigned) { | |
| 329 | + | |
| 330 | + // Set writeCache to contents of $data | |
| 331 | + // The writeCache will be carried over to the | |
| 332 | + // next write round, and added to the start of | |
| 333 | + // $data to ensure that written blocks are | |
| 334 | + // always the correct length. If there is still | |
| 335 | + // data in writeCache after the writing round | |
| 336 | + // has finished, then the data will be written | |
| 337 | + // to disk by $this->flush(). | |
| 338 | + $this->writeCache = $data; | |
| 339 | + | |
| 340 | + // Clear $data ready for next round | |
| 341 | + $data = ''; | |
| 342 | + | |
| 343 | +            } else { | |
| 344 | + | |
| 345 | + // Read the chunk from the start of $data | |
| 346 | + $chunk = substr($data, 0, $this->unencryptedBlockSizeSigned); | |
| 347 | + | |
| 348 | + $encrypted .= $this->crypt->symmetricEncryptFileContent($chunk, $this->fileKey, $this->version + 1, $position); | |
| 349 | + | |
| 350 | + // Remove the chunk we just processed from | |
| 351 | + // $data, leaving only unprocessed data in $data | |
| 352 | + // var, for handling on the next round | |
| 353 | + $data = substr($data, $this->unencryptedBlockSizeSigned); | |
| 354 | + | |
| 355 | + } | |
| 356 | + | |
| 357 | + } | |
| 358 | + | |
| 359 | + return $encrypted; | |
| 360 | + } | |
| 361 | + | |
| 362 | + /** | |
| 363 | + * decrypt data | |
| 364 | + * | |
| 365 | + * @param string $data you want to decrypt | |
| 366 | + * @param int $position | |
| 367 | + * @return string decrypted data | |
| 368 | + * @throws DecryptionFailedException | |
| 369 | + */ | |
| 370 | +    public function decrypt($data, $position = 0) { | |
| 371 | +        if (empty($this->fileKey)) { | |
| 372 | + $msg = 'Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.'; | |
| 373 | +            $hint = $this->l->t('Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.'); | |
| 374 | + $this->logger->error($msg); | |
| 375 | + | |
| 376 | + throw new DecryptionFailedException($msg, $hint); | |
| 377 | + } | |
| 378 | + | |
| 379 | + return $this->crypt->symmetricDecryptFileContent($data, $this->fileKey, $this->cipher, $this->version, $position); | |
| 380 | + } | |
| 381 | + | |
| 382 | + /** | |
| 383 | + * update encrypted file, e.g. give additional users access to the file | |
| 384 | + * | |
| 385 | + * @param string $path path to the file which should be updated | |
| 386 | + * @param string $uid of the user who performs the operation | |
| 387 | + * @param array $accessList who has access to the file contains the key 'users' and 'public' | |
| 388 | + * @return boolean | |
| 389 | + */ | |
| 390 | +    public function update($path, $uid, array $accessList) { | |
| 391 | + | |
| 392 | +        if (empty($accessList)) { | |
| 393 | +            if (isset(self::$rememberVersion[$path])) { | |
| 394 | + $this->keyManager->setVersion($path, self::$rememberVersion[$path], new View()); | |
| 395 | + unset(self::$rememberVersion[$path]); | |
| 396 | + } | |
| 397 | + return; | |
| 398 | + } | |
| 399 | + | |
| 400 | + $fileKey = $this->keyManager->getFileKey($path, $uid); | |
| 401 | + | |
| 402 | +        if (!empty($fileKey)) { | |
| 403 | + | |
| 404 | + $publicKeys = array(); | |
| 405 | +            if ($this->useMasterPassword === true) { | |
| 406 | + $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey(); | |
| 407 | +            } else { | |
| 408 | +                foreach ($accessList['users'] as $user) { | |
| 409 | +                    try { | |
| 410 | + $publicKeys[$user] = $this->keyManager->getPublicKey($user); | |
| 411 | +                    } catch (PublicKeyMissingException $e) { | |
| 412 | +                        $this->logger->warning('Could not encrypt file for ' . $user . ': ' . $e->getMessage()); | |
| 413 | + } | |
| 414 | + } | |
| 415 | + } | |
| 416 | + | |
| 417 | + $publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $this->getOwner($path)); | |
| 418 | + | |
| 419 | + $encryptedFileKey = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys); | |
| 420 | + | |
| 421 | + $this->keyManager->deleteAllFileKeys($path); | |
| 422 | + | |
| 423 | + $this->keyManager->setAllFileKeys($path, $encryptedFileKey); | |
| 424 | + | |
| 425 | +        } else { | |
| 426 | +            $this->logger->debug('no file key found, we assume that the file "{file}" is not encrypted', | |
| 427 | +                array('file' => $path, 'app' => 'encryption')); | |
| 428 | + | |
| 429 | + return false; | |
| 430 | + } | |
| 431 | + | |
| 432 | + return true; | |
| 433 | + } | |
| 434 | + | |
| 435 | + /** | |
| 436 | + * should the file be encrypted or not | |
| 437 | + * | |
| 438 | + * @param string $path | |
| 439 | + * @return boolean | |
| 440 | + */ | |
| 441 | +    public function shouldEncrypt($path) { | |
| 442 | +        if ($this->util->shouldEncryptHomeStorage() === false) { | |
| 443 | + $storage = $this->util->getStorage($path); | |
| 444 | +            if ($storage->instanceOfStorage('\OCP\Files\IHomeStorage')) { | |
| 445 | + return false; | |
| 446 | + } | |
| 447 | + } | |
| 448 | +        $parts = explode('/', $path); | |
| 449 | +        if (count($parts) < 4) { | |
| 450 | + return false; | |
| 451 | + } | |
| 452 | + | |
| 453 | +        if ($parts[2] === 'files') { | |
| 454 | + return true; | |
| 455 | + } | |
| 456 | +        if ($parts[2] === 'files_versions') { | |
| 457 | + return true; | |
| 458 | + } | |
| 459 | +        if ($parts[2] === 'files_trashbin') { | |
| 460 | + return true; | |
| 461 | + } | |
| 462 | + | |
| 463 | + return false; | |
| 464 | + } | |
| 465 | + | |
| 466 | + /** | |
| 467 | + * get size of the unencrypted payload per block. | |
| 468 | + * Nextcloud read/write files with a block size of 8192 byte | |
| 469 | + * | |
| 470 | + * @param bool $signed | |
| 471 | + * @return int | |
| 472 | + */ | |
| 473 | +    public function getUnencryptedBlockSize($signed = false) { | |
| 474 | +        if ($signed === false) { | |
| 475 | + return $this->unencryptedBlockSize; | |
| 476 | + } | |
| 477 | + | |
| 478 | + return $this->unencryptedBlockSizeSigned; | |
| 479 | + } | |
| 480 | + | |
| 481 | + /** | |
| 482 | + * check if the encryption module is able to read the file, | |
| 483 | + * e.g. if all encryption keys exists | |
| 484 | + * | |
| 485 | + * @param string $path | |
| 486 | + * @param string $uid user for whom we want to check if he can read the file | |
| 487 | + * @return bool | |
| 488 | + * @throws DecryptionFailedException | |
| 489 | + */ | |
| 490 | +    public function isReadable($path, $uid) { | |
| 491 | + $fileKey = $this->keyManager->getFileKey($path, $uid); | |
| 492 | +        if (empty($fileKey)) { | |
| 493 | + $owner = $this->util->getOwner($path); | |
| 494 | +            if ($owner !== $uid) { | |
| 495 | + // if it is a shared file we throw a exception with a useful | |
| 496 | + // error message because in this case it means that the file was | |
| 497 | + // shared with the user at a point where the user didn't had a | |
| 498 | + // valid private/public key | |
| 499 | + $msg = 'Encryption module "' . $this->getDisplayName() . | |
| 500 | + '" is not able to read ' . $path; | |
| 501 | +                $hint = $this->l->t('Can not read this file, probably this is a shared file. Please ask the file owner to reshare the file with you.'); | |
| 502 | + $this->logger->warning($msg); | |
| 503 | + throw new DecryptionFailedException($msg, $hint); | |
| 504 | + } | |
| 505 | + return false; | |
| 506 | + } | |
| 507 | + | |
| 508 | + return true; | |
| 509 | + } | |
| 510 | + | |
| 511 | + /** | |
| 512 | + * Initial encryption of all files | |
| 513 | + * | |
| 514 | + * @param InputInterface $input | |
| 515 | + * @param OutputInterface $output write some status information to the terminal during encryption | |
| 516 | + */ | |
| 517 | +    public function encryptAll(InputInterface $input, OutputInterface $output) { | |
| 518 | + $this->encryptAll->encryptAll($input, $output); | |
| 519 | + } | |
| 520 | + | |
| 521 | + /** | |
| 522 | + * prepare module to perform decrypt all operation | |
| 523 | + * | |
| 524 | + * @param InputInterface $input | |
| 525 | + * @param OutputInterface $output | |
| 526 | + * @param string $user | |
| 527 | + * @return bool | |
| 528 | + */ | |
| 529 | +    public function prepareDecryptAll(InputInterface $input, OutputInterface $output, $user = '') { | |
| 530 | + return $this->decryptAll->prepare($input, $output, $user); | |
| 531 | + } | |
| 532 | + | |
| 533 | + | |
| 534 | + /** | |
| 535 | + * @param string $path | |
| 536 | + * @return string | |
| 537 | + */ | |
| 538 | +    protected function getPathToRealFile($path) { | |
| 539 | + $realPath = $path; | |
| 540 | +        $parts = explode('/', $path); | |
| 541 | +        if ($parts[2] === 'files_versions') { | |
| 542 | +            $realPath = '/' . $parts[1] . '/files/' . implode('/', array_slice($parts, 3)); | |
| 543 | + $length = strrpos($realPath, '.'); | |
| 544 | + $realPath = substr($realPath, 0, $length); | |
| 545 | + } | |
| 546 | + | |
| 547 | + return $realPath; | |
| 548 | + } | |
| 549 | + | |
| 550 | + /** | |
| 551 | + * remove .part file extension and the ocTransferId from the file to get the | |
| 552 | + * original file name | |
| 553 | + * | |
| 554 | + * @param string $path | |
| 555 | + * @return string | |
| 556 | + */ | |
| 557 | +    protected function stripPartFileExtension($path) { | |
| 558 | +        if (pathinfo($path, PATHINFO_EXTENSION) === 'part') { | |
| 559 | + $pos = strrpos($path, '.', -6); | |
| 560 | + $path = substr($path, 0, $pos); | |
| 561 | + } | |
| 562 | + | |
| 563 | + return $path; | |
| 564 | + } | |
| 565 | + | |
| 566 | + /** | |
| 567 | + * get owner of a file | |
| 568 | + * | |
| 569 | + * @param string $path | |
| 570 | + * @return string | |
| 571 | + */ | |
| 572 | +    protected function getOwner($path) { | |
| 573 | +        if (!isset($this->owner[$path])) { | |
| 574 | + $this->owner[$path] = $this->util->getOwner($path); | |
| 575 | + } | |
| 576 | + return $this->owner[$path]; | |
| 577 | + } | |
| 578 | + | |
| 579 | + /** | |
| 580 | + * Check if the module is ready to be used by that specific user. | |
| 581 | + * In case a module is not ready - because e.g. key pairs have not been generated | |
| 582 | + * upon login this method can return false before any operation starts and might | |
| 583 | + * cause issues during operations. | |
| 584 | + * | |
| 585 | + * @param string $user | |
| 586 | + * @return boolean | |
| 587 | + * @since 9.1.0 | |
| 588 | + */ | |
| 589 | +    public function isReadyForUser($user) { | |
| 590 | + return $this->keyManager->userHasKeys($user); | |
| 591 | + } | |
| 592 | + | |
| 593 | + /** | |
| 594 | + * We only need a detailed access list if the master key is not enabled | |
| 595 | + * | |
| 596 | + * @return bool | |
| 597 | + */ | |
| 598 | +    public function needDetailedAccessList() { | |
| 599 | + return !$this->util->isMasterKeyEnabled(); | |
| 600 | + } | |
| 601 | 601 | } | 
| @@ -488,7 +488,7 @@ | ||
| 488 | 488 | |
| 489 | 489 | |
| 490 | 490 | /** | 
| 491 | - * @param $path | |
| 491 | + * @param string $path | |
| 492 | 492 | * @param $uid | 
| 493 | 493 | * @return mixed | 
| 494 | 494 | */ | 
| @@ -38,685 +38,685 @@ | ||
| 38 | 38 | |
| 39 | 39 |  class KeyManager { | 
| 40 | 40 | |
| 41 | - /** | |
| 42 | - * @var Session | |
| 43 | - */ | |
| 44 | - protected $session; | |
| 45 | - /** | |
| 46 | - * @var IStorage | |
| 47 | - */ | |
| 48 | - private $keyStorage; | |
| 49 | - /** | |
| 50 | - * @var Crypt | |
| 51 | - */ | |
| 52 | - private $crypt; | |
| 53 | - /** | |
| 54 | - * @var string | |
| 55 | - */ | |
| 56 | - private $recoveryKeyId; | |
| 57 | - /** | |
| 58 | - * @var string | |
| 59 | - */ | |
| 60 | - private $publicShareKeyId; | |
| 61 | - /** | |
| 62 | - * @var string | |
| 63 | - */ | |
| 64 | - private $masterKeyId; | |
| 65 | - /** | |
| 66 | - * @var string UserID | |
| 67 | - */ | |
| 68 | - private $keyId; | |
| 69 | - /** | |
| 70 | - * @var string | |
| 71 | - */ | |
| 72 | - private $publicKeyId = 'publicKey'; | |
| 73 | - /** | |
| 74 | - * @var string | |
| 75 | - */ | |
| 76 | - private $privateKeyId = 'privateKey'; | |
| 77 | - | |
| 78 | - /** | |
| 79 | - * @var string | |
| 80 | - */ | |
| 81 | - private $shareKeyId = 'shareKey'; | |
| 82 | - | |
| 83 | - /** | |
| 84 | - * @var string | |
| 85 | - */ | |
| 86 | - private $fileKeyId = 'fileKey'; | |
| 87 | - /** | |
| 88 | - * @var IConfig | |
| 89 | - */ | |
| 90 | - private $config; | |
| 91 | - /** | |
| 92 | - * @var ILogger | |
| 93 | - */ | |
| 94 | - private $log; | |
| 95 | - /** | |
| 96 | - * @var Util | |
| 97 | - */ | |
| 98 | - private $util; | |
| 99 | - | |
| 100 | - /** | |
| 101 | - * @param IStorage $keyStorage | |
| 102 | - * @param Crypt $crypt | |
| 103 | - * @param IConfig $config | |
| 104 | - * @param IUserSession $userSession | |
| 105 | - * @param Session $session | |
| 106 | - * @param ILogger $log | |
| 107 | - * @param Util $util | |
| 108 | - */ | |
| 109 | - public function __construct( | |
| 110 | - IStorage $keyStorage, | |
| 111 | - Crypt $crypt, | |
| 112 | - IConfig $config, | |
| 113 | - IUserSession $userSession, | |
| 114 | - Session $session, | |
| 115 | - ILogger $log, | |
| 116 | - Util $util | |
| 117 | -	) { | |
| 118 | - | |
| 119 | - $this->util = $util; | |
| 120 | - $this->session = $session; | |
| 121 | - $this->keyStorage = $keyStorage; | |
| 122 | - $this->crypt = $crypt; | |
| 123 | - $this->config = $config; | |
| 124 | - $this->log = $log; | |
| 125 | - | |
| 126 | -		$this->recoveryKeyId = $this->config->getAppValue('encryption', | |
| 127 | - 'recoveryKeyId'); | |
| 128 | -		if (empty($this->recoveryKeyId)) { | |
| 129 | - $this->recoveryKeyId = 'recoveryKey_' . substr(md5(time()), 0, 8); | |
| 130 | -			$this->config->setAppValue('encryption', | |
| 131 | - 'recoveryKeyId', | |
| 132 | - $this->recoveryKeyId); | |
| 133 | - } | |
| 134 | - | |
| 135 | -		$this->publicShareKeyId = $this->config->getAppValue('encryption', | |
| 136 | - 'publicShareKeyId'); | |
| 137 | -		if (empty($this->publicShareKeyId)) { | |
| 138 | - $this->publicShareKeyId = 'pubShare_' . substr(md5(time()), 0, 8); | |
| 139 | -			$this->config->setAppValue('encryption', 'publicShareKeyId', $this->publicShareKeyId); | |
| 140 | - } | |
| 141 | - | |
| 142 | -		$this->masterKeyId = $this->config->getAppValue('encryption', | |
| 143 | - 'masterKeyId'); | |
| 144 | -		if (empty($this->masterKeyId)) { | |
| 145 | - $this->masterKeyId = 'master_' . substr(md5(time()), 0, 8); | |
| 146 | -			$this->config->setAppValue('encryption', 'masterKeyId', $this->masterKeyId); | |
| 147 | - } | |
| 148 | - | |
| 149 | - $this->keyId = $userSession && $userSession->isLoggedIn() ? $userSession->getUser()->getUID() : false; | |
| 150 | - $this->log = $log; | |
| 151 | - } | |
| 152 | - | |
| 153 | - /** | |
| 154 | - * check if key pair for public link shares exists, if not we create one | |
| 155 | - */ | |
| 156 | -	public function validateShareKey() { | |
| 157 | - $shareKey = $this->getPublicShareKey(); | |
| 158 | -		if (empty($shareKey)) { | |
| 159 | - $keyPair = $this->crypt->createKeyPair(); | |
| 160 | - | |
| 161 | - // Save public key | |
| 162 | - $this->keyStorage->setSystemUserKey( | |
| 163 | - $this->publicShareKeyId . '.publicKey', $keyPair['publicKey'], | |
| 164 | - Encryption::ID); | |
| 165 | - | |
| 166 | - // Encrypt private key empty passphrase | |
| 167 | - $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], ''); | |
| 168 | - $header = $this->crypt->generateHeader(); | |
| 169 | - $this->setSystemPrivateKey($this->publicShareKeyId, $header . $encryptedKey); | |
| 170 | - } | |
| 171 | - } | |
| 172 | - | |
| 173 | - /** | |
| 174 | - * check if a key pair for the master key exists, if not we create one | |
| 175 | - */ | |
| 176 | -	public function validateMasterKey() { | |
| 177 | - | |
| 178 | -		if ($this->util->isMasterKeyEnabled() === false) { | |
| 179 | - return; | |
| 180 | - } | |
| 181 | - | |
| 182 | - $publicMasterKey = $this->getPublicMasterKey(); | |
| 183 | -		if (empty($publicMasterKey)) { | |
| 184 | - $keyPair = $this->crypt->createKeyPair(); | |
| 185 | - | |
| 186 | - // Save public key | |
| 187 | - $this->keyStorage->setSystemUserKey( | |
| 188 | - $this->masterKeyId . '.publicKey', $keyPair['publicKey'], | |
| 189 | - Encryption::ID); | |
| 190 | - | |
| 191 | - // Encrypt private key with system password | |
| 192 | - $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $this->getMasterKeyPassword(), $this->masterKeyId); | |
| 193 | - $header = $this->crypt->generateHeader(); | |
| 194 | - $this->setSystemPrivateKey($this->masterKeyId, $header . $encryptedKey); | |
| 195 | - } | |
| 196 | - | |
| 197 | -		if (!$this->session->isPrivateKeySet()) { | |
| 198 | - $masterKey = $this->getSystemPrivateKey($this->masterKeyId); | |
| 199 | - $decryptedMasterKey = $this->crypt->decryptPrivateKey($masterKey, $this->getMasterKeyPassword(), $this->masterKeyId); | |
| 200 | - $this->session->setPrivateKey($decryptedMasterKey); | |
| 201 | - } | |
| 202 | - | |
| 203 | - // after the encryption key is available we are ready to go | |
| 204 | - $this->session->setStatus(Session::INIT_SUCCESSFUL); | |
| 205 | - } | |
| 206 | - | |
| 207 | - /** | |
| 208 | - * @return bool | |
| 209 | - */ | |
| 210 | -	public function recoveryKeyExists() { | |
| 211 | - $key = $this->getRecoveryKey(); | |
| 212 | - return (!empty($key)); | |
| 213 | - } | |
| 214 | - | |
| 215 | - /** | |
| 216 | - * get recovery key | |
| 217 | - * | |
| 218 | - * @return string | |
| 219 | - */ | |
| 220 | -	public function getRecoveryKey() { | |
| 221 | - return $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.publicKey', Encryption::ID); | |
| 222 | - } | |
| 223 | - | |
| 224 | - /** | |
| 225 | - * get recovery key ID | |
| 226 | - * | |
| 227 | - * @return string | |
| 228 | - */ | |
| 229 | -	public function getRecoveryKeyId() { | |
| 230 | - return $this->recoveryKeyId; | |
| 231 | - } | |
| 232 | - | |
| 233 | - /** | |
| 234 | - * @param string $password | |
| 235 | - * @return bool | |
| 236 | - */ | |
| 237 | -	public function checkRecoveryPassword($password) { | |
| 238 | - $recoveryKey = $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.privateKey', Encryption::ID); | |
| 239 | - $decryptedRecoveryKey = $this->crypt->decryptPrivateKey($recoveryKey, $password); | |
| 240 | - | |
| 241 | -		if ($decryptedRecoveryKey) { | |
| 242 | - return true; | |
| 243 | - } | |
| 244 | - return false; | |
| 245 | - } | |
| 246 | - | |
| 247 | - /** | |
| 248 | - * @param string $uid | |
| 249 | - * @param string $password | |
| 250 | - * @param string $keyPair | |
| 251 | - * @return bool | |
| 252 | - */ | |
| 253 | -	public function storeKeyPair($uid, $password, $keyPair) { | |
| 254 | - // Save Public Key | |
| 255 | - $this->setPublicKey($uid, $keyPair['publicKey']); | |
| 256 | - | |
| 257 | - $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $password, $uid); | |
| 258 | - | |
| 259 | - $header = $this->crypt->generateHeader(); | |
| 260 | - | |
| 261 | -		if ($encryptedKey) { | |
| 262 | - $this->setPrivateKey($uid, $header . $encryptedKey); | |
| 263 | - return true; | |
| 264 | - } | |
| 265 | - return false; | |
| 266 | - } | |
| 267 | - | |
| 268 | - /** | |
| 269 | - * @param string $password | |
| 270 | - * @param array $keyPair | |
| 271 | - * @return bool | |
| 272 | - */ | |
| 273 | -	public function setRecoveryKey($password, $keyPair) { | |
| 274 | - // Save Public Key | |
| 275 | - $this->keyStorage->setSystemUserKey($this->getRecoveryKeyId(). | |
| 276 | - '.publicKey', | |
| 277 | - $keyPair['publicKey'], | |
| 278 | - Encryption::ID); | |
| 279 | - | |
| 280 | - $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $password); | |
| 281 | - $header = $this->crypt->generateHeader(); | |
| 282 | - | |
| 283 | -		if ($encryptedKey) { | |
| 284 | - $this->setSystemPrivateKey($this->getRecoveryKeyId(), $header . $encryptedKey); | |
| 285 | - return true; | |
| 286 | - } | |
| 287 | - return false; | |
| 288 | - } | |
| 289 | - | |
| 290 | - /** | |
| 291 | - * @param $userId | |
| 292 | - * @param $key | |
| 293 | - * @return bool | |
| 294 | - */ | |
| 295 | -	public function setPublicKey($userId, $key) { | |
| 296 | - return $this->keyStorage->setUserKey($userId, $this->publicKeyId, $key, Encryption::ID); | |
| 297 | - } | |
| 298 | - | |
| 299 | - /** | |
| 300 | - * @param $userId | |
| 301 | - * @param string $key | |
| 302 | - * @return bool | |
| 303 | - */ | |
| 304 | -	public function setPrivateKey($userId, $key) { | |
| 305 | - return $this->keyStorage->setUserKey($userId, | |
| 306 | - $this->privateKeyId, | |
| 307 | - $key, | |
| 308 | - Encryption::ID); | |
| 309 | - } | |
| 310 | - | |
| 311 | - /** | |
| 312 | - * write file key to key storage | |
| 313 | - * | |
| 314 | - * @param string $path | |
| 315 | - * @param string $key | |
| 316 | - * @return boolean | |
| 317 | - */ | |
| 318 | -	public function setFileKey($path, $key) { | |
| 319 | - return $this->keyStorage->setFileKey($path, $this->fileKeyId, $key, Encryption::ID); | |
| 320 | - } | |
| 321 | - | |
| 322 | - /** | |
| 323 | - * set all file keys (the file key and the corresponding share keys) | |
| 324 | - * | |
| 325 | - * @param string $path | |
| 326 | - * @param array $keys | |
| 327 | - */ | |
| 328 | -	public function setAllFileKeys($path, $keys) { | |
| 329 | - $this->setFileKey($path, $keys['data']); | |
| 330 | -		foreach ($keys['keys'] as $uid => $keyFile) { | |
| 331 | - $this->setShareKey($path, $uid, $keyFile); | |
| 332 | - } | |
| 333 | - } | |
| 334 | - | |
| 335 | - /** | |
| 336 | - * write share key to the key storage | |
| 337 | - * | |
| 338 | - * @param string $path | |
| 339 | - * @param string $uid | |
| 340 | - * @param string $key | |
| 341 | - * @return boolean | |
| 342 | - */ | |
| 343 | -	public function setShareKey($path, $uid, $key) { | |
| 344 | - $keyId = $uid . '.' . $this->shareKeyId; | |
| 345 | - return $this->keyStorage->setFileKey($path, $keyId, $key, Encryption::ID); | |
| 346 | - } | |
| 347 | - | |
| 348 | - /** | |
| 349 | - * Decrypt private key and store it | |
| 350 | - * | |
| 351 | - * @param string $uid user id | |
| 352 | - * @param string $passPhrase users password | |
| 353 | - * @return boolean | |
| 354 | - */ | |
| 355 | -	public function init($uid, $passPhrase) { | |
| 356 | - | |
| 357 | - $this->session->setStatus(Session::INIT_EXECUTED); | |
| 358 | - | |
| 359 | -		try { | |
| 360 | -			if($this->util->isMasterKeyEnabled()) { | |
| 361 | - $uid = $this->getMasterKeyId(); | |
| 362 | - $passPhrase = $this->getMasterKeyPassword(); | |
| 363 | - $privateKey = $this->getSystemPrivateKey($uid); | |
| 364 | -			} else { | |
| 365 | - $privateKey = $this->getPrivateKey($uid); | |
| 366 | - } | |
| 367 | - $privateKey = $this->crypt->decryptPrivateKey($privateKey, $passPhrase, $uid); | |
| 368 | -		} catch (PrivateKeyMissingException $e) { | |
| 369 | - return false; | |
| 370 | -		} catch (DecryptionFailedException $e) { | |
| 371 | - return false; | |
| 372 | -		} catch (\Exception $e) { | |
| 373 | - $this->log->warning( | |
| 374 | - 'Could not decrypt the private key from user "' . $uid . '"" during login. ' . | |
| 375 | - 'Assume password change on the user back-end. Error message: ' | |
| 376 | - . $e->getMessage() | |
| 377 | - ); | |
| 378 | - return false; | |
| 379 | - } | |
| 380 | - | |
| 381 | -		if ($privateKey) { | |
| 382 | - $this->session->setPrivateKey($privateKey); | |
| 383 | - $this->session->setStatus(Session::INIT_SUCCESSFUL); | |
| 384 | - return true; | |
| 385 | - } | |
| 386 | - | |
| 387 | - return false; | |
| 388 | - } | |
| 389 | - | |
| 390 | - /** | |
| 391 | - * @param $userId | |
| 392 | - * @return string | |
| 393 | - * @throws PrivateKeyMissingException | |
| 394 | - */ | |
| 395 | -	public function getPrivateKey($userId) { | |
| 396 | - $privateKey = $this->keyStorage->getUserKey($userId, | |
| 397 | - $this->privateKeyId, Encryption::ID); | |
| 398 | - | |
| 399 | -		if (strlen($privateKey) !== 0) { | |
| 400 | - return $privateKey; | |
| 401 | - } | |
| 402 | - throw new PrivateKeyMissingException($userId); | |
| 403 | - } | |
| 404 | - | |
| 405 | - /** | |
| 406 | - * @param string $path | |
| 407 | - * @param $uid | |
| 408 | - * @return string | |
| 409 | - */ | |
| 410 | -	public function getFileKey($path, $uid) { | |
| 411 | -		if ($uid === '') { | |
| 412 | - $uid = null; | |
| 413 | - } | |
| 414 | - $publicAccess = is_null($uid); | |
| 415 | - $encryptedFileKey = $this->keyStorage->getFileKey($path, $this->fileKeyId, Encryption::ID); | |
| 416 | - | |
| 417 | -		if (empty($encryptedFileKey)) { | |
| 418 | - return ''; | |
| 419 | - } | |
| 420 | - | |
| 421 | -		if ($this->util->isMasterKeyEnabled()) { | |
| 422 | - $uid = $this->getMasterKeyId(); | |
| 423 | - $shareKey = $this->getShareKey($path, $uid); | |
| 424 | -			if ($publicAccess) { | |
| 425 | - $privateKey = $this->getSystemPrivateKey($uid); | |
| 426 | - $privateKey = $this->crypt->decryptPrivateKey($privateKey, $this->getMasterKeyPassword(), $uid); | |
| 427 | -			} else { | |
| 428 | - // when logged in, the master key is already decrypted in the session | |
| 429 | - $privateKey = $this->session->getPrivateKey(); | |
| 430 | - } | |
| 431 | -		} else if ($publicAccess) { | |
| 432 | - // use public share key for public links | |
| 433 | - $uid = $this->getPublicShareKeyId(); | |
| 434 | - $shareKey = $this->getShareKey($path, $uid); | |
| 435 | - $privateKey = $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.privateKey', Encryption::ID); | |
| 436 | - $privateKey = $this->crypt->decryptPrivateKey($privateKey); | |
| 437 | -		} else { | |
| 438 | - $shareKey = $this->getShareKey($path, $uid); | |
| 439 | - $privateKey = $this->session->getPrivateKey(); | |
| 440 | - } | |
| 441 | - | |
| 442 | -		if ($encryptedFileKey && $shareKey && $privateKey) { | |
| 443 | - return $this->crypt->multiKeyDecrypt($encryptedFileKey, | |
| 444 | - $shareKey, | |
| 445 | - $privateKey); | |
| 446 | - } | |
| 447 | - | |
| 448 | - return ''; | |
| 449 | - } | |
| 450 | - | |
| 451 | - /** | |
| 452 | - * Get the current version of a file | |
| 453 | - * | |
| 454 | - * @param string $path | |
| 455 | - * @param View $view | |
| 456 | - * @return int | |
| 457 | - */ | |
| 458 | -	public function getVersion($path, View $view) { | |
| 459 | - $fileInfo = $view->getFileInfo($path); | |
| 460 | -		if($fileInfo === false) { | |
| 461 | - return 0; | |
| 462 | - } | |
| 463 | - return $fileInfo->getEncryptedVersion(); | |
| 464 | - } | |
| 465 | - | |
| 466 | - /** | |
| 467 | - * Set the current version of a file | |
| 468 | - * | |
| 469 | - * @param string $path | |
| 470 | - * @param int $version | |
| 471 | - * @param View $view | |
| 472 | - */ | |
| 473 | -	public function setVersion($path, $version, View $view) { | |
| 474 | - $fileInfo= $view->getFileInfo($path); | |
| 475 | - | |
| 476 | -		if($fileInfo !== false) { | |
| 477 | - $cache = $fileInfo->getStorage()->getCache(); | |
| 478 | - $cache->update($fileInfo->getId(), ['encrypted' => $version, 'encryptedVersion' => $version]); | |
| 479 | - } | |
| 480 | - } | |
| 481 | - | |
| 482 | - /** | |
| 483 | - * get the encrypted file key | |
| 484 | - * | |
| 485 | - * @param string $path | |
| 486 | - * @return string | |
| 487 | - */ | |
| 488 | -	public function getEncryptedFileKey($path) { | |
| 489 | - $encryptedFileKey = $this->keyStorage->getFileKey($path, | |
| 490 | - $this->fileKeyId, Encryption::ID); | |
| 491 | - | |
| 492 | - return $encryptedFileKey; | |
| 493 | - } | |
| 494 | - | |
| 495 | - /** | |
| 496 | - * delete share key | |
| 497 | - * | |
| 498 | - * @param string $path | |
| 499 | - * @param string $keyId | |
| 500 | - * @return boolean | |
| 501 | - */ | |
| 502 | -	public function deleteShareKey($path, $keyId) { | |
| 503 | - return $this->keyStorage->deleteFileKey( | |
| 504 | - $path, | |
| 505 | - $keyId . '.' . $this->shareKeyId, | |
| 506 | - Encryption::ID); | |
| 507 | - } | |
| 508 | - | |
| 509 | - | |
| 510 | - /** | |
| 511 | - * @param $path | |
| 512 | - * @param $uid | |
| 513 | - * @return mixed | |
| 514 | - */ | |
| 515 | -	public function getShareKey($path, $uid) { | |
| 516 | - $keyId = $uid . '.' . $this->shareKeyId; | |
| 517 | - return $this->keyStorage->getFileKey($path, $keyId, Encryption::ID); | |
| 518 | - } | |
| 519 | - | |
| 520 | - /** | |
| 521 | - * check if user has a private and a public key | |
| 522 | - * | |
| 523 | - * @param string $userId | |
| 524 | - * @return bool | |
| 525 | - * @throws PrivateKeyMissingException | |
| 526 | - * @throws PublicKeyMissingException | |
| 527 | - */ | |
| 528 | -	public function userHasKeys($userId) { | |
| 529 | - $privateKey = $publicKey = true; | |
| 530 | - $exception = null; | |
| 531 | - | |
| 532 | -		try { | |
| 533 | - $this->getPrivateKey($userId); | |
| 534 | -		} catch (PrivateKeyMissingException $e) { | |
| 535 | - $privateKey = false; | |
| 536 | - $exception = $e; | |
| 537 | - } | |
| 538 | -		try { | |
| 539 | - $this->getPublicKey($userId); | |
| 540 | -		} catch (PublicKeyMissingException $e) { | |
| 541 | - $publicKey = false; | |
| 542 | - $exception = $e; | |
| 543 | - } | |
| 544 | - | |
| 545 | -		if ($privateKey && $publicKey) { | |
| 546 | - return true; | |
| 547 | -		} elseif (!$privateKey && !$publicKey) { | |
| 548 | - return false; | |
| 549 | -		} else { | |
| 550 | - throw $exception; | |
| 551 | - } | |
| 552 | - } | |
| 553 | - | |
| 554 | - /** | |
| 555 | - * @param $userId | |
| 556 | - * @return mixed | |
| 557 | - * @throws PublicKeyMissingException | |
| 558 | - */ | |
| 559 | -	public function getPublicKey($userId) { | |
| 560 | - $publicKey = $this->keyStorage->getUserKey($userId, $this->publicKeyId, Encryption::ID); | |
| 561 | - | |
| 562 | -		if (strlen($publicKey) !== 0) { | |
| 563 | - return $publicKey; | |
| 564 | - } | |
| 565 | - throw new PublicKeyMissingException($userId); | |
| 566 | - } | |
| 567 | - | |
| 568 | -	public function getPublicShareKeyId() { | |
| 569 | - return $this->publicShareKeyId; | |
| 570 | - } | |
| 571 | - | |
| 572 | - /** | |
| 573 | - * get public key for public link shares | |
| 574 | - * | |
| 575 | - * @return string | |
| 576 | - */ | |
| 577 | -	public function getPublicShareKey() { | |
| 578 | - return $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.publicKey', Encryption::ID); | |
| 579 | - } | |
| 580 | - | |
| 581 | - /** | |
| 582 | - * @param string $purpose | |
| 583 | - * @param string $uid | |
| 584 | - */ | |
| 585 | -	public function backupUserKeys($purpose, $uid) { | |
| 586 | - $this->keyStorage->backupUserKeys(Encryption::ID, $purpose, $uid); | |
| 587 | - } | |
| 588 | - | |
| 589 | - /** | |
| 590 | - * creat a backup of the users private and public key and then delete it | |
| 591 | - * | |
| 592 | - * @param string $uid | |
| 593 | - */ | |
| 594 | -	public function deleteUserKeys($uid) { | |
| 595 | - $this->deletePublicKey($uid); | |
| 596 | - $this->deletePrivateKey($uid); | |
| 597 | - } | |
| 598 | - | |
| 599 | - /** | |
| 600 | - * @param $uid | |
| 601 | - * @return bool | |
| 602 | - */ | |
| 603 | -	public function deletePublicKey($uid) { | |
| 604 | - return $this->keyStorage->deleteUserKey($uid, $this->publicKeyId, Encryption::ID); | |
| 605 | - } | |
| 606 | - | |
| 607 | - /** | |
| 608 | - * @param string $uid | |
| 609 | - * @return bool | |
| 610 | - */ | |
| 611 | -	private function deletePrivateKey($uid) { | |
| 612 | - return $this->keyStorage->deleteUserKey($uid, $this->privateKeyId, Encryption::ID); | |
| 613 | - } | |
| 614 | - | |
| 615 | - /** | |
| 616 | - * @param string $path | |
| 617 | - * @return bool | |
| 618 | - */ | |
| 619 | -	public function deleteAllFileKeys($path) { | |
| 620 | - return $this->keyStorage->deleteAllFileKeys($path); | |
| 621 | - } | |
| 622 | - | |
| 623 | - /** | |
| 624 | - * @param array $userIds | |
| 625 | - * @return array | |
| 626 | - * @throws PublicKeyMissingException | |
| 627 | - */ | |
| 628 | -	public function getPublicKeys(array $userIds) { | |
| 629 | - $keys = []; | |
| 630 | - | |
| 631 | -		foreach ($userIds as $userId) { | |
| 632 | -			try { | |
| 633 | - $keys[$userId] = $this->getPublicKey($userId); | |
| 634 | -			} catch (PublicKeyMissingException $e) { | |
| 635 | - continue; | |
| 636 | - } | |
| 637 | - } | |
| 638 | - | |
| 639 | - return $keys; | |
| 640 | - | |
| 641 | - } | |
| 642 | - | |
| 643 | - /** | |
| 644 | - * @param string $keyId | |
| 645 | - * @return string returns openssl key | |
| 646 | - */ | |
| 647 | -	public function getSystemPrivateKey($keyId) { | |
| 648 | - return $this->keyStorage->getSystemUserKey($keyId . '.' . $this->privateKeyId, Encryption::ID); | |
| 649 | - } | |
| 650 | - | |
| 651 | - /** | |
| 652 | - * @param string $keyId | |
| 653 | - * @param string $key | |
| 654 | - * @return string returns openssl key | |
| 655 | - */ | |
| 656 | -	public function setSystemPrivateKey($keyId, $key) { | |
| 657 | - return $this->keyStorage->setSystemUserKey( | |
| 658 | - $keyId . '.' . $this->privateKeyId, | |
| 659 | - $key, | |
| 660 | - Encryption::ID); | |
| 661 | - } | |
| 662 | - | |
| 663 | - /** | |
| 664 | - * add system keys such as the public share key and the recovery key | |
| 665 | - * | |
| 666 | - * @param array $accessList | |
| 667 | - * @param array $publicKeys | |
| 668 | - * @param string $uid | |
| 669 | - * @return array | |
| 670 | - * @throws PublicKeyMissingException | |
| 671 | - */ | |
| 672 | -	public function addSystemKeys(array $accessList, array $publicKeys, $uid) { | |
| 673 | -		if (!empty($accessList['public'])) { | |
| 674 | - $publicShareKey = $this->getPublicShareKey(); | |
| 675 | -			if (empty($publicShareKey)) { | |
| 676 | - throw new PublicKeyMissingException($this->getPublicShareKeyId()); | |
| 677 | - } | |
| 678 | - $publicKeys[$this->getPublicShareKeyId()] = $publicShareKey; | |
| 679 | - } | |
| 680 | - | |
| 681 | - if ($this->recoveryKeyExists() && | |
| 682 | -			$this->util->isRecoveryEnabledForUser($uid)) { | |
| 683 | - | |
| 684 | - $publicKeys[$this->getRecoveryKeyId()] = $this->getRecoveryKey(); | |
| 685 | - } | |
| 686 | - | |
| 687 | - return $publicKeys; | |
| 688 | - } | |
| 689 | - | |
| 690 | - /** | |
| 691 | - * get master key password | |
| 692 | - * | |
| 693 | - * @return string | |
| 694 | - * @throws \Exception | |
| 695 | - */ | |
| 696 | -	public function getMasterKeyPassword() { | |
| 697 | -		$password = $this->config->getSystemValue('secret'); | |
| 698 | -		if (empty($password)){ | |
| 699 | -			throw new \Exception('Can not get secret from Nextcloud instance'); | |
| 700 | - } | |
| 701 | - | |
| 702 | - return $password; | |
| 703 | - } | |
| 704 | - | |
| 705 | - /** | |
| 706 | - * return master key id | |
| 707 | - * | |
| 708 | - * @return string | |
| 709 | - */ | |
| 710 | -	public function getMasterKeyId() { | |
| 711 | - return $this->masterKeyId; | |
| 712 | - } | |
| 713 | - | |
| 714 | - /** | |
| 715 | - * get public master key | |
| 716 | - * | |
| 717 | - * @return string | |
| 718 | - */ | |
| 719 | -	public function getPublicMasterKey() { | |
| 720 | - return $this->keyStorage->getSystemUserKey($this->masterKeyId . '.publicKey', Encryption::ID); | |
| 721 | - } | |
| 41 | + /** | |
| 42 | + * @var Session | |
| 43 | + */ | |
| 44 | + protected $session; | |
| 45 | + /** | |
| 46 | + * @var IStorage | |
| 47 | + */ | |
| 48 | + private $keyStorage; | |
| 49 | + /** | |
| 50 | + * @var Crypt | |
| 51 | + */ | |
| 52 | + private $crypt; | |
| 53 | + /** | |
| 54 | + * @var string | |
| 55 | + */ | |
| 56 | + private $recoveryKeyId; | |
| 57 | + /** | |
| 58 | + * @var string | |
| 59 | + */ | |
| 60 | + private $publicShareKeyId; | |
| 61 | + /** | |
| 62 | + * @var string | |
| 63 | + */ | |
| 64 | + private $masterKeyId; | |
| 65 | + /** | |
| 66 | + * @var string UserID | |
| 67 | + */ | |
| 68 | + private $keyId; | |
| 69 | + /** | |
| 70 | + * @var string | |
| 71 | + */ | |
| 72 | + private $publicKeyId = 'publicKey'; | |
| 73 | + /** | |
| 74 | + * @var string | |
| 75 | + */ | |
| 76 | + private $privateKeyId = 'privateKey'; | |
| 77 | + | |
| 78 | + /** | |
| 79 | + * @var string | |
| 80 | + */ | |
| 81 | + private $shareKeyId = 'shareKey'; | |
| 82 | + | |
| 83 | + /** | |
| 84 | + * @var string | |
| 85 | + */ | |
| 86 | + private $fileKeyId = 'fileKey'; | |
| 87 | + /** | |
| 88 | + * @var IConfig | |
| 89 | + */ | |
| 90 | + private $config; | |
| 91 | + /** | |
| 92 | + * @var ILogger | |
| 93 | + */ | |
| 94 | + private $log; | |
| 95 | + /** | |
| 96 | + * @var Util | |
| 97 | + */ | |
| 98 | + private $util; | |
| 99 | + | |
| 100 | + /** | |
| 101 | + * @param IStorage $keyStorage | |
| 102 | + * @param Crypt $crypt | |
| 103 | + * @param IConfig $config | |
| 104 | + * @param IUserSession $userSession | |
| 105 | + * @param Session $session | |
| 106 | + * @param ILogger $log | |
| 107 | + * @param Util $util | |
| 108 | + */ | |
| 109 | + public function __construct( | |
| 110 | + IStorage $keyStorage, | |
| 111 | + Crypt $crypt, | |
| 112 | + IConfig $config, | |
| 113 | + IUserSession $userSession, | |
| 114 | + Session $session, | |
| 115 | + ILogger $log, | |
| 116 | + Util $util | |
| 117 | +    ) { | |
| 118 | + | |
| 119 | + $this->util = $util; | |
| 120 | + $this->session = $session; | |
| 121 | + $this->keyStorage = $keyStorage; | |
| 122 | + $this->crypt = $crypt; | |
| 123 | + $this->config = $config; | |
| 124 | + $this->log = $log; | |
| 125 | + | |
| 126 | +        $this->recoveryKeyId = $this->config->getAppValue('encryption', | |
| 127 | + 'recoveryKeyId'); | |
| 128 | +        if (empty($this->recoveryKeyId)) { | |
| 129 | + $this->recoveryKeyId = 'recoveryKey_' . substr(md5(time()), 0, 8); | |
| 130 | +            $this->config->setAppValue('encryption', | |
| 131 | + 'recoveryKeyId', | |
| 132 | + $this->recoveryKeyId); | |
| 133 | + } | |
| 134 | + | |
| 135 | +        $this->publicShareKeyId = $this->config->getAppValue('encryption', | |
| 136 | + 'publicShareKeyId'); | |
| 137 | +        if (empty($this->publicShareKeyId)) { | |
| 138 | + $this->publicShareKeyId = 'pubShare_' . substr(md5(time()), 0, 8); | |
| 139 | +            $this->config->setAppValue('encryption', 'publicShareKeyId', $this->publicShareKeyId); | |
| 140 | + } | |
| 141 | + | |
| 142 | +        $this->masterKeyId = $this->config->getAppValue('encryption', | |
| 143 | + 'masterKeyId'); | |
| 144 | +        if (empty($this->masterKeyId)) { | |
| 145 | + $this->masterKeyId = 'master_' . substr(md5(time()), 0, 8); | |
| 146 | +            $this->config->setAppValue('encryption', 'masterKeyId', $this->masterKeyId); | |
| 147 | + } | |
| 148 | + | |
| 149 | + $this->keyId = $userSession && $userSession->isLoggedIn() ? $userSession->getUser()->getUID() : false; | |
| 150 | + $this->log = $log; | |
| 151 | + } | |
| 152 | + | |
| 153 | + /** | |
| 154 | + * check if key pair for public link shares exists, if not we create one | |
| 155 | + */ | |
| 156 | +    public function validateShareKey() { | |
| 157 | + $shareKey = $this->getPublicShareKey(); | |
| 158 | +        if (empty($shareKey)) { | |
| 159 | + $keyPair = $this->crypt->createKeyPair(); | |
| 160 | + | |
| 161 | + // Save public key | |
| 162 | + $this->keyStorage->setSystemUserKey( | |
| 163 | + $this->publicShareKeyId . '.publicKey', $keyPair['publicKey'], | |
| 164 | + Encryption::ID); | |
| 165 | + | |
| 166 | + // Encrypt private key empty passphrase | |
| 167 | + $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], ''); | |
| 168 | + $header = $this->crypt->generateHeader(); | |
| 169 | + $this->setSystemPrivateKey($this->publicShareKeyId, $header . $encryptedKey); | |
| 170 | + } | |
| 171 | + } | |
| 172 | + | |
| 173 | + /** | |
| 174 | + * check if a key pair for the master key exists, if not we create one | |
| 175 | + */ | |
| 176 | +    public function validateMasterKey() { | |
| 177 | + | |
| 178 | +        if ($this->util->isMasterKeyEnabled() === false) { | |
| 179 | + return; | |
| 180 | + } | |
| 181 | + | |
| 182 | + $publicMasterKey = $this->getPublicMasterKey(); | |
| 183 | +        if (empty($publicMasterKey)) { | |
| 184 | + $keyPair = $this->crypt->createKeyPair(); | |
| 185 | + | |
| 186 | + // Save public key | |
| 187 | + $this->keyStorage->setSystemUserKey( | |
| 188 | + $this->masterKeyId . '.publicKey', $keyPair['publicKey'], | |
| 189 | + Encryption::ID); | |
| 190 | + | |
| 191 | + // Encrypt private key with system password | |
| 192 | + $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $this->getMasterKeyPassword(), $this->masterKeyId); | |
| 193 | + $header = $this->crypt->generateHeader(); | |
| 194 | + $this->setSystemPrivateKey($this->masterKeyId, $header . $encryptedKey); | |
| 195 | + } | |
| 196 | + | |
| 197 | +        if (!$this->session->isPrivateKeySet()) { | |
| 198 | + $masterKey = $this->getSystemPrivateKey($this->masterKeyId); | |
| 199 | + $decryptedMasterKey = $this->crypt->decryptPrivateKey($masterKey, $this->getMasterKeyPassword(), $this->masterKeyId); | |
| 200 | + $this->session->setPrivateKey($decryptedMasterKey); | |
| 201 | + } | |
| 202 | + | |
| 203 | + // after the encryption key is available we are ready to go | |
| 204 | + $this->session->setStatus(Session::INIT_SUCCESSFUL); | |
| 205 | + } | |
| 206 | + | |
| 207 | + /** | |
| 208 | + * @return bool | |
| 209 | + */ | |
| 210 | +    public function recoveryKeyExists() { | |
| 211 | + $key = $this->getRecoveryKey(); | |
| 212 | + return (!empty($key)); | |
| 213 | + } | |
| 214 | + | |
| 215 | + /** | |
| 216 | + * get recovery key | |
| 217 | + * | |
| 218 | + * @return string | |
| 219 | + */ | |
| 220 | +    public function getRecoveryKey() { | |
| 221 | + return $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.publicKey', Encryption::ID); | |
| 222 | + } | |
| 223 | + | |
| 224 | + /** | |
| 225 | + * get recovery key ID | |
| 226 | + * | |
| 227 | + * @return string | |
| 228 | + */ | |
| 229 | +    public function getRecoveryKeyId() { | |
| 230 | + return $this->recoveryKeyId; | |
| 231 | + } | |
| 232 | + | |
| 233 | + /** | |
| 234 | + * @param string $password | |
| 235 | + * @return bool | |
| 236 | + */ | |
| 237 | +    public function checkRecoveryPassword($password) { | |
| 238 | + $recoveryKey = $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.privateKey', Encryption::ID); | |
| 239 | + $decryptedRecoveryKey = $this->crypt->decryptPrivateKey($recoveryKey, $password); | |
| 240 | + | |
| 241 | +        if ($decryptedRecoveryKey) { | |
| 242 | + return true; | |
| 243 | + } | |
| 244 | + return false; | |
| 245 | + } | |
| 246 | + | |
| 247 | + /** | |
| 248 | + * @param string $uid | |
| 249 | + * @param string $password | |
| 250 | + * @param string $keyPair | |
| 251 | + * @return bool | |
| 252 | + */ | |
| 253 | +    public function storeKeyPair($uid, $password, $keyPair) { | |
| 254 | + // Save Public Key | |
| 255 | + $this->setPublicKey($uid, $keyPair['publicKey']); | |
| 256 | + | |
| 257 | + $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $password, $uid); | |
| 258 | + | |
| 259 | + $header = $this->crypt->generateHeader(); | |
| 260 | + | |
| 261 | +        if ($encryptedKey) { | |
| 262 | + $this->setPrivateKey($uid, $header . $encryptedKey); | |
| 263 | + return true; | |
| 264 | + } | |
| 265 | + return false; | |
| 266 | + } | |
| 267 | + | |
| 268 | + /** | |
| 269 | + * @param string $password | |
| 270 | + * @param array $keyPair | |
| 271 | + * @return bool | |
| 272 | + */ | |
| 273 | +    public function setRecoveryKey($password, $keyPair) { | |
| 274 | + // Save Public Key | |
| 275 | + $this->keyStorage->setSystemUserKey($this->getRecoveryKeyId(). | |
| 276 | + '.publicKey', | |
| 277 | + $keyPair['publicKey'], | |
| 278 | + Encryption::ID); | |
| 279 | + | |
| 280 | + $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $password); | |
| 281 | + $header = $this->crypt->generateHeader(); | |
| 282 | + | |
| 283 | +        if ($encryptedKey) { | |
| 284 | + $this->setSystemPrivateKey($this->getRecoveryKeyId(), $header . $encryptedKey); | |
| 285 | + return true; | |
| 286 | + } | |
| 287 | + return false; | |
| 288 | + } | |
| 289 | + | |
| 290 | + /** | |
| 291 | + * @param $userId | |
| 292 | + * @param $key | |
| 293 | + * @return bool | |
| 294 | + */ | |
| 295 | +    public function setPublicKey($userId, $key) { | |
| 296 | + return $this->keyStorage->setUserKey($userId, $this->publicKeyId, $key, Encryption::ID); | |
| 297 | + } | |
| 298 | + | |
| 299 | + /** | |
| 300 | + * @param $userId | |
| 301 | + * @param string $key | |
| 302 | + * @return bool | |
| 303 | + */ | |
| 304 | +    public function setPrivateKey($userId, $key) { | |
| 305 | + return $this->keyStorage->setUserKey($userId, | |
| 306 | + $this->privateKeyId, | |
| 307 | + $key, | |
| 308 | + Encryption::ID); | |
| 309 | + } | |
| 310 | + | |
| 311 | + /** | |
| 312 | + * write file key to key storage | |
| 313 | + * | |
| 314 | + * @param string $path | |
| 315 | + * @param string $key | |
| 316 | + * @return boolean | |
| 317 | + */ | |
| 318 | +    public function setFileKey($path, $key) { | |
| 319 | + return $this->keyStorage->setFileKey($path, $this->fileKeyId, $key, Encryption::ID); | |
| 320 | + } | |
| 321 | + | |
| 322 | + /** | |
| 323 | + * set all file keys (the file key and the corresponding share keys) | |
| 324 | + * | |
| 325 | + * @param string $path | |
| 326 | + * @param array $keys | |
| 327 | + */ | |
| 328 | +    public function setAllFileKeys($path, $keys) { | |
| 329 | + $this->setFileKey($path, $keys['data']); | |
| 330 | +        foreach ($keys['keys'] as $uid => $keyFile) { | |
| 331 | + $this->setShareKey($path, $uid, $keyFile); | |
| 332 | + } | |
| 333 | + } | |
| 334 | + | |
| 335 | + /** | |
| 336 | + * write share key to the key storage | |
| 337 | + * | |
| 338 | + * @param string $path | |
| 339 | + * @param string $uid | |
| 340 | + * @param string $key | |
| 341 | + * @return boolean | |
| 342 | + */ | |
| 343 | +    public function setShareKey($path, $uid, $key) { | |
| 344 | + $keyId = $uid . '.' . $this->shareKeyId; | |
| 345 | + return $this->keyStorage->setFileKey($path, $keyId, $key, Encryption::ID); | |
| 346 | + } | |
| 347 | + | |
| 348 | + /** | |
| 349 | + * Decrypt private key and store it | |
| 350 | + * | |
| 351 | + * @param string $uid user id | |
| 352 | + * @param string $passPhrase users password | |
| 353 | + * @return boolean | |
| 354 | + */ | |
| 355 | +    public function init($uid, $passPhrase) { | |
| 356 | + | |
| 357 | + $this->session->setStatus(Session::INIT_EXECUTED); | |
| 358 | + | |
| 359 | +        try { | |
| 360 | +            if($this->util->isMasterKeyEnabled()) { | |
| 361 | + $uid = $this->getMasterKeyId(); | |
| 362 | + $passPhrase = $this->getMasterKeyPassword(); | |
| 363 | + $privateKey = $this->getSystemPrivateKey($uid); | |
| 364 | +            } else { | |
| 365 | + $privateKey = $this->getPrivateKey($uid); | |
| 366 | + } | |
| 367 | + $privateKey = $this->crypt->decryptPrivateKey($privateKey, $passPhrase, $uid); | |
| 368 | +        } catch (PrivateKeyMissingException $e) { | |
| 369 | + return false; | |
| 370 | +        } catch (DecryptionFailedException $e) { | |
| 371 | + return false; | |
| 372 | +        } catch (\Exception $e) { | |
| 373 | + $this->log->warning( | |
| 374 | + 'Could not decrypt the private key from user "' . $uid . '"" during login. ' . | |
| 375 | + 'Assume password change on the user back-end. Error message: ' | |
| 376 | + . $e->getMessage() | |
| 377 | + ); | |
| 378 | + return false; | |
| 379 | + } | |
| 380 | + | |
| 381 | +        if ($privateKey) { | |
| 382 | + $this->session->setPrivateKey($privateKey); | |
| 383 | + $this->session->setStatus(Session::INIT_SUCCESSFUL); | |
| 384 | + return true; | |
| 385 | + } | |
| 386 | + | |
| 387 | + return false; | |
| 388 | + } | |
| 389 | + | |
| 390 | + /** | |
| 391 | + * @param $userId | |
| 392 | + * @return string | |
| 393 | + * @throws PrivateKeyMissingException | |
| 394 | + */ | |
| 395 | +    public function getPrivateKey($userId) { | |
| 396 | + $privateKey = $this->keyStorage->getUserKey($userId, | |
| 397 | + $this->privateKeyId, Encryption::ID); | |
| 398 | + | |
| 399 | +        if (strlen($privateKey) !== 0) { | |
| 400 | + return $privateKey; | |
| 401 | + } | |
| 402 | + throw new PrivateKeyMissingException($userId); | |
| 403 | + } | |
| 404 | + | |
| 405 | + /** | |
| 406 | + * @param string $path | |
| 407 | + * @param $uid | |
| 408 | + * @return string | |
| 409 | + */ | |
| 410 | +    public function getFileKey($path, $uid) { | |
| 411 | +        if ($uid === '') { | |
| 412 | + $uid = null; | |
| 413 | + } | |
| 414 | + $publicAccess = is_null($uid); | |
| 415 | + $encryptedFileKey = $this->keyStorage->getFileKey($path, $this->fileKeyId, Encryption::ID); | |
| 416 | + | |
| 417 | +        if (empty($encryptedFileKey)) { | |
| 418 | + return ''; | |
| 419 | + } | |
| 420 | + | |
| 421 | +        if ($this->util->isMasterKeyEnabled()) { | |
| 422 | + $uid = $this->getMasterKeyId(); | |
| 423 | + $shareKey = $this->getShareKey($path, $uid); | |
| 424 | +            if ($publicAccess) { | |
| 425 | + $privateKey = $this->getSystemPrivateKey($uid); | |
| 426 | + $privateKey = $this->crypt->decryptPrivateKey($privateKey, $this->getMasterKeyPassword(), $uid); | |
| 427 | +            } else { | |
| 428 | + // when logged in, the master key is already decrypted in the session | |
| 429 | + $privateKey = $this->session->getPrivateKey(); | |
| 430 | + } | |
| 431 | +        } else if ($publicAccess) { | |
| 432 | + // use public share key for public links | |
| 433 | + $uid = $this->getPublicShareKeyId(); | |
| 434 | + $shareKey = $this->getShareKey($path, $uid); | |
| 435 | + $privateKey = $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.privateKey', Encryption::ID); | |
| 436 | + $privateKey = $this->crypt->decryptPrivateKey($privateKey); | |
| 437 | +        } else { | |
| 438 | + $shareKey = $this->getShareKey($path, $uid); | |
| 439 | + $privateKey = $this->session->getPrivateKey(); | |
| 440 | + } | |
| 441 | + | |
| 442 | +        if ($encryptedFileKey && $shareKey && $privateKey) { | |
| 443 | + return $this->crypt->multiKeyDecrypt($encryptedFileKey, | |
| 444 | + $shareKey, | |
| 445 | + $privateKey); | |
| 446 | + } | |
| 447 | + | |
| 448 | + return ''; | |
| 449 | + } | |
| 450 | + | |
| 451 | + /** | |
| 452 | + * Get the current version of a file | |
| 453 | + * | |
| 454 | + * @param string $path | |
| 455 | + * @param View $view | |
| 456 | + * @return int | |
| 457 | + */ | |
| 458 | +    public function getVersion($path, View $view) { | |
| 459 | + $fileInfo = $view->getFileInfo($path); | |
| 460 | +        if($fileInfo === false) { | |
| 461 | + return 0; | |
| 462 | + } | |
| 463 | + return $fileInfo->getEncryptedVersion(); | |
| 464 | + } | |
| 465 | + | |
| 466 | + /** | |
| 467 | + * Set the current version of a file | |
| 468 | + * | |
| 469 | + * @param string $path | |
| 470 | + * @param int $version | |
| 471 | + * @param View $view | |
| 472 | + */ | |
| 473 | +    public function setVersion($path, $version, View $view) { | |
| 474 | + $fileInfo= $view->getFileInfo($path); | |
| 475 | + | |
| 476 | +        if($fileInfo !== false) { | |
| 477 | + $cache = $fileInfo->getStorage()->getCache(); | |
| 478 | + $cache->update($fileInfo->getId(), ['encrypted' => $version, 'encryptedVersion' => $version]); | |
| 479 | + } | |
| 480 | + } | |
| 481 | + | |
| 482 | + /** | |
| 483 | + * get the encrypted file key | |
| 484 | + * | |
| 485 | + * @param string $path | |
| 486 | + * @return string | |
| 487 | + */ | |
| 488 | +    public function getEncryptedFileKey($path) { | |
| 489 | + $encryptedFileKey = $this->keyStorage->getFileKey($path, | |
| 490 | + $this->fileKeyId, Encryption::ID); | |
| 491 | + | |
| 492 | + return $encryptedFileKey; | |
| 493 | + } | |
| 494 | + | |
| 495 | + /** | |
| 496 | + * delete share key | |
| 497 | + * | |
| 498 | + * @param string $path | |
| 499 | + * @param string $keyId | |
| 500 | + * @return boolean | |
| 501 | + */ | |
| 502 | +    public function deleteShareKey($path, $keyId) { | |
| 503 | + return $this->keyStorage->deleteFileKey( | |
| 504 | + $path, | |
| 505 | + $keyId . '.' . $this->shareKeyId, | |
| 506 | + Encryption::ID); | |
| 507 | + } | |
| 508 | + | |
| 509 | + | |
| 510 | + /** | |
| 511 | + * @param $path | |
| 512 | + * @param $uid | |
| 513 | + * @return mixed | |
| 514 | + */ | |
| 515 | +    public function getShareKey($path, $uid) { | |
| 516 | + $keyId = $uid . '.' . $this->shareKeyId; | |
| 517 | + return $this->keyStorage->getFileKey($path, $keyId, Encryption::ID); | |
| 518 | + } | |
| 519 | + | |
| 520 | + /** | |
| 521 | + * check if user has a private and a public key | |
| 522 | + * | |
| 523 | + * @param string $userId | |
| 524 | + * @return bool | |
| 525 | + * @throws PrivateKeyMissingException | |
| 526 | + * @throws PublicKeyMissingException | |
| 527 | + */ | |
| 528 | +    public function userHasKeys($userId) { | |
| 529 | + $privateKey = $publicKey = true; | |
| 530 | + $exception = null; | |
| 531 | + | |
| 532 | +        try { | |
| 533 | + $this->getPrivateKey($userId); | |
| 534 | +        } catch (PrivateKeyMissingException $e) { | |
| 535 | + $privateKey = false; | |
| 536 | + $exception = $e; | |
| 537 | + } | |
| 538 | +        try { | |
| 539 | + $this->getPublicKey($userId); | |
| 540 | +        } catch (PublicKeyMissingException $e) { | |
| 541 | + $publicKey = false; | |
| 542 | + $exception = $e; | |
| 543 | + } | |
| 544 | + | |
| 545 | +        if ($privateKey && $publicKey) { | |
| 546 | + return true; | |
| 547 | +        } elseif (!$privateKey && !$publicKey) { | |
| 548 | + return false; | |
| 549 | +        } else { | |
| 550 | + throw $exception; | |
| 551 | + } | |
| 552 | + } | |
| 553 | + | |
| 554 | + /** | |
| 555 | + * @param $userId | |
| 556 | + * @return mixed | |
| 557 | + * @throws PublicKeyMissingException | |
| 558 | + */ | |
| 559 | +    public function getPublicKey($userId) { | |
| 560 | + $publicKey = $this->keyStorage->getUserKey($userId, $this->publicKeyId, Encryption::ID); | |
| 561 | + | |
| 562 | +        if (strlen($publicKey) !== 0) { | |
| 563 | + return $publicKey; | |
| 564 | + } | |
| 565 | + throw new PublicKeyMissingException($userId); | |
| 566 | + } | |
| 567 | + | |
| 568 | +    public function getPublicShareKeyId() { | |
| 569 | + return $this->publicShareKeyId; | |
| 570 | + } | |
| 571 | + | |
| 572 | + /** | |
| 573 | + * get public key for public link shares | |
| 574 | + * | |
| 575 | + * @return string | |
| 576 | + */ | |
| 577 | +    public function getPublicShareKey() { | |
| 578 | + return $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.publicKey', Encryption::ID); | |
| 579 | + } | |
| 580 | + | |
| 581 | + /** | |
| 582 | + * @param string $purpose | |
| 583 | + * @param string $uid | |
| 584 | + */ | |
| 585 | +    public function backupUserKeys($purpose, $uid) { | |
| 586 | + $this->keyStorage->backupUserKeys(Encryption::ID, $purpose, $uid); | |
| 587 | + } | |
| 588 | + | |
| 589 | + /** | |
| 590 | + * creat a backup of the users private and public key and then delete it | |
| 591 | + * | |
| 592 | + * @param string $uid | |
| 593 | + */ | |
| 594 | +    public function deleteUserKeys($uid) { | |
| 595 | + $this->deletePublicKey($uid); | |
| 596 | + $this->deletePrivateKey($uid); | |
| 597 | + } | |
| 598 | + | |
| 599 | + /** | |
| 600 | + * @param $uid | |
| 601 | + * @return bool | |
| 602 | + */ | |
| 603 | +    public function deletePublicKey($uid) { | |
| 604 | + return $this->keyStorage->deleteUserKey($uid, $this->publicKeyId, Encryption::ID); | |
| 605 | + } | |
| 606 | + | |
| 607 | + /** | |
| 608 | + * @param string $uid | |
| 609 | + * @return bool | |
| 610 | + */ | |
| 611 | +    private function deletePrivateKey($uid) { | |
| 612 | + return $this->keyStorage->deleteUserKey($uid, $this->privateKeyId, Encryption::ID); | |
| 613 | + } | |
| 614 | + | |
| 615 | + /** | |
| 616 | + * @param string $path | |
| 617 | + * @return bool | |
| 618 | + */ | |
| 619 | +    public function deleteAllFileKeys($path) { | |
| 620 | + return $this->keyStorage->deleteAllFileKeys($path); | |
| 621 | + } | |
| 622 | + | |
| 623 | + /** | |
| 624 | + * @param array $userIds | |
| 625 | + * @return array | |
| 626 | + * @throws PublicKeyMissingException | |
| 627 | + */ | |
| 628 | +    public function getPublicKeys(array $userIds) { | |
| 629 | + $keys = []; | |
| 630 | + | |
| 631 | +        foreach ($userIds as $userId) { | |
| 632 | +            try { | |
| 633 | + $keys[$userId] = $this->getPublicKey($userId); | |
| 634 | +            } catch (PublicKeyMissingException $e) { | |
| 635 | + continue; | |
| 636 | + } | |
| 637 | + } | |
| 638 | + | |
| 639 | + return $keys; | |
| 640 | + | |
| 641 | + } | |
| 642 | + | |
| 643 | + /** | |
| 644 | + * @param string $keyId | |
| 645 | + * @return string returns openssl key | |
| 646 | + */ | |
| 647 | +    public function getSystemPrivateKey($keyId) { | |
| 648 | + return $this->keyStorage->getSystemUserKey($keyId . '.' . $this->privateKeyId, Encryption::ID); | |
| 649 | + } | |
| 650 | + | |
| 651 | + /** | |
| 652 | + * @param string $keyId | |
| 653 | + * @param string $key | |
| 654 | + * @return string returns openssl key | |
| 655 | + */ | |
| 656 | +    public function setSystemPrivateKey($keyId, $key) { | |
| 657 | + return $this->keyStorage->setSystemUserKey( | |
| 658 | + $keyId . '.' . $this->privateKeyId, | |
| 659 | + $key, | |
| 660 | + Encryption::ID); | |
| 661 | + } | |
| 662 | + | |
| 663 | + /** | |
| 664 | + * add system keys such as the public share key and the recovery key | |
| 665 | + * | |
| 666 | + * @param array $accessList | |
| 667 | + * @param array $publicKeys | |
| 668 | + * @param string $uid | |
| 669 | + * @return array | |
| 670 | + * @throws PublicKeyMissingException | |
| 671 | + */ | |
| 672 | +    public function addSystemKeys(array $accessList, array $publicKeys, $uid) { | |
| 673 | +        if (!empty($accessList['public'])) { | |
| 674 | + $publicShareKey = $this->getPublicShareKey(); | |
| 675 | +            if (empty($publicShareKey)) { | |
| 676 | + throw new PublicKeyMissingException($this->getPublicShareKeyId()); | |
| 677 | + } | |
| 678 | + $publicKeys[$this->getPublicShareKeyId()] = $publicShareKey; | |
| 679 | + } | |
| 680 | + | |
| 681 | + if ($this->recoveryKeyExists() && | |
| 682 | +            $this->util->isRecoveryEnabledForUser($uid)) { | |
| 683 | + | |
| 684 | + $publicKeys[$this->getRecoveryKeyId()] = $this->getRecoveryKey(); | |
| 685 | + } | |
| 686 | + | |
| 687 | + return $publicKeys; | |
| 688 | + } | |
| 689 | + | |
| 690 | + /** | |
| 691 | + * get master key password | |
| 692 | + * | |
| 693 | + * @return string | |
| 694 | + * @throws \Exception | |
| 695 | + */ | |
| 696 | +    public function getMasterKeyPassword() { | |
| 697 | +        $password = $this->config->getSystemValue('secret'); | |
| 698 | +        if (empty($password)){ | |
| 699 | +            throw new \Exception('Can not get secret from Nextcloud instance'); | |
| 700 | + } | |
| 701 | + | |
| 702 | + return $password; | |
| 703 | + } | |
| 704 | + | |
| 705 | + /** | |
| 706 | + * return master key id | |
| 707 | + * | |
| 708 | + * @return string | |
| 709 | + */ | |
| 710 | +    public function getMasterKeyId() { | |
| 711 | + return $this->masterKeyId; | |
| 712 | + } | |
| 713 | + | |
| 714 | + /** | |
| 715 | + * get public master key | |
| 716 | + * | |
| 717 | + * @return string | |
| 718 | + */ | |
| 719 | +    public function getPublicMasterKey() { | |
| 720 | + return $this->keyStorage->getSystemUserKey($this->masterKeyId . '.publicKey', Encryption::ID); | |
| 721 | + } | |
| 722 | 722 | } | 
| @@ -126,7 +126,7 @@ discard block | ||
| 126 | 126 |  		$this->recoveryKeyId = $this->config->getAppValue('encryption', | 
| 127 | 127 | 'recoveryKeyId'); | 
| 128 | 128 |  		if (empty($this->recoveryKeyId)) { | 
| 129 | - $this->recoveryKeyId = 'recoveryKey_' . substr(md5(time()), 0, 8); | |
| 129 | + $this->recoveryKeyId = 'recoveryKey_'.substr(md5(time()), 0, 8); | |
| 130 | 130 |  			$this->config->setAppValue('encryption', | 
| 131 | 131 | 'recoveryKeyId', | 
| 132 | 132 | $this->recoveryKeyId); | 
| @@ -135,14 +135,14 @@ discard block | ||
| 135 | 135 |  		$this->publicShareKeyId = $this->config->getAppValue('encryption', | 
| 136 | 136 | 'publicShareKeyId'); | 
| 137 | 137 |  		if (empty($this->publicShareKeyId)) { | 
| 138 | - $this->publicShareKeyId = 'pubShare_' . substr(md5(time()), 0, 8); | |
| 138 | + $this->publicShareKeyId = 'pubShare_'.substr(md5(time()), 0, 8); | |
| 139 | 139 |  			$this->config->setAppValue('encryption', 'publicShareKeyId', $this->publicShareKeyId); | 
| 140 | 140 | } | 
| 141 | 141 | |
| 142 | 142 |  		$this->masterKeyId = $this->config->getAppValue('encryption', | 
| 143 | 143 | 'masterKeyId'); | 
| 144 | 144 |  		if (empty($this->masterKeyId)) { | 
| 145 | - $this->masterKeyId = 'master_' . substr(md5(time()), 0, 8); | |
| 145 | + $this->masterKeyId = 'master_'.substr(md5(time()), 0, 8); | |
| 146 | 146 |  			$this->config->setAppValue('encryption', 'masterKeyId', $this->masterKeyId); | 
| 147 | 147 | } | 
| 148 | 148 | |
| @@ -160,13 +160,13 @@ discard block | ||
| 160 | 160 | |
| 161 | 161 | // Save public key | 
| 162 | 162 | $this->keyStorage->setSystemUserKey( | 
| 163 | - $this->publicShareKeyId . '.publicKey', $keyPair['publicKey'], | |
| 163 | + $this->publicShareKeyId.'.publicKey', $keyPair['publicKey'], | |
| 164 | 164 | Encryption::ID); | 
| 165 | 165 | |
| 166 | 166 | // Encrypt private key empty passphrase | 
| 167 | 167 | $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], ''); | 
| 168 | 168 | $header = $this->crypt->generateHeader(); | 
| 169 | - $this->setSystemPrivateKey($this->publicShareKeyId, $header . $encryptedKey); | |
| 169 | + $this->setSystemPrivateKey($this->publicShareKeyId, $header.$encryptedKey); | |
| 170 | 170 | } | 
| 171 | 171 | } | 
| 172 | 172 | |
| @@ -185,13 +185,13 @@ discard block | ||
| 185 | 185 | |
| 186 | 186 | // Save public key | 
| 187 | 187 | $this->keyStorage->setSystemUserKey( | 
| 188 | - $this->masterKeyId . '.publicKey', $keyPair['publicKey'], | |
| 188 | + $this->masterKeyId.'.publicKey', $keyPair['publicKey'], | |
| 189 | 189 | Encryption::ID); | 
| 190 | 190 | |
| 191 | 191 | // Encrypt private key with system password | 
| 192 | 192 | $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $this->getMasterKeyPassword(), $this->masterKeyId); | 
| 193 | 193 | $header = $this->crypt->generateHeader(); | 
| 194 | - $this->setSystemPrivateKey($this->masterKeyId, $header . $encryptedKey); | |
| 194 | + $this->setSystemPrivateKey($this->masterKeyId, $header.$encryptedKey); | |
| 195 | 195 | } | 
| 196 | 196 | |
| 197 | 197 |  		if (!$this->session->isPrivateKeySet()) { | 
| @@ -218,7 +218,7 @@ discard block | ||
| 218 | 218 | * @return string | 
| 219 | 219 | */ | 
| 220 | 220 |  	public function getRecoveryKey() { | 
| 221 | - return $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.publicKey', Encryption::ID); | |
| 221 | + return $this->keyStorage->getSystemUserKey($this->recoveryKeyId.'.publicKey', Encryption::ID); | |
| 222 | 222 | } | 
| 223 | 223 | |
| 224 | 224 | /** | 
| @@ -235,7 +235,7 @@ discard block | ||
| 235 | 235 | * @return bool | 
| 236 | 236 | */ | 
| 237 | 237 |  	public function checkRecoveryPassword($password) { | 
| 238 | - $recoveryKey = $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.privateKey', Encryption::ID); | |
| 238 | + $recoveryKey = $this->keyStorage->getSystemUserKey($this->recoveryKeyId.'.privateKey', Encryption::ID); | |
| 239 | 239 | $decryptedRecoveryKey = $this->crypt->decryptPrivateKey($recoveryKey, $password); | 
| 240 | 240 | |
| 241 | 241 |  		if ($decryptedRecoveryKey) { | 
| @@ -259,7 +259,7 @@ discard block | ||
| 259 | 259 | $header = $this->crypt->generateHeader(); | 
| 260 | 260 | |
| 261 | 261 |  		if ($encryptedKey) { | 
| 262 | - $this->setPrivateKey($uid, $header . $encryptedKey); | |
| 262 | + $this->setPrivateKey($uid, $header.$encryptedKey); | |
| 263 | 263 | return true; | 
| 264 | 264 | } | 
| 265 | 265 | return false; | 
| @@ -281,7 +281,7 @@ discard block | ||
| 281 | 281 | $header = $this->crypt->generateHeader(); | 
| 282 | 282 | |
| 283 | 283 |  		if ($encryptedKey) { | 
| 284 | - $this->setSystemPrivateKey($this->getRecoveryKeyId(), $header . $encryptedKey); | |
| 284 | + $this->setSystemPrivateKey($this->getRecoveryKeyId(), $header.$encryptedKey); | |
| 285 | 285 | return true; | 
| 286 | 286 | } | 
| 287 | 287 | return false; | 
| @@ -341,7 +341,7 @@ discard block | ||
| 341 | 341 | * @return boolean | 
| 342 | 342 | */ | 
| 343 | 343 |  	public function setShareKey($path, $uid, $key) { | 
| 344 | - $keyId = $uid . '.' . $this->shareKeyId; | |
| 344 | + $keyId = $uid.'.'.$this->shareKeyId; | |
| 345 | 345 | return $this->keyStorage->setFileKey($path, $keyId, $key, Encryption::ID); | 
| 346 | 346 | } | 
| 347 | 347 | |
| @@ -357,7 +357,7 @@ discard block | ||
| 357 | 357 | $this->session->setStatus(Session::INIT_EXECUTED); | 
| 358 | 358 | |
| 359 | 359 |  		try { | 
| 360 | -			if($this->util->isMasterKeyEnabled()) { | |
| 360 | +			if ($this->util->isMasterKeyEnabled()) { | |
| 361 | 361 | $uid = $this->getMasterKeyId(); | 
| 362 | 362 | $passPhrase = $this->getMasterKeyPassword(); | 
| 363 | 363 | $privateKey = $this->getSystemPrivateKey($uid); | 
| @@ -371,7 +371,7 @@ discard block | ||
| 371 | 371 | return false; | 
| 372 | 372 |  		} catch (\Exception $e) { | 
| 373 | 373 | $this->log->warning( | 
| 374 | - 'Could not decrypt the private key from user "' . $uid . '"" during login. ' . | |
| 374 | + 'Could not decrypt the private key from user "'.$uid.'"" during login. '. | |
| 375 | 375 | 'Assume password change on the user back-end. Error message: ' | 
| 376 | 376 | . $e->getMessage() | 
| 377 | 377 | ); | 
| @@ -432,7 +432,7 @@ discard block | ||
| 432 | 432 | // use public share key for public links | 
| 433 | 433 | $uid = $this->getPublicShareKeyId(); | 
| 434 | 434 | $shareKey = $this->getShareKey($path, $uid); | 
| 435 | - $privateKey = $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.privateKey', Encryption::ID); | |
| 435 | + $privateKey = $this->keyStorage->getSystemUserKey($this->publicShareKeyId.'.privateKey', Encryption::ID); | |
| 436 | 436 | $privateKey = $this->crypt->decryptPrivateKey($privateKey); | 
| 437 | 437 |  		} else { | 
| 438 | 438 | $shareKey = $this->getShareKey($path, $uid); | 
| @@ -457,7 +457,7 @@ discard block | ||
| 457 | 457 | */ | 
| 458 | 458 |  	public function getVersion($path, View $view) { | 
| 459 | 459 | $fileInfo = $view->getFileInfo($path); | 
| 460 | -		if($fileInfo === false) { | |
| 460 | +		if ($fileInfo === false) { | |
| 461 | 461 | return 0; | 
| 462 | 462 | } | 
| 463 | 463 | return $fileInfo->getEncryptedVersion(); | 
| @@ -471,9 +471,9 @@ discard block | ||
| 471 | 471 | * @param View $view | 
| 472 | 472 | */ | 
| 473 | 473 |  	public function setVersion($path, $version, View $view) { | 
| 474 | - $fileInfo= $view->getFileInfo($path); | |
| 474 | + $fileInfo = $view->getFileInfo($path); | |
| 475 | 475 | |
| 476 | -		if($fileInfo !== false) { | |
| 476 | +		if ($fileInfo !== false) { | |
| 477 | 477 | $cache = $fileInfo->getStorage()->getCache(); | 
| 478 | 478 | $cache->update($fileInfo->getId(), ['encrypted' => $version, 'encryptedVersion' => $version]); | 
| 479 | 479 | } | 
| @@ -502,7 +502,7 @@ discard block | ||
| 502 | 502 |  	public function deleteShareKey($path, $keyId) { | 
| 503 | 503 | return $this->keyStorage->deleteFileKey( | 
| 504 | 504 | $path, | 
| 505 | - $keyId . '.' . $this->shareKeyId, | |
| 505 | + $keyId.'.'.$this->shareKeyId, | |
| 506 | 506 | Encryption::ID); | 
| 507 | 507 | } | 
| 508 | 508 | |
| @@ -513,7 +513,7 @@ discard block | ||
| 513 | 513 | * @return mixed | 
| 514 | 514 | */ | 
| 515 | 515 |  	public function getShareKey($path, $uid) { | 
| 516 | - $keyId = $uid . '.' . $this->shareKeyId; | |
| 516 | + $keyId = $uid.'.'.$this->shareKeyId; | |
| 517 | 517 | return $this->keyStorage->getFileKey($path, $keyId, Encryption::ID); | 
| 518 | 518 | } | 
| 519 | 519 | |
| @@ -575,7 +575,7 @@ discard block | ||
| 575 | 575 | * @return string | 
| 576 | 576 | */ | 
| 577 | 577 |  	public function getPublicShareKey() { | 
| 578 | - return $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.publicKey', Encryption::ID); | |
| 578 | + return $this->keyStorage->getSystemUserKey($this->publicShareKeyId.'.publicKey', Encryption::ID); | |
| 579 | 579 | } | 
| 580 | 580 | |
| 581 | 581 | /** | 
| @@ -645,7 +645,7 @@ discard block | ||
| 645 | 645 | * @return string returns openssl key | 
| 646 | 646 | */ | 
| 647 | 647 |  	public function getSystemPrivateKey($keyId) { | 
| 648 | - return $this->keyStorage->getSystemUserKey($keyId . '.' . $this->privateKeyId, Encryption::ID); | |
| 648 | + return $this->keyStorage->getSystemUserKey($keyId.'.'.$this->privateKeyId, Encryption::ID); | |
| 649 | 649 | } | 
| 650 | 650 | |
| 651 | 651 | /** | 
| @@ -655,7 +655,7 @@ discard block | ||
| 655 | 655 | */ | 
| 656 | 656 |  	public function setSystemPrivateKey($keyId, $key) { | 
| 657 | 657 | return $this->keyStorage->setSystemUserKey( | 
| 658 | - $keyId . '.' . $this->privateKeyId, | |
| 658 | + $keyId.'.'.$this->privateKeyId, | |
| 659 | 659 | $key, | 
| 660 | 660 | Encryption::ID); | 
| 661 | 661 | } | 
| @@ -695,7 +695,7 @@ discard block | ||
| 695 | 695 | */ | 
| 696 | 696 |  	public function getMasterKeyPassword() { | 
| 697 | 697 |  		$password = $this->config->getSystemValue('secret'); | 
| 698 | -		if (empty($password)){ | |
| 698 | +		if (empty($password)) { | |
| 699 | 699 |  			throw new \Exception('Can not get secret from Nextcloud instance'); | 
| 700 | 700 | } | 
| 701 | 701 | |
| @@ -717,6 +717,6 @@ discard block | ||
| 717 | 717 | * @return string | 
| 718 | 718 | */ | 
| 719 | 719 |  	public function getPublicMasterKey() { | 
| 720 | - return $this->keyStorage->getSystemUserKey($this->masterKeyId . '.publicKey', Encryption::ID); | |
| 720 | + return $this->keyStorage->getSystemUserKey($this->masterKeyId.'.publicKey', Encryption::ID); | |
| 721 | 721 | } | 
| 722 | 722 | } | 
| @@ -391,7 +391,7 @@ discard block | ||
| 391 | 391 | /** | 
| 392 | 392 | * store remote ID in federated reShare table | 
| 393 | 393 | * | 
| 394 | - * @param $shareId | |
| 394 | + * @param integer $shareId | |
| 395 | 395 | * @param $remoteId | 
| 396 | 396 | */ | 
| 397 | 397 |  	public function storeRemoteId($shareId, $remoteId) { | 
| @@ -729,7 +729,7 @@ discard block | ||
| 729 | 729 | /** | 
| 730 | 730 | * get database row of a give share | 
| 731 | 731 | * | 
| 732 | - * @param $id | |
| 732 | + * @param integer $id | |
| 733 | 733 | * @return array | 
| 734 | 734 | * @throws ShareNotFound | 
| 735 | 735 | */ | 
| @@ -182,7 +182,7 @@ discard block | ||
| 182 | 182 |  		if ($remoteShare) { | 
| 183 | 183 |  			try { | 
| 184 | 184 | $ownerCloudId = $this->cloudIdManager->getCloudId($remoteShare['owner'], $remoteShare['remote']); | 
| 185 | - $shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_' . time()); | |
| 185 | + $shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_'.time()); | |
| 186 | 186 | $share->setId($shareId); | 
| 187 | 187 | list($token, $remoteId) = $this->askOwnerToReShare($shareWith, $share, $shareId); | 
| 188 | 188 | // remote share was create successfully if we get a valid token as return | 
| @@ -254,11 +254,11 @@ discard block | ||
| 254 | 254 | $failure = true; | 
| 255 | 255 | } | 
| 256 | 256 |  		} catch (\Exception $e) { | 
| 257 | -			$this->logger->error('Failed to notify remote server of federated share, removing share (' . $e->getMessage() . ')'); | |
| 257 | +			$this->logger->error('Failed to notify remote server of federated share, removing share ('.$e->getMessage().')'); | |
| 258 | 258 | $failure = true; | 
| 259 | 259 | } | 
| 260 | 260 | |
| 261 | -		if($failure) { | |
| 261 | +		if ($failure) { | |
| 262 | 262 | $this->removeShareFromTableById($shareId); | 
| 263 | 263 |  			$message_t = $this->l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable or uses a self-signed certificate.', | 
| 264 | 264 | [$share->getNode()->getName(), $share->getSharedWith()]); | 
| @@ -309,7 +309,7 @@ discard block | ||
| 309 | 309 |  			->andWhere($query->expr()->eq('mountpoint', $query->createNamedParameter($share->getTarget()))); | 
| 310 | 310 | $result = $query->execute()->fetchAll(); | 
| 311 | 311 | |
| 312 | -		if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) { | |
| 312 | +		if (isset($result[0]) && (int) $result[0]['remote_id'] > 0) { | |
| 313 | 313 | return $result[0]; | 
| 314 | 314 | } | 
| 315 | 315 | |
| @@ -351,7 +351,7 @@ discard block | ||
| 351 | 351 | $qb->execute(); | 
| 352 | 352 | $id = $qb->getLastInsertId(); | 
| 353 | 353 | |
| 354 | - return (int)$id; | |
| 354 | + return (int) $id; | |
| 355 | 355 | } | 
| 356 | 356 | |
| 357 | 357 | /** | 
| @@ -441,14 +441,14 @@ discard block | ||
| 441 | 441 |  	public function getRemoteId(IShare $share) { | 
| 442 | 442 | $query = $this->dbConnection->getQueryBuilder(); | 
| 443 | 443 |  		$query->select('remote_id')->from('federated_reshares') | 
| 444 | -			->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId()))); | |
| 444 | +			->where($query->expr()->eq('share_id', $query->createNamedParameter((int) $share->getId()))); | |
| 445 | 445 | $data = $query->execute()->fetch(); | 
| 446 | 446 | |
| 447 | 447 |  		if (!is_array($data) || !isset($data['remote_id'])) { | 
| 448 | 448 | throw new ShareNotFound(); | 
| 449 | 449 | } | 
| 450 | 450 | |
| 451 | - return (int)$data['remote_id']; | |
| 451 | + return (int) $data['remote_id']; | |
| 452 | 452 | } | 
| 453 | 453 | |
| 454 | 454 | /** | 
| @@ -479,7 +479,7 @@ discard block | ||
| 479 | 479 |  			->orderBy('id'); | 
| 480 | 480 | |
| 481 | 481 | $cursor = $qb->execute(); | 
| 482 | -		while($data = $cursor->fetch()) { | |
| 482 | +		while ($data = $cursor->fetch()) { | |
| 483 | 483 | $children[] = $this->createShareObject($data); | 
| 484 | 484 | } | 
| 485 | 485 | $cursor->closeCursor(); | 
| @@ -608,7 +608,7 @@ discard block | ||
| 608 | 608 | ); | 
| 609 | 609 | } | 
| 610 | 610 | |
| 611 | -		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid')); | |
| 611 | +		$qb->innerJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid')); | |
| 612 | 612 |  		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId()))); | 
| 613 | 613 | |
| 614 | 614 |  		$qb->orderBy('id'); | 
| @@ -671,7 +671,7 @@ discard block | ||
| 671 | 671 | |
| 672 | 672 | $cursor = $qb->execute(); | 
| 673 | 673 | $shares = []; | 
| 674 | -		while($data = $cursor->fetch()) { | |
| 674 | +		while ($data = $cursor->fetch()) { | |
| 675 | 675 | $shares[] = $this->createShareObject($data); | 
| 676 | 676 | } | 
| 677 | 677 | $cursor->closeCursor(); | 
| @@ -723,7 +723,7 @@ discard block | ||
| 723 | 723 | ->execute(); | 
| 724 | 724 | |
| 725 | 725 | $shares = []; | 
| 726 | -		while($data = $cursor->fetch()) { | |
| 726 | +		while ($data = $cursor->fetch()) { | |
| 727 | 727 | $shares[] = $this->createShareObject($data); | 
| 728 | 728 | } | 
| 729 | 729 | $cursor->closeCursor(); | 
| @@ -762,7 +762,7 @@ discard block | ||
| 762 | 762 | |
| 763 | 763 | $cursor = $qb->execute(); | 
| 764 | 764 | |
| 765 | -		while($data = $cursor->fetch()) { | |
| 765 | +		while ($data = $cursor->fetch()) { | |
| 766 | 766 | $shares[] = $this->createShareObject($data); | 
| 767 | 767 | } | 
| 768 | 768 | $cursor->closeCursor(); | 
| @@ -839,15 +839,15 @@ discard block | ||
| 839 | 839 |  	private function createShareObject($data) { | 
| 840 | 840 | |
| 841 | 841 | $share = new Share($this->rootFolder, $this->userManager); | 
| 842 | - $share->setId((int)$data['id']) | |
| 843 | - ->setShareType((int)$data['share_type']) | |
| 844 | - ->setPermissions((int)$data['permissions']) | |
| 842 | + $share->setId((int) $data['id']) | |
| 843 | + ->setShareType((int) $data['share_type']) | |
| 844 | + ->setPermissions((int) $data['permissions']) | |
| 845 | 845 | ->setTarget($data['file_target']) | 
| 846 | - ->setMailSend((bool)$data['mail_send']) | |
| 846 | + ->setMailSend((bool) $data['mail_send']) | |
| 847 | 847 | ->setToken($data['token']); | 
| 848 | 848 | |
| 849 | 849 | $shareTime = new \DateTime(); | 
| 850 | - $shareTime->setTimestamp((int)$data['stime']); | |
| 850 | + $shareTime->setTimestamp((int) $data['stime']); | |
| 851 | 851 | $share->setShareTime($shareTime); | 
| 852 | 852 | $share->setSharedWith($data['share_with']); | 
| 853 | 853 | |
| @@ -857,13 +857,13 @@ discard block | ||
| 857 | 857 |  		} else { | 
| 858 | 858 | //OLD SHARE | 
| 859 | 859 | $share->setSharedBy($data['uid_owner']); | 
| 860 | - $path = $this->getNode($share->getSharedBy(), (int)$data['file_source']); | |
| 860 | + $path = $this->getNode($share->getSharedBy(), (int) $data['file_source']); | |
| 861 | 861 | |
| 862 | 862 | $owner = $path->getOwner(); | 
| 863 | 863 | $share->setShareOwner($owner->getUID()); | 
| 864 | 864 | } | 
| 865 | 865 | |
| 866 | - $share->setNodeId((int)$data['file_source']); | |
| 866 | + $share->setNodeId((int) $data['file_source']); | |
| 867 | 867 | $share->setNodeType($data['item_type']); | 
| 868 | 868 | |
| 869 | 869 | $share->setProviderId($this->identifier()); | 
| @@ -50,988 +50,988 @@ | ||
| 50 | 50 | */ | 
| 51 | 51 |  class FederatedShareProvider implements IShareProvider { | 
| 52 | 52 | |
| 53 | - const SHARE_TYPE_REMOTE = 6; | |
| 54 | - | |
| 55 | - /** @var IDBConnection */ | |
| 56 | - private $dbConnection; | |
| 57 | - | |
| 58 | - /** @var AddressHandler */ | |
| 59 | - private $addressHandler; | |
| 60 | - | |
| 61 | - /** @var Notifications */ | |
| 62 | - private $notifications; | |
| 63 | - | |
| 64 | - /** @var TokenHandler */ | |
| 65 | - private $tokenHandler; | |
| 66 | - | |
| 67 | - /** @var IL10N */ | |
| 68 | - private $l; | |
| 69 | - | |
| 70 | - /** @var ILogger */ | |
| 71 | - private $logger; | |
| 72 | - | |
| 73 | - /** @var IRootFolder */ | |
| 74 | - private $rootFolder; | |
| 75 | - | |
| 76 | - /** @var IConfig */ | |
| 77 | - private $config; | |
| 78 | - | |
| 79 | - /** @var string */ | |
| 80 | - private $externalShareTable = 'share_external'; | |
| 81 | - | |
| 82 | - /** @var IUserManager */ | |
| 83 | - private $userManager; | |
| 84 | - | |
| 85 | - /** @var ICloudIdManager */ | |
| 86 | - private $cloudIdManager; | |
| 87 | - | |
| 88 | - /** @var \OCP\GlobalScale\IConfig */ | |
| 89 | - private $gsConfig; | |
| 90 | - | |
| 91 | - /** | |
| 92 | - * DefaultShareProvider constructor. | |
| 93 | - * | |
| 94 | - * @param IDBConnection $connection | |
| 95 | - * @param AddressHandler $addressHandler | |
| 96 | - * @param Notifications $notifications | |
| 97 | - * @param TokenHandler $tokenHandler | |
| 98 | - * @param IL10N $l10n | |
| 99 | - * @param ILogger $logger | |
| 100 | - * @param IRootFolder $rootFolder | |
| 101 | - * @param IConfig $config | |
| 102 | - * @param IUserManager $userManager | |
| 103 | - * @param ICloudIdManager $cloudIdManager | |
| 104 | - * @param \OCP\GlobalScale\IConfig $globalScaleConfig | |
| 105 | - */ | |
| 106 | - public function __construct( | |
| 107 | - IDBConnection $connection, | |
| 108 | - AddressHandler $addressHandler, | |
| 109 | - Notifications $notifications, | |
| 110 | - TokenHandler $tokenHandler, | |
| 111 | - IL10N $l10n, | |
| 112 | - ILogger $logger, | |
| 113 | - IRootFolder $rootFolder, | |
| 114 | - IConfig $config, | |
| 115 | - IUserManager $userManager, | |
| 116 | - ICloudIdManager $cloudIdManager, | |
| 117 | - \OCP\GlobalScale\IConfig $globalScaleConfig | |
| 118 | -	) { | |
| 119 | - $this->dbConnection = $connection; | |
| 120 | - $this->addressHandler = $addressHandler; | |
| 121 | - $this->notifications = $notifications; | |
| 122 | - $this->tokenHandler = $tokenHandler; | |
| 123 | - $this->l = $l10n; | |
| 124 | - $this->logger = $logger; | |
| 125 | - $this->rootFolder = $rootFolder; | |
| 126 | - $this->config = $config; | |
| 127 | - $this->userManager = $userManager; | |
| 128 | - $this->cloudIdManager = $cloudIdManager; | |
| 129 | - $this->gsConfig = $globalScaleConfig; | |
| 130 | - } | |
| 131 | - | |
| 132 | - /** | |
| 133 | - * Return the identifier of this provider. | |
| 134 | - * | |
| 135 | - * @return string Containing only [a-zA-Z0-9] | |
| 136 | - */ | |
| 137 | -	public function identifier() { | |
| 138 | - return 'ocFederatedSharing'; | |
| 139 | - } | |
| 140 | - | |
| 141 | - /** | |
| 142 | - * Share a path | |
| 143 | - * | |
| 144 | - * @param IShare $share | |
| 145 | - * @return IShare The share object | |
| 146 | - * @throws ShareNotFound | |
| 147 | - * @throws \Exception | |
| 148 | - */ | |
| 149 | -	public function create(IShare $share) { | |
| 150 | - | |
| 151 | - $shareWith = $share->getSharedWith(); | |
| 152 | - $itemSource = $share->getNodeId(); | |
| 153 | - $itemType = $share->getNodeType(); | |
| 154 | - $permissions = $share->getPermissions(); | |
| 155 | - $sharedBy = $share->getSharedBy(); | |
| 156 | - | |
| 157 | - /* | |
| 53 | + const SHARE_TYPE_REMOTE = 6; | |
| 54 | + | |
| 55 | + /** @var IDBConnection */ | |
| 56 | + private $dbConnection; | |
| 57 | + | |
| 58 | + /** @var AddressHandler */ | |
| 59 | + private $addressHandler; | |
| 60 | + | |
| 61 | + /** @var Notifications */ | |
| 62 | + private $notifications; | |
| 63 | + | |
| 64 | + /** @var TokenHandler */ | |
| 65 | + private $tokenHandler; | |
| 66 | + | |
| 67 | + /** @var IL10N */ | |
| 68 | + private $l; | |
| 69 | + | |
| 70 | + /** @var ILogger */ | |
| 71 | + private $logger; | |
| 72 | + | |
| 73 | + /** @var IRootFolder */ | |
| 74 | + private $rootFolder; | |
| 75 | + | |
| 76 | + /** @var IConfig */ | |
| 77 | + private $config; | |
| 78 | + | |
| 79 | + /** @var string */ | |
| 80 | + private $externalShareTable = 'share_external'; | |
| 81 | + | |
| 82 | + /** @var IUserManager */ | |
| 83 | + private $userManager; | |
| 84 | + | |
| 85 | + /** @var ICloudIdManager */ | |
| 86 | + private $cloudIdManager; | |
| 87 | + | |
| 88 | + /** @var \OCP\GlobalScale\IConfig */ | |
| 89 | + private $gsConfig; | |
| 90 | + | |
| 91 | + /** | |
| 92 | + * DefaultShareProvider constructor. | |
| 93 | + * | |
| 94 | + * @param IDBConnection $connection | |
| 95 | + * @param AddressHandler $addressHandler | |
| 96 | + * @param Notifications $notifications | |
| 97 | + * @param TokenHandler $tokenHandler | |
| 98 | + * @param IL10N $l10n | |
| 99 | + * @param ILogger $logger | |
| 100 | + * @param IRootFolder $rootFolder | |
| 101 | + * @param IConfig $config | |
| 102 | + * @param IUserManager $userManager | |
| 103 | + * @param ICloudIdManager $cloudIdManager | |
| 104 | + * @param \OCP\GlobalScale\IConfig $globalScaleConfig | |
| 105 | + */ | |
| 106 | + public function __construct( | |
| 107 | + IDBConnection $connection, | |
| 108 | + AddressHandler $addressHandler, | |
| 109 | + Notifications $notifications, | |
| 110 | + TokenHandler $tokenHandler, | |
| 111 | + IL10N $l10n, | |
| 112 | + ILogger $logger, | |
| 113 | + IRootFolder $rootFolder, | |
| 114 | + IConfig $config, | |
| 115 | + IUserManager $userManager, | |
| 116 | + ICloudIdManager $cloudIdManager, | |
| 117 | + \OCP\GlobalScale\IConfig $globalScaleConfig | |
| 118 | +    ) { | |
| 119 | + $this->dbConnection = $connection; | |
| 120 | + $this->addressHandler = $addressHandler; | |
| 121 | + $this->notifications = $notifications; | |
| 122 | + $this->tokenHandler = $tokenHandler; | |
| 123 | + $this->l = $l10n; | |
| 124 | + $this->logger = $logger; | |
| 125 | + $this->rootFolder = $rootFolder; | |
| 126 | + $this->config = $config; | |
| 127 | + $this->userManager = $userManager; | |
| 128 | + $this->cloudIdManager = $cloudIdManager; | |
| 129 | + $this->gsConfig = $globalScaleConfig; | |
| 130 | + } | |
| 131 | + | |
| 132 | + /** | |
| 133 | + * Return the identifier of this provider. | |
| 134 | + * | |
| 135 | + * @return string Containing only [a-zA-Z0-9] | |
| 136 | + */ | |
| 137 | +    public function identifier() { | |
| 138 | + return 'ocFederatedSharing'; | |
| 139 | + } | |
| 140 | + | |
| 141 | + /** | |
| 142 | + * Share a path | |
| 143 | + * | |
| 144 | + * @param IShare $share | |
| 145 | + * @return IShare The share object | |
| 146 | + * @throws ShareNotFound | |
| 147 | + * @throws \Exception | |
| 148 | + */ | |
| 149 | +    public function create(IShare $share) { | |
| 150 | + | |
| 151 | + $shareWith = $share->getSharedWith(); | |
| 152 | + $itemSource = $share->getNodeId(); | |
| 153 | + $itemType = $share->getNodeType(); | |
| 154 | + $permissions = $share->getPermissions(); | |
| 155 | + $sharedBy = $share->getSharedBy(); | |
| 156 | + | |
| 157 | + /* | |
| 158 | 158 | * Check if file is not already shared with the remote user | 
| 159 | 159 | */ | 
| 160 | - $alreadyShared = $this->getSharedWith($shareWith, self::SHARE_TYPE_REMOTE, $share->getNode(), 1, 0); | |
| 161 | -		if (!empty($alreadyShared)) { | |
| 162 | - $message = 'Sharing %s failed, because this item is already shared with %s'; | |
| 163 | -			$message_t = $this->l->t('Sharing %s failed, because this item is already shared with %s', array($share->getNode()->getName(), $shareWith)); | |
| 164 | - $this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']); | |
| 165 | - throw new \Exception($message_t); | |
| 166 | - } | |
| 167 | - | |
| 168 | - | |
| 169 | - // don't allow federated shares if source and target server are the same | |
| 170 | - $cloudId = $this->cloudIdManager->resolveCloudId($shareWith); | |
| 171 | - $currentServer = $this->addressHandler->generateRemoteURL(); | |
| 172 | - $currentUser = $sharedBy; | |
| 173 | -		if ($this->addressHandler->compareAddresses($cloudId->getUser(), $cloudId->getRemote(), $currentUser, $currentServer)) { | |
| 174 | - $message = 'Not allowed to create a federated share with the same user.'; | |
| 175 | -			$message_t = $this->l->t('Not allowed to create a federated share with the same user'); | |
| 176 | - $this->logger->debug($message, ['app' => 'Federated File Sharing']); | |
| 177 | - throw new \Exception($message_t); | |
| 178 | - } | |
| 179 | - | |
| 180 | - | |
| 181 | - $share->setSharedWith($cloudId->getId()); | |
| 182 | - | |
| 183 | -		try { | |
| 184 | - $remoteShare = $this->getShareFromExternalShareTable($share); | |
| 185 | -		} catch (ShareNotFound $e) { | |
| 186 | - $remoteShare = null; | |
| 187 | - } | |
| 188 | - | |
| 189 | -		if ($remoteShare) { | |
| 190 | -			try { | |
| 191 | - $ownerCloudId = $this->cloudIdManager->getCloudId($remoteShare['owner'], $remoteShare['remote']); | |
| 192 | - $shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_' . time()); | |
| 193 | - $share->setId($shareId); | |
| 194 | - list($token, $remoteId) = $this->askOwnerToReShare($shareWith, $share, $shareId); | |
| 195 | - // remote share was create successfully if we get a valid token as return | |
| 196 | - $send = is_string($token) && $token !== ''; | |
| 197 | -			} catch (\Exception $e) { | |
| 198 | - // fall back to old re-share behavior if the remote server | |
| 199 | - // doesn't support flat re-shares (was introduced with Nextcloud 9.1) | |
| 200 | - $this->removeShareFromTable($share); | |
| 201 | - $shareId = $this->createFederatedShare($share); | |
| 202 | - } | |
| 203 | -			if ($send) { | |
| 204 | - $this->updateSuccessfulReshare($shareId, $token); | |
| 205 | - $this->storeRemoteId($shareId, $remoteId); | |
| 206 | -			} else { | |
| 207 | - $this->removeShareFromTable($share); | |
| 208 | -				$message_t = $this->l->t('File is already shared with %s', [$shareWith]); | |
| 209 | - throw new \Exception($message_t); | |
| 210 | - } | |
| 211 | - | |
| 212 | -		} else { | |
| 213 | - $shareId = $this->createFederatedShare($share); | |
| 214 | - } | |
| 215 | - | |
| 216 | - $data = $this->getRawShare($shareId); | |
| 217 | - return $this->createShareObject($data); | |
| 218 | - } | |
| 219 | - | |
| 220 | - /** | |
| 221 | - * create federated share and inform the recipient | |
| 222 | - * | |
| 223 | - * @param IShare $share | |
| 224 | - * @return int | |
| 225 | - * @throws ShareNotFound | |
| 226 | - * @throws \Exception | |
| 227 | - */ | |
| 228 | -	protected function createFederatedShare(IShare $share) { | |
| 229 | - $token = $this->tokenHandler->generateToken(); | |
| 230 | - $shareId = $this->addShareToDB( | |
| 231 | - $share->getNodeId(), | |
| 232 | - $share->getNodeType(), | |
| 233 | - $share->getSharedWith(), | |
| 234 | - $share->getSharedBy(), | |
| 235 | - $share->getShareOwner(), | |
| 236 | - $share->getPermissions(), | |
| 237 | - $token | |
| 238 | - ); | |
| 239 | - | |
| 240 | - $failure = false; | |
| 241 | - | |
| 242 | -		try { | |
| 243 | - $sharedByFederatedId = $share->getSharedBy(); | |
| 244 | -			if ($this->userManager->userExists($sharedByFederatedId)) { | |
| 245 | - $cloudId = $this->cloudIdManager->getCloudId($sharedByFederatedId, $this->addressHandler->generateRemoteURL()); | |
| 246 | - $sharedByFederatedId = $cloudId->getId(); | |
| 247 | - } | |
| 248 | - $ownerCloudId = $this->cloudIdManager->getCloudId($share->getShareOwner(), $this->addressHandler->generateRemoteURL()); | |
| 249 | - $send = $this->notifications->sendRemoteShare( | |
| 250 | - $token, | |
| 251 | - $share->getSharedWith(), | |
| 252 | - $share->getNode()->getName(), | |
| 253 | - $shareId, | |
| 254 | - $share->getShareOwner(), | |
| 255 | - $ownerCloudId->getId(), | |
| 256 | - $share->getSharedBy(), | |
| 257 | - $sharedByFederatedId | |
| 258 | - ); | |
| 259 | - | |
| 260 | -			if ($send === false) { | |
| 261 | - $failure = true; | |
| 262 | - } | |
| 263 | -		} catch (\Exception $e) { | |
| 264 | -			$this->logger->error('Failed to notify remote server of federated share, removing share (' . $e->getMessage() . ')'); | |
| 265 | - $failure = true; | |
| 266 | - } | |
| 267 | - | |
| 268 | -		if($failure) { | |
| 269 | - $this->removeShareFromTableById($shareId); | |
| 270 | -			$message_t = $this->l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable or uses a self-signed certificate.', | |
| 271 | - [$share->getNode()->getName(), $share->getSharedWith()]); | |
| 272 | - throw new \Exception($message_t); | |
| 273 | - } | |
| 274 | - | |
| 275 | - return $shareId; | |
| 276 | - | |
| 277 | - } | |
| 278 | - | |
| 279 | - /** | |
| 280 | - * @param string $shareWith | |
| 281 | - * @param IShare $share | |
| 282 | - * @param string $shareId internal share Id | |
| 283 | - * @return array | |
| 284 | - * @throws \Exception | |
| 285 | - */ | |
| 286 | -	protected function askOwnerToReShare($shareWith, IShare $share, $shareId) { | |
| 287 | - | |
| 288 | - $remoteShare = $this->getShareFromExternalShareTable($share); | |
| 289 | - $token = $remoteShare['share_token']; | |
| 290 | - $remoteId = $remoteShare['remote_id']; | |
| 291 | - $remote = $remoteShare['remote']; | |
| 292 | - | |
| 293 | - list($token, $remoteId) = $this->notifications->requestReShare( | |
| 294 | - $token, | |
| 295 | - $remoteId, | |
| 296 | - $shareId, | |
| 297 | - $remote, | |
| 298 | - $shareWith, | |
| 299 | - $share->getPermissions() | |
| 300 | - ); | |
| 301 | - | |
| 302 | - return [$token, $remoteId]; | |
| 303 | - } | |
| 304 | - | |
| 305 | - /** | |
| 306 | - * get federated share from the share_external table but exclude mounted link shares | |
| 307 | - * | |
| 308 | - * @param IShare $share | |
| 309 | - * @return array | |
| 310 | - * @throws ShareNotFound | |
| 311 | - */ | |
| 312 | -	protected function getShareFromExternalShareTable(IShare $share) { | |
| 313 | - $query = $this->dbConnection->getQueryBuilder(); | |
| 314 | -		$query->select('*')->from($this->externalShareTable) | |
| 315 | -			->where($query->expr()->eq('user', $query->createNamedParameter($share->getShareOwner()))) | |
| 316 | -			->andWhere($query->expr()->eq('mountpoint', $query->createNamedParameter($share->getTarget()))); | |
| 317 | - $result = $query->execute()->fetchAll(); | |
| 318 | - | |
| 319 | -		if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) { | |
| 320 | - return $result[0]; | |
| 321 | - } | |
| 322 | - | |
| 323 | -		throw new ShareNotFound('share not found in share_external table'); | |
| 324 | - } | |
| 325 | - | |
| 326 | - /** | |
| 327 | - * add share to the database and return the ID | |
| 328 | - * | |
| 329 | - * @param int $itemSource | |
| 330 | - * @param string $itemType | |
| 331 | - * @param string $shareWith | |
| 332 | - * @param string $sharedBy | |
| 333 | - * @param string $uidOwner | |
| 334 | - * @param int $permissions | |
| 335 | - * @param string $token | |
| 336 | - * @return int | |
| 337 | - */ | |
| 338 | -	private function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) { | |
| 339 | - $qb = $this->dbConnection->getQueryBuilder(); | |
| 340 | -		$qb->insert('share') | |
| 341 | -			->setValue('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)) | |
| 342 | -			->setValue('item_type', $qb->createNamedParameter($itemType)) | |
| 343 | -			->setValue('item_source', $qb->createNamedParameter($itemSource)) | |
| 344 | -			->setValue('file_source', $qb->createNamedParameter($itemSource)) | |
| 345 | -			->setValue('share_with', $qb->createNamedParameter($shareWith)) | |
| 346 | -			->setValue('uid_owner', $qb->createNamedParameter($uidOwner)) | |
| 347 | -			->setValue('uid_initiator', $qb->createNamedParameter($sharedBy)) | |
| 348 | -			->setValue('permissions', $qb->createNamedParameter($permissions)) | |
| 349 | -			->setValue('token', $qb->createNamedParameter($token)) | |
| 350 | -			->setValue('stime', $qb->createNamedParameter(time())); | |
| 351 | - | |
| 352 | - /* | |
| 160 | + $alreadyShared = $this->getSharedWith($shareWith, self::SHARE_TYPE_REMOTE, $share->getNode(), 1, 0); | |
| 161 | +        if (!empty($alreadyShared)) { | |
| 162 | + $message = 'Sharing %s failed, because this item is already shared with %s'; | |
| 163 | +            $message_t = $this->l->t('Sharing %s failed, because this item is already shared with %s', array($share->getNode()->getName(), $shareWith)); | |
| 164 | + $this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']); | |
| 165 | + throw new \Exception($message_t); | |
| 166 | + } | |
| 167 | + | |
| 168 | + | |
| 169 | + // don't allow federated shares if source and target server are the same | |
| 170 | + $cloudId = $this->cloudIdManager->resolveCloudId($shareWith); | |
| 171 | + $currentServer = $this->addressHandler->generateRemoteURL(); | |
| 172 | + $currentUser = $sharedBy; | |
| 173 | +        if ($this->addressHandler->compareAddresses($cloudId->getUser(), $cloudId->getRemote(), $currentUser, $currentServer)) { | |
| 174 | + $message = 'Not allowed to create a federated share with the same user.'; | |
| 175 | +            $message_t = $this->l->t('Not allowed to create a federated share with the same user'); | |
| 176 | + $this->logger->debug($message, ['app' => 'Federated File Sharing']); | |
| 177 | + throw new \Exception($message_t); | |
| 178 | + } | |
| 179 | + | |
| 180 | + | |
| 181 | + $share->setSharedWith($cloudId->getId()); | |
| 182 | + | |
| 183 | +        try { | |
| 184 | + $remoteShare = $this->getShareFromExternalShareTable($share); | |
| 185 | +        } catch (ShareNotFound $e) { | |
| 186 | + $remoteShare = null; | |
| 187 | + } | |
| 188 | + | |
| 189 | +        if ($remoteShare) { | |
| 190 | +            try { | |
| 191 | + $ownerCloudId = $this->cloudIdManager->getCloudId($remoteShare['owner'], $remoteShare['remote']); | |
| 192 | + $shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_' . time()); | |
| 193 | + $share->setId($shareId); | |
| 194 | + list($token, $remoteId) = $this->askOwnerToReShare($shareWith, $share, $shareId); | |
| 195 | + // remote share was create successfully if we get a valid token as return | |
| 196 | + $send = is_string($token) && $token !== ''; | |
| 197 | +            } catch (\Exception $e) { | |
| 198 | + // fall back to old re-share behavior if the remote server | |
| 199 | + // doesn't support flat re-shares (was introduced with Nextcloud 9.1) | |
| 200 | + $this->removeShareFromTable($share); | |
| 201 | + $shareId = $this->createFederatedShare($share); | |
| 202 | + } | |
| 203 | +            if ($send) { | |
| 204 | + $this->updateSuccessfulReshare($shareId, $token); | |
| 205 | + $this->storeRemoteId($shareId, $remoteId); | |
| 206 | +            } else { | |
| 207 | + $this->removeShareFromTable($share); | |
| 208 | +                $message_t = $this->l->t('File is already shared with %s', [$shareWith]); | |
| 209 | + throw new \Exception($message_t); | |
| 210 | + } | |
| 211 | + | |
| 212 | +        } else { | |
| 213 | + $shareId = $this->createFederatedShare($share); | |
| 214 | + } | |
| 215 | + | |
| 216 | + $data = $this->getRawShare($shareId); | |
| 217 | + return $this->createShareObject($data); | |
| 218 | + } | |
| 219 | + | |
| 220 | + /** | |
| 221 | + * create federated share and inform the recipient | |
| 222 | + * | |
| 223 | + * @param IShare $share | |
| 224 | + * @return int | |
| 225 | + * @throws ShareNotFound | |
| 226 | + * @throws \Exception | |
| 227 | + */ | |
| 228 | +    protected function createFederatedShare(IShare $share) { | |
| 229 | + $token = $this->tokenHandler->generateToken(); | |
| 230 | + $shareId = $this->addShareToDB( | |
| 231 | + $share->getNodeId(), | |
| 232 | + $share->getNodeType(), | |
| 233 | + $share->getSharedWith(), | |
| 234 | + $share->getSharedBy(), | |
| 235 | + $share->getShareOwner(), | |
| 236 | + $share->getPermissions(), | |
| 237 | + $token | |
| 238 | + ); | |
| 239 | + | |
| 240 | + $failure = false; | |
| 241 | + | |
| 242 | +        try { | |
| 243 | + $sharedByFederatedId = $share->getSharedBy(); | |
| 244 | +            if ($this->userManager->userExists($sharedByFederatedId)) { | |
| 245 | + $cloudId = $this->cloudIdManager->getCloudId($sharedByFederatedId, $this->addressHandler->generateRemoteURL()); | |
| 246 | + $sharedByFederatedId = $cloudId->getId(); | |
| 247 | + } | |
| 248 | + $ownerCloudId = $this->cloudIdManager->getCloudId($share->getShareOwner(), $this->addressHandler->generateRemoteURL()); | |
| 249 | + $send = $this->notifications->sendRemoteShare( | |
| 250 | + $token, | |
| 251 | + $share->getSharedWith(), | |
| 252 | + $share->getNode()->getName(), | |
| 253 | + $shareId, | |
| 254 | + $share->getShareOwner(), | |
| 255 | + $ownerCloudId->getId(), | |
| 256 | + $share->getSharedBy(), | |
| 257 | + $sharedByFederatedId | |
| 258 | + ); | |
| 259 | + | |
| 260 | +            if ($send === false) { | |
| 261 | + $failure = true; | |
| 262 | + } | |
| 263 | +        } catch (\Exception $e) { | |
| 264 | +            $this->logger->error('Failed to notify remote server of federated share, removing share (' . $e->getMessage() . ')'); | |
| 265 | + $failure = true; | |
| 266 | + } | |
| 267 | + | |
| 268 | +        if($failure) { | |
| 269 | + $this->removeShareFromTableById($shareId); | |
| 270 | +            $message_t = $this->l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable or uses a self-signed certificate.', | |
| 271 | + [$share->getNode()->getName(), $share->getSharedWith()]); | |
| 272 | + throw new \Exception($message_t); | |
| 273 | + } | |
| 274 | + | |
| 275 | + return $shareId; | |
| 276 | + | |
| 277 | + } | |
| 278 | + | |
| 279 | + /** | |
| 280 | + * @param string $shareWith | |
| 281 | + * @param IShare $share | |
| 282 | + * @param string $shareId internal share Id | |
| 283 | + * @return array | |
| 284 | + * @throws \Exception | |
| 285 | + */ | |
| 286 | +    protected function askOwnerToReShare($shareWith, IShare $share, $shareId) { | |
| 287 | + | |
| 288 | + $remoteShare = $this->getShareFromExternalShareTable($share); | |
| 289 | + $token = $remoteShare['share_token']; | |
| 290 | + $remoteId = $remoteShare['remote_id']; | |
| 291 | + $remote = $remoteShare['remote']; | |
| 292 | + | |
| 293 | + list($token, $remoteId) = $this->notifications->requestReShare( | |
| 294 | + $token, | |
| 295 | + $remoteId, | |
| 296 | + $shareId, | |
| 297 | + $remote, | |
| 298 | + $shareWith, | |
| 299 | + $share->getPermissions() | |
| 300 | + ); | |
| 301 | + | |
| 302 | + return [$token, $remoteId]; | |
| 303 | + } | |
| 304 | + | |
| 305 | + /** | |
| 306 | + * get federated share from the share_external table but exclude mounted link shares | |
| 307 | + * | |
| 308 | + * @param IShare $share | |
| 309 | + * @return array | |
| 310 | + * @throws ShareNotFound | |
| 311 | + */ | |
| 312 | +    protected function getShareFromExternalShareTable(IShare $share) { | |
| 313 | + $query = $this->dbConnection->getQueryBuilder(); | |
| 314 | +        $query->select('*')->from($this->externalShareTable) | |
| 315 | +            ->where($query->expr()->eq('user', $query->createNamedParameter($share->getShareOwner()))) | |
| 316 | +            ->andWhere($query->expr()->eq('mountpoint', $query->createNamedParameter($share->getTarget()))); | |
| 317 | + $result = $query->execute()->fetchAll(); | |
| 318 | + | |
| 319 | +        if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) { | |
| 320 | + return $result[0]; | |
| 321 | + } | |
| 322 | + | |
| 323 | +        throw new ShareNotFound('share not found in share_external table'); | |
| 324 | + } | |
| 325 | + | |
| 326 | + /** | |
| 327 | + * add share to the database and return the ID | |
| 328 | + * | |
| 329 | + * @param int $itemSource | |
| 330 | + * @param string $itemType | |
| 331 | + * @param string $shareWith | |
| 332 | + * @param string $sharedBy | |
| 333 | + * @param string $uidOwner | |
| 334 | + * @param int $permissions | |
| 335 | + * @param string $token | |
| 336 | + * @return int | |
| 337 | + */ | |
| 338 | +    private function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) { | |
| 339 | + $qb = $this->dbConnection->getQueryBuilder(); | |
| 340 | +        $qb->insert('share') | |
| 341 | +            ->setValue('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)) | |
| 342 | +            ->setValue('item_type', $qb->createNamedParameter($itemType)) | |
| 343 | +            ->setValue('item_source', $qb->createNamedParameter($itemSource)) | |
| 344 | +            ->setValue('file_source', $qb->createNamedParameter($itemSource)) | |
| 345 | +            ->setValue('share_with', $qb->createNamedParameter($shareWith)) | |
| 346 | +            ->setValue('uid_owner', $qb->createNamedParameter($uidOwner)) | |
| 347 | +            ->setValue('uid_initiator', $qb->createNamedParameter($sharedBy)) | |
| 348 | +            ->setValue('permissions', $qb->createNamedParameter($permissions)) | |
| 349 | +            ->setValue('token', $qb->createNamedParameter($token)) | |
| 350 | +            ->setValue('stime', $qb->createNamedParameter(time())); | |
| 351 | + | |
| 352 | + /* | |
| 353 | 353 | * Added to fix https://github.com/owncloud/core/issues/22215 | 
| 354 | 354 | * Can be removed once we get rid of ajax/share.php | 
| 355 | 355 | */ | 
| 356 | -		$qb->setValue('file_target', $qb->createNamedParameter('')); | |
| 357 | - | |
| 358 | - $qb->execute(); | |
| 359 | - $id = $qb->getLastInsertId(); | |
| 360 | - | |
| 361 | - return (int)$id; | |
| 362 | - } | |
| 363 | - | |
| 364 | - /** | |
| 365 | - * Update a share | |
| 366 | - * | |
| 367 | - * @param IShare $share | |
| 368 | - * @return IShare The share object | |
| 369 | - */ | |
| 370 | -	public function update(IShare $share) { | |
| 371 | - /* | |
| 356 | +        $qb->setValue('file_target', $qb->createNamedParameter('')); | |
| 357 | + | |
| 358 | + $qb->execute(); | |
| 359 | + $id = $qb->getLastInsertId(); | |
| 360 | + | |
| 361 | + return (int)$id; | |
| 362 | + } | |
| 363 | + | |
| 364 | + /** | |
| 365 | + * Update a share | |
| 366 | + * | |
| 367 | + * @param IShare $share | |
| 368 | + * @return IShare The share object | |
| 369 | + */ | |
| 370 | +    public function update(IShare $share) { | |
| 371 | + /* | |
| 372 | 372 | * We allow updating the permissions of federated shares | 
| 373 | 373 | */ | 
| 374 | - $qb = $this->dbConnection->getQueryBuilder(); | |
| 375 | -			$qb->update('share') | |
| 376 | -				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId()))) | |
| 377 | -				->set('permissions', $qb->createNamedParameter($share->getPermissions())) | |
| 378 | -				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner())) | |
| 379 | -				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy())) | |
| 380 | - ->execute(); | |
| 381 | - | |
| 382 | - // send the updated permission to the owner/initiator, if they are not the same | |
| 383 | -		if ($share->getShareOwner() !== $share->getSharedBy()) { | |
| 384 | - $this->sendPermissionUpdate($share); | |
| 385 | - } | |
| 386 | - | |
| 387 | - return $share; | |
| 388 | - } | |
| 389 | - | |
| 390 | - /** | |
| 391 | - * send the updated permission to the owner/initiator, if they are not the same | |
| 392 | - * | |
| 393 | - * @param IShare $share | |
| 394 | - * @throws ShareNotFound | |
| 395 | - * @throws \OC\HintException | |
| 396 | - */ | |
| 397 | -	protected function sendPermissionUpdate(IShare $share) { | |
| 398 | - $remoteId = $this->getRemoteId($share); | |
| 399 | - // if the local user is the owner we send the permission change to the initiator | |
| 400 | -		if ($this->userManager->userExists($share->getShareOwner())) { | |
| 401 | - list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy()); | |
| 402 | -		} else { // ... if not we send the permission change to the owner | |
| 403 | - list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner()); | |
| 404 | - } | |
| 405 | - $this->notifications->sendPermissionChange($remote, $remoteId, $share->getToken(), $share->getPermissions()); | |
| 406 | - } | |
| 407 | - | |
| 408 | - | |
| 409 | - /** | |
| 410 | - * update successful reShare with the correct token | |
| 411 | - * | |
| 412 | - * @param int $shareId | |
| 413 | - * @param string $token | |
| 414 | - */ | |
| 415 | -	protected function updateSuccessfulReShare($shareId, $token) { | |
| 416 | - $query = $this->dbConnection->getQueryBuilder(); | |
| 417 | -		$query->update('share') | |
| 418 | -			->where($query->expr()->eq('id', $query->createNamedParameter($shareId))) | |
| 419 | -			->set('token', $query->createNamedParameter($token)) | |
| 420 | - ->execute(); | |
| 421 | - } | |
| 422 | - | |
| 423 | - /** | |
| 424 | - * store remote ID in federated reShare table | |
| 425 | - * | |
| 426 | - * @param $shareId | |
| 427 | - * @param $remoteId | |
| 428 | - */ | |
| 429 | -	public function storeRemoteId($shareId, $remoteId) { | |
| 430 | - $query = $this->dbConnection->getQueryBuilder(); | |
| 431 | -		$query->insert('federated_reshares') | |
| 432 | - ->values( | |
| 433 | - [ | |
| 434 | - 'share_id' => $query->createNamedParameter($shareId), | |
| 435 | - 'remote_id' => $query->createNamedParameter($remoteId), | |
| 436 | - ] | |
| 437 | - ); | |
| 438 | - $query->execute(); | |
| 439 | - } | |
| 440 | - | |
| 441 | - /** | |
| 442 | - * get share ID on remote server for federated re-shares | |
| 443 | - * | |
| 444 | - * @param IShare $share | |
| 445 | - * @return int | |
| 446 | - * @throws ShareNotFound | |
| 447 | - */ | |
| 448 | -	public function getRemoteId(IShare $share) { | |
| 449 | - $query = $this->dbConnection->getQueryBuilder(); | |
| 450 | -		$query->select('remote_id')->from('federated_reshares') | |
| 451 | -			->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId()))); | |
| 452 | - $data = $query->execute()->fetch(); | |
| 453 | - | |
| 454 | -		if (!is_array($data) || !isset($data['remote_id'])) { | |
| 455 | - throw new ShareNotFound(); | |
| 456 | - } | |
| 457 | - | |
| 458 | - return (int)$data['remote_id']; | |
| 459 | - } | |
| 460 | - | |
| 461 | - /** | |
| 462 | - * @inheritdoc | |
| 463 | - */ | |
| 464 | -	public function move(IShare $share, $recipient) { | |
| 465 | - /* | |
| 374 | + $qb = $this->dbConnection->getQueryBuilder(); | |
| 375 | +            $qb->update('share') | |
| 376 | +                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId()))) | |
| 377 | +                ->set('permissions', $qb->createNamedParameter($share->getPermissions())) | |
| 378 | +                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner())) | |
| 379 | +                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy())) | |
| 380 | + ->execute(); | |
| 381 | + | |
| 382 | + // send the updated permission to the owner/initiator, if they are not the same | |
| 383 | +        if ($share->getShareOwner() !== $share->getSharedBy()) { | |
| 384 | + $this->sendPermissionUpdate($share); | |
| 385 | + } | |
| 386 | + | |
| 387 | + return $share; | |
| 388 | + } | |
| 389 | + | |
| 390 | + /** | |
| 391 | + * send the updated permission to the owner/initiator, if they are not the same | |
| 392 | + * | |
| 393 | + * @param IShare $share | |
| 394 | + * @throws ShareNotFound | |
| 395 | + * @throws \OC\HintException | |
| 396 | + */ | |
| 397 | +    protected function sendPermissionUpdate(IShare $share) { | |
| 398 | + $remoteId = $this->getRemoteId($share); | |
| 399 | + // if the local user is the owner we send the permission change to the initiator | |
| 400 | +        if ($this->userManager->userExists($share->getShareOwner())) { | |
| 401 | + list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy()); | |
| 402 | +        } else { // ... if not we send the permission change to the owner | |
| 403 | + list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner()); | |
| 404 | + } | |
| 405 | + $this->notifications->sendPermissionChange($remote, $remoteId, $share->getToken(), $share->getPermissions()); | |
| 406 | + } | |
| 407 | + | |
| 408 | + | |
| 409 | + /** | |
| 410 | + * update successful reShare with the correct token | |
| 411 | + * | |
| 412 | + * @param int $shareId | |
| 413 | + * @param string $token | |
| 414 | + */ | |
| 415 | +    protected function updateSuccessfulReShare($shareId, $token) { | |
| 416 | + $query = $this->dbConnection->getQueryBuilder(); | |
| 417 | +        $query->update('share') | |
| 418 | +            ->where($query->expr()->eq('id', $query->createNamedParameter($shareId))) | |
| 419 | +            ->set('token', $query->createNamedParameter($token)) | |
| 420 | + ->execute(); | |
| 421 | + } | |
| 422 | + | |
| 423 | + /** | |
| 424 | + * store remote ID in federated reShare table | |
| 425 | + * | |
| 426 | + * @param $shareId | |
| 427 | + * @param $remoteId | |
| 428 | + */ | |
| 429 | +    public function storeRemoteId($shareId, $remoteId) { | |
| 430 | + $query = $this->dbConnection->getQueryBuilder(); | |
| 431 | +        $query->insert('federated_reshares') | |
| 432 | + ->values( | |
| 433 | + [ | |
| 434 | + 'share_id' => $query->createNamedParameter($shareId), | |
| 435 | + 'remote_id' => $query->createNamedParameter($remoteId), | |
| 436 | + ] | |
| 437 | + ); | |
| 438 | + $query->execute(); | |
| 439 | + } | |
| 440 | + | |
| 441 | + /** | |
| 442 | + * get share ID on remote server for federated re-shares | |
| 443 | + * | |
| 444 | + * @param IShare $share | |
| 445 | + * @return int | |
| 446 | + * @throws ShareNotFound | |
| 447 | + */ | |
| 448 | +    public function getRemoteId(IShare $share) { | |
| 449 | + $query = $this->dbConnection->getQueryBuilder(); | |
| 450 | +        $query->select('remote_id')->from('federated_reshares') | |
| 451 | +            ->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId()))); | |
| 452 | + $data = $query->execute()->fetch(); | |
| 453 | + | |
| 454 | +        if (!is_array($data) || !isset($data['remote_id'])) { | |
| 455 | + throw new ShareNotFound(); | |
| 456 | + } | |
| 457 | + | |
| 458 | + return (int)$data['remote_id']; | |
| 459 | + } | |
| 460 | + | |
| 461 | + /** | |
| 462 | + * @inheritdoc | |
| 463 | + */ | |
| 464 | +    public function move(IShare $share, $recipient) { | |
| 465 | + /* | |
| 466 | 466 | * This function does nothing yet as it is just for outgoing | 
| 467 | 467 | * federated shares. | 
| 468 | 468 | */ | 
| 469 | - return $share; | |
| 470 | - } | |
| 471 | - | |
| 472 | - /** | |
| 473 | - * Get all children of this share | |
| 474 | - * | |
| 475 | - * @param IShare $parent | |
| 476 | - * @return IShare[] | |
| 477 | - */ | |
| 478 | -	public function getChildren(IShare $parent) { | |
| 479 | - $children = []; | |
| 480 | - | |
| 481 | - $qb = $this->dbConnection->getQueryBuilder(); | |
| 482 | -		$qb->select('*') | |
| 483 | -			->from('share') | |
| 484 | -			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId()))) | |
| 485 | -			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))) | |
| 486 | -			->orderBy('id'); | |
| 487 | - | |
| 488 | - $cursor = $qb->execute(); | |
| 489 | -		while($data = $cursor->fetch()) { | |
| 490 | - $children[] = $this->createShareObject($data); | |
| 491 | - } | |
| 492 | - $cursor->closeCursor(); | |
| 493 | - | |
| 494 | - return $children; | |
| 495 | - } | |
| 496 | - | |
| 497 | - /** | |
| 498 | - * Delete a share (owner unShares the file) | |
| 499 | - * | |
| 500 | - * @param IShare $share | |
| 501 | - */ | |
| 502 | -	public function delete(IShare $share) { | |
| 503 | - | |
| 504 | - list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedWith()); | |
| 505 | - | |
| 506 | - $isOwner = false; | |
| 507 | - | |
| 508 | - $this->removeShareFromTable($share); | |
| 509 | - | |
| 510 | - // if the local user is the owner we can send the unShare request directly... | |
| 511 | -		if ($this->userManager->userExists($share->getShareOwner())) { | |
| 512 | - $this->notifications->sendRemoteUnShare($remote, $share->getId(), $share->getToken()); | |
| 513 | - $this->revokeShare($share, true); | |
| 514 | - $isOwner = true; | |
| 515 | -		} else { // ... if not we need to correct ID for the unShare request | |
| 516 | - $remoteId = $this->getRemoteId($share); | |
| 517 | - $this->notifications->sendRemoteUnShare($remote, $remoteId, $share->getToken()); | |
| 518 | - $this->revokeShare($share, false); | |
| 519 | - } | |
| 520 | - | |
| 521 | - // send revoke notification to the other user, if initiator and owner are not the same user | |
| 522 | -		if ($share->getShareOwner() !== $share->getSharedBy()) { | |
| 523 | - $remoteId = $this->getRemoteId($share); | |
| 524 | -			if ($isOwner) { | |
| 525 | - list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy()); | |
| 526 | -			} else { | |
| 527 | - list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner()); | |
| 528 | - } | |
| 529 | - $this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken()); | |
| 530 | - } | |
| 531 | - } | |
| 532 | - | |
| 533 | - /** | |
| 534 | - * in case of a re-share we need to send the other use (initiator or owner) | |
| 535 | - * a message that the file was unshared | |
| 536 | - * | |
| 537 | - * @param IShare $share | |
| 538 | - * @param bool $isOwner the user can either be the owner or the user who re-sahred it | |
| 539 | - * @throws ShareNotFound | |
| 540 | - * @throws \OC\HintException | |
| 541 | - */ | |
| 542 | -	protected function revokeShare($share, $isOwner) { | |
| 543 | - // also send a unShare request to the initiator, if this is a different user than the owner | |
| 544 | -		if ($share->getShareOwner() !== $share->getSharedBy()) { | |
| 545 | -			if ($isOwner) { | |
| 546 | - list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy()); | |
| 547 | -			} else { | |
| 548 | - list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner()); | |
| 549 | - } | |
| 550 | - $remoteId = $this->getRemoteId($share); | |
| 551 | - $this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken()); | |
| 552 | - } | |
| 553 | - } | |
| 554 | - | |
| 555 | - /** | |
| 556 | - * remove share from table | |
| 557 | - * | |
| 558 | - * @param IShare $share | |
| 559 | - */ | |
| 560 | -	public function removeShareFromTable(IShare $share) { | |
| 561 | - $this->removeShareFromTableById($share->getId()); | |
| 562 | - } | |
| 563 | - | |
| 564 | - /** | |
| 565 | - * remove share from table | |
| 566 | - * | |
| 567 | - * @param string $shareId | |
| 568 | - */ | |
| 569 | -	private function removeShareFromTableById($shareId) { | |
| 570 | - $qb = $this->dbConnection->getQueryBuilder(); | |
| 571 | -		$qb->delete('share') | |
| 572 | -			->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId))); | |
| 573 | - $qb->execute(); | |
| 574 | - | |
| 575 | -		$qb->delete('federated_reshares') | |
| 576 | -			->where($qb->expr()->eq('share_id', $qb->createNamedParameter($shareId))); | |
| 577 | - $qb->execute(); | |
| 578 | - } | |
| 579 | - | |
| 580 | - /** | |
| 581 | - * @inheritdoc | |
| 582 | - */ | |
| 583 | -	public function deleteFromSelf(IShare $share, $recipient) { | |
| 584 | - // nothing to do here. Technically deleteFromSelf in the context of federated | |
| 585 | - // shares is a umount of a external storage. This is handled here | |
| 586 | - // apps/files_sharing/lib/external/manager.php | |
| 587 | - // TODO move this code over to this app | |
| 588 | - return; | |
| 589 | - } | |
| 590 | - | |
| 591 | - | |
| 592 | -	public function getSharesInFolder($userId, Folder $node, $reshares) { | |
| 593 | - $qb = $this->dbConnection->getQueryBuilder(); | |
| 594 | -		$qb->select('*') | |
| 595 | -			->from('share', 's') | |
| 596 | - ->andWhere($qb->expr()->orX( | |
| 597 | -				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')), | |
| 598 | -				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder')) | |
| 599 | - )) | |
| 600 | - ->andWhere( | |
| 601 | -				$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)) | |
| 602 | - ); | |
| 603 | - | |
| 604 | - /** | |
| 605 | - * Reshares for this user are shares where they are the owner. | |
| 606 | - */ | |
| 607 | -		if ($reshares === false) { | |
| 608 | -			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))); | |
| 609 | -		} else { | |
| 610 | - $qb->andWhere( | |
| 611 | - $qb->expr()->orX( | |
| 612 | -					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)), | |
| 613 | -					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)) | |
| 614 | - ) | |
| 615 | - ); | |
| 616 | - } | |
| 617 | - | |
| 618 | -		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid')); | |
| 619 | -		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId()))); | |
| 620 | - | |
| 621 | -		$qb->orderBy('id'); | |
| 622 | - | |
| 623 | - $cursor = $qb->execute(); | |
| 624 | - $shares = []; | |
| 625 | -		while ($data = $cursor->fetch()) { | |
| 626 | - $shares[$data['fileid']][] = $this->createShareObject($data); | |
| 627 | - } | |
| 628 | - $cursor->closeCursor(); | |
| 629 | - | |
| 630 | - return $shares; | |
| 631 | - } | |
| 632 | - | |
| 633 | - /** | |
| 634 | - * @inheritdoc | |
| 635 | - */ | |
| 636 | -	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) { | |
| 637 | - $qb = $this->dbConnection->getQueryBuilder(); | |
| 638 | -		$qb->select('*') | |
| 639 | -			->from('share'); | |
| 640 | - | |
| 641 | -		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))); | |
| 642 | - | |
| 643 | - /** | |
| 644 | - * Reshares for this user are shares where they are the owner. | |
| 645 | - */ | |
| 646 | -		if ($reshares === false) { | |
| 647 | - //Special case for old shares created via the web UI | |
| 648 | - $or1 = $qb->expr()->andX( | |
| 649 | -				$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)), | |
| 650 | -				$qb->expr()->isNull('uid_initiator') | |
| 651 | - ); | |
| 652 | - | |
| 653 | - $qb->andWhere( | |
| 654 | - $qb->expr()->orX( | |
| 655 | -					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)), | |
| 656 | - $or1 | |
| 657 | - ) | |
| 658 | - ); | |
| 659 | -		} else { | |
| 660 | - $qb->andWhere( | |
| 661 | - $qb->expr()->orX( | |
| 662 | -					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)), | |
| 663 | -					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)) | |
| 664 | - ) | |
| 665 | - ); | |
| 666 | - } | |
| 667 | - | |
| 668 | -		if ($node !== null) { | |
| 669 | -			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId()))); | |
| 670 | - } | |
| 671 | - | |
| 672 | -		if ($limit !== -1) { | |
| 673 | - $qb->setMaxResults($limit); | |
| 674 | - } | |
| 675 | - | |
| 676 | - $qb->setFirstResult($offset); | |
| 677 | -		$qb->orderBy('id'); | |
| 678 | - | |
| 679 | - $cursor = $qb->execute(); | |
| 680 | - $shares = []; | |
| 681 | -		while($data = $cursor->fetch()) { | |
| 682 | - $shares[] = $this->createShareObject($data); | |
| 683 | - } | |
| 684 | - $cursor->closeCursor(); | |
| 685 | - | |
| 686 | - return $shares; | |
| 687 | - } | |
| 688 | - | |
| 689 | - /** | |
| 690 | - * @inheritdoc | |
| 691 | - */ | |
| 692 | -	public function getShareById($id, $recipientId = null) { | |
| 693 | - $qb = $this->dbConnection->getQueryBuilder(); | |
| 694 | - | |
| 695 | -		$qb->select('*') | |
| 696 | -			->from('share') | |
| 697 | -			->where($qb->expr()->eq('id', $qb->createNamedParameter($id))) | |
| 698 | -			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))); | |
| 699 | - | |
| 700 | - $cursor = $qb->execute(); | |
| 701 | - $data = $cursor->fetch(); | |
| 702 | - $cursor->closeCursor(); | |
| 703 | - | |
| 704 | -		if ($data === false) { | |
| 705 | - throw new ShareNotFound(); | |
| 706 | - } | |
| 707 | - | |
| 708 | -		try { | |
| 709 | - $share = $this->createShareObject($data); | |
| 710 | -		} catch (InvalidShare $e) { | |
| 711 | - throw new ShareNotFound(); | |
| 712 | - } | |
| 713 | - | |
| 714 | - return $share; | |
| 715 | - } | |
| 716 | - | |
| 717 | - /** | |
| 718 | - * Get shares for a given path | |
| 719 | - * | |
| 720 | - * @param \OCP\Files\Node $path | |
| 721 | - * @return IShare[] | |
| 722 | - */ | |
| 723 | -	public function getSharesByPath(Node $path) { | |
| 724 | - $qb = $this->dbConnection->getQueryBuilder(); | |
| 725 | - | |
| 726 | -		$cursor = $qb->select('*') | |
| 727 | -			->from('share') | |
| 728 | -			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId()))) | |
| 729 | -			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))) | |
| 730 | - ->execute(); | |
| 731 | - | |
| 732 | - $shares = []; | |
| 733 | -		while($data = $cursor->fetch()) { | |
| 734 | - $shares[] = $this->createShareObject($data); | |
| 735 | - } | |
| 736 | - $cursor->closeCursor(); | |
| 737 | - | |
| 738 | - return $shares; | |
| 739 | - } | |
| 740 | - | |
| 741 | - /** | |
| 742 | - * @inheritdoc | |
| 743 | - */ | |
| 744 | -	public function getSharedWith($userId, $shareType, $node, $limit, $offset) { | |
| 745 | - /** @var IShare[] $shares */ | |
| 746 | - $shares = []; | |
| 747 | - | |
| 748 | - //Get shares directly with this user | |
| 749 | - $qb = $this->dbConnection->getQueryBuilder(); | |
| 750 | -		$qb->select('*') | |
| 751 | -			->from('share'); | |
| 752 | - | |
| 753 | - // Order by id | |
| 754 | -		$qb->orderBy('id'); | |
| 755 | - | |
| 756 | - // Set limit and offset | |
| 757 | -		if ($limit !== -1) { | |
| 758 | - $qb->setMaxResults($limit); | |
| 759 | - } | |
| 760 | - $qb->setFirstResult($offset); | |
| 761 | - | |
| 762 | -		$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))); | |
| 763 | -		$qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId))); | |
| 764 | - | |
| 765 | - // Filter by node if provided | |
| 766 | -		if ($node !== null) { | |
| 767 | -			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId()))); | |
| 768 | - } | |
| 769 | - | |
| 770 | - $cursor = $qb->execute(); | |
| 771 | - | |
| 772 | -		while($data = $cursor->fetch()) { | |
| 773 | - $shares[] = $this->createShareObject($data); | |
| 774 | - } | |
| 775 | - $cursor->closeCursor(); | |
| 776 | - | |
| 777 | - | |
| 778 | - return $shares; | |
| 779 | - } | |
| 780 | - | |
| 781 | - /** | |
| 782 | - * Get a share by token | |
| 783 | - * | |
| 784 | - * @param string $token | |
| 785 | - * @return IShare | |
| 786 | - * @throws ShareNotFound | |
| 787 | - */ | |
| 788 | -	public function getShareByToken($token) { | |
| 789 | - $qb = $this->dbConnection->getQueryBuilder(); | |
| 790 | - | |
| 791 | -		$cursor = $qb->select('*') | |
| 792 | -			->from('share') | |
| 793 | -			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))) | |
| 794 | -			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token))) | |
| 795 | - ->execute(); | |
| 796 | - | |
| 797 | - $data = $cursor->fetch(); | |
| 798 | - | |
| 799 | -		if ($data === false) { | |
| 800 | -			throw new ShareNotFound('Share not found', $this->l->t('Could not find share')); | |
| 801 | - } | |
| 802 | - | |
| 803 | -		try { | |
| 804 | - $share = $this->createShareObject($data); | |
| 805 | -		} catch (InvalidShare $e) { | |
| 806 | -			throw new ShareNotFound('Share not found', $this->l->t('Could not find share')); | |
| 807 | - } | |
| 808 | - | |
| 809 | - return $share; | |
| 810 | - } | |
| 811 | - | |
| 812 | - /** | |
| 813 | - * get database row of a give share | |
| 814 | - * | |
| 815 | - * @param $id | |
| 816 | - * @return array | |
| 817 | - * @throws ShareNotFound | |
| 818 | - */ | |
| 819 | -	private function getRawShare($id) { | |
| 820 | - | |
| 821 | - // Now fetch the inserted share and create a complete share object | |
| 822 | - $qb = $this->dbConnection->getQueryBuilder(); | |
| 823 | -		$qb->select('*') | |
| 824 | -			->from('share') | |
| 825 | -			->where($qb->expr()->eq('id', $qb->createNamedParameter($id))); | |
| 826 | - | |
| 827 | - $cursor = $qb->execute(); | |
| 828 | - $data = $cursor->fetch(); | |
| 829 | - $cursor->closeCursor(); | |
| 830 | - | |
| 831 | -		if ($data === false) { | |
| 832 | - throw new ShareNotFound; | |
| 833 | - } | |
| 834 | - | |
| 835 | - return $data; | |
| 836 | - } | |
| 837 | - | |
| 838 | - /** | |
| 839 | - * Create a share object from an database row | |
| 840 | - * | |
| 841 | - * @param array $data | |
| 842 | - * @return IShare | |
| 843 | - * @throws InvalidShare | |
| 844 | - * @throws ShareNotFound | |
| 845 | - */ | |
| 846 | -	private function createShareObject($data) { | |
| 847 | - | |
| 848 | - $share = new Share($this->rootFolder, $this->userManager); | |
| 849 | - $share->setId((int)$data['id']) | |
| 850 | - ->setShareType((int)$data['share_type']) | |
| 851 | - ->setPermissions((int)$data['permissions']) | |
| 852 | - ->setTarget($data['file_target']) | |
| 853 | - ->setMailSend((bool)$data['mail_send']) | |
| 854 | - ->setToken($data['token']); | |
| 855 | - | |
| 856 | - $shareTime = new \DateTime(); | |
| 857 | - $shareTime->setTimestamp((int)$data['stime']); | |
| 858 | - $share->setShareTime($shareTime); | |
| 859 | - $share->setSharedWith($data['share_with']); | |
| 860 | - | |
| 861 | -		if ($data['uid_initiator'] !== null) { | |
| 862 | - $share->setShareOwner($data['uid_owner']); | |
| 863 | - $share->setSharedBy($data['uid_initiator']); | |
| 864 | -		} else { | |
| 865 | - //OLD SHARE | |
| 866 | - $share->setSharedBy($data['uid_owner']); | |
| 867 | - $path = $this->getNode($share->getSharedBy(), (int)$data['file_source']); | |
| 868 | - | |
| 869 | - $owner = $path->getOwner(); | |
| 870 | - $share->setShareOwner($owner->getUID()); | |
| 871 | - } | |
| 872 | - | |
| 873 | - $share->setNodeId((int)$data['file_source']); | |
| 874 | - $share->setNodeType($data['item_type']); | |
| 875 | - | |
| 876 | - $share->setProviderId($this->identifier()); | |
| 877 | - | |
| 878 | - return $share; | |
| 879 | - } | |
| 880 | - | |
| 881 | - /** | |
| 882 | - * Get the node with file $id for $user | |
| 883 | - * | |
| 884 | - * @param string $userId | |
| 885 | - * @param int $id | |
| 886 | - * @return \OCP\Files\File|\OCP\Files\Folder | |
| 887 | - * @throws InvalidShare | |
| 888 | - */ | |
| 889 | -	private function getNode($userId, $id) { | |
| 890 | -		try { | |
| 891 | - $userFolder = $this->rootFolder->getUserFolder($userId); | |
| 892 | -		} catch (NotFoundException $e) { | |
| 893 | - throw new InvalidShare(); | |
| 894 | - } | |
| 895 | - | |
| 896 | - $nodes = $userFolder->getById($id); | |
| 897 | - | |
| 898 | -		if (empty($nodes)) { | |
| 899 | - throw new InvalidShare(); | |
| 900 | - } | |
| 901 | - | |
| 902 | - return $nodes[0]; | |
| 903 | - } | |
| 904 | - | |
| 905 | - /** | |
| 906 | - * A user is deleted from the system | |
| 907 | - * So clean up the relevant shares. | |
| 908 | - * | |
| 909 | - * @param string $uid | |
| 910 | - * @param int $shareType | |
| 911 | - */ | |
| 912 | -	public function userDeleted($uid, $shareType) { | |
| 913 | - //TODO: probabaly a good idea to send unshare info to remote servers | |
| 914 | - | |
| 915 | - $qb = $this->dbConnection->getQueryBuilder(); | |
| 916 | - | |
| 917 | -		$qb->delete('share') | |
| 918 | -			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE))) | |
| 919 | -			->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))) | |
| 920 | - ->execute(); | |
| 921 | - } | |
| 922 | - | |
| 923 | - /** | |
| 924 | - * This provider does not handle groups | |
| 925 | - * | |
| 926 | - * @param string $gid | |
| 927 | - */ | |
| 928 | -	public function groupDeleted($gid) { | |
| 929 | - // We don't handle groups here | |
| 930 | - return; | |
| 931 | - } | |
| 932 | - | |
| 933 | - /** | |
| 934 | - * This provider does not handle groups | |
| 935 | - * | |
| 936 | - * @param string $uid | |
| 937 | - * @param string $gid | |
| 938 | - */ | |
| 939 | -	public function userDeletedFromGroup($uid, $gid) { | |
| 940 | - // We don't handle groups here | |
| 941 | - return; | |
| 942 | - } | |
| 943 | - | |
| 944 | - /** | |
| 945 | - * check if users from other Nextcloud instances are allowed to mount public links share by this instance | |
| 946 | - * | |
| 947 | - * @return bool | |
| 948 | - */ | |
| 949 | -	public function isOutgoingServer2serverShareEnabled() { | |
| 950 | -		if ($this->gsConfig->onlyInternalFederation()) { | |
| 951 | - return false; | |
| 952 | - } | |
| 953 | -		$result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes'); | |
| 954 | - return ($result === 'yes'); | |
| 955 | - } | |
| 956 | - | |
| 957 | - /** | |
| 958 | - * check if users are allowed to mount public links from other Nextclouds | |
| 959 | - * | |
| 960 | - * @return bool | |
| 961 | - */ | |
| 962 | -	public function isIncomingServer2serverShareEnabled() { | |
| 963 | -		if ($this->gsConfig->onlyInternalFederation()) { | |
| 964 | - return false; | |
| 965 | - } | |
| 966 | -		$result = $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes'); | |
| 967 | - return ($result === 'yes'); | |
| 968 | - } | |
| 969 | - | |
| 970 | - /** | |
| 971 | - * Check if querying sharees on the lookup server is enabled | |
| 972 | - * | |
| 973 | - * @return bool | |
| 974 | - */ | |
| 975 | -	public function isLookupServerQueriesEnabled() { | |
| 976 | - // in a global scale setup we should always query the lookup server | |
| 977 | -		if ($this->gsConfig->isGlobalScaleEnabled()) { | |
| 978 | - return true; | |
| 979 | - } | |
| 980 | -		$result = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no'); | |
| 981 | - return ($result === 'yes'); | |
| 982 | - } | |
| 983 | - | |
| 984 | - | |
| 985 | - /** | |
| 986 | - * Check if it is allowed to publish user specific data to the lookup server | |
| 987 | - * | |
| 988 | - * @return bool | |
| 989 | - */ | |
| 990 | -	public function isLookupServerUploadEnabled() { | |
| 991 | - // in a global scale setup the admin is responsible to keep the lookup server up-to-date | |
| 992 | -		if ($this->gsConfig->isGlobalScaleEnabled()) { | |
| 993 | - return false; | |
| 994 | - } | |
| 995 | -		$result = $this->config->getAppValue('files_sharing', 'lookupServerUploadEnabled', 'yes'); | |
| 996 | - return ($result === 'yes'); | |
| 997 | - } | |
| 998 | - | |
| 999 | - /** | |
| 1000 | - * @inheritdoc | |
| 1001 | - */ | |
| 1002 | -	public function getAccessList($nodes, $currentAccess) { | |
| 1003 | - $ids = []; | |
| 1004 | -		foreach ($nodes as $node) { | |
| 1005 | - $ids[] = $node->getId(); | |
| 1006 | - } | |
| 1007 | - | |
| 1008 | - $qb = $this->dbConnection->getQueryBuilder(); | |
| 1009 | -		$qb->select('share_with', 'token', 'file_source') | |
| 1010 | -			->from('share') | |
| 1011 | -			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE))) | |
| 1012 | -			->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY))) | |
| 1013 | - ->andWhere($qb->expr()->orX( | |
| 1014 | -				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')), | |
| 1015 | -				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder')) | |
| 1016 | - )); | |
| 1017 | - $cursor = $qb->execute(); | |
| 1018 | - | |
| 1019 | -		if ($currentAccess === false) { | |
| 1020 | - $remote = $cursor->fetch() !== false; | |
| 1021 | - $cursor->closeCursor(); | |
| 1022 | - | |
| 1023 | - return ['remote' => $remote]; | |
| 1024 | - } | |
| 1025 | - | |
| 1026 | - $remote = []; | |
| 1027 | -		while ($row = $cursor->fetch()) { | |
| 1028 | - $remote[$row['share_with']] = [ | |
| 1029 | - 'node_id' => $row['file_source'], | |
| 1030 | - 'token' => $row['token'], | |
| 1031 | - ]; | |
| 1032 | - } | |
| 1033 | - $cursor->closeCursor(); | |
| 1034 | - | |
| 1035 | - return ['remote' => $remote]; | |
| 1036 | - } | |
| 469 | + return $share; | |
| 470 | + } | |
| 471 | + | |
| 472 | + /** | |
| 473 | + * Get all children of this share | |
| 474 | + * | |
| 475 | + * @param IShare $parent | |
| 476 | + * @return IShare[] | |
| 477 | + */ | |
| 478 | +    public function getChildren(IShare $parent) { | |
| 479 | + $children = []; | |
| 480 | + | |
| 481 | + $qb = $this->dbConnection->getQueryBuilder(); | |
| 482 | +        $qb->select('*') | |
| 483 | +            ->from('share') | |
| 484 | +            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId()))) | |
| 485 | +            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))) | |
| 486 | +            ->orderBy('id'); | |
| 487 | + | |
| 488 | + $cursor = $qb->execute(); | |
| 489 | +        while($data = $cursor->fetch()) { | |
| 490 | + $children[] = $this->createShareObject($data); | |
| 491 | + } | |
| 492 | + $cursor->closeCursor(); | |
| 493 | + | |
| 494 | + return $children; | |
| 495 | + } | |
| 496 | + | |
| 497 | + /** | |
| 498 | + * Delete a share (owner unShares the file) | |
| 499 | + * | |
| 500 | + * @param IShare $share | |
| 501 | + */ | |
| 502 | +    public function delete(IShare $share) { | |
| 503 | + | |
| 504 | + list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedWith()); | |
| 505 | + | |
| 506 | + $isOwner = false; | |
| 507 | + | |
| 508 | + $this->removeShareFromTable($share); | |
| 509 | + | |
| 510 | + // if the local user is the owner we can send the unShare request directly... | |
| 511 | +        if ($this->userManager->userExists($share->getShareOwner())) { | |
| 512 | + $this->notifications->sendRemoteUnShare($remote, $share->getId(), $share->getToken()); | |
| 513 | + $this->revokeShare($share, true); | |
| 514 | + $isOwner = true; | |
| 515 | +        } else { // ... if not we need to correct ID for the unShare request | |
| 516 | + $remoteId = $this->getRemoteId($share); | |
| 517 | + $this->notifications->sendRemoteUnShare($remote, $remoteId, $share->getToken()); | |
| 518 | + $this->revokeShare($share, false); | |
| 519 | + } | |
| 520 | + | |
| 521 | + // send revoke notification to the other user, if initiator and owner are not the same user | |
| 522 | +        if ($share->getShareOwner() !== $share->getSharedBy()) { | |
| 523 | + $remoteId = $this->getRemoteId($share); | |
| 524 | +            if ($isOwner) { | |
| 525 | + list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy()); | |
| 526 | +            } else { | |
| 527 | + list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner()); | |
| 528 | + } | |
| 529 | + $this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken()); | |
| 530 | + } | |
| 531 | + } | |
| 532 | + | |
| 533 | + /** | |
| 534 | + * in case of a re-share we need to send the other use (initiator or owner) | |
| 535 | + * a message that the file was unshared | |
| 536 | + * | |
| 537 | + * @param IShare $share | |
| 538 | + * @param bool $isOwner the user can either be the owner or the user who re-sahred it | |
| 539 | + * @throws ShareNotFound | |
| 540 | + * @throws \OC\HintException | |
| 541 | + */ | |
| 542 | +    protected function revokeShare($share, $isOwner) { | |
| 543 | + // also send a unShare request to the initiator, if this is a different user than the owner | |
| 544 | +        if ($share->getShareOwner() !== $share->getSharedBy()) { | |
| 545 | +            if ($isOwner) { | |
| 546 | + list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy()); | |
| 547 | +            } else { | |
| 548 | + list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner()); | |
| 549 | + } | |
| 550 | + $remoteId = $this->getRemoteId($share); | |
| 551 | + $this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken()); | |
| 552 | + } | |
| 553 | + } | |
| 554 | + | |
| 555 | + /** | |
| 556 | + * remove share from table | |
| 557 | + * | |
| 558 | + * @param IShare $share | |
| 559 | + */ | |
| 560 | +    public function removeShareFromTable(IShare $share) { | |
| 561 | + $this->removeShareFromTableById($share->getId()); | |
| 562 | + } | |
| 563 | + | |
| 564 | + /** | |
| 565 | + * remove share from table | |
| 566 | + * | |
| 567 | + * @param string $shareId | |
| 568 | + */ | |
| 569 | +    private function removeShareFromTableById($shareId) { | |
| 570 | + $qb = $this->dbConnection->getQueryBuilder(); | |
| 571 | +        $qb->delete('share') | |
| 572 | +            ->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId))); | |
| 573 | + $qb->execute(); | |
| 574 | + | |
| 575 | +        $qb->delete('federated_reshares') | |
| 576 | +            ->where($qb->expr()->eq('share_id', $qb->createNamedParameter($shareId))); | |
| 577 | + $qb->execute(); | |
| 578 | + } | |
| 579 | + | |
| 580 | + /** | |
| 581 | + * @inheritdoc | |
| 582 | + */ | |
| 583 | +    public function deleteFromSelf(IShare $share, $recipient) { | |
| 584 | + // nothing to do here. Technically deleteFromSelf in the context of federated | |
| 585 | + // shares is a umount of a external storage. This is handled here | |
| 586 | + // apps/files_sharing/lib/external/manager.php | |
| 587 | + // TODO move this code over to this app | |
| 588 | + return; | |
| 589 | + } | |
| 590 | + | |
| 591 | + | |
| 592 | +    public function getSharesInFolder($userId, Folder $node, $reshares) { | |
| 593 | + $qb = $this->dbConnection->getQueryBuilder(); | |
| 594 | +        $qb->select('*') | |
| 595 | +            ->from('share', 's') | |
| 596 | + ->andWhere($qb->expr()->orX( | |
| 597 | +                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')), | |
| 598 | +                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder')) | |
| 599 | + )) | |
| 600 | + ->andWhere( | |
| 601 | +                $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)) | |
| 602 | + ); | |
| 603 | + | |
| 604 | + /** | |
| 605 | + * Reshares for this user are shares where they are the owner. | |
| 606 | + */ | |
| 607 | +        if ($reshares === false) { | |
| 608 | +            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))); | |
| 609 | +        } else { | |
| 610 | + $qb->andWhere( | |
| 611 | + $qb->expr()->orX( | |
| 612 | +                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)), | |
| 613 | +                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)) | |
| 614 | + ) | |
| 615 | + ); | |
| 616 | + } | |
| 617 | + | |
| 618 | +        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid')); | |
| 619 | +        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId()))); | |
| 620 | + | |
| 621 | +        $qb->orderBy('id'); | |
| 622 | + | |
| 623 | + $cursor = $qb->execute(); | |
| 624 | + $shares = []; | |
| 625 | +        while ($data = $cursor->fetch()) { | |
| 626 | + $shares[$data['fileid']][] = $this->createShareObject($data); | |
| 627 | + } | |
| 628 | + $cursor->closeCursor(); | |
| 629 | + | |
| 630 | + return $shares; | |
| 631 | + } | |
| 632 | + | |
| 633 | + /** | |
| 634 | + * @inheritdoc | |
| 635 | + */ | |
| 636 | +    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) { | |
| 637 | + $qb = $this->dbConnection->getQueryBuilder(); | |
| 638 | +        $qb->select('*') | |
| 639 | +            ->from('share'); | |
| 640 | + | |
| 641 | +        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))); | |
| 642 | + | |
| 643 | + /** | |
| 644 | + * Reshares for this user are shares where they are the owner. | |
| 645 | + */ | |
| 646 | +        if ($reshares === false) { | |
| 647 | + //Special case for old shares created via the web UI | |
| 648 | + $or1 = $qb->expr()->andX( | |
| 649 | +                $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)), | |
| 650 | +                $qb->expr()->isNull('uid_initiator') | |
| 651 | + ); | |
| 652 | + | |
| 653 | + $qb->andWhere( | |
| 654 | + $qb->expr()->orX( | |
| 655 | +                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)), | |
| 656 | + $or1 | |
| 657 | + ) | |
| 658 | + ); | |
| 659 | +        } else { | |
| 660 | + $qb->andWhere( | |
| 661 | + $qb->expr()->orX( | |
| 662 | +                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)), | |
| 663 | +                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)) | |
| 664 | + ) | |
| 665 | + ); | |
| 666 | + } | |
| 667 | + | |
| 668 | +        if ($node !== null) { | |
| 669 | +            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId()))); | |
| 670 | + } | |
| 671 | + | |
| 672 | +        if ($limit !== -1) { | |
| 673 | + $qb->setMaxResults($limit); | |
| 674 | + } | |
| 675 | + | |
| 676 | + $qb->setFirstResult($offset); | |
| 677 | +        $qb->orderBy('id'); | |
| 678 | + | |
| 679 | + $cursor = $qb->execute(); | |
| 680 | + $shares = []; | |
| 681 | +        while($data = $cursor->fetch()) { | |
| 682 | + $shares[] = $this->createShareObject($data); | |
| 683 | + } | |
| 684 | + $cursor->closeCursor(); | |
| 685 | + | |
| 686 | + return $shares; | |
| 687 | + } | |
| 688 | + | |
| 689 | + /** | |
| 690 | + * @inheritdoc | |
| 691 | + */ | |
| 692 | +    public function getShareById($id, $recipientId = null) { | |
| 693 | + $qb = $this->dbConnection->getQueryBuilder(); | |
| 694 | + | |
| 695 | +        $qb->select('*') | |
| 696 | +            ->from('share') | |
| 697 | +            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id))) | |
| 698 | +            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))); | |
| 699 | + | |
| 700 | + $cursor = $qb->execute(); | |
| 701 | + $data = $cursor->fetch(); | |
| 702 | + $cursor->closeCursor(); | |
| 703 | + | |
| 704 | +        if ($data === false) { | |
| 705 | + throw new ShareNotFound(); | |
| 706 | + } | |
| 707 | + | |
| 708 | +        try { | |
| 709 | + $share = $this->createShareObject($data); | |
| 710 | +        } catch (InvalidShare $e) { | |
| 711 | + throw new ShareNotFound(); | |
| 712 | + } | |
| 713 | + | |
| 714 | + return $share; | |
| 715 | + } | |
| 716 | + | |
| 717 | + /** | |
| 718 | + * Get shares for a given path | |
| 719 | + * | |
| 720 | + * @param \OCP\Files\Node $path | |
| 721 | + * @return IShare[] | |
| 722 | + */ | |
| 723 | +    public function getSharesByPath(Node $path) { | |
| 724 | + $qb = $this->dbConnection->getQueryBuilder(); | |
| 725 | + | |
| 726 | +        $cursor = $qb->select('*') | |
| 727 | +            ->from('share') | |
| 728 | +            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId()))) | |
| 729 | +            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))) | |
| 730 | + ->execute(); | |
| 731 | + | |
| 732 | + $shares = []; | |
| 733 | +        while($data = $cursor->fetch()) { | |
| 734 | + $shares[] = $this->createShareObject($data); | |
| 735 | + } | |
| 736 | + $cursor->closeCursor(); | |
| 737 | + | |
| 738 | + return $shares; | |
| 739 | + } | |
| 740 | + | |
| 741 | + /** | |
| 742 | + * @inheritdoc | |
| 743 | + */ | |
| 744 | +    public function getSharedWith($userId, $shareType, $node, $limit, $offset) { | |
| 745 | + /** @var IShare[] $shares */ | |
| 746 | + $shares = []; | |
| 747 | + | |
| 748 | + //Get shares directly with this user | |
| 749 | + $qb = $this->dbConnection->getQueryBuilder(); | |
| 750 | +        $qb->select('*') | |
| 751 | +            ->from('share'); | |
| 752 | + | |
| 753 | + // Order by id | |
| 754 | +        $qb->orderBy('id'); | |
| 755 | + | |
| 756 | + // Set limit and offset | |
| 757 | +        if ($limit !== -1) { | |
| 758 | + $qb->setMaxResults($limit); | |
| 759 | + } | |
| 760 | + $qb->setFirstResult($offset); | |
| 761 | + | |
| 762 | +        $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))); | |
| 763 | +        $qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId))); | |
| 764 | + | |
| 765 | + // Filter by node if provided | |
| 766 | +        if ($node !== null) { | |
| 767 | +            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId()))); | |
| 768 | + } | |
| 769 | + | |
| 770 | + $cursor = $qb->execute(); | |
| 771 | + | |
| 772 | +        while($data = $cursor->fetch()) { | |
| 773 | + $shares[] = $this->createShareObject($data); | |
| 774 | + } | |
| 775 | + $cursor->closeCursor(); | |
| 776 | + | |
| 777 | + | |
| 778 | + return $shares; | |
| 779 | + } | |
| 780 | + | |
| 781 | + /** | |
| 782 | + * Get a share by token | |
| 783 | + * | |
| 784 | + * @param string $token | |
| 785 | + * @return IShare | |
| 786 | + * @throws ShareNotFound | |
| 787 | + */ | |
| 788 | +    public function getShareByToken($token) { | |
| 789 | + $qb = $this->dbConnection->getQueryBuilder(); | |
| 790 | + | |
| 791 | +        $cursor = $qb->select('*') | |
| 792 | +            ->from('share') | |
| 793 | +            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))) | |
| 794 | +            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token))) | |
| 795 | + ->execute(); | |
| 796 | + | |
| 797 | + $data = $cursor->fetch(); | |
| 798 | + | |
| 799 | +        if ($data === false) { | |
| 800 | +            throw new ShareNotFound('Share not found', $this->l->t('Could not find share')); | |
| 801 | + } | |
| 802 | + | |
| 803 | +        try { | |
| 804 | + $share = $this->createShareObject($data); | |
| 805 | +        } catch (InvalidShare $e) { | |
| 806 | +            throw new ShareNotFound('Share not found', $this->l->t('Could not find share')); | |
| 807 | + } | |
| 808 | + | |
| 809 | + return $share; | |
| 810 | + } | |
| 811 | + | |
| 812 | + /** | |
| 813 | + * get database row of a give share | |
| 814 | + * | |
| 815 | + * @param $id | |
| 816 | + * @return array | |
| 817 | + * @throws ShareNotFound | |
| 818 | + */ | |
| 819 | +    private function getRawShare($id) { | |
| 820 | + | |
| 821 | + // Now fetch the inserted share and create a complete share object | |
| 822 | + $qb = $this->dbConnection->getQueryBuilder(); | |
| 823 | +        $qb->select('*') | |
| 824 | +            ->from('share') | |
| 825 | +            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id))); | |
| 826 | + | |
| 827 | + $cursor = $qb->execute(); | |
| 828 | + $data = $cursor->fetch(); | |
| 829 | + $cursor->closeCursor(); | |
| 830 | + | |
| 831 | +        if ($data === false) { | |
| 832 | + throw new ShareNotFound; | |
| 833 | + } | |
| 834 | + | |
| 835 | + return $data; | |
| 836 | + } | |
| 837 | + | |
| 838 | + /** | |
| 839 | + * Create a share object from an database row | |
| 840 | + * | |
| 841 | + * @param array $data | |
| 842 | + * @return IShare | |
| 843 | + * @throws InvalidShare | |
| 844 | + * @throws ShareNotFound | |
| 845 | + */ | |
| 846 | +    private function createShareObject($data) { | |
| 847 | + | |
| 848 | + $share = new Share($this->rootFolder, $this->userManager); | |
| 849 | + $share->setId((int)$data['id']) | |
| 850 | + ->setShareType((int)$data['share_type']) | |
| 851 | + ->setPermissions((int)$data['permissions']) | |
| 852 | + ->setTarget($data['file_target']) | |
| 853 | + ->setMailSend((bool)$data['mail_send']) | |
| 854 | + ->setToken($data['token']); | |
| 855 | + | |
| 856 | + $shareTime = new \DateTime(); | |
| 857 | + $shareTime->setTimestamp((int)$data['stime']); | |
| 858 | + $share->setShareTime($shareTime); | |
| 859 | + $share->setSharedWith($data['share_with']); | |
| 860 | + | |
| 861 | +        if ($data['uid_initiator'] !== null) { | |
| 862 | + $share->setShareOwner($data['uid_owner']); | |
| 863 | + $share->setSharedBy($data['uid_initiator']); | |
| 864 | +        } else { | |
| 865 | + //OLD SHARE | |
| 866 | + $share->setSharedBy($data['uid_owner']); | |
| 867 | + $path = $this->getNode($share->getSharedBy(), (int)$data['file_source']); | |
| 868 | + | |
| 869 | + $owner = $path->getOwner(); | |
| 870 | + $share->setShareOwner($owner->getUID()); | |
| 871 | + } | |
| 872 | + | |
| 873 | + $share->setNodeId((int)$data['file_source']); | |
| 874 | + $share->setNodeType($data['item_type']); | |
| 875 | + | |
| 876 | + $share->setProviderId($this->identifier()); | |
| 877 | + | |
| 878 | + return $share; | |
| 879 | + } | |
| 880 | + | |
| 881 | + /** | |
| 882 | + * Get the node with file $id for $user | |
| 883 | + * | |
| 884 | + * @param string $userId | |
| 885 | + * @param int $id | |
| 886 | + * @return \OCP\Files\File|\OCP\Files\Folder | |
| 887 | + * @throws InvalidShare | |
| 888 | + */ | |
| 889 | +    private function getNode($userId, $id) { | |
| 890 | +        try { | |
| 891 | + $userFolder = $this->rootFolder->getUserFolder($userId); | |
| 892 | +        } catch (NotFoundException $e) { | |
| 893 | + throw new InvalidShare(); | |
| 894 | + } | |
| 895 | + | |
| 896 | + $nodes = $userFolder->getById($id); | |
| 897 | + | |
| 898 | +        if (empty($nodes)) { | |
| 899 | + throw new InvalidShare(); | |
| 900 | + } | |
| 901 | + | |
| 902 | + return $nodes[0]; | |
| 903 | + } | |
| 904 | + | |
| 905 | + /** | |
| 906 | + * A user is deleted from the system | |
| 907 | + * So clean up the relevant shares. | |
| 908 | + * | |
| 909 | + * @param string $uid | |
| 910 | + * @param int $shareType | |
| 911 | + */ | |
| 912 | +    public function userDeleted($uid, $shareType) { | |
| 913 | + //TODO: probabaly a good idea to send unshare info to remote servers | |
| 914 | + | |
| 915 | + $qb = $this->dbConnection->getQueryBuilder(); | |
| 916 | + | |
| 917 | +        $qb->delete('share') | |
| 918 | +            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE))) | |
| 919 | +            ->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))) | |
| 920 | + ->execute(); | |
| 921 | + } | |
| 922 | + | |
| 923 | + /** | |
| 924 | + * This provider does not handle groups | |
| 925 | + * | |
| 926 | + * @param string $gid | |
| 927 | + */ | |
| 928 | +    public function groupDeleted($gid) { | |
| 929 | + // We don't handle groups here | |
| 930 | + return; | |
| 931 | + } | |
| 932 | + | |
| 933 | + /** | |
| 934 | + * This provider does not handle groups | |
| 935 | + * | |
| 936 | + * @param string $uid | |
| 937 | + * @param string $gid | |
| 938 | + */ | |
| 939 | +    public function userDeletedFromGroup($uid, $gid) { | |
| 940 | + // We don't handle groups here | |
| 941 | + return; | |
| 942 | + } | |
| 943 | + | |
| 944 | + /** | |
| 945 | + * check if users from other Nextcloud instances are allowed to mount public links share by this instance | |
| 946 | + * | |
| 947 | + * @return bool | |
| 948 | + */ | |
| 949 | +    public function isOutgoingServer2serverShareEnabled() { | |
| 950 | +        if ($this->gsConfig->onlyInternalFederation()) { | |
| 951 | + return false; | |
| 952 | + } | |
| 953 | +        $result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes'); | |
| 954 | + return ($result === 'yes'); | |
| 955 | + } | |
| 956 | + | |
| 957 | + /** | |
| 958 | + * check if users are allowed to mount public links from other Nextclouds | |
| 959 | + * | |
| 960 | + * @return bool | |
| 961 | + */ | |
| 962 | +    public function isIncomingServer2serverShareEnabled() { | |
| 963 | +        if ($this->gsConfig->onlyInternalFederation()) { | |
| 964 | + return false; | |
| 965 | + } | |
| 966 | +        $result = $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes'); | |
| 967 | + return ($result === 'yes'); | |
| 968 | + } | |
| 969 | + | |
| 970 | + /** | |
| 971 | + * Check if querying sharees on the lookup server is enabled | |
| 972 | + * | |
| 973 | + * @return bool | |
| 974 | + */ | |
| 975 | +    public function isLookupServerQueriesEnabled() { | |
| 976 | + // in a global scale setup we should always query the lookup server | |
| 977 | +        if ($this->gsConfig->isGlobalScaleEnabled()) { | |
| 978 | + return true; | |
| 979 | + } | |
| 980 | +        $result = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no'); | |
| 981 | + return ($result === 'yes'); | |
| 982 | + } | |
| 983 | + | |
| 984 | + | |
| 985 | + /** | |
| 986 | + * Check if it is allowed to publish user specific data to the lookup server | |
| 987 | + * | |
| 988 | + * @return bool | |
| 989 | + */ | |
| 990 | +    public function isLookupServerUploadEnabled() { | |
| 991 | + // in a global scale setup the admin is responsible to keep the lookup server up-to-date | |
| 992 | +        if ($this->gsConfig->isGlobalScaleEnabled()) { | |
| 993 | + return false; | |
| 994 | + } | |
| 995 | +        $result = $this->config->getAppValue('files_sharing', 'lookupServerUploadEnabled', 'yes'); | |
| 996 | + return ($result === 'yes'); | |
| 997 | + } | |
| 998 | + | |
| 999 | + /** | |
| 1000 | + * @inheritdoc | |
| 1001 | + */ | |
| 1002 | +    public function getAccessList($nodes, $currentAccess) { | |
| 1003 | + $ids = []; | |
| 1004 | +        foreach ($nodes as $node) { | |
| 1005 | + $ids[] = $node->getId(); | |
| 1006 | + } | |
| 1007 | + | |
| 1008 | + $qb = $this->dbConnection->getQueryBuilder(); | |
| 1009 | +        $qb->select('share_with', 'token', 'file_source') | |
| 1010 | +            ->from('share') | |
| 1011 | +            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE))) | |
| 1012 | +            ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY))) | |
| 1013 | + ->andWhere($qb->expr()->orX( | |
| 1014 | +                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')), | |
| 1015 | +                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder')) | |
| 1016 | + )); | |
| 1017 | + $cursor = $qb->execute(); | |
| 1018 | + | |
| 1019 | +        if ($currentAccess === false) { | |
| 1020 | + $remote = $cursor->fetch() !== false; | |
| 1021 | + $cursor->closeCursor(); | |
| 1022 | + | |
| 1023 | + return ['remote' => $remote]; | |
| 1024 | + } | |
| 1025 | + | |
| 1026 | + $remote = []; | |
| 1027 | +        while ($row = $cursor->fetch()) { | |
| 1028 | + $remote[$row['share_with']] = [ | |
| 1029 | + 'node_id' => $row['file_source'], | |
| 1030 | + 'token' => $row['token'], | |
| 1031 | + ]; | |
| 1032 | + } | |
| 1033 | + $cursor->closeCursor(); | |
| 1034 | + | |
| 1035 | + return ['remote' => $remote]; | |
| 1036 | + } | |
| 1037 | 1037 | } | 
| @@ -110,7 +110,7 @@ | ||
| 110 | 110 | * check if it is a file located in data/user/files only files in the | 
| 111 | 111 | * 'files' directory should be moved to the trash | 
| 112 | 112 | * | 
| 113 | - * @param $path | |
| 113 | + * @param string $path | |
| 114 | 114 | * @return bool | 
| 115 | 115 | */ | 
| 116 | 116 |  	protected function shouldMoveToTrash($path){ | 
| @@ -112,7 +112,7 @@ discard block | ||
| 112 | 112 |  			if ($currentUser) { | 
| 113 | 113 | $currentUserId = $currentUser->getUID(); | 
| 114 | 114 | |
| 115 | - $view = new View($currentUserId . '/files'); | |
| 115 | + $view = new View($currentUserId.'/files'); | |
| 116 | 116 | $fileInfo = $view->getFileInfo($oldPath); | 
| 117 | 117 |  				if ($fileInfo) { | 
| 118 | 118 | $sourceStorage = $fileInfo->getStorage(); | 
| @@ -129,11 +129,11 @@ discard block | ||
| 129 | 129 |  		} catch (\Exception $e) { | 
| 130 | 130 | // do nothing, in this case we just disable the trashbin and continue | 
| 131 | 131 | $logger = \OC::$server->getLogger(); | 
| 132 | -			$logger->debug('Trashbin storage could not check if a file was moved out of a shared folder: ' . $e->getMessage()); | |
| 132 | +			$logger->debug('Trashbin storage could not check if a file was moved out of a shared folder: '.$e->getMessage()); | |
| 133 | 133 | } | 
| 134 | 134 | |
| 135 | -		if($fileMovedOutOfSharedFolder) { | |
| 136 | - self::$moveOutOfSharedFolder['/' . $currentUserId . '/files' . $oldPath] = true; | |
| 135 | +		if ($fileMovedOutOfSharedFolder) { | |
| 136 | + self::$moveOutOfSharedFolder['/'.$currentUserId.'/files'.$oldPath] = true; | |
| 137 | 137 |  		} else { | 
| 138 | 138 | self::$disableTrash = true; | 
| 139 | 139 | } | 
| @@ -173,16 +173,16 @@ discard block | ||
| 173 | 173 | */ | 
| 174 | 174 |  	public function unlink($path) { | 
| 175 | 175 |  		try { | 
| 176 | -			if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) { | |
| 176 | +			if (isset(self::$moveOutOfSharedFolder[$this->mountPoint.$path])) { | |
| 177 | 177 | $result = $this->doDelete($path, 'unlink', true); | 
| 178 | - unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]); | |
| 178 | + unset(self::$moveOutOfSharedFolder[$this->mountPoint.$path]); | |
| 179 | 179 |  			} else { | 
| 180 | 180 | $result = $this->doDelete($path, 'unlink'); | 
| 181 | 181 | } | 
| 182 | 182 |  		} catch (GenericEncryptionException $e) { | 
| 183 | 183 | // in case of a encryption exception we delete the file right away | 
| 184 | 184 | $this->logger->info( | 
| 185 | - "Can't move file" . $path . | |
| 185 | + "Can't move file".$path. | |
| 186 | 186 | "to the trash bin, therefore it was deleted right away"); | 
| 187 | 187 | |
| 188 | 188 | $result = $this->storage->unlink($path); | 
| @@ -199,9 +199,9 @@ discard block | ||
| 199 | 199 | * @return bool true if the operation succeeded, false otherwise | 
| 200 | 200 | */ | 
| 201 | 201 |  	public function rmdir($path) { | 
| 202 | -		if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) { | |
| 202 | +		if (isset(self::$moveOutOfSharedFolder[$this->mountPoint.$path])) { | |
| 203 | 203 | $result = $this->doDelete($path, 'rmdir', true); | 
| 204 | - unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]); | |
| 204 | + unset(self::$moveOutOfSharedFolder[$this->mountPoint.$path]); | |
| 205 | 205 |  		} else { | 
| 206 | 206 | $result = $this->doDelete($path, 'rmdir'); | 
| 207 | 207 | } | 
| @@ -216,7 +216,7 @@ discard block | ||
| 216 | 216 | * @param $path | 
| 217 | 217 | * @return bool | 
| 218 | 218 | */ | 
| 219 | -	protected function shouldMoveToTrash($path){ | |
| 219 | +	protected function shouldMoveToTrash($path) { | |
| 220 | 220 | |
| 221 | 221 | // check if there is a app which want to disable the trash bin for this file | 
| 222 | 222 | $fileId = $this->storage->getCache()->getId($path); | 
| @@ -229,7 +229,7 @@ discard block | ||
| 229 | 229 | } | 
| 230 | 230 | } | 
| 231 | 231 | |
| 232 | - $normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path); | |
| 232 | + $normalized = Filesystem::normalizePath($this->mountPoint.'/'.$path); | |
| 233 | 233 |  		$parts = explode('/', $normalized); | 
| 234 | 234 |  		if (count($parts) < 4) { | 
| 235 | 235 | return false; | 
| @@ -277,7 +277,7 @@ discard block | ||
| 277 | 277 | return false; | 
| 278 | 278 | } | 
| 279 | 279 | |
| 280 | - $normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path, true, false, true); | |
| 280 | + $normalized = Filesystem::normalizePath($this->mountPoint.'/'.$path, true, false, true); | |
| 281 | 281 | $result = true; | 
| 282 | 282 | $view = Filesystem::getView(); | 
| 283 | 283 |  		if (!isset($this->deletedFiles[$normalized]) && $view instanceof View) { | 
| @@ -305,7 +305,7 @@ discard block | ||
| 305 | 305 | * Setup the storate wrapper callback | 
| 306 | 306 | */ | 
| 307 | 307 |  	public static function setupStorage() { | 
| 308 | -		\OC\Files\Filesystem::addStorageWrapper('oc_trashbin', function ($mountPoint, $storage) { | |
| 308 | +		\OC\Files\Filesystem::addStorageWrapper('oc_trashbin', function($mountPoint, $storage) { | |
| 309 | 309 | return new \OCA\Files_Trashbin\Storage( | 
| 310 | 310 |  				array('storage' => $storage, 'mountPoint' => $mountPoint), | 
| 311 | 311 | \OC::$server->getUserManager(), | 
| @@ -40,282 +40,282 @@ | ||
| 40 | 40 | |
| 41 | 41 |  class Storage extends Wrapper { | 
| 42 | 42 | |
| 43 | - private $mountPoint; | |
| 44 | - // remember already deleted files to avoid infinite loops if the trash bin | |
| 45 | - // move files across storages | |
| 46 | - private $deletedFiles = array(); | |
| 47 | - | |
| 48 | - /** | |
| 49 | - * Disable trash logic | |
| 50 | - * | |
| 51 | - * @var bool | |
| 52 | - */ | |
| 53 | - private static $disableTrash = false; | |
| 54 | - | |
| 55 | - /** | |
| 56 | - * remember which file/folder was moved out of s shared folder | |
| 57 | - * in this case we want to add a copy to the owners trash bin | |
| 58 | - * | |
| 59 | - * @var array | |
| 60 | - */ | |
| 61 | - private static $moveOutOfSharedFolder = []; | |
| 62 | - | |
| 63 | - /** @var IUserManager */ | |
| 64 | - private $userManager; | |
| 65 | - | |
| 66 | - /** @var ILogger */ | |
| 67 | - private $logger; | |
| 68 | - | |
| 69 | - /** @var EventDispatcher */ | |
| 70 | - private $eventDispatcher; | |
| 71 | - | |
| 72 | - /** @var IRootFolder */ | |
| 73 | - private $rootFolder; | |
| 74 | - | |
| 75 | - /** | |
| 76 | - * Storage constructor. | |
| 77 | - * | |
| 78 | - * @param array $parameters | |
| 79 | - * @param IUserManager|null $userManager | |
| 80 | - * @param ILogger|null $logger | |
| 81 | - * @param EventDispatcher|null $eventDispatcher | |
| 82 | - * @param IRootFolder|null $rootFolder | |
| 83 | - */ | |
| 84 | - public function __construct($parameters, | |
| 85 | - IUserManager $userManager = null, | |
| 86 | - ILogger $logger = null, | |
| 87 | - EventDispatcher $eventDispatcher = null, | |
| 88 | -								IRootFolder $rootFolder = null) { | |
| 89 | - $this->mountPoint = $parameters['mountPoint']; | |
| 90 | - $this->userManager = $userManager; | |
| 91 | - $this->logger = $logger; | |
| 92 | - $this->eventDispatcher = $eventDispatcher; | |
| 93 | - $this->rootFolder = $rootFolder; | |
| 94 | - parent::__construct($parameters); | |
| 95 | - } | |
| 96 | - | |
| 97 | - /** | |
| 98 | - * @internal | |
| 99 | - */ | |
| 100 | -	public static function preRenameHook($params) { | |
| 101 | - // in cross-storage cases, a rename is a copy + unlink, | |
| 102 | - // that last unlink must not go to trash, only exception: | |
| 103 | - // if the file was moved from a shared storage to a local folder, | |
| 104 | - // in this case the owner should get a copy in his trash bin so that | |
| 105 | - // they can restore the files again | |
| 106 | - | |
| 107 | - $oldPath = $params['oldpath']; | |
| 108 | - $newPath = dirname($params['newpath']); | |
| 109 | - $currentUser = \OC::$server->getUserSession()->getUser(); | |
| 110 | - | |
| 111 | - $fileMovedOutOfSharedFolder = false; | |
| 112 | - | |
| 113 | -		try { | |
| 114 | -			if ($currentUser) { | |
| 115 | - $currentUserId = $currentUser->getUID(); | |
| 116 | - | |
| 117 | - $view = new View($currentUserId . '/files'); | |
| 118 | - $fileInfo = $view->getFileInfo($oldPath); | |
| 119 | -				if ($fileInfo) { | |
| 120 | - $sourceStorage = $fileInfo->getStorage(); | |
| 121 | - $sourceOwner = $view->getOwner($oldPath); | |
| 122 | - $targetOwner = $view->getOwner($newPath); | |
| 123 | - | |
| 124 | - if ($sourceOwner !== $targetOwner | |
| 125 | -						&& $sourceStorage->instanceOfStorage('OCA\Files_Sharing\SharedStorage') | |
| 126 | -					) { | |
| 127 | - $fileMovedOutOfSharedFolder = true; | |
| 128 | - } | |
| 129 | - } | |
| 130 | - } | |
| 131 | -		} catch (\Exception $e) { | |
| 132 | - // do nothing, in this case we just disable the trashbin and continue | |
| 133 | - $logger = \OC::$server->getLogger(); | |
| 134 | -			$logger->debug('Trashbin storage could not check if a file was moved out of a shared folder: ' . $e->getMessage()); | |
| 135 | - } | |
| 136 | - | |
| 137 | -		if($fileMovedOutOfSharedFolder) { | |
| 138 | - self::$moveOutOfSharedFolder['/' . $currentUserId . '/files' . $oldPath] = true; | |
| 139 | -		} else { | |
| 140 | - self::$disableTrash = true; | |
| 141 | - } | |
| 142 | - | |
| 143 | - } | |
| 144 | - | |
| 145 | - /** | |
| 146 | - * @internal | |
| 147 | - */ | |
| 148 | -	public static function postRenameHook($params) { | |
| 149 | - self::$disableTrash = false; | |
| 150 | - } | |
| 151 | - | |
| 152 | - /** | |
| 153 | - * Rename path1 to path2 by calling the wrapped storage. | |
| 154 | - * | |
| 155 | - * @param string $path1 first path | |
| 156 | - * @param string $path2 second path | |
| 157 | - * @return bool | |
| 158 | - */ | |
| 159 | -	public function rename($path1, $path2) { | |
| 160 | - $result = $this->storage->rename($path1, $path2); | |
| 161 | -		if ($result === false) { | |
| 162 | - // when rename failed, the post_rename hook isn't triggered, | |
| 163 | - // but we still want to reenable the trash logic | |
| 164 | - self::$disableTrash = false; | |
| 165 | - } | |
| 166 | - return $result; | |
| 167 | - } | |
| 168 | - | |
| 169 | - /** | |
| 170 | - * Deletes the given file by moving it into the trashbin. | |
| 171 | - * | |
| 172 | - * @param string $path path of file or folder to delete | |
| 173 | - * | |
| 174 | - * @return bool true if the operation succeeded, false otherwise | |
| 175 | - */ | |
| 176 | -	public function unlink($path) { | |
| 177 | -		try { | |
| 178 | -			if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) { | |
| 179 | - $result = $this->doDelete($path, 'unlink', true); | |
| 180 | - unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]); | |
| 181 | -			} else { | |
| 182 | - $result = $this->doDelete($path, 'unlink'); | |
| 183 | - } | |
| 184 | -		} catch (GenericEncryptionException $e) { | |
| 185 | - // in case of a encryption exception we delete the file right away | |
| 186 | - $this->logger->info( | |
| 187 | - "Can't move file" . $path . | |
| 188 | - "to the trash bin, therefore it was deleted right away"); | |
| 189 | - | |
| 190 | - $result = $this->storage->unlink($path); | |
| 191 | - } | |
| 192 | - | |
| 193 | - return $result; | |
| 194 | - } | |
| 195 | - | |
| 196 | - /** | |
| 197 | - * Deletes the given folder by moving it into the trashbin. | |
| 198 | - * | |
| 199 | - * @param string $path path of folder to delete | |
| 200 | - * | |
| 201 | - * @return bool true if the operation succeeded, false otherwise | |
| 202 | - */ | |
| 203 | -	public function rmdir($path) { | |
| 204 | -		if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) { | |
| 205 | - $result = $this->doDelete($path, 'rmdir', true); | |
| 206 | - unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]); | |
| 207 | -		} else { | |
| 208 | - $result = $this->doDelete($path, 'rmdir'); | |
| 209 | - } | |
| 210 | - | |
| 211 | - return $result; | |
| 212 | - } | |
| 213 | - | |
| 214 | - /** | |
| 215 | - * check if it is a file located in data/user/files only files in the | |
| 216 | - * 'files' directory should be moved to the trash | |
| 217 | - * | |
| 218 | - * @param $path | |
| 219 | - * @return bool | |
| 220 | - */ | |
| 221 | -	protected function shouldMoveToTrash($path){ | |
| 222 | - | |
| 223 | - // check if there is a app which want to disable the trash bin for this file | |
| 224 | - $fileId = $this->storage->getCache()->getId($path); | |
| 225 | - $nodes = $this->rootFolder->getById($fileId); | |
| 226 | -		foreach ($nodes as $node) { | |
| 227 | - $event = $this->createMoveToTrashEvent($node); | |
| 228 | -			$this->eventDispatcher->dispatch('OCA\Files_Trashbin::moveToTrash', $event); | |
| 229 | -			if ($event->shouldMoveToTrashBin() === false) { | |
| 230 | - return false; | |
| 231 | - } | |
| 232 | - } | |
| 233 | - | |
| 234 | - $normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path); | |
| 235 | -		$parts = explode('/', $normalized); | |
| 236 | -		if (count($parts) < 4) { | |
| 237 | - return false; | |
| 238 | - } | |
| 239 | - | |
| 240 | -		if ($parts[2] === 'files' && $this->userManager->userExists($parts[1])) { | |
| 241 | - return true; | |
| 242 | - } | |
| 243 | - | |
| 244 | - return false; | |
| 245 | - } | |
| 246 | - | |
| 247 | - /** | |
| 248 | - * get move to trash event | |
| 249 | - * | |
| 250 | - * @param Node $node | |
| 251 | - * @return MoveToTrashEvent | |
| 252 | - */ | |
| 253 | -	protected function createMoveToTrashEvent(Node $node) { | |
| 254 | - $event = new MoveToTrashEvent($node); | |
| 255 | - return $event; | |
| 256 | - } | |
| 257 | - | |
| 258 | - /** | |
| 259 | - * Run the delete operation with the given method | |
| 260 | - * | |
| 261 | - * @param string $path path of file or folder to delete | |
| 262 | - * @param string $method either "unlink" or "rmdir" | |
| 263 | - * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder) | |
| 264 | - * | |
| 265 | - * @return bool true if the operation succeeded, false otherwise | |
| 266 | - */ | |
| 267 | -	private function doDelete($path, $method, $ownerOnly = false) { | |
| 268 | - if (self::$disableTrash | |
| 269 | -			|| !\OC_App::isEnabled('files_trashbin') | |
| 270 | - || (pathinfo($path, PATHINFO_EXTENSION) === 'part') | |
| 271 | - || $this->shouldMoveToTrash($path) === false | |
| 272 | -		) { | |
| 273 | - return call_user_func_array([$this->storage, $method], [$path]); | |
| 274 | - } | |
| 275 | - | |
| 276 | - // check permissions before we continue, this is especially important for | |
| 277 | - // shared files | |
| 278 | -		if (!$this->isDeletable($path)) { | |
| 279 | - return false; | |
| 280 | - } | |
| 281 | - | |
| 282 | - $normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path, true, false, true); | |
| 283 | - $result = true; | |
| 284 | - $view = Filesystem::getView(); | |
| 285 | -		if (!isset($this->deletedFiles[$normalized]) && $view instanceof View) { | |
| 286 | - $this->deletedFiles[$normalized] = $normalized; | |
| 287 | -			if ($filesPath = $view->getRelativePath($normalized)) { | |
| 288 | - $filesPath = trim($filesPath, '/'); | |
| 289 | - $result = \OCA\Files_Trashbin\Trashbin::move2trash($filesPath, $ownerOnly); | |
| 290 | - // in cross-storage cases the file will be copied | |
| 291 | - // but not deleted, so we delete it here | |
| 292 | -				if ($result) { | |
| 293 | - call_user_func_array([$this->storage, $method], [$path]); | |
| 294 | - } | |
| 295 | -			} else { | |
| 296 | - $result = call_user_func_array([$this->storage, $method], [$path]); | |
| 297 | - } | |
| 298 | - unset($this->deletedFiles[$normalized]); | |
| 299 | -		} else if ($this->storage->file_exists($path)) { | |
| 300 | - $result = call_user_func_array([$this->storage, $method], [$path]); | |
| 301 | - } | |
| 302 | - | |
| 303 | - return $result; | |
| 304 | - } | |
| 305 | - | |
| 306 | - /** | |
| 307 | - * Setup the storate wrapper callback | |
| 308 | - */ | |
| 309 | -	public static function setupStorage() { | |
| 310 | -		\OC\Files\Filesystem::addStorageWrapper('oc_trashbin', function ($mountPoint, $storage) { | |
| 311 | - return new \OCA\Files_Trashbin\Storage( | |
| 312 | -				array('storage' => $storage, 'mountPoint' => $mountPoint), | |
| 313 | - \OC::$server->getUserManager(), | |
| 314 | - \OC::$server->getLogger(), | |
| 315 | - \OC::$server->getEventDispatcher(), | |
| 316 | - \OC::$server->getLazyRootFolder() | |
| 317 | - ); | |
| 318 | - }, 1); | |
| 319 | - } | |
| 43 | + private $mountPoint; | |
| 44 | + // remember already deleted files to avoid infinite loops if the trash bin | |
| 45 | + // move files across storages | |
| 46 | + private $deletedFiles = array(); | |
| 47 | + | |
| 48 | + /** | |
| 49 | + * Disable trash logic | |
| 50 | + * | |
| 51 | + * @var bool | |
| 52 | + */ | |
| 53 | + private static $disableTrash = false; | |
| 54 | + | |
| 55 | + /** | |
| 56 | + * remember which file/folder was moved out of s shared folder | |
| 57 | + * in this case we want to add a copy to the owners trash bin | |
| 58 | + * | |
| 59 | + * @var array | |
| 60 | + */ | |
| 61 | + private static $moveOutOfSharedFolder = []; | |
| 62 | + | |
| 63 | + /** @var IUserManager */ | |
| 64 | + private $userManager; | |
| 65 | + | |
| 66 | + /** @var ILogger */ | |
| 67 | + private $logger; | |
| 68 | + | |
| 69 | + /** @var EventDispatcher */ | |
| 70 | + private $eventDispatcher; | |
| 71 | + | |
| 72 | + /** @var IRootFolder */ | |
| 73 | + private $rootFolder; | |
| 74 | + | |
| 75 | + /** | |
| 76 | + * Storage constructor. | |
| 77 | + * | |
| 78 | + * @param array $parameters | |
| 79 | + * @param IUserManager|null $userManager | |
| 80 | + * @param ILogger|null $logger | |
| 81 | + * @param EventDispatcher|null $eventDispatcher | |
| 82 | + * @param IRootFolder|null $rootFolder | |
| 83 | + */ | |
| 84 | + public function __construct($parameters, | |
| 85 | + IUserManager $userManager = null, | |
| 86 | + ILogger $logger = null, | |
| 87 | + EventDispatcher $eventDispatcher = null, | |
| 88 | +                                IRootFolder $rootFolder = null) { | |
| 89 | + $this->mountPoint = $parameters['mountPoint']; | |
| 90 | + $this->userManager = $userManager; | |
| 91 | + $this->logger = $logger; | |
| 92 | + $this->eventDispatcher = $eventDispatcher; | |
| 93 | + $this->rootFolder = $rootFolder; | |
| 94 | + parent::__construct($parameters); | |
| 95 | + } | |
| 96 | + | |
| 97 | + /** | |
| 98 | + * @internal | |
| 99 | + */ | |
| 100 | +    public static function preRenameHook($params) { | |
| 101 | + // in cross-storage cases, a rename is a copy + unlink, | |
| 102 | + // that last unlink must not go to trash, only exception: | |
| 103 | + // if the file was moved from a shared storage to a local folder, | |
| 104 | + // in this case the owner should get a copy in his trash bin so that | |
| 105 | + // they can restore the files again | |
| 106 | + | |
| 107 | + $oldPath = $params['oldpath']; | |
| 108 | + $newPath = dirname($params['newpath']); | |
| 109 | + $currentUser = \OC::$server->getUserSession()->getUser(); | |
| 110 | + | |
| 111 | + $fileMovedOutOfSharedFolder = false; | |
| 112 | + | |
| 113 | +        try { | |
| 114 | +            if ($currentUser) { | |
| 115 | + $currentUserId = $currentUser->getUID(); | |
| 116 | + | |
| 117 | + $view = new View($currentUserId . '/files'); | |
| 118 | + $fileInfo = $view->getFileInfo($oldPath); | |
| 119 | +                if ($fileInfo) { | |
| 120 | + $sourceStorage = $fileInfo->getStorage(); | |
| 121 | + $sourceOwner = $view->getOwner($oldPath); | |
| 122 | + $targetOwner = $view->getOwner($newPath); | |
| 123 | + | |
| 124 | + if ($sourceOwner !== $targetOwner | |
| 125 | +                        && $sourceStorage->instanceOfStorage('OCA\Files_Sharing\SharedStorage') | |
| 126 | +                    ) { | |
| 127 | + $fileMovedOutOfSharedFolder = true; | |
| 128 | + } | |
| 129 | + } | |
| 130 | + } | |
| 131 | +        } catch (\Exception $e) { | |
| 132 | + // do nothing, in this case we just disable the trashbin and continue | |
| 133 | + $logger = \OC::$server->getLogger(); | |
| 134 | +            $logger->debug('Trashbin storage could not check if a file was moved out of a shared folder: ' . $e->getMessage()); | |
| 135 | + } | |
| 136 | + | |
| 137 | +        if($fileMovedOutOfSharedFolder) { | |
| 138 | + self::$moveOutOfSharedFolder['/' . $currentUserId . '/files' . $oldPath] = true; | |
| 139 | +        } else { | |
| 140 | + self::$disableTrash = true; | |
| 141 | + } | |
| 142 | + | |
| 143 | + } | |
| 144 | + | |
| 145 | + /** | |
| 146 | + * @internal | |
| 147 | + */ | |
| 148 | +    public static function postRenameHook($params) { | |
| 149 | + self::$disableTrash = false; | |
| 150 | + } | |
| 151 | + | |
| 152 | + /** | |
| 153 | + * Rename path1 to path2 by calling the wrapped storage. | |
| 154 | + * | |
| 155 | + * @param string $path1 first path | |
| 156 | + * @param string $path2 second path | |
| 157 | + * @return bool | |
| 158 | + */ | |
| 159 | +    public function rename($path1, $path2) { | |
| 160 | + $result = $this->storage->rename($path1, $path2); | |
| 161 | +        if ($result === false) { | |
| 162 | + // when rename failed, the post_rename hook isn't triggered, | |
| 163 | + // but we still want to reenable the trash logic | |
| 164 | + self::$disableTrash = false; | |
| 165 | + } | |
| 166 | + return $result; | |
| 167 | + } | |
| 168 | + | |
| 169 | + /** | |
| 170 | + * Deletes the given file by moving it into the trashbin. | |
| 171 | + * | |
| 172 | + * @param string $path path of file or folder to delete | |
| 173 | + * | |
| 174 | + * @return bool true if the operation succeeded, false otherwise | |
| 175 | + */ | |
| 176 | +    public function unlink($path) { | |
| 177 | +        try { | |
| 178 | +            if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) { | |
| 179 | + $result = $this->doDelete($path, 'unlink', true); | |
| 180 | + unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]); | |
| 181 | +            } else { | |
| 182 | + $result = $this->doDelete($path, 'unlink'); | |
| 183 | + } | |
| 184 | +        } catch (GenericEncryptionException $e) { | |
| 185 | + // in case of a encryption exception we delete the file right away | |
| 186 | + $this->logger->info( | |
| 187 | + "Can't move file" . $path . | |
| 188 | + "to the trash bin, therefore it was deleted right away"); | |
| 189 | + | |
| 190 | + $result = $this->storage->unlink($path); | |
| 191 | + } | |
| 192 | + | |
| 193 | + return $result; | |
| 194 | + } | |
| 195 | + | |
| 196 | + /** | |
| 197 | + * Deletes the given folder by moving it into the trashbin. | |
| 198 | + * | |
| 199 | + * @param string $path path of folder to delete | |
| 200 | + * | |
| 201 | + * @return bool true if the operation succeeded, false otherwise | |
| 202 | + */ | |
| 203 | +    public function rmdir($path) { | |
| 204 | +        if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) { | |
| 205 | + $result = $this->doDelete($path, 'rmdir', true); | |
| 206 | + unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]); | |
| 207 | +        } else { | |
| 208 | + $result = $this->doDelete($path, 'rmdir'); | |
| 209 | + } | |
| 210 | + | |
| 211 | + return $result; | |
| 212 | + } | |
| 213 | + | |
| 214 | + /** | |
| 215 | + * check if it is a file located in data/user/files only files in the | |
| 216 | + * 'files' directory should be moved to the trash | |
| 217 | + * | |
| 218 | + * @param $path | |
| 219 | + * @return bool | |
| 220 | + */ | |
| 221 | +    protected function shouldMoveToTrash($path){ | |
| 222 | + | |
| 223 | + // check if there is a app which want to disable the trash bin for this file | |
| 224 | + $fileId = $this->storage->getCache()->getId($path); | |
| 225 | + $nodes = $this->rootFolder->getById($fileId); | |
| 226 | +        foreach ($nodes as $node) { | |
| 227 | + $event = $this->createMoveToTrashEvent($node); | |
| 228 | +            $this->eventDispatcher->dispatch('OCA\Files_Trashbin::moveToTrash', $event); | |
| 229 | +            if ($event->shouldMoveToTrashBin() === false) { | |
| 230 | + return false; | |
| 231 | + } | |
| 232 | + } | |
| 233 | + | |
| 234 | + $normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path); | |
| 235 | +        $parts = explode('/', $normalized); | |
| 236 | +        if (count($parts) < 4) { | |
| 237 | + return false; | |
| 238 | + } | |
| 239 | + | |
| 240 | +        if ($parts[2] === 'files' && $this->userManager->userExists($parts[1])) { | |
| 241 | + return true; | |
| 242 | + } | |
| 243 | + | |
| 244 | + return false; | |
| 245 | + } | |
| 246 | + | |
| 247 | + /** | |
| 248 | + * get move to trash event | |
| 249 | + * | |
| 250 | + * @param Node $node | |
| 251 | + * @return MoveToTrashEvent | |
| 252 | + */ | |
| 253 | +    protected function createMoveToTrashEvent(Node $node) { | |
| 254 | + $event = new MoveToTrashEvent($node); | |
| 255 | + return $event; | |
| 256 | + } | |
| 257 | + | |
| 258 | + /** | |
| 259 | + * Run the delete operation with the given method | |
| 260 | + * | |
| 261 | + * @param string $path path of file or folder to delete | |
| 262 | + * @param string $method either "unlink" or "rmdir" | |
| 263 | + * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder) | |
| 264 | + * | |
| 265 | + * @return bool true if the operation succeeded, false otherwise | |
| 266 | + */ | |
| 267 | +    private function doDelete($path, $method, $ownerOnly = false) { | |
| 268 | + if (self::$disableTrash | |
| 269 | +            || !\OC_App::isEnabled('files_trashbin') | |
| 270 | + || (pathinfo($path, PATHINFO_EXTENSION) === 'part') | |
| 271 | + || $this->shouldMoveToTrash($path) === false | |
| 272 | +        ) { | |
| 273 | + return call_user_func_array([$this->storage, $method], [$path]); | |
| 274 | + } | |
| 275 | + | |
| 276 | + // check permissions before we continue, this is especially important for | |
| 277 | + // shared files | |
| 278 | +        if (!$this->isDeletable($path)) { | |
| 279 | + return false; | |
| 280 | + } | |
| 281 | + | |
| 282 | + $normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path, true, false, true); | |
| 283 | + $result = true; | |
| 284 | + $view = Filesystem::getView(); | |
| 285 | +        if (!isset($this->deletedFiles[$normalized]) && $view instanceof View) { | |
| 286 | + $this->deletedFiles[$normalized] = $normalized; | |
| 287 | +            if ($filesPath = $view->getRelativePath($normalized)) { | |
| 288 | + $filesPath = trim($filesPath, '/'); | |
| 289 | + $result = \OCA\Files_Trashbin\Trashbin::move2trash($filesPath, $ownerOnly); | |
| 290 | + // in cross-storage cases the file will be copied | |
| 291 | + // but not deleted, so we delete it here | |
| 292 | +                if ($result) { | |
| 293 | + call_user_func_array([$this->storage, $method], [$path]); | |
| 294 | + } | |
| 295 | +            } else { | |
| 296 | + $result = call_user_func_array([$this->storage, $method], [$path]); | |
| 297 | + } | |
| 298 | + unset($this->deletedFiles[$normalized]); | |
| 299 | +        } else if ($this->storage->file_exists($path)) { | |
| 300 | + $result = call_user_func_array([$this->storage, $method], [$path]); | |
| 301 | + } | |
| 302 | + | |
| 303 | + return $result; | |
| 304 | + } | |
| 305 | + | |
| 306 | + /** | |
| 307 | + * Setup the storate wrapper callback | |
| 308 | + */ | |
| 309 | +    public static function setupStorage() { | |
| 310 | +        \OC\Files\Filesystem::addStorageWrapper('oc_trashbin', function ($mountPoint, $storage) { | |
| 311 | + return new \OCA\Files_Trashbin\Storage( | |
| 312 | +                array('storage' => $storage, 'mountPoint' => $mountPoint), | |
| 313 | + \OC::$server->getUserManager(), | |
| 314 | + \OC::$server->getLogger(), | |
| 315 | + \OC::$server->getEventDispatcher(), | |
| 316 | + \OC::$server->getLazyRootFolder() | |
| 317 | + ); | |
| 318 | + }, 1); | |
| 319 | + } | |
| 320 | 320 | |
| 321 | 321 | } |