| @@ -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 | } | 
| @@ -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 | |
| @@ -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 | |
| @@ -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 | */ | 
| @@ -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 | -		'{DAV:}quota-available-bytes', | |
| 51 | -		'{http://owncloud.org/ns}permissions', | |
| 52 | -		'{http://owncloud.org/ns}downloadURL', | |
| 53 | -		'{http://owncloud.org/ns}dDC', | |
| 54 | -		'{http://owncloud.org/ns}size', | |
| 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 | +        '{DAV:}quota-available-bytes', | |
| 51 | +        '{http://owncloud.org/ns}permissions', | |
| 52 | +        '{http://owncloud.org/ns}downloadURL', | |
| 53 | +        '{http://owncloud.org/ns}dDC', | |
| 54 | +        '{http://owncloud.org/ns}size', | |
| 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 | } | 
| @@ -232,6 +232,9 @@ | ||
| 232 | 232 | return '"' . $this->info->getEtag() . '"'; | 
| 233 | 233 | } | 
| 234 | 234 | |
| 235 | + /** | |
| 236 | + * @param string $path | |
| 237 | + */ | |
| 235 | 238 |  	private function getPartFileBasePath($path) { | 
| 236 | 239 |  		$partFileInStorage = \OC::$server->getConfig()->getSystemValue('part_file_in_storage', true); | 
| 237 | 240 |  		if ($partFileInStorage) { | 
| @@ -58,519 +58,519 @@ | ||
| 58 | 58 | |
| 59 | 59 |  class File extends Node implements IFile { | 
| 60 | 60 | |
| 61 | - /** | |
| 62 | - * Updates the data | |
| 63 | - * | |
| 64 | - * The data argument is a readable stream resource. | |
| 65 | - * | |
| 66 | - * After a successful put operation, you may choose to return an ETag. The | |
| 67 | - * etag must always be surrounded by double-quotes. These quotes must | |
| 68 | - * appear in the actual string you're returning. | |
| 69 | - * | |
| 70 | - * Clients may use the ETag from a PUT request to later on make sure that | |
| 71 | - * when they update the file, the contents haven't changed in the mean | |
| 72 | - * time. | |
| 73 | - * | |
| 74 | - * If you don't plan to store the file byte-by-byte, and you return a | |
| 75 | - * different object on a subsequent GET you are strongly recommended to not | |
| 76 | - * return an ETag, and just return null. | |
| 77 | - * | |
| 78 | - * @param resource $data | |
| 79 | - * | |
| 80 | - * @throws Forbidden | |
| 81 | - * @throws UnsupportedMediaType | |
| 82 | - * @throws BadRequest | |
| 83 | - * @throws Exception | |
| 84 | - * @throws EntityTooLarge | |
| 85 | - * @throws ServiceUnavailable | |
| 86 | - * @throws FileLocked | |
| 87 | - * @return string|null | |
| 88 | - */ | |
| 89 | -	public function put($data) { | |
| 90 | -		try { | |
| 91 | - $exists = $this->fileView->file_exists($this->path); | |
| 92 | -			if ($this->info && $exists && !$this->info->isUpdateable()) { | |
| 93 | - throw new Forbidden(); | |
| 94 | - } | |
| 95 | -		} catch (StorageNotAvailableException $e) { | |
| 96 | -			throw new ServiceUnavailable("File is not updatable: " . $e->getMessage()); | |
| 97 | - } | |
| 98 | - | |
| 99 | - // verify path of the target | |
| 100 | - $this->verifyPath(); | |
| 101 | - | |
| 102 | - // chunked handling | |
| 103 | -		if (isset($_SERVER['HTTP_OC_CHUNKED'])) { | |
| 104 | -			try { | |
| 105 | - return $this->createFileChunked($data); | |
| 106 | -			} catch (\Exception $e) { | |
| 107 | - $this->convertToSabreException($e); | |
| 108 | - } | |
| 109 | - } | |
| 110 | - | |
| 111 | - list($partStorage) = $this->fileView->resolvePath($this->path); | |
| 112 | - $needsPartFile = $this->needsPartFile($partStorage) && (strlen($this->path) > 1); | |
| 113 | - | |
| 114 | -		if ($needsPartFile) { | |
| 115 | - // mark file as partial while uploading (ignored by the scanner) | |
| 116 | - $partFilePath = $this->getPartFileBasePath($this->path) . '.ocTransferId' . rand() . '.part'; | |
| 117 | -		} else { | |
| 118 | - // upload file directly as the final path | |
| 119 | - $partFilePath = $this->path; | |
| 120 | - | |
| 121 | - $this->emitPreHooks($exists); | |
| 122 | - } | |
| 123 | - | |
| 124 | - // the part file and target file might be on a different storage in case of a single file storage (e.g. single file share) | |
| 125 | - /** @var \OC\Files\Storage\Storage $partStorage */ | |
| 126 | - list($partStorage, $internalPartPath) = $this->fileView->resolvePath($partFilePath); | |
| 127 | - /** @var \OC\Files\Storage\Storage $storage */ | |
| 128 | - list($storage, $internalPath) = $this->fileView->resolvePath($this->path); | |
| 129 | -		try { | |
| 130 | - $target = $partStorage->fopen($internalPartPath, 'wb'); | |
| 131 | -			if ($target === false) { | |
| 132 | -				\OCP\Util::writeLog('webdav', '\OC\Files\Filesystem::fopen() failed', \OCP\Util::ERROR); | |
| 133 | - // because we have no clue about the cause we can only throw back a 500/Internal Server Error | |
| 134 | -				throw new Exception('Could not write file contents'); | |
| 135 | - } | |
| 136 | - list($count, $result) = \OC_Helper::streamCopy($data, $target); | |
| 137 | - fclose($target); | |
| 138 | - | |
| 139 | -			if ($result === false) { | |
| 140 | - $expected = -1; | |
| 141 | -				if (isset($_SERVER['CONTENT_LENGTH'])) { | |
| 142 | - $expected = $_SERVER['CONTENT_LENGTH']; | |
| 143 | - } | |
| 144 | -				throw new Exception('Error while copying file to target location (copied bytes: ' . $count . ', expected filesize: ' . $expected . ' )'); | |
| 145 | - } | |
| 146 | - | |
| 147 | - // if content length is sent by client: | |
| 148 | - // double check if the file was fully received | |
| 149 | - // compare expected and actual size | |
| 150 | -			if (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['REQUEST_METHOD'] === 'PUT') { | |
| 151 | - $expected = $_SERVER['CONTENT_LENGTH']; | |
| 152 | -				if ($count != $expected) { | |
| 153 | -					throw new BadRequest('expected filesize ' . $expected . ' got ' . $count); | |
| 154 | - } | |
| 155 | - } | |
| 156 | - | |
| 157 | -		} catch (\Exception $e) { | |
| 158 | -			if ($needsPartFile) { | |
| 159 | - $partStorage->unlink($internalPartPath); | |
| 160 | - } | |
| 161 | - $this->convertToSabreException($e); | |
| 162 | - } | |
| 163 | - | |
| 164 | -		try { | |
| 165 | - $view = \OC\Files\Filesystem::getView(); | |
| 166 | - $run = ($view && $needsPartFile) ? $this->emitPreHooks($exists) : true; | |
| 167 | - | |
| 168 | -			try { | |
| 169 | - $this->changeLock(ILockingProvider::LOCK_EXCLUSIVE); | |
| 170 | -			} catch (LockedException $e) { | |
| 171 | -				if ($needsPartFile) { | |
| 172 | - $partStorage->unlink($internalPartPath); | |
| 173 | - } | |
| 174 | - throw new FileLocked($e->getMessage(), $e->getCode(), $e); | |
| 175 | - } | |
| 176 | - | |
| 177 | -			if ($needsPartFile) { | |
| 178 | - // rename to correct path | |
| 179 | -				try { | |
| 180 | -					if ($run) { | |
| 181 | - $renameOkay = $storage->moveFromStorage($partStorage, $internalPartPath, $internalPath); | |
| 182 | - $fileExists = $storage->file_exists($internalPath); | |
| 183 | - } | |
| 184 | -					if (!$run || $renameOkay === false || $fileExists === false) { | |
| 185 | -						\OCP\Util::writeLog('webdav', 'renaming part file to final file failed ($run: ' . ( $run ? 'true' : 'false' ) . ', $renameOkay: '  . ( $renameOkay ? 'true' : 'false' ) . ', $fileExists: ' . ( $fileExists ? 'true' : 'false' ) . ')', \OCP\Util::ERROR); | |
| 186 | -						throw new Exception('Could not rename part file to final file'); | |
| 187 | - } | |
| 188 | -				} catch (ForbiddenException $ex) { | |
| 189 | - throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry()); | |
| 190 | -				} catch (\Exception $e) { | |
| 191 | - $partStorage->unlink($internalPartPath); | |
| 192 | - $this->convertToSabreException($e); | |
| 193 | - } | |
| 194 | - } | |
| 195 | - | |
| 196 | - // since we skipped the view we need to scan and emit the hooks ourselves | |
| 197 | - $storage->getUpdater()->update($internalPath); | |
| 198 | - | |
| 199 | -			try { | |
| 200 | - $this->changeLock(ILockingProvider::LOCK_SHARED); | |
| 201 | -			} catch (LockedException $e) { | |
| 202 | - throw new FileLocked($e->getMessage(), $e->getCode(), $e); | |
| 203 | - } | |
| 204 | - | |
| 205 | - // allow sync clients to send the mtime along in a header | |
| 206 | - $request = \OC::$server->getRequest(); | |
| 207 | -			if (isset($request->server['HTTP_X_OC_MTIME'])) { | |
| 208 | - $mtimeStr = $request->server['HTTP_X_OC_MTIME']; | |
| 209 | -				if (!is_numeric($mtimeStr)) { | |
| 210 | -					throw new \InvalidArgumentException('X-OC-Mtime header must be an integer (unix timestamp).'); | |
| 211 | - } | |
| 212 | - $mtime = intval($mtimeStr); | |
| 213 | -				if ($this->fileView->touch($this->path, $mtime)) { | |
| 214 | -					header('X-OC-MTime: accepted'); | |
| 215 | - } | |
| 216 | - } | |
| 61 | + /** | |
| 62 | + * Updates the data | |
| 63 | + * | |
| 64 | + * The data argument is a readable stream resource. | |
| 65 | + * | |
| 66 | + * After a successful put operation, you may choose to return an ETag. The | |
| 67 | + * etag must always be surrounded by double-quotes. These quotes must | |
| 68 | + * appear in the actual string you're returning. | |
| 69 | + * | |
| 70 | + * Clients may use the ETag from a PUT request to later on make sure that | |
| 71 | + * when they update the file, the contents haven't changed in the mean | |
| 72 | + * time. | |
| 73 | + * | |
| 74 | + * If you don't plan to store the file byte-by-byte, and you return a | |
| 75 | + * different object on a subsequent GET you are strongly recommended to not | |
| 76 | + * return an ETag, and just return null. | |
| 77 | + * | |
| 78 | + * @param resource $data | |
| 79 | + * | |
| 80 | + * @throws Forbidden | |
| 81 | + * @throws UnsupportedMediaType | |
| 82 | + * @throws BadRequest | |
| 83 | + * @throws Exception | |
| 84 | + * @throws EntityTooLarge | |
| 85 | + * @throws ServiceUnavailable | |
| 86 | + * @throws FileLocked | |
| 87 | + * @return string|null | |
| 88 | + */ | |
| 89 | +    public function put($data) { | |
| 90 | +        try { | |
| 91 | + $exists = $this->fileView->file_exists($this->path); | |
| 92 | +            if ($this->info && $exists && !$this->info->isUpdateable()) { | |
| 93 | + throw new Forbidden(); | |
| 94 | + } | |
| 95 | +        } catch (StorageNotAvailableException $e) { | |
| 96 | +            throw new ServiceUnavailable("File is not updatable: " . $e->getMessage()); | |
| 97 | + } | |
| 98 | + | |
| 99 | + // verify path of the target | |
| 100 | + $this->verifyPath(); | |
| 101 | + | |
| 102 | + // chunked handling | |
| 103 | +        if (isset($_SERVER['HTTP_OC_CHUNKED'])) { | |
| 104 | +            try { | |
| 105 | + return $this->createFileChunked($data); | |
| 106 | +            } catch (\Exception $e) { | |
| 107 | + $this->convertToSabreException($e); | |
| 108 | + } | |
| 109 | + } | |
| 110 | + | |
| 111 | + list($partStorage) = $this->fileView->resolvePath($this->path); | |
| 112 | + $needsPartFile = $this->needsPartFile($partStorage) && (strlen($this->path) > 1); | |
| 113 | + | |
| 114 | +        if ($needsPartFile) { | |
| 115 | + // mark file as partial while uploading (ignored by the scanner) | |
| 116 | + $partFilePath = $this->getPartFileBasePath($this->path) . '.ocTransferId' . rand() . '.part'; | |
| 117 | +        } else { | |
| 118 | + // upload file directly as the final path | |
| 119 | + $partFilePath = $this->path; | |
| 120 | + | |
| 121 | + $this->emitPreHooks($exists); | |
| 122 | + } | |
| 123 | + | |
| 124 | + // the part file and target file might be on a different storage in case of a single file storage (e.g. single file share) | |
| 125 | + /** @var \OC\Files\Storage\Storage $partStorage */ | |
| 126 | + list($partStorage, $internalPartPath) = $this->fileView->resolvePath($partFilePath); | |
| 127 | + /** @var \OC\Files\Storage\Storage $storage */ | |
| 128 | + list($storage, $internalPath) = $this->fileView->resolvePath($this->path); | |
| 129 | +        try { | |
| 130 | + $target = $partStorage->fopen($internalPartPath, 'wb'); | |
| 131 | +            if ($target === false) { | |
| 132 | +                \OCP\Util::writeLog('webdav', '\OC\Files\Filesystem::fopen() failed', \OCP\Util::ERROR); | |
| 133 | + // because we have no clue about the cause we can only throw back a 500/Internal Server Error | |
| 134 | +                throw new Exception('Could not write file contents'); | |
| 135 | + } | |
| 136 | + list($count, $result) = \OC_Helper::streamCopy($data, $target); | |
| 137 | + fclose($target); | |
| 138 | + | |
| 139 | +            if ($result === false) { | |
| 140 | + $expected = -1; | |
| 141 | +                if (isset($_SERVER['CONTENT_LENGTH'])) { | |
| 142 | + $expected = $_SERVER['CONTENT_LENGTH']; | |
| 143 | + } | |
| 144 | +                throw new Exception('Error while copying file to target location (copied bytes: ' . $count . ', expected filesize: ' . $expected . ' )'); | |
| 145 | + } | |
| 146 | + | |
| 147 | + // if content length is sent by client: | |
| 148 | + // double check if the file was fully received | |
| 149 | + // compare expected and actual size | |
| 150 | +            if (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['REQUEST_METHOD'] === 'PUT') { | |
| 151 | + $expected = $_SERVER['CONTENT_LENGTH']; | |
| 152 | +                if ($count != $expected) { | |
| 153 | +                    throw new BadRequest('expected filesize ' . $expected . ' got ' . $count); | |
| 154 | + } | |
| 155 | + } | |
| 156 | + | |
| 157 | +        } catch (\Exception $e) { | |
| 158 | +            if ($needsPartFile) { | |
| 159 | + $partStorage->unlink($internalPartPath); | |
| 160 | + } | |
| 161 | + $this->convertToSabreException($e); | |
| 162 | + } | |
| 163 | + | |
| 164 | +        try { | |
| 165 | + $view = \OC\Files\Filesystem::getView(); | |
| 166 | + $run = ($view && $needsPartFile) ? $this->emitPreHooks($exists) : true; | |
| 167 | + | |
| 168 | +            try { | |
| 169 | + $this->changeLock(ILockingProvider::LOCK_EXCLUSIVE); | |
| 170 | +            } catch (LockedException $e) { | |
| 171 | +                if ($needsPartFile) { | |
| 172 | + $partStorage->unlink($internalPartPath); | |
| 173 | + } | |
| 174 | + throw new FileLocked($e->getMessage(), $e->getCode(), $e); | |
| 175 | + } | |
| 176 | + | |
| 177 | +            if ($needsPartFile) { | |
| 178 | + // rename to correct path | |
| 179 | +                try { | |
| 180 | +                    if ($run) { | |
| 181 | + $renameOkay = $storage->moveFromStorage($partStorage, $internalPartPath, $internalPath); | |
| 182 | + $fileExists = $storage->file_exists($internalPath); | |
| 183 | + } | |
| 184 | +                    if (!$run || $renameOkay === false || $fileExists === false) { | |
| 185 | +                        \OCP\Util::writeLog('webdav', 'renaming part file to final file failed ($run: ' . ( $run ? 'true' : 'false' ) . ', $renameOkay: '  . ( $renameOkay ? 'true' : 'false' ) . ', $fileExists: ' . ( $fileExists ? 'true' : 'false' ) . ')', \OCP\Util::ERROR); | |
| 186 | +                        throw new Exception('Could not rename part file to final file'); | |
| 187 | + } | |
| 188 | +                } catch (ForbiddenException $ex) { | |
| 189 | + throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry()); | |
| 190 | +                } catch (\Exception $e) { | |
| 191 | + $partStorage->unlink($internalPartPath); | |
| 192 | + $this->convertToSabreException($e); | |
| 193 | + } | |
| 194 | + } | |
| 195 | + | |
| 196 | + // since we skipped the view we need to scan and emit the hooks ourselves | |
| 197 | + $storage->getUpdater()->update($internalPath); | |
| 198 | + | |
| 199 | +            try { | |
| 200 | + $this->changeLock(ILockingProvider::LOCK_SHARED); | |
| 201 | +            } catch (LockedException $e) { | |
| 202 | + throw new FileLocked($e->getMessage(), $e->getCode(), $e); | |
| 203 | + } | |
| 204 | + | |
| 205 | + // allow sync clients to send the mtime along in a header | |
| 206 | + $request = \OC::$server->getRequest(); | |
| 207 | +            if (isset($request->server['HTTP_X_OC_MTIME'])) { | |
| 208 | + $mtimeStr = $request->server['HTTP_X_OC_MTIME']; | |
| 209 | +                if (!is_numeric($mtimeStr)) { | |
| 210 | +                    throw new \InvalidArgumentException('X-OC-Mtime header must be an integer (unix timestamp).'); | |
| 211 | + } | |
| 212 | + $mtime = intval($mtimeStr); | |
| 213 | +                if ($this->fileView->touch($this->path, $mtime)) { | |
| 214 | +                    header('X-OC-MTime: accepted'); | |
| 215 | + } | |
| 216 | + } | |
| 217 | 217 | |
| 218 | -			if ($view) { | |
| 219 | - $this->emitPostHooks($exists); | |
| 220 | - } | |
| 221 | - | |
| 222 | - $this->refreshInfo(); | |
| 223 | - | |
| 224 | -			if (isset($request->server['HTTP_OC_CHECKSUM'])) { | |
| 225 | - $checksum = trim($request->server['HTTP_OC_CHECKSUM']); | |
| 226 | - $this->fileView->putFileInfo($this->path, ['checksum' => $checksum]); | |
| 227 | - $this->refreshInfo(); | |
| 228 | -			} else if ($this->getChecksum() !== null && $this->getChecksum() !== '') { | |
| 229 | - $this->fileView->putFileInfo($this->path, ['checksum' => '']); | |
| 230 | - $this->refreshInfo(); | |
| 231 | - } | |
| 232 | - | |
| 233 | -		} catch (StorageNotAvailableException $e) { | |
| 234 | -			throw new ServiceUnavailable("Failed to check file size: " . $e->getMessage()); | |
| 235 | - } | |
| 236 | - | |
| 237 | - return '"' . $this->info->getEtag() . '"'; | |
| 238 | - } | |
| 239 | - | |
| 240 | -	private function getPartFileBasePath($path) { | |
| 241 | -		$partFileInStorage = \OC::$server->getConfig()->getSystemValue('part_file_in_storage', true); | |
| 242 | -		if ($partFileInStorage) { | |
| 243 | - return $path; | |
| 244 | -		} else { | |
| 245 | - return md5($path); // will place it in the root of the view with a unique name | |
| 246 | - } | |
| 247 | - } | |
| 248 | - | |
| 249 | - /** | |
| 250 | - * @param string $path | |
| 251 | - */ | |
| 252 | -	private function emitPreHooks($exists, $path = null) { | |
| 253 | -		if (is_null($path)) { | |
| 254 | - $path = $this->path; | |
| 255 | - } | |
| 256 | - $hookPath = Filesystem::getView()->getRelativePath($this->fileView->getAbsolutePath($path)); | |
| 257 | - $run = true; | |
| 258 | - | |
| 259 | -		if (!$exists) { | |
| 260 | - \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_create, array( | |
| 261 | - \OC\Files\Filesystem::signal_param_path => $hookPath, | |
| 262 | - \OC\Files\Filesystem::signal_param_run => &$run, | |
| 263 | - )); | |
| 264 | -		} else { | |
| 265 | - \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_update, array( | |
| 266 | - \OC\Files\Filesystem::signal_param_path => $hookPath, | |
| 267 | - \OC\Files\Filesystem::signal_param_run => &$run, | |
| 268 | - )); | |
| 269 | - } | |
| 270 | - \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_write, array( | |
| 271 | - \OC\Files\Filesystem::signal_param_path => $hookPath, | |
| 272 | - \OC\Files\Filesystem::signal_param_run => &$run, | |
| 273 | - )); | |
| 274 | - return $run; | |
| 275 | - } | |
| 276 | - | |
| 277 | - /** | |
| 278 | - * @param string $path | |
| 279 | - */ | |
| 280 | -	private function emitPostHooks($exists, $path = null) { | |
| 281 | -		if (is_null($path)) { | |
| 282 | - $path = $this->path; | |
| 283 | - } | |
| 284 | - $hookPath = Filesystem::getView()->getRelativePath($this->fileView->getAbsolutePath($path)); | |
| 285 | -		if (!$exists) { | |
| 286 | - \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_create, array( | |
| 287 | - \OC\Files\Filesystem::signal_param_path => $hookPath | |
| 288 | - )); | |
| 289 | -		} else { | |
| 290 | - \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_update, array( | |
| 291 | - \OC\Files\Filesystem::signal_param_path => $hookPath | |
| 292 | - )); | |
| 293 | - } | |
| 294 | - \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_write, array( | |
| 295 | - \OC\Files\Filesystem::signal_param_path => $hookPath | |
| 296 | - )); | |
| 297 | - } | |
| 298 | - | |
| 299 | - /** | |
| 300 | - * Returns the data | |
| 301 | - * | |
| 302 | - * @return resource | |
| 303 | - * @throws Forbidden | |
| 304 | - * @throws ServiceUnavailable | |
| 305 | - */ | |
| 306 | -	public function get() { | |
| 307 | - //throw exception if encryption is disabled but files are still encrypted | |
| 308 | -		try { | |
| 309 | -			if (!$this->info->isReadable()) { | |
| 310 | - // do a if the file did not exist | |
| 311 | - throw new NotFound(); | |
| 312 | - } | |
| 313 | - $res = $this->fileView->fopen(ltrim($this->path, '/'), 'rb'); | |
| 314 | -			if ($res === false) { | |
| 315 | -				throw new ServiceUnavailable("Could not open file"); | |
| 316 | - } | |
| 317 | - return $res; | |
| 318 | -		} catch (GenericEncryptionException $e) { | |
| 319 | - // returning 503 will allow retry of the operation at a later point in time | |
| 320 | -			throw new ServiceUnavailable("Encryption not ready: " . $e->getMessage()); | |
| 321 | -		} catch (StorageNotAvailableException $e) { | |
| 322 | -			throw new ServiceUnavailable("Failed to open file: " . $e->getMessage()); | |
| 323 | -		} catch (ForbiddenException $ex) { | |
| 324 | - throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry()); | |
| 325 | -		} catch (LockedException $e) { | |
| 326 | - throw new FileLocked($e->getMessage(), $e->getCode(), $e); | |
| 327 | - } | |
| 328 | - } | |
| 329 | - | |
| 330 | - /** | |
| 331 | - * Delete the current file | |
| 332 | - * | |
| 333 | - * @throws Forbidden | |
| 334 | - * @throws ServiceUnavailable | |
| 335 | - */ | |
| 336 | -	public function delete() { | |
| 337 | -		if (!$this->info->isDeletable()) { | |
| 338 | - throw new Forbidden(); | |
| 339 | - } | |
| 340 | - | |
| 341 | -		try { | |
| 342 | -			if (!$this->fileView->unlink($this->path)) { | |
| 343 | - // assume it wasn't possible to delete due to permissions | |
| 344 | - throw new Forbidden(); | |
| 345 | - } | |
| 346 | -		} catch (StorageNotAvailableException $e) { | |
| 347 | -			throw new ServiceUnavailable("Failed to unlink: " . $e->getMessage()); | |
| 348 | -		} catch (ForbiddenException $ex) { | |
| 349 | - throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry()); | |
| 350 | -		} catch (LockedException $e) { | |
| 351 | - throw new FileLocked($e->getMessage(), $e->getCode(), $e); | |
| 352 | - } | |
| 353 | - } | |
| 354 | - | |
| 355 | - /** | |
| 356 | - * Returns the mime-type for a file | |
| 357 | - * | |
| 358 | - * If null is returned, we'll assume application/octet-stream | |
| 359 | - * | |
| 360 | - * @return string | |
| 361 | - */ | |
| 362 | -	public function getContentType() { | |
| 363 | - $mimeType = $this->info->getMimetype(); | |
| 364 | - | |
| 365 | - // PROPFIND needs to return the correct mime type, for consistency with the web UI | |
| 366 | -		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') { | |
| 367 | - return $mimeType; | |
| 368 | - } | |
| 369 | - return \OC::$server->getMimeTypeDetector()->getSecureMimeType($mimeType); | |
| 370 | - } | |
| 371 | - | |
| 372 | - /** | |
| 373 | - * @return array|false | |
| 374 | - */ | |
| 375 | -	public function getDirectDownload() { | |
| 376 | -		if (\OCP\App::isEnabled('encryption')) { | |
| 377 | - return []; | |
| 378 | - } | |
| 379 | - /** @var \OCP\Files\Storage $storage */ | |
| 380 | - list($storage, $internalPath) = $this->fileView->resolvePath($this->path); | |
| 381 | -		if (is_null($storage)) { | |
| 382 | - return []; | |
| 383 | - } | |
| 384 | - | |
| 385 | - return $storage->getDirectDownload($internalPath); | |
| 386 | - } | |
| 387 | - | |
| 388 | - /** | |
| 389 | - * @param resource $data | |
| 390 | - * @return null|string | |
| 391 | - * @throws Exception | |
| 392 | - * @throws BadRequest | |
| 393 | - * @throws NotImplemented | |
| 394 | - * @throws ServiceUnavailable | |
| 395 | - */ | |
| 396 | -	private function createFileChunked($data) { | |
| 397 | - list($path, $name) = \Sabre\HTTP\URLUtil::splitPath($this->path); | |
| 398 | - | |
| 399 | - $info = \OC_FileChunking::decodeName($name); | |
| 400 | -		if (empty($info)) { | |
| 401 | -			throw new NotImplemented('Invalid chunk name'); | |
| 402 | - } | |
| 403 | - | |
| 404 | - $chunk_handler = new \OC_FileChunking($info); | |
| 405 | - $bytesWritten = $chunk_handler->store($info['index'], $data); | |
| 406 | - | |
| 407 | - //detect aborted upload | |
| 408 | -		if (isset ($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PUT') { | |
| 409 | -			if (isset($_SERVER['CONTENT_LENGTH'])) { | |
| 410 | - $expected = $_SERVER['CONTENT_LENGTH']; | |
| 411 | -				if ($bytesWritten != $expected) { | |
| 412 | - $chunk_handler->remove($info['index']); | |
| 413 | - throw new BadRequest( | |
| 414 | - 'expected filesize ' . $expected . ' got ' . $bytesWritten); | |
| 415 | - } | |
| 416 | - } | |
| 417 | - } | |
| 418 | - | |
| 419 | -		if ($chunk_handler->isComplete()) { | |
| 420 | - list($storage,) = $this->fileView->resolvePath($path); | |
| 421 | - $needsPartFile = $this->needsPartFile($storage); | |
| 422 | - $partFile = null; | |
| 423 | - | |
| 424 | - $targetPath = $path . '/' . $info['name']; | |
| 425 | - /** @var \OC\Files\Storage\Storage $targetStorage */ | |
| 426 | - list($targetStorage, $targetInternalPath) = $this->fileView->resolvePath($targetPath); | |
| 427 | - | |
| 428 | - $exists = $this->fileView->file_exists($targetPath); | |
| 429 | - | |
| 430 | -			try { | |
| 431 | - $this->fileView->lockFile($targetPath, ILockingProvider::LOCK_SHARED); | |
| 432 | - | |
| 433 | - $this->emitPreHooks($exists, $targetPath); | |
| 434 | - $this->fileView->changeLock($targetPath, ILockingProvider::LOCK_EXCLUSIVE); | |
| 435 | - /** @var \OC\Files\Storage\Storage $targetStorage */ | |
| 436 | - list($targetStorage, $targetInternalPath) = $this->fileView->resolvePath($targetPath); | |
| 437 | - | |
| 438 | -				if ($needsPartFile) { | |
| 439 | - // we first assembly the target file as a part file | |
| 440 | - $partFile = $this->getPartFileBasePath($path . '/' . $info['name']) . '.ocTransferId' . $info['transferid'] . '.part'; | |
| 441 | - /** @var \OC\Files\Storage\Storage $targetStorage */ | |
| 442 | - list($partStorage, $partInternalPath) = $this->fileView->resolvePath($partFile); | |
| 443 | - | |
| 444 | - | |
| 445 | - $chunk_handler->file_assemble($partStorage, $partInternalPath); | |
| 446 | - | |
| 447 | - // here is the final atomic rename | |
| 448 | - $renameOkay = $targetStorage->moveFromStorage($partStorage, $partInternalPath, $targetInternalPath); | |
| 449 | - $fileExists = $targetStorage->file_exists($targetInternalPath); | |
| 450 | -					if ($renameOkay === false || $fileExists === false) { | |
| 451 | -						\OCP\Util::writeLog('webdav', '\OC\Files\Filesystem::rename() failed', \OCP\Util::ERROR); | |
| 452 | - // only delete if an error occurred and the target file was already created | |
| 453 | -						if ($fileExists) { | |
| 454 | - // set to null to avoid double-deletion when handling exception | |
| 455 | - // stray part file | |
| 456 | - $partFile = null; | |
| 457 | - $targetStorage->unlink($targetInternalPath); | |
| 458 | - } | |
| 459 | - $this->fileView->changeLock($targetPath, ILockingProvider::LOCK_SHARED); | |
| 460 | -						throw new Exception('Could not rename part file assembled from chunks'); | |
| 461 | - } | |
| 462 | -				} else { | |
| 463 | - // assemble directly into the final file | |
| 464 | - $chunk_handler->file_assemble($targetStorage, $targetInternalPath); | |
| 465 | - } | |
| 466 | - | |
| 467 | - // allow sync clients to send the mtime along in a header | |
| 468 | - $request = \OC::$server->getRequest(); | |
| 469 | -				if (isset($request->server['HTTP_X_OC_MTIME'])) { | |
| 470 | -					if ($targetStorage->touch($targetInternalPath, $request->server['HTTP_X_OC_MTIME'])) { | |
| 471 | -						header('X-OC-MTime: accepted'); | |
| 472 | - } | |
| 473 | - } | |
| 474 | - | |
| 475 | - // since we skipped the view we need to scan and emit the hooks ourselves | |
| 476 | - $targetStorage->getUpdater()->update($targetInternalPath); | |
| 477 | - | |
| 478 | - $this->fileView->changeLock($targetPath, ILockingProvider::LOCK_SHARED); | |
| 479 | - | |
| 480 | - $this->emitPostHooks($exists, $targetPath); | |
| 481 | - | |
| 482 | - // FIXME: should call refreshInfo but can't because $this->path is not the of the final file | |
| 483 | - $info = $this->fileView->getFileInfo($targetPath); | |
| 484 | - | |
| 485 | -				if (isset($request->server['HTTP_OC_CHECKSUM'])) { | |
| 486 | - $checksum = trim($request->server['HTTP_OC_CHECKSUM']); | |
| 487 | - $this->fileView->putFileInfo($targetPath, ['checksum' => $checksum]); | |
| 488 | -				} else if ($info->getChecksum() !== null && $info->getChecksum() !== '') { | |
| 489 | - $this->fileView->putFileInfo($this->path, ['checksum' => '']); | |
| 490 | - } | |
| 491 | - | |
| 492 | - $this->fileView->unlockFile($targetPath, ILockingProvider::LOCK_SHARED); | |
| 493 | - | |
| 494 | - return $info->getEtag(); | |
| 495 | -			} catch (\Exception $e) { | |
| 496 | -				if ($partFile !== null) { | |
| 497 | - $targetStorage->unlink($targetInternalPath); | |
| 498 | - } | |
| 499 | - $this->convertToSabreException($e); | |
| 500 | - } | |
| 501 | - } | |
| 502 | - | |
| 503 | - return null; | |
| 504 | - } | |
| 505 | - | |
| 506 | - /** | |
| 507 | - * Returns whether a part file is needed for the given storage | |
| 508 | - * or whether the file can be assembled/uploaded directly on the | |
| 509 | - * target storage. | |
| 510 | - * | |
| 511 | - * @param \OCP\Files\Storage $storage | |
| 512 | - * @return bool true if the storage needs part file handling | |
| 513 | - */ | |
| 514 | -	private function needsPartFile($storage) { | |
| 515 | - // TODO: in the future use ChunkHandler provided by storage | |
| 516 | -		return !$storage->instanceOfStorage('OCA\Files_Sharing\External\Storage') && | |
| 517 | -			!$storage->instanceOfStorage('OC\Files\Storage\OwnCloud') && | |
| 518 | - $storage->needsPartFile(); | |
| 519 | - } | |
| 520 | - | |
| 521 | - /** | |
| 522 | - * Convert the given exception to a SabreException instance | |
| 523 | - * | |
| 524 | - * @param \Exception $e | |
| 525 | - * | |
| 526 | - * @throws \Sabre\DAV\Exception | |
| 527 | - */ | |
| 528 | -	private function convertToSabreException(\Exception $e) { | |
| 529 | -		if ($e instanceof \Sabre\DAV\Exception) { | |
| 530 | - throw $e; | |
| 531 | - } | |
| 532 | -		if ($e instanceof NotPermittedException) { | |
| 533 | - // a more general case - due to whatever reason the content could not be written | |
| 534 | - throw new Forbidden($e->getMessage(), 0, $e); | |
| 535 | - } | |
| 536 | -		if ($e instanceof ForbiddenException) { | |
| 537 | - // the path for the file was forbidden | |
| 538 | - throw new DAVForbiddenException($e->getMessage(), $e->getRetry(), $e); | |
| 539 | - } | |
| 540 | -		if ($e instanceof EntityTooLargeException) { | |
| 541 | - // the file is too big to be stored | |
| 542 | - throw new EntityTooLarge($e->getMessage(), 0, $e); | |
| 543 | - } | |
| 544 | -		if ($e instanceof InvalidContentException) { | |
| 545 | - // the file content is not permitted | |
| 546 | - throw new UnsupportedMediaType($e->getMessage(), 0, $e); | |
| 547 | - } | |
| 548 | -		if ($e instanceof InvalidPathException) { | |
| 549 | - // the path for the file was not valid | |
| 550 | - // TODO: find proper http status code for this case | |
| 551 | - throw new Forbidden($e->getMessage(), 0, $e); | |
| 552 | - } | |
| 553 | -		if ($e instanceof LockedException || $e instanceof LockNotAcquiredException) { | |
| 554 | - // the file is currently being written to by another process | |
| 555 | - throw new FileLocked($e->getMessage(), $e->getCode(), $e); | |
| 556 | - } | |
| 557 | -		if ($e instanceof GenericEncryptionException) { | |
| 558 | - // returning 503 will allow retry of the operation at a later point in time | |
| 559 | -			throw new ServiceUnavailable('Encryption not ready: ' . $e->getMessage(), 0, $e); | |
| 560 | - } | |
| 561 | -		if ($e instanceof StorageNotAvailableException) { | |
| 562 | -			throw new ServiceUnavailable('Failed to write file contents: ' . $e->getMessage(), 0, $e); | |
| 563 | - } | |
| 564 | - | |
| 565 | - throw new \Sabre\DAV\Exception($e->getMessage(), 0, $e); | |
| 566 | - } | |
| 567 | - | |
| 568 | - /** | |
| 569 | - * Get the checksum for this file | |
| 570 | - * | |
| 571 | - * @return string | |
| 572 | - */ | |
| 573 | -	public function getChecksum() { | |
| 574 | - return $this->info->getChecksum(); | |
| 575 | - } | |
| 218 | +            if ($view) { | |
| 219 | + $this->emitPostHooks($exists); | |
| 220 | + } | |
| 221 | + | |
| 222 | + $this->refreshInfo(); | |
| 223 | + | |
| 224 | +            if (isset($request->server['HTTP_OC_CHECKSUM'])) { | |
| 225 | + $checksum = trim($request->server['HTTP_OC_CHECKSUM']); | |
| 226 | + $this->fileView->putFileInfo($this->path, ['checksum' => $checksum]); | |
| 227 | + $this->refreshInfo(); | |
| 228 | +            } else if ($this->getChecksum() !== null && $this->getChecksum() !== '') { | |
| 229 | + $this->fileView->putFileInfo($this->path, ['checksum' => '']); | |
| 230 | + $this->refreshInfo(); | |
| 231 | + } | |
| 232 | + | |
| 233 | +        } catch (StorageNotAvailableException $e) { | |
| 234 | +            throw new ServiceUnavailable("Failed to check file size: " . $e->getMessage()); | |
| 235 | + } | |
| 236 | + | |
| 237 | + return '"' . $this->info->getEtag() . '"'; | |
| 238 | + } | |
| 239 | + | |
| 240 | +    private function getPartFileBasePath($path) { | |
| 241 | +        $partFileInStorage = \OC::$server->getConfig()->getSystemValue('part_file_in_storage', true); | |
| 242 | +        if ($partFileInStorage) { | |
| 243 | + return $path; | |
| 244 | +        } else { | |
| 245 | + return md5($path); // will place it in the root of the view with a unique name | |
| 246 | + } | |
| 247 | + } | |
| 248 | + | |
| 249 | + /** | |
| 250 | + * @param string $path | |
| 251 | + */ | |
| 252 | +    private function emitPreHooks($exists, $path = null) { | |
| 253 | +        if (is_null($path)) { | |
| 254 | + $path = $this->path; | |
| 255 | + } | |
| 256 | + $hookPath = Filesystem::getView()->getRelativePath($this->fileView->getAbsolutePath($path)); | |
| 257 | + $run = true; | |
| 258 | + | |
| 259 | +        if (!$exists) { | |
| 260 | + \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_create, array( | |
| 261 | + \OC\Files\Filesystem::signal_param_path => $hookPath, | |
| 262 | + \OC\Files\Filesystem::signal_param_run => &$run, | |
| 263 | + )); | |
| 264 | +        } else { | |
| 265 | + \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_update, array( | |
| 266 | + \OC\Files\Filesystem::signal_param_path => $hookPath, | |
| 267 | + \OC\Files\Filesystem::signal_param_run => &$run, | |
| 268 | + )); | |
| 269 | + } | |
| 270 | + \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_write, array( | |
| 271 | + \OC\Files\Filesystem::signal_param_path => $hookPath, | |
| 272 | + \OC\Files\Filesystem::signal_param_run => &$run, | |
| 273 | + )); | |
| 274 | + return $run; | |
| 275 | + } | |
| 276 | + | |
| 277 | + /** | |
| 278 | + * @param string $path | |
| 279 | + */ | |
| 280 | +    private function emitPostHooks($exists, $path = null) { | |
| 281 | +        if (is_null($path)) { | |
| 282 | + $path = $this->path; | |
| 283 | + } | |
| 284 | + $hookPath = Filesystem::getView()->getRelativePath($this->fileView->getAbsolutePath($path)); | |
| 285 | +        if (!$exists) { | |
| 286 | + \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_create, array( | |
| 287 | + \OC\Files\Filesystem::signal_param_path => $hookPath | |
| 288 | + )); | |
| 289 | +        } else { | |
| 290 | + \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_update, array( | |
| 291 | + \OC\Files\Filesystem::signal_param_path => $hookPath | |
| 292 | + )); | |
| 293 | + } | |
| 294 | + \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_write, array( | |
| 295 | + \OC\Files\Filesystem::signal_param_path => $hookPath | |
| 296 | + )); | |
| 297 | + } | |
| 298 | + | |
| 299 | + /** | |
| 300 | + * Returns the data | |
| 301 | + * | |
| 302 | + * @return resource | |
| 303 | + * @throws Forbidden | |
| 304 | + * @throws ServiceUnavailable | |
| 305 | + */ | |
| 306 | +    public function get() { | |
| 307 | + //throw exception if encryption is disabled but files are still encrypted | |
| 308 | +        try { | |
| 309 | +            if (!$this->info->isReadable()) { | |
| 310 | + // do a if the file did not exist | |
| 311 | + throw new NotFound(); | |
| 312 | + } | |
| 313 | + $res = $this->fileView->fopen(ltrim($this->path, '/'), 'rb'); | |
| 314 | +            if ($res === false) { | |
| 315 | +                throw new ServiceUnavailable("Could not open file"); | |
| 316 | + } | |
| 317 | + return $res; | |
| 318 | +        } catch (GenericEncryptionException $e) { | |
| 319 | + // returning 503 will allow retry of the operation at a later point in time | |
| 320 | +            throw new ServiceUnavailable("Encryption not ready: " . $e->getMessage()); | |
| 321 | +        } catch (StorageNotAvailableException $e) { | |
| 322 | +            throw new ServiceUnavailable("Failed to open file: " . $e->getMessage()); | |
| 323 | +        } catch (ForbiddenException $ex) { | |
| 324 | + throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry()); | |
| 325 | +        } catch (LockedException $e) { | |
| 326 | + throw new FileLocked($e->getMessage(), $e->getCode(), $e); | |
| 327 | + } | |
| 328 | + } | |
| 329 | + | |
| 330 | + /** | |
| 331 | + * Delete the current file | |
| 332 | + * | |
| 333 | + * @throws Forbidden | |
| 334 | + * @throws ServiceUnavailable | |
| 335 | + */ | |
| 336 | +    public function delete() { | |
| 337 | +        if (!$this->info->isDeletable()) { | |
| 338 | + throw new Forbidden(); | |
| 339 | + } | |
| 340 | + | |
| 341 | +        try { | |
| 342 | +            if (!$this->fileView->unlink($this->path)) { | |
| 343 | + // assume it wasn't possible to delete due to permissions | |
| 344 | + throw new Forbidden(); | |
| 345 | + } | |
| 346 | +        } catch (StorageNotAvailableException $e) { | |
| 347 | +            throw new ServiceUnavailable("Failed to unlink: " . $e->getMessage()); | |
| 348 | +        } catch (ForbiddenException $ex) { | |
| 349 | + throw new DAVForbiddenException($ex->getMessage(), $ex->getRetry()); | |
| 350 | +        } catch (LockedException $e) { | |
| 351 | + throw new FileLocked($e->getMessage(), $e->getCode(), $e); | |
| 352 | + } | |
| 353 | + } | |
| 354 | + | |
| 355 | + /** | |
| 356 | + * Returns the mime-type for a file | |
| 357 | + * | |
| 358 | + * If null is returned, we'll assume application/octet-stream | |
| 359 | + * | |
| 360 | + * @return string | |
| 361 | + */ | |
| 362 | +    public function getContentType() { | |
| 363 | + $mimeType = $this->info->getMimetype(); | |
| 364 | + | |
| 365 | + // PROPFIND needs to return the correct mime type, for consistency with the web UI | |
| 366 | +        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') { | |
| 367 | + return $mimeType; | |
| 368 | + } | |
| 369 | + return \OC::$server->getMimeTypeDetector()->getSecureMimeType($mimeType); | |
| 370 | + } | |
| 371 | + | |
| 372 | + /** | |
| 373 | + * @return array|false | |
| 374 | + */ | |
| 375 | +    public function getDirectDownload() { | |
| 376 | +        if (\OCP\App::isEnabled('encryption')) { | |
| 377 | + return []; | |
| 378 | + } | |
| 379 | + /** @var \OCP\Files\Storage $storage */ | |
| 380 | + list($storage, $internalPath) = $this->fileView->resolvePath($this->path); | |
| 381 | +        if (is_null($storage)) { | |
| 382 | + return []; | |
| 383 | + } | |
| 384 | + | |
| 385 | + return $storage->getDirectDownload($internalPath); | |
| 386 | + } | |
| 387 | + | |
| 388 | + /** | |
| 389 | + * @param resource $data | |
| 390 | + * @return null|string | |
| 391 | + * @throws Exception | |
| 392 | + * @throws BadRequest | |
| 393 | + * @throws NotImplemented | |
| 394 | + * @throws ServiceUnavailable | |
| 395 | + */ | |
| 396 | +    private function createFileChunked($data) { | |
| 397 | + list($path, $name) = \Sabre\HTTP\URLUtil::splitPath($this->path); | |
| 398 | + | |
| 399 | + $info = \OC_FileChunking::decodeName($name); | |
| 400 | +        if (empty($info)) { | |
| 401 | +            throw new NotImplemented('Invalid chunk name'); | |
| 402 | + } | |
| 403 | + | |
| 404 | + $chunk_handler = new \OC_FileChunking($info); | |
| 405 | + $bytesWritten = $chunk_handler->store($info['index'], $data); | |
| 406 | + | |
| 407 | + //detect aborted upload | |
| 408 | +        if (isset ($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PUT') { | |
| 409 | +            if (isset($_SERVER['CONTENT_LENGTH'])) { | |
| 410 | + $expected = $_SERVER['CONTENT_LENGTH']; | |
| 411 | +                if ($bytesWritten != $expected) { | |
| 412 | + $chunk_handler->remove($info['index']); | |
| 413 | + throw new BadRequest( | |
| 414 | + 'expected filesize ' . $expected . ' got ' . $bytesWritten); | |
| 415 | + } | |
| 416 | + } | |
| 417 | + } | |
| 418 | + | |
| 419 | +        if ($chunk_handler->isComplete()) { | |
| 420 | + list($storage,) = $this->fileView->resolvePath($path); | |
| 421 | + $needsPartFile = $this->needsPartFile($storage); | |
| 422 | + $partFile = null; | |
| 423 | + | |
| 424 | + $targetPath = $path . '/' . $info['name']; | |
| 425 | + /** @var \OC\Files\Storage\Storage $targetStorage */ | |
| 426 | + list($targetStorage, $targetInternalPath) = $this->fileView->resolvePath($targetPath); | |
| 427 | + | |
| 428 | + $exists = $this->fileView->file_exists($targetPath); | |
| 429 | + | |
| 430 | +            try { | |
| 431 | + $this->fileView->lockFile($targetPath, ILockingProvider::LOCK_SHARED); | |
| 432 | + | |
| 433 | + $this->emitPreHooks($exists, $targetPath); | |
| 434 | + $this->fileView->changeLock($targetPath, ILockingProvider::LOCK_EXCLUSIVE); | |
| 435 | + /** @var \OC\Files\Storage\Storage $targetStorage */ | |
| 436 | + list($targetStorage, $targetInternalPath) = $this->fileView->resolvePath($targetPath); | |
| 437 | + | |
| 438 | +                if ($needsPartFile) { | |
| 439 | + // we first assembly the target file as a part file | |
| 440 | + $partFile = $this->getPartFileBasePath($path . '/' . $info['name']) . '.ocTransferId' . $info['transferid'] . '.part'; | |
| 441 | + /** @var \OC\Files\Storage\Storage $targetStorage */ | |
| 442 | + list($partStorage, $partInternalPath) = $this->fileView->resolvePath($partFile); | |
| 443 | + | |
| 444 | + | |
| 445 | + $chunk_handler->file_assemble($partStorage, $partInternalPath); | |
| 446 | + | |
| 447 | + // here is the final atomic rename | |
| 448 | + $renameOkay = $targetStorage->moveFromStorage($partStorage, $partInternalPath, $targetInternalPath); | |
| 449 | + $fileExists = $targetStorage->file_exists($targetInternalPath); | |
| 450 | +                    if ($renameOkay === false || $fileExists === false) { | |
| 451 | +                        \OCP\Util::writeLog('webdav', '\OC\Files\Filesystem::rename() failed', \OCP\Util::ERROR); | |
| 452 | + // only delete if an error occurred and the target file was already created | |
| 453 | +                        if ($fileExists) { | |
| 454 | + // set to null to avoid double-deletion when handling exception | |
| 455 | + // stray part file | |
| 456 | + $partFile = null; | |
| 457 | + $targetStorage->unlink($targetInternalPath); | |
| 458 | + } | |
| 459 | + $this->fileView->changeLock($targetPath, ILockingProvider::LOCK_SHARED); | |
| 460 | +                        throw new Exception('Could not rename part file assembled from chunks'); | |
| 461 | + } | |
| 462 | +                } else { | |
| 463 | + // assemble directly into the final file | |
| 464 | + $chunk_handler->file_assemble($targetStorage, $targetInternalPath); | |
| 465 | + } | |
| 466 | + | |
| 467 | + // allow sync clients to send the mtime along in a header | |
| 468 | + $request = \OC::$server->getRequest(); | |
| 469 | +                if (isset($request->server['HTTP_X_OC_MTIME'])) { | |
| 470 | +                    if ($targetStorage->touch($targetInternalPath, $request->server['HTTP_X_OC_MTIME'])) { | |
| 471 | +                        header('X-OC-MTime: accepted'); | |
| 472 | + } | |
| 473 | + } | |
| 474 | + | |
| 475 | + // since we skipped the view we need to scan and emit the hooks ourselves | |
| 476 | + $targetStorage->getUpdater()->update($targetInternalPath); | |
| 477 | + | |
| 478 | + $this->fileView->changeLock($targetPath, ILockingProvider::LOCK_SHARED); | |
| 479 | + | |
| 480 | + $this->emitPostHooks($exists, $targetPath); | |
| 481 | + | |
| 482 | + // FIXME: should call refreshInfo but can't because $this->path is not the of the final file | |
| 483 | + $info = $this->fileView->getFileInfo($targetPath); | |
| 484 | + | |
| 485 | +                if (isset($request->server['HTTP_OC_CHECKSUM'])) { | |
| 486 | + $checksum = trim($request->server['HTTP_OC_CHECKSUM']); | |
| 487 | + $this->fileView->putFileInfo($targetPath, ['checksum' => $checksum]); | |
| 488 | +                } else if ($info->getChecksum() !== null && $info->getChecksum() !== '') { | |
| 489 | + $this->fileView->putFileInfo($this->path, ['checksum' => '']); | |
| 490 | + } | |
| 491 | + | |
| 492 | + $this->fileView->unlockFile($targetPath, ILockingProvider::LOCK_SHARED); | |
| 493 | + | |
| 494 | + return $info->getEtag(); | |
| 495 | +            } catch (\Exception $e) { | |
| 496 | +                if ($partFile !== null) { | |
| 497 | + $targetStorage->unlink($targetInternalPath); | |
| 498 | + } | |
| 499 | + $this->convertToSabreException($e); | |
| 500 | + } | |
| 501 | + } | |
| 502 | + | |
| 503 | + return null; | |
| 504 | + } | |
| 505 | + | |
| 506 | + /** | |
| 507 | + * Returns whether a part file is needed for the given storage | |
| 508 | + * or whether the file can be assembled/uploaded directly on the | |
| 509 | + * target storage. | |
| 510 | + * | |
| 511 | + * @param \OCP\Files\Storage $storage | |
| 512 | + * @return bool true if the storage needs part file handling | |
| 513 | + */ | |
| 514 | +    private function needsPartFile($storage) { | |
| 515 | + // TODO: in the future use ChunkHandler provided by storage | |
| 516 | +        return !$storage->instanceOfStorage('OCA\Files_Sharing\External\Storage') && | |
| 517 | +            !$storage->instanceOfStorage('OC\Files\Storage\OwnCloud') && | |
| 518 | + $storage->needsPartFile(); | |
| 519 | + } | |
| 520 | + | |
| 521 | + /** | |
| 522 | + * Convert the given exception to a SabreException instance | |
| 523 | + * | |
| 524 | + * @param \Exception $e | |
| 525 | + * | |
| 526 | + * @throws \Sabre\DAV\Exception | |
| 527 | + */ | |
| 528 | +    private function convertToSabreException(\Exception $e) { | |
| 529 | +        if ($e instanceof \Sabre\DAV\Exception) { | |
| 530 | + throw $e; | |
| 531 | + } | |
| 532 | +        if ($e instanceof NotPermittedException) { | |
| 533 | + // a more general case - due to whatever reason the content could not be written | |
| 534 | + throw new Forbidden($e->getMessage(), 0, $e); | |
| 535 | + } | |
| 536 | +        if ($e instanceof ForbiddenException) { | |
| 537 | + // the path for the file was forbidden | |
| 538 | + throw new DAVForbiddenException($e->getMessage(), $e->getRetry(), $e); | |
| 539 | + } | |
| 540 | +        if ($e instanceof EntityTooLargeException) { | |
| 541 | + // the file is too big to be stored | |
| 542 | + throw new EntityTooLarge($e->getMessage(), 0, $e); | |
| 543 | + } | |
| 544 | +        if ($e instanceof InvalidContentException) { | |
| 545 | + // the file content is not permitted | |
| 546 | + throw new UnsupportedMediaType($e->getMessage(), 0, $e); | |
| 547 | + } | |
| 548 | +        if ($e instanceof InvalidPathException) { | |
| 549 | + // the path for the file was not valid | |
| 550 | + // TODO: find proper http status code for this case | |
| 551 | + throw new Forbidden($e->getMessage(), 0, $e); | |
| 552 | + } | |
| 553 | +        if ($e instanceof LockedException || $e instanceof LockNotAcquiredException) { | |
| 554 | + // the file is currently being written to by another process | |
| 555 | + throw new FileLocked($e->getMessage(), $e->getCode(), $e); | |
| 556 | + } | |
| 557 | +        if ($e instanceof GenericEncryptionException) { | |
| 558 | + // returning 503 will allow retry of the operation at a later point in time | |
| 559 | +            throw new ServiceUnavailable('Encryption not ready: ' . $e->getMessage(), 0, $e); | |
| 560 | + } | |
| 561 | +        if ($e instanceof StorageNotAvailableException) { | |
| 562 | +            throw new ServiceUnavailable('Failed to write file contents: ' . $e->getMessage(), 0, $e); | |
| 563 | + } | |
| 564 | + | |
| 565 | + throw new \Sabre\DAV\Exception($e->getMessage(), 0, $e); | |
| 566 | + } | |
| 567 | + | |
| 568 | + /** | |
| 569 | + * Get the checksum for this file | |
| 570 | + * | |
| 571 | + * @return string | |
| 572 | + */ | |
| 573 | +    public function getChecksum() { | |
| 574 | + return $this->info->getChecksum(); | |
| 575 | + } | |
| 576 | 576 | } | 
| @@ -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 | 
| @@ -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, $name) = URLUtil::splitPath($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, $name) = URLUtil::splitPath($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 | } | 
| @@ -118,7 +118,7 @@ discard block | ||
| 118 | 118 | |
| 119 | 119 | /** | 
| 120 | 120 | * @param string $data | 
| 121 | - * @return int | |
| 121 | + * @return boolean | |
| 122 | 122 | */ | 
| 123 | 123 |  	public function stream_write($data) { | 
| 124 | 124 | return false; | 
| @@ -224,7 +224,7 @@ discard block | ||
| 224 | 224 | } | 
| 225 | 225 | |
| 226 | 226 | /** | 
| 227 | - * @param $pos | |
| 227 | + * @param integer $pos | |
| 228 | 228 | * @return IFile | null | 
| 229 | 229 | */ | 
| 230 | 230 |  	private function getNodeForPosition($pos) { | 
| @@ -35,243 +35,243 @@ | ||
| 35 | 35 | */ | 
| 36 | 36 |  class AssemblyStream implements \Icewind\Streams\File { | 
| 37 | 37 | |
| 38 | - /** @var resource */ | |
| 39 | - private $context; | |
| 40 | - | |
| 41 | - /** @var IFile[] */ | |
| 42 | - private $nodes; | |
| 43 | - | |
| 44 | - /** @var int */ | |
| 45 | - private $pos = 0; | |
| 46 | - | |
| 47 | - /** @var array */ | |
| 48 | - private $sortedNodes; | |
| 49 | - | |
| 50 | - /** @var int */ | |
| 51 | - private $size; | |
| 52 | - | |
| 53 | - /** @var resource */ | |
| 54 | - private $currentStream = null; | |
| 55 | - | |
| 56 | - /** | |
| 57 | - * @param string $path | |
| 58 | - * @param string $mode | |
| 59 | - * @param int $options | |
| 60 | - * @param string &$opened_path | |
| 61 | - * @return bool | |
| 62 | - */ | |
| 63 | -	public function stream_open($path, $mode, $options, &$opened_path) { | |
| 64 | -		$this->loadContext('assembly'); | |
| 65 | - | |
| 66 | - // sort the nodes | |
| 67 | - $nodes = $this->nodes; | |
| 68 | - // http://stackoverflow.com/a/10985500 | |
| 69 | -		@usort($nodes, function(IFile $a, IFile $b) { | |
| 70 | - return strnatcmp($a->getName(), $b->getName()); | |
| 71 | - }); | |
| 72 | - $this->nodes = $nodes; | |
| 73 | - | |
| 74 | - // build additional information | |
| 75 | - $this->sortedNodes = []; | |
| 76 | - $start = 0; | |
| 77 | -		foreach($this->nodes as $node) { | |
| 78 | - $size = $node->getSize(); | |
| 79 | - $name = $node->getName(); | |
| 80 | - $this->sortedNodes[$name] = ['node' => $node, 'start' => $start, 'end' => $start + $size]; | |
| 81 | - $start += $size; | |
| 82 | - $this->size = $start; | |
| 83 | - } | |
| 84 | - return true; | |
| 85 | - } | |
| 86 | - | |
| 87 | - /** | |
| 88 | - * @param string $offset | |
| 89 | - * @param int $whence | |
| 90 | - * @return bool | |
| 91 | - */ | |
| 92 | -	public function stream_seek($offset, $whence = SEEK_SET) { | |
| 93 | - return false; | |
| 94 | - } | |
| 95 | - | |
| 96 | - /** | |
| 97 | - * @return int | |
| 98 | - */ | |
| 99 | -	public function stream_tell() { | |
| 100 | - return $this->pos; | |
| 101 | - } | |
| 102 | - | |
| 103 | - /** | |
| 104 | - * @param int $count | |
| 105 | - * @return string | |
| 106 | - */ | |
| 107 | -	public function stream_read($count) { | |
| 108 | -		do { | |
| 109 | -			if ($this->currentStream === null) { | |
| 110 | - list($node, $posInNode) = $this->getNodeForPosition($this->pos); | |
| 111 | -				if (is_null($node)) { | |
| 112 | - // reached last node, no more data | |
| 113 | - return ''; | |
| 114 | - } | |
| 115 | - $this->currentStream = $this->getStream($node); | |
| 116 | - fseek($this->currentStream, $posInNode); | |
| 117 | - } | |
| 118 | - | |
| 119 | - $data = fread($this->currentStream, $count); | |
| 120 | - // isset is faster than strlen | |
| 121 | -			if (isset($data[$count - 1])) { | |
| 122 | - // we read the full count | |
| 123 | - $read = $count; | |
| 124 | -			} else { | |
| 125 | - // reaching end of stream, which happens less often so strlen is ok | |
| 126 | - $read = strlen($data); | |
| 127 | - } | |
| 128 | - | |
| 129 | -			if (feof($this->currentStream)) { | |
| 130 | - fclose($this->currentStream); | |
| 131 | - $this->currentNode = null; | |
| 132 | - $this->currentStream = null; | |
| 133 | - } | |
| 134 | - // if no data read, try again with the next node because | |
| 135 | - // returning empty data can make the caller think there is no more | |
| 136 | - // data left to read | |
| 137 | - } while ($read === 0); | |
| 138 | - | |
| 139 | - // update position | |
| 140 | - $this->pos += $read; | |
| 141 | - return $data; | |
| 142 | - } | |
| 143 | - | |
| 144 | - /** | |
| 145 | - * @param string $data | |
| 146 | - * @return int | |
| 147 | - */ | |
| 148 | -	public function stream_write($data) { | |
| 149 | - return false; | |
| 150 | - } | |
| 151 | - | |
| 152 | - /** | |
| 153 | - * @param int $option | |
| 154 | - * @param int $arg1 | |
| 155 | - * @param int $arg2 | |
| 156 | - * @return bool | |
| 157 | - */ | |
| 158 | -	public function stream_set_option($option, $arg1, $arg2) { | |
| 159 | - return false; | |
| 160 | - } | |
| 161 | - | |
| 162 | - /** | |
| 163 | - * @param int $size | |
| 164 | - * @return bool | |
| 165 | - */ | |
| 166 | -	public function stream_truncate($size) { | |
| 167 | - return false; | |
| 168 | - } | |
| 169 | - | |
| 170 | - /** | |
| 171 | - * @return array | |
| 172 | - */ | |
| 173 | -	public function stream_stat() { | |
| 174 | - return []; | |
| 175 | - } | |
| 176 | - | |
| 177 | - /** | |
| 178 | - * @param int $operation | |
| 179 | - * @return bool | |
| 180 | - */ | |
| 181 | -	public function stream_lock($operation) { | |
| 182 | - return false; | |
| 183 | - } | |
| 184 | - | |
| 185 | - /** | |
| 186 | - * @return bool | |
| 187 | - */ | |
| 188 | -	public function stream_flush() { | |
| 189 | - return false; | |
| 190 | - } | |
| 191 | - | |
| 192 | - /** | |
| 193 | - * @return bool | |
| 194 | - */ | |
| 195 | -	public function stream_eof() { | |
| 196 | - return $this->pos >= $this->size; | |
| 197 | - } | |
| 198 | - | |
| 199 | - /** | |
| 200 | - * @return bool | |
| 201 | - */ | |
| 202 | -	public function stream_close() { | |
| 203 | - return true; | |
| 204 | - } | |
| 205 | - | |
| 206 | - | |
| 207 | - /** | |
| 208 | - * Load the source from the stream context and return the context options | |
| 209 | - * | |
| 210 | - * @param string $name | |
| 211 | - * @return array | |
| 212 | - * @throws \Exception | |
| 213 | - */ | |
| 214 | -	protected function loadContext($name) { | |
| 215 | - $context = stream_context_get_options($this->context); | |
| 216 | -		if (isset($context[$name])) { | |
| 217 | - $context = $context[$name]; | |
| 218 | -		} else { | |
| 219 | -			throw new \BadMethodCallException('Invalid context, "' . $name . '" options not set'); | |
| 220 | - } | |
| 221 | -		if (isset($context['nodes']) and is_array($context['nodes'])) { | |
| 222 | - $this->nodes = $context['nodes']; | |
| 223 | -		} else { | |
| 224 | -			throw new \BadMethodCallException('Invalid context, nodes not set'); | |
| 225 | - } | |
| 226 | - return $context; | |
| 227 | - } | |
| 228 | - | |
| 229 | - /** | |
| 230 | - * @param IFile[] $nodes | |
| 231 | - * @return resource | |
| 232 | - * | |
| 233 | - * @throws \BadMethodCallException | |
| 234 | - */ | |
| 235 | -	public static function wrap(array $nodes) { | |
| 236 | - $context = stream_context_create([ | |
| 237 | - 'assembly' => [ | |
| 238 | - 'nodes' => $nodes] | |
| 239 | - ]); | |
| 240 | -		stream_wrapper_register('assembly', '\OCA\DAV\Upload\AssemblyStream'); | |
| 241 | -		try { | |
| 242 | -			$wrapped = fopen('assembly://', 'r', null, $context); | |
| 243 | -		} catch (\BadMethodCallException $e) { | |
| 244 | -			stream_wrapper_unregister('assembly'); | |
| 245 | - throw $e; | |
| 246 | - } | |
| 247 | -		stream_wrapper_unregister('assembly'); | |
| 248 | - return $wrapped; | |
| 249 | - } | |
| 250 | - | |
| 251 | - /** | |
| 252 | - * @param $pos | |
| 253 | - * @return IFile | null | |
| 254 | - */ | |
| 255 | -	private function getNodeForPosition($pos) { | |
| 256 | -		foreach($this->sortedNodes as $node) { | |
| 257 | -			if ($pos >= $node['start'] && $pos < $node['end']) { | |
| 258 | - return [$node['node'], $pos - $node['start']]; | |
| 259 | - } | |
| 260 | - } | |
| 261 | - return null; | |
| 262 | - } | |
| 263 | - | |
| 264 | - /** | |
| 265 | - * @param IFile $node | |
| 266 | - * @return resource | |
| 267 | - */ | |
| 268 | -	private function getStream(IFile $node) { | |
| 269 | - $data = $node->get(); | |
| 270 | -		if (is_resource($data)) { | |
| 271 | - return $data; | |
| 272 | - } | |
| 273 | - | |
| 274 | -		return fopen('data://text/plain,' . $data,'r'); | |
| 275 | - } | |
| 38 | + /** @var resource */ | |
| 39 | + private $context; | |
| 40 | + | |
| 41 | + /** @var IFile[] */ | |
| 42 | + private $nodes; | |
| 43 | + | |
| 44 | + /** @var int */ | |
| 45 | + private $pos = 0; | |
| 46 | + | |
| 47 | + /** @var array */ | |
| 48 | + private $sortedNodes; | |
| 49 | + | |
| 50 | + /** @var int */ | |
| 51 | + private $size; | |
| 52 | + | |
| 53 | + /** @var resource */ | |
| 54 | + private $currentStream = null; | |
| 55 | + | |
| 56 | + /** | |
| 57 | + * @param string $path | |
| 58 | + * @param string $mode | |
| 59 | + * @param int $options | |
| 60 | + * @param string &$opened_path | |
| 61 | + * @return bool | |
| 62 | + */ | |
| 63 | +    public function stream_open($path, $mode, $options, &$opened_path) { | |
| 64 | +        $this->loadContext('assembly'); | |
| 65 | + | |
| 66 | + // sort the nodes | |
| 67 | + $nodes = $this->nodes; | |
| 68 | + // http://stackoverflow.com/a/10985500 | |
| 69 | +        @usort($nodes, function(IFile $a, IFile $b) { | |
| 70 | + return strnatcmp($a->getName(), $b->getName()); | |
| 71 | + }); | |
| 72 | + $this->nodes = $nodes; | |
| 73 | + | |
| 74 | + // build additional information | |
| 75 | + $this->sortedNodes = []; | |
| 76 | + $start = 0; | |
| 77 | +        foreach($this->nodes as $node) { | |
| 78 | + $size = $node->getSize(); | |
| 79 | + $name = $node->getName(); | |
| 80 | + $this->sortedNodes[$name] = ['node' => $node, 'start' => $start, 'end' => $start + $size]; | |
| 81 | + $start += $size; | |
| 82 | + $this->size = $start; | |
| 83 | + } | |
| 84 | + return true; | |
| 85 | + } | |
| 86 | + | |
| 87 | + /** | |
| 88 | + * @param string $offset | |
| 89 | + * @param int $whence | |
| 90 | + * @return bool | |
| 91 | + */ | |
| 92 | +    public function stream_seek($offset, $whence = SEEK_SET) { | |
| 93 | + return false; | |
| 94 | + } | |
| 95 | + | |
| 96 | + /** | |
| 97 | + * @return int | |
| 98 | + */ | |
| 99 | +    public function stream_tell() { | |
| 100 | + return $this->pos; | |
| 101 | + } | |
| 102 | + | |
| 103 | + /** | |
| 104 | + * @param int $count | |
| 105 | + * @return string | |
| 106 | + */ | |
| 107 | +    public function stream_read($count) { | |
| 108 | +        do { | |
| 109 | +            if ($this->currentStream === null) { | |
| 110 | + list($node, $posInNode) = $this->getNodeForPosition($this->pos); | |
| 111 | +                if (is_null($node)) { | |
| 112 | + // reached last node, no more data | |
| 113 | + return ''; | |
| 114 | + } | |
| 115 | + $this->currentStream = $this->getStream($node); | |
| 116 | + fseek($this->currentStream, $posInNode); | |
| 117 | + } | |
| 118 | + | |
| 119 | + $data = fread($this->currentStream, $count); | |
| 120 | + // isset is faster than strlen | |
| 121 | +            if (isset($data[$count - 1])) { | |
| 122 | + // we read the full count | |
| 123 | + $read = $count; | |
| 124 | +            } else { | |
| 125 | + // reaching end of stream, which happens less often so strlen is ok | |
| 126 | + $read = strlen($data); | |
| 127 | + } | |
| 128 | + | |
| 129 | +            if (feof($this->currentStream)) { | |
| 130 | + fclose($this->currentStream); | |
| 131 | + $this->currentNode = null; | |
| 132 | + $this->currentStream = null; | |
| 133 | + } | |
| 134 | + // if no data read, try again with the next node because | |
| 135 | + // returning empty data can make the caller think there is no more | |
| 136 | + // data left to read | |
| 137 | + } while ($read === 0); | |
| 138 | + | |
| 139 | + // update position | |
| 140 | + $this->pos += $read; | |
| 141 | + return $data; | |
| 142 | + } | |
| 143 | + | |
| 144 | + /** | |
| 145 | + * @param string $data | |
| 146 | + * @return int | |
| 147 | + */ | |
| 148 | +    public function stream_write($data) { | |
| 149 | + return false; | |
| 150 | + } | |
| 151 | + | |
| 152 | + /** | |
| 153 | + * @param int $option | |
| 154 | + * @param int $arg1 | |
| 155 | + * @param int $arg2 | |
| 156 | + * @return bool | |
| 157 | + */ | |
| 158 | +    public function stream_set_option($option, $arg1, $arg2) { | |
| 159 | + return false; | |
| 160 | + } | |
| 161 | + | |
| 162 | + /** | |
| 163 | + * @param int $size | |
| 164 | + * @return bool | |
| 165 | + */ | |
| 166 | +    public function stream_truncate($size) { | |
| 167 | + return false; | |
| 168 | + } | |
| 169 | + | |
| 170 | + /** | |
| 171 | + * @return array | |
| 172 | + */ | |
| 173 | +    public function stream_stat() { | |
| 174 | + return []; | |
| 175 | + } | |
| 176 | + | |
| 177 | + /** | |
| 178 | + * @param int $operation | |
| 179 | + * @return bool | |
| 180 | + */ | |
| 181 | +    public function stream_lock($operation) { | |
| 182 | + return false; | |
| 183 | + } | |
| 184 | + | |
| 185 | + /** | |
| 186 | + * @return bool | |
| 187 | + */ | |
| 188 | +    public function stream_flush() { | |
| 189 | + return false; | |
| 190 | + } | |
| 191 | + | |
| 192 | + /** | |
| 193 | + * @return bool | |
| 194 | + */ | |
| 195 | +    public function stream_eof() { | |
| 196 | + return $this->pos >= $this->size; | |
| 197 | + } | |
| 198 | + | |
| 199 | + /** | |
| 200 | + * @return bool | |
| 201 | + */ | |
| 202 | +    public function stream_close() { | |
| 203 | + return true; | |
| 204 | + } | |
| 205 | + | |
| 206 | + | |
| 207 | + /** | |
| 208 | + * Load the source from the stream context and return the context options | |
| 209 | + * | |
| 210 | + * @param string $name | |
| 211 | + * @return array | |
| 212 | + * @throws \Exception | |
| 213 | + */ | |
| 214 | +    protected function loadContext($name) { | |
| 215 | + $context = stream_context_get_options($this->context); | |
| 216 | +        if (isset($context[$name])) { | |
| 217 | + $context = $context[$name]; | |
| 218 | +        } else { | |
| 219 | +            throw new \BadMethodCallException('Invalid context, "' . $name . '" options not set'); | |
| 220 | + } | |
| 221 | +        if (isset($context['nodes']) and is_array($context['nodes'])) { | |
| 222 | + $this->nodes = $context['nodes']; | |
| 223 | +        } else { | |
| 224 | +            throw new \BadMethodCallException('Invalid context, nodes not set'); | |
| 225 | + } | |
| 226 | + return $context; | |
| 227 | + } | |
| 228 | + | |
| 229 | + /** | |
| 230 | + * @param IFile[] $nodes | |
| 231 | + * @return resource | |
| 232 | + * | |
| 233 | + * @throws \BadMethodCallException | |
| 234 | + */ | |
| 235 | +    public static function wrap(array $nodes) { | |
| 236 | + $context = stream_context_create([ | |
| 237 | + 'assembly' => [ | |
| 238 | + 'nodes' => $nodes] | |
| 239 | + ]); | |
| 240 | +        stream_wrapper_register('assembly', '\OCA\DAV\Upload\AssemblyStream'); | |
| 241 | +        try { | |
| 242 | +            $wrapped = fopen('assembly://', 'r', null, $context); | |
| 243 | +        } catch (\BadMethodCallException $e) { | |
| 244 | +            stream_wrapper_unregister('assembly'); | |
| 245 | + throw $e; | |
| 246 | + } | |
| 247 | +        stream_wrapper_unregister('assembly'); | |
| 248 | + return $wrapped; | |
| 249 | + } | |
| 250 | + | |
| 251 | + /** | |
| 252 | + * @param $pos | |
| 253 | + * @return IFile | null | |
| 254 | + */ | |
| 255 | +    private function getNodeForPosition($pos) { | |
| 256 | +        foreach($this->sortedNodes as $node) { | |
| 257 | +            if ($pos >= $node['start'] && $pos < $node['end']) { | |
| 258 | + return [$node['node'], $pos - $node['start']]; | |
| 259 | + } | |
| 260 | + } | |
| 261 | + return null; | |
| 262 | + } | |
| 263 | + | |
| 264 | + /** | |
| 265 | + * @param IFile $node | |
| 266 | + * @return resource | |
| 267 | + */ | |
| 268 | +    private function getStream(IFile $node) { | |
| 269 | + $data = $node->get(); | |
| 270 | +        if (is_resource($data)) { | |
| 271 | + return $data; | |
| 272 | + } | |
| 273 | + | |
| 274 | +        return fopen('data://text/plain,' . $data,'r'); | |
| 275 | + } | |
| 276 | 276 | |
| 277 | 277 | } | 
| @@ -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 | |
| @@ -43,549 +43,549 @@ | ||
| 43 | 43 | |
| 44 | 44 |  class Encryption implements IEncryptionModule { | 
| 45 | 45 | |
| 46 | - const ID = 'OC_DEFAULT_MODULE'; | |
| 47 | - const DISPLAY_NAME = 'Default encryption module'; | |
| 48 | - | |
| 49 | - /** | |
| 50 | - * @var Crypt | |
| 51 | - */ | |
| 52 | - private $crypt; | |
| 53 | - | |
| 54 | - /** @var string */ | |
| 55 | - private $cipher; | |
| 56 | - | |
| 57 | - /** @var string */ | |
| 58 | - private $path; | |
| 59 | - | |
| 60 | - /** @var string */ | |
| 61 | - private $user; | |
| 62 | - | |
| 63 | - /** @var array */ | |
| 64 | - private $owner; | |
| 65 | - | |
| 66 | - /** @var string */ | |
| 67 | - private $fileKey; | |
| 68 | - | |
| 69 | - /** @var string */ | |
| 70 | - private $writeCache; | |
| 71 | - | |
| 72 | - /** @var KeyManager */ | |
| 73 | - private $keyManager; | |
| 74 | - | |
| 75 | - /** @var array */ | |
| 76 | - private $accessList; | |
| 77 | - | |
| 78 | - /** @var boolean */ | |
| 79 | - private $isWriteOperation; | |
| 80 | - | |
| 81 | - /** @var Util */ | |
| 82 | - private $util; | |
| 83 | - | |
| 84 | - /** @var Session */ | |
| 85 | - private $session; | |
| 86 | - | |
| 87 | - /** @var ILogger */ | |
| 88 | - private $logger; | |
| 89 | - | |
| 90 | - /** @var IL10N */ | |
| 91 | - private $l; | |
| 92 | - | |
| 93 | - /** @var EncryptAll */ | |
| 94 | - private $encryptAll; | |
| 95 | - | |
| 96 | - /** @var bool */ | |
| 97 | - private $useMasterPassword; | |
| 98 | - | |
| 99 | - /** @var DecryptAll */ | |
| 100 | - private $decryptAll; | |
| 101 | - | |
| 102 | - /** @var int unencrypted block size if block contains signature */ | |
| 103 | - private $unencryptedBlockSizeSigned = 6072; | |
| 104 | - | |
| 105 | - /** @var int unencrypted block size */ | |
| 106 | - private $unencryptedBlockSize = 6126; | |
| 107 | - | |
| 108 | - /** @var int Current version of the file */ | |
| 109 | - private $version = 0; | |
| 110 | - | |
| 111 | - /** @var array remember encryption signature version */ | |
| 112 | - private static $rememberVersion = []; | |
| 113 | - | |
| 114 | - | |
| 115 | - /** | |
| 116 | - * | |
| 117 | - * @param Crypt $crypt | |
| 118 | - * @param KeyManager $keyManager | |
| 119 | - * @param Util $util | |
| 120 | - * @param Session $session | |
| 121 | - * @param EncryptAll $encryptAll | |
| 122 | - * @param DecryptAll $decryptAll | |
| 123 | - * @param ILogger $logger | |
| 124 | - * @param IL10N $il10n | |
| 125 | - */ | |
| 126 | - public function __construct(Crypt $crypt, | |
| 127 | - KeyManager $keyManager, | |
| 128 | - Util $util, | |
| 129 | - Session $session, | |
| 130 | - EncryptAll $encryptAll, | |
| 131 | - DecryptAll $decryptAll, | |
| 132 | - ILogger $logger, | |
| 133 | -								IL10N $il10n) { | |
| 134 | - $this->crypt = $crypt; | |
| 135 | - $this->keyManager = $keyManager; | |
| 136 | - $this->util = $util; | |
| 137 | - $this->session = $session; | |
| 138 | - $this->encryptAll = $encryptAll; | |
| 139 | - $this->decryptAll = $decryptAll; | |
| 140 | - $this->logger = $logger; | |
| 141 | - $this->l = $il10n; | |
| 142 | - $this->owner = []; | |
| 143 | - $this->useMasterPassword = $util->isMasterKeyEnabled(); | |
| 144 | - } | |
| 145 | - | |
| 146 | - /** | |
| 147 | - * @return string defining the technical unique id | |
| 148 | - */ | |
| 149 | -	public function getId() { | |
| 150 | - return self::ID; | |
| 151 | - } | |
| 152 | - | |
| 153 | - /** | |
| 154 | - * In comparison to getKey() this function returns a human readable (maybe translated) name | |
| 155 | - * | |
| 156 | - * @return string | |
| 157 | - */ | |
| 158 | -	public function getDisplayName() { | |
| 159 | - return self::DISPLAY_NAME; | |
| 160 | - } | |
| 161 | - | |
| 162 | - /** | |
| 163 | - * start receiving chunks from a file. This is the place where you can | |
| 164 | - * perform some initial step before starting encrypting/decrypting the | |
| 165 | - * chunks | |
| 166 | - * | |
| 167 | - * @param string $path to the file | |
| 168 | - * @param string $user who read/write the file | |
| 169 | - * @param string $mode php stream open mode | |
| 170 | - * @param array $header contains the header data read from the file | |
| 171 | - * @param array $accessList who has access to the file contains the key 'users' and 'public' | |
| 172 | - * | |
| 173 | - * @return array $header contain data as key-value pairs which should be | |
| 174 | - * written to the header, in case of a write operation | |
| 175 | - * or if no additional data is needed return a empty array | |
| 176 | - */ | |
| 177 | -	public function begin($path, $user, $mode, array $header, array $accessList) { | |
| 178 | - $this->path = $this->getPathToRealFile($path); | |
| 179 | - $this->accessList = $accessList; | |
| 180 | - $this->user = $user; | |
| 181 | - $this->isWriteOperation = false; | |
| 182 | - $this->writeCache = ''; | |
| 183 | - | |
| 184 | -		if($this->session->isReady() === false) { | |
| 185 | - // if the master key is enabled we can initialize encryption | |
| 186 | - // with a empty password and user name | |
| 187 | -			if ($this->util->isMasterKeyEnabled()) { | |
| 188 | -				$this->keyManager->init('', ''); | |
| 189 | - } | |
| 190 | - } | |
| 191 | - | |
| 192 | -		if ($this->session->decryptAllModeActivated()) { | |
| 193 | - $encryptedFileKey = $this->keyManager->getEncryptedFileKey($this->path); | |
| 194 | - $shareKey = $this->keyManager->getShareKey($this->path, $this->session->getDecryptAllUid()); | |
| 195 | - $this->fileKey = $this->crypt->multiKeyDecrypt($encryptedFileKey, | |
| 196 | - $shareKey, | |
| 197 | - $this->session->getDecryptAllKey()); | |
| 198 | -		} else { | |
| 199 | - $this->fileKey = $this->keyManager->getFileKey($this->path, $this->user); | |
| 200 | - } | |
| 201 | - | |
| 202 | - // always use the version from the original file, also part files | |
| 203 | - // need to have a correct version number if they get moved over to the | |
| 204 | - // final location | |
| 205 | - $this->version = (int)$this->keyManager->getVersion($this->stripPartFileExtension($path), new View()); | |
| 206 | - | |
| 207 | - if ( | |
| 208 | - $mode === 'w' | |
| 209 | - || $mode === 'w+' | |
| 210 | - || $mode === 'wb' | |
| 211 | - || $mode === 'wb+' | |
| 212 | -		) { | |
| 213 | - $this->isWriteOperation = true; | |
| 214 | -			if (empty($this->fileKey)) { | |
| 215 | - $this->fileKey = $this->crypt->generateFileKey(); | |
| 216 | - } | |
| 217 | -		} else { | |
| 218 | - // if we read a part file we need to increase the version by 1 | |
| 219 | - // because the version number was also increased by writing | |
| 220 | - // the part file | |
| 221 | -			if(Scanner::isPartialFile($path)) { | |
| 222 | - $this->version = $this->version + 1; | |
| 223 | - } | |
| 224 | - } | |
| 225 | - | |
| 226 | -		if ($this->isWriteOperation) { | |
| 227 | - $this->cipher = $this->crypt->getCipher(); | |
| 228 | -		} elseif (isset($header['cipher'])) { | |
| 229 | - $this->cipher = $header['cipher']; | |
| 230 | -		} else { | |
| 231 | - // if we read a file without a header we fall-back to the legacy cipher | |
| 232 | - // which was used in <=oC6 | |
| 233 | - $this->cipher = $this->crypt->getLegacyCipher(); | |
| 234 | - } | |
| 235 | - | |
| 236 | -		return array('cipher' => $this->cipher, 'signed' => 'true'); | |
| 237 | - } | |
| 238 | - | |
| 239 | - /** | |
| 240 | - * last chunk received. This is the place where you can perform some final | |
| 241 | - * operation and return some remaining data if something is left in your | |
| 242 | - * buffer. | |
| 243 | - * | |
| 244 | - * @param string $path to the file | |
| 245 | - * @param int $position | |
| 246 | - * @return string remained data which should be written to the file in case | |
| 247 | - * of a write operation | |
| 248 | - * @throws PublicKeyMissingException | |
| 249 | - * @throws \Exception | |
| 250 | - * @throws \OCA\Encryption\Exceptions\MultiKeyEncryptException | |
| 251 | - */ | |
| 252 | -	public function end($path, $position = 0) { | |
| 253 | - $result = ''; | |
| 254 | -		if ($this->isWriteOperation) { | |
| 255 | - $this->keyManager->setVersion($path, $this->version + 1, new View()); | |
| 256 | - // in case of a part file we remember the new signature versions | |
| 257 | - // the version will be set later on update. | |
| 258 | - // This way we make sure that other apps listening to the pre-hooks | |
| 259 | - // still get the old version which should be the correct value for them | |
| 260 | -			if (Scanner::isPartialFile($path)) { | |
| 261 | - self::$rememberVersion[$this->stripPartFileExtension($path)] = $this->version + 1; | |
| 262 | - } | |
| 263 | -			if (!empty($this->writeCache)) { | |
| 264 | - $result = $this->crypt->symmetricEncryptFileContent($this->writeCache, $this->fileKey, $this->version + 1, $position); | |
| 265 | - $this->writeCache = ''; | |
| 266 | - } | |
| 267 | - $publicKeys = array(); | |
| 268 | -			if ($this->useMasterPassword === true) { | |
| 269 | - $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey(); | |
| 270 | -			} else { | |
| 271 | -				foreach ($this->accessList['users'] as $uid) { | |
| 272 | -					try { | |
| 273 | - $publicKeys[$uid] = $this->keyManager->getPublicKey($uid); | |
| 274 | -					} catch (PublicKeyMissingException $e) { | |
| 275 | - $this->logger->warning( | |
| 276 | -							'no public key found for user "{uid}", user will not be able to read the file', | |
| 277 | - ['app' => 'encryption', 'uid' => $uid] | |
| 278 | - ); | |
| 279 | - // if the public key of the owner is missing we should fail | |
| 280 | -						if ($uid === $this->user) { | |
| 281 | - throw $e; | |
| 282 | - } | |
| 283 | - } | |
| 284 | - } | |
| 285 | - } | |
| 286 | - | |
| 287 | - $publicKeys = $this->keyManager->addSystemKeys($this->accessList, $publicKeys, $this->getOwner($path)); | |
| 288 | - $encryptedKeyfiles = $this->crypt->multiKeyEncrypt($this->fileKey, $publicKeys); | |
| 289 | - $this->keyManager->setAllFileKeys($this->path, $encryptedKeyfiles); | |
| 290 | - } | |
| 291 | - return $result; | |
| 292 | - } | |
| 293 | - | |
| 294 | - | |
| 295 | - | |
| 296 | - /** | |
| 297 | - * encrypt data | |
| 298 | - * | |
| 299 | - * @param string $data you want to encrypt | |
| 300 | - * @param int $position | |
| 301 | - * @return string encrypted data | |
| 302 | - */ | |
| 303 | -	public function encrypt($data, $position = 0) { | |
| 304 | - // If extra data is left over from the last round, make sure it | |
| 305 | - // is integrated into the next block | |
| 306 | -		if ($this->writeCache) { | |
| 307 | - | |
| 308 | - // Concat writeCache to start of $data | |
| 309 | - $data = $this->writeCache . $data; | |
| 310 | - | |
| 311 | - // Clear the write cache, ready for reuse - it has been | |
| 312 | - // flushed and its old contents processed | |
| 313 | - $this->writeCache = ''; | |
| 314 | - | |
| 315 | - } | |
| 316 | - | |
| 317 | - $encrypted = ''; | |
| 318 | - // While there still remains some data to be processed & written | |
| 319 | -		while (strlen($data) > 0) { | |
| 320 | - | |
| 321 | - // Remaining length for this iteration, not of the | |
| 322 | - // entire file (may be greater than 8192 bytes) | |
| 323 | - $remainingLength = strlen($data); | |
| 324 | - | |
| 325 | - // If data remaining to be written is less than the | |
| 326 | - // size of 1 6126 byte block | |
| 327 | -			if ($remainingLength < $this->unencryptedBlockSizeSigned) { | |
| 328 | - | |
| 329 | - // Set writeCache to contents of $data | |
| 330 | - // The writeCache will be carried over to the | |
| 331 | - // next write round, and added to the start of | |
| 332 | - // $data to ensure that written blocks are | |
| 333 | - // always the correct length. If there is still | |
| 334 | - // data in writeCache after the writing round | |
| 335 | - // has finished, then the data will be written | |
| 336 | - // to disk by $this->flush(). | |
| 337 | - $this->writeCache = $data; | |
| 338 | - | |
| 339 | - // Clear $data ready for next round | |
| 340 | - $data = ''; | |
| 341 | - | |
| 342 | -			} else { | |
| 343 | - | |
| 344 | - // Read the chunk from the start of $data | |
| 345 | - $chunk = substr($data, 0, $this->unencryptedBlockSizeSigned); | |
| 346 | - | |
| 347 | - $encrypted .= $this->crypt->symmetricEncryptFileContent($chunk, $this->fileKey, $this->version + 1, $position); | |
| 348 | - | |
| 349 | - // Remove the chunk we just processed from | |
| 350 | - // $data, leaving only unprocessed data in $data | |
| 351 | - // var, for handling on the next round | |
| 352 | - $data = substr($data, $this->unencryptedBlockSizeSigned); | |
| 353 | - | |
| 354 | - } | |
| 355 | - | |
| 356 | - } | |
| 357 | - | |
| 358 | - return $encrypted; | |
| 359 | - } | |
| 360 | - | |
| 361 | - /** | |
| 362 | - * decrypt data | |
| 363 | - * | |
| 364 | - * @param string $data you want to decrypt | |
| 365 | - * @param int $position | |
| 366 | - * @return string decrypted data | |
| 367 | - * @throws DecryptionFailedException | |
| 368 | - */ | |
| 369 | -	public function decrypt($data, $position = 0) { | |
| 370 | -		if (empty($this->fileKey)) { | |
| 371 | - $msg = 'Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.'; | |
| 372 | -			$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.'); | |
| 373 | - $this->logger->error($msg); | |
| 374 | - | |
| 375 | - throw new DecryptionFailedException($msg, $hint); | |
| 376 | - } | |
| 377 | - | |
| 378 | - return $this->crypt->symmetricDecryptFileContent($data, $this->fileKey, $this->cipher, $this->version, $position); | |
| 379 | - } | |
| 380 | - | |
| 381 | - /** | |
| 382 | - * update encrypted file, e.g. give additional users access to the file | |
| 383 | - * | |
| 384 | - * @param string $path path to the file which should be updated | |
| 385 | - * @param string $uid of the user who performs the operation | |
| 386 | - * @param array $accessList who has access to the file contains the key 'users' and 'public' | |
| 387 | - * @return boolean | |
| 388 | - */ | |
| 389 | -	public function update($path, $uid, array $accessList) { | |
| 390 | - | |
| 391 | -		if (empty($accessList)) { | |
| 392 | -			if (isset(self::$rememberVersion[$path])) { | |
| 393 | - $this->keyManager->setVersion($path, self::$rememberVersion[$path], new View()); | |
| 394 | - unset(self::$rememberVersion[$path]); | |
| 395 | - } | |
| 396 | - return; | |
| 397 | - } | |
| 398 | - | |
| 399 | - $fileKey = $this->keyManager->getFileKey($path, $uid); | |
| 400 | - | |
| 401 | -		if (!empty($fileKey)) { | |
| 402 | - | |
| 403 | - $publicKeys = array(); | |
| 404 | -			if ($this->useMasterPassword === true) { | |
| 405 | - $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey(); | |
| 406 | -			} else { | |
| 407 | -				foreach ($accessList['users'] as $user) { | |
| 408 | -					try { | |
| 409 | - $publicKeys[$user] = $this->keyManager->getPublicKey($user); | |
| 410 | -					} catch (PublicKeyMissingException $e) { | |
| 411 | -						$this->logger->warning('Could not encrypt file for ' . $user . ': ' . $e->getMessage()); | |
| 412 | - } | |
| 413 | - } | |
| 414 | - } | |
| 415 | - | |
| 416 | - $publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $this->getOwner($path)); | |
| 417 | - | |
| 418 | - $encryptedFileKey = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys); | |
| 419 | - | |
| 420 | - $this->keyManager->deleteAllFileKeys($path); | |
| 421 | - | |
| 422 | - $this->keyManager->setAllFileKeys($path, $encryptedFileKey); | |
| 423 | - | |
| 424 | -		} else { | |
| 425 | -			$this->logger->debug('no file key found, we assume that the file "{file}" is not encrypted', | |
| 426 | -				array('file' => $path, 'app' => 'encryption')); | |
| 427 | - | |
| 428 | - return false; | |
| 429 | - } | |
| 430 | - | |
| 431 | - return true; | |
| 432 | - } | |
| 433 | - | |
| 434 | - /** | |
| 435 | - * should the file be encrypted or not | |
| 436 | - * | |
| 437 | - * @param string $path | |
| 438 | - * @return boolean | |
| 439 | - */ | |
| 440 | -	public function shouldEncrypt($path) { | |
| 441 | -		if ($this->util->shouldEncryptHomeStorage() === false) { | |
| 442 | - $storage = $this->util->getStorage($path); | |
| 443 | -			if ($storage->instanceOfStorage('\OCP\Files\IHomeStorage')) { | |
| 444 | - return false; | |
| 445 | - } | |
| 446 | - } | |
| 447 | -		$parts = explode('/', $path); | |
| 448 | -		if (count($parts) < 4) { | |
| 449 | - return false; | |
| 450 | - } | |
| 451 | - | |
| 452 | -		if ($parts[2] == 'files') { | |
| 453 | - return true; | |
| 454 | - } | |
| 455 | -		if ($parts[2] == 'files_versions') { | |
| 456 | - return true; | |
| 457 | - } | |
| 458 | -		if ($parts[2] == 'files_trashbin') { | |
| 459 | - return true; | |
| 460 | - } | |
| 461 | - | |
| 462 | - return false; | |
| 463 | - } | |
| 464 | - | |
| 465 | - /** | |
| 466 | - * get size of the unencrypted payload per block. | |
| 467 | - * Nextcloud read/write files with a block size of 8192 byte | |
| 468 | - * | |
| 469 | - * @param bool $signed | |
| 470 | - * @return int | |
| 471 | - */ | |
| 472 | -	public function getUnencryptedBlockSize($signed = false) { | |
| 473 | -		if ($signed === false) { | |
| 474 | - return $this->unencryptedBlockSize; | |
| 475 | - } | |
| 476 | - | |
| 477 | - return $this->unencryptedBlockSizeSigned; | |
| 478 | - } | |
| 479 | - | |
| 480 | - /** | |
| 481 | - * check if the encryption module is able to read the file, | |
| 482 | - * e.g. if all encryption keys exists | |
| 483 | - * | |
| 484 | - * @param string $path | |
| 485 | - * @param string $uid user for whom we want to check if he can read the file | |
| 486 | - * @return bool | |
| 487 | - * @throws DecryptionFailedException | |
| 488 | - */ | |
| 489 | -	public function isReadable($path, $uid) { | |
| 490 | - $fileKey = $this->keyManager->getFileKey($path, $uid); | |
| 491 | -		if (empty($fileKey)) { | |
| 492 | - $owner = $this->util->getOwner($path); | |
| 493 | -			if ($owner !== $uid) { | |
| 494 | - // if it is a shared file we throw a exception with a useful | |
| 495 | - // error message because in this case it means that the file was | |
| 496 | - // shared with the user at a point where the user didn't had a | |
| 497 | - // valid private/public key | |
| 498 | - $msg = 'Encryption module "' . $this->getDisplayName() . | |
| 499 | - '" is not able to read ' . $path; | |
| 500 | -				$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.'); | |
| 501 | - $this->logger->warning($msg); | |
| 502 | - throw new DecryptionFailedException($msg, $hint); | |
| 503 | - } | |
| 504 | - return false; | |
| 505 | - } | |
| 506 | - | |
| 507 | - return true; | |
| 508 | - } | |
| 509 | - | |
| 510 | - /** | |
| 511 | - * Initial encryption of all files | |
| 512 | - * | |
| 513 | - * @param InputInterface $input | |
| 514 | - * @param OutputInterface $output write some status information to the terminal during encryption | |
| 515 | - */ | |
| 516 | -	public function encryptAll(InputInterface $input, OutputInterface $output) { | |
| 517 | - $this->encryptAll->encryptAll($input, $output); | |
| 518 | - } | |
| 519 | - | |
| 520 | - /** | |
| 521 | - * prepare module to perform decrypt all operation | |
| 522 | - * | |
| 523 | - * @param InputInterface $input | |
| 524 | - * @param OutputInterface $output | |
| 525 | - * @param string $user | |
| 526 | - * @return bool | |
| 527 | - */ | |
| 528 | -	public function prepareDecryptAll(InputInterface $input, OutputInterface $output, $user = '') { | |
| 529 | - return $this->decryptAll->prepare($input, $output, $user); | |
| 530 | - } | |
| 531 | - | |
| 532 | - | |
| 533 | - /** | |
| 534 | - * @param string $path | |
| 535 | - * @return string | |
| 536 | - */ | |
| 537 | -	protected function getPathToRealFile($path) { | |
| 538 | - $realPath = $path; | |
| 539 | -		$parts = explode('/', $path); | |
| 540 | -		if ($parts[2] === 'files_versions') { | |
| 541 | -			$realPath = '/' . $parts[1] . '/files/' . implode('/', array_slice($parts, 3)); | |
| 542 | - $length = strrpos($realPath, '.'); | |
| 543 | - $realPath = substr($realPath, 0, $length); | |
| 544 | - } | |
| 545 | - | |
| 546 | - return $realPath; | |
| 547 | - } | |
| 548 | - | |
| 549 | - /** | |
| 550 | - * remove .part file extension and the ocTransferId from the file to get the | |
| 551 | - * original file name | |
| 552 | - * | |
| 553 | - * @param string $path | |
| 554 | - * @return string | |
| 555 | - */ | |
| 556 | -	protected function stripPartFileExtension($path) { | |
| 557 | -		if (pathinfo($path, PATHINFO_EXTENSION) === 'part') { | |
| 558 | - $pos = strrpos($path, '.', -6); | |
| 559 | - $path = substr($path, 0, $pos); | |
| 560 | - } | |
| 561 | - | |
| 562 | - return $path; | |
| 563 | - } | |
| 564 | - | |
| 565 | - /** | |
| 566 | - * get owner of a file | |
| 567 | - * | |
| 568 | - * @param string $path | |
| 569 | - * @return string | |
| 570 | - */ | |
| 571 | -	protected function getOwner($path) { | |
| 572 | -		if (!isset($this->owner[$path])) { | |
| 573 | - $this->owner[$path] = $this->util->getOwner($path); | |
| 574 | - } | |
| 575 | - return $this->owner[$path]; | |
| 576 | - } | |
| 577 | - | |
| 578 | - /** | |
| 579 | - * Check if the module is ready to be used by that specific user. | |
| 580 | - * In case a module is not ready - because e.g. key pairs have not been generated | |
| 581 | - * upon login this method can return false before any operation starts and might | |
| 582 | - * cause issues during operations. | |
| 583 | - * | |
| 584 | - * @param string $user | |
| 585 | - * @return boolean | |
| 586 | - * @since 9.1.0 | |
| 587 | - */ | |
| 588 | -	public function isReadyForUser($user) { | |
| 589 | - return $this->keyManager->userHasKeys($user); | |
| 590 | - } | |
| 46 | + const ID = 'OC_DEFAULT_MODULE'; | |
| 47 | + const DISPLAY_NAME = 'Default encryption module'; | |
| 48 | + | |
| 49 | + /** | |
| 50 | + * @var Crypt | |
| 51 | + */ | |
| 52 | + private $crypt; | |
| 53 | + | |
| 54 | + /** @var string */ | |
| 55 | + private $cipher; | |
| 56 | + | |
| 57 | + /** @var string */ | |
| 58 | + private $path; | |
| 59 | + | |
| 60 | + /** @var string */ | |
| 61 | + private $user; | |
| 62 | + | |
| 63 | + /** @var array */ | |
| 64 | + private $owner; | |
| 65 | + | |
| 66 | + /** @var string */ | |
| 67 | + private $fileKey; | |
| 68 | + | |
| 69 | + /** @var string */ | |
| 70 | + private $writeCache; | |
| 71 | + | |
| 72 | + /** @var KeyManager */ | |
| 73 | + private $keyManager; | |
| 74 | + | |
| 75 | + /** @var array */ | |
| 76 | + private $accessList; | |
| 77 | + | |
| 78 | + /** @var boolean */ | |
| 79 | + private $isWriteOperation; | |
| 80 | + | |
| 81 | + /** @var Util */ | |
| 82 | + private $util; | |
| 83 | + | |
| 84 | + /** @var Session */ | |
| 85 | + private $session; | |
| 86 | + | |
| 87 | + /** @var ILogger */ | |
| 88 | + private $logger; | |
| 89 | + | |
| 90 | + /** @var IL10N */ | |
| 91 | + private $l; | |
| 92 | + | |
| 93 | + /** @var EncryptAll */ | |
| 94 | + private $encryptAll; | |
| 95 | + | |
| 96 | + /** @var bool */ | |
| 97 | + private $useMasterPassword; | |
| 98 | + | |
| 99 | + /** @var DecryptAll */ | |
| 100 | + private $decryptAll; | |
| 101 | + | |
| 102 | + /** @var int unencrypted block size if block contains signature */ | |
| 103 | + private $unencryptedBlockSizeSigned = 6072; | |
| 104 | + | |
| 105 | + /** @var int unencrypted block size */ | |
| 106 | + private $unencryptedBlockSize = 6126; | |
| 107 | + | |
| 108 | + /** @var int Current version of the file */ | |
| 109 | + private $version = 0; | |
| 110 | + | |
| 111 | + /** @var array remember encryption signature version */ | |
| 112 | + private static $rememberVersion = []; | |
| 113 | + | |
| 114 | + | |
| 115 | + /** | |
| 116 | + * | |
| 117 | + * @param Crypt $crypt | |
| 118 | + * @param KeyManager $keyManager | |
| 119 | + * @param Util $util | |
| 120 | + * @param Session $session | |
| 121 | + * @param EncryptAll $encryptAll | |
| 122 | + * @param DecryptAll $decryptAll | |
| 123 | + * @param ILogger $logger | |
| 124 | + * @param IL10N $il10n | |
| 125 | + */ | |
| 126 | + public function __construct(Crypt $crypt, | |
| 127 | + KeyManager $keyManager, | |
| 128 | + Util $util, | |
| 129 | + Session $session, | |
| 130 | + EncryptAll $encryptAll, | |
| 131 | + DecryptAll $decryptAll, | |
| 132 | + ILogger $logger, | |
| 133 | +                                IL10N $il10n) { | |
| 134 | + $this->crypt = $crypt; | |
| 135 | + $this->keyManager = $keyManager; | |
| 136 | + $this->util = $util; | |
| 137 | + $this->session = $session; | |
| 138 | + $this->encryptAll = $encryptAll; | |
| 139 | + $this->decryptAll = $decryptAll; | |
| 140 | + $this->logger = $logger; | |
| 141 | + $this->l = $il10n; | |
| 142 | + $this->owner = []; | |
| 143 | + $this->useMasterPassword = $util->isMasterKeyEnabled(); | |
| 144 | + } | |
| 145 | + | |
| 146 | + /** | |
| 147 | + * @return string defining the technical unique id | |
| 148 | + */ | |
| 149 | +    public function getId() { | |
| 150 | + return self::ID; | |
| 151 | + } | |
| 152 | + | |
| 153 | + /** | |
| 154 | + * In comparison to getKey() this function returns a human readable (maybe translated) name | |
| 155 | + * | |
| 156 | + * @return string | |
| 157 | + */ | |
| 158 | +    public function getDisplayName() { | |
| 159 | + return self::DISPLAY_NAME; | |
| 160 | + } | |
| 161 | + | |
| 162 | + /** | |
| 163 | + * start receiving chunks from a file. This is the place where you can | |
| 164 | + * perform some initial step before starting encrypting/decrypting the | |
| 165 | + * chunks | |
| 166 | + * | |
| 167 | + * @param string $path to the file | |
| 168 | + * @param string $user who read/write the file | |
| 169 | + * @param string $mode php stream open mode | |
| 170 | + * @param array $header contains the header data read from the file | |
| 171 | + * @param array $accessList who has access to the file contains the key 'users' and 'public' | |
| 172 | + * | |
| 173 | + * @return array $header contain data as key-value pairs which should be | |
| 174 | + * written to the header, in case of a write operation | |
| 175 | + * or if no additional data is needed return a empty array | |
| 176 | + */ | |
| 177 | +    public function begin($path, $user, $mode, array $header, array $accessList) { | |
| 178 | + $this->path = $this->getPathToRealFile($path); | |
| 179 | + $this->accessList = $accessList; | |
| 180 | + $this->user = $user; | |
| 181 | + $this->isWriteOperation = false; | |
| 182 | + $this->writeCache = ''; | |
| 183 | + | |
| 184 | +        if($this->session->isReady() === false) { | |
| 185 | + // if the master key is enabled we can initialize encryption | |
| 186 | + // with a empty password and user name | |
| 187 | +            if ($this->util->isMasterKeyEnabled()) { | |
| 188 | +                $this->keyManager->init('', ''); | |
| 189 | + } | |
| 190 | + } | |
| 191 | + | |
| 192 | +        if ($this->session->decryptAllModeActivated()) { | |
| 193 | + $encryptedFileKey = $this->keyManager->getEncryptedFileKey($this->path); | |
| 194 | + $shareKey = $this->keyManager->getShareKey($this->path, $this->session->getDecryptAllUid()); | |
| 195 | + $this->fileKey = $this->crypt->multiKeyDecrypt($encryptedFileKey, | |
| 196 | + $shareKey, | |
| 197 | + $this->session->getDecryptAllKey()); | |
| 198 | +        } else { | |
| 199 | + $this->fileKey = $this->keyManager->getFileKey($this->path, $this->user); | |
| 200 | + } | |
| 201 | + | |
| 202 | + // always use the version from the original file, also part files | |
| 203 | + // need to have a correct version number if they get moved over to the | |
| 204 | + // final location | |
| 205 | + $this->version = (int)$this->keyManager->getVersion($this->stripPartFileExtension($path), new View()); | |
| 206 | + | |
| 207 | + if ( | |
| 208 | + $mode === 'w' | |
| 209 | + || $mode === 'w+' | |
| 210 | + || $mode === 'wb' | |
| 211 | + || $mode === 'wb+' | |
| 212 | +        ) { | |
| 213 | + $this->isWriteOperation = true; | |
| 214 | +            if (empty($this->fileKey)) { | |
| 215 | + $this->fileKey = $this->crypt->generateFileKey(); | |
| 216 | + } | |
| 217 | +        } else { | |
| 218 | + // if we read a part file we need to increase the version by 1 | |
| 219 | + // because the version number was also increased by writing | |
| 220 | + // the part file | |
| 221 | +            if(Scanner::isPartialFile($path)) { | |
| 222 | + $this->version = $this->version + 1; | |
| 223 | + } | |
| 224 | + } | |
| 225 | + | |
| 226 | +        if ($this->isWriteOperation) { | |
| 227 | + $this->cipher = $this->crypt->getCipher(); | |
| 228 | +        } elseif (isset($header['cipher'])) { | |
| 229 | + $this->cipher = $header['cipher']; | |
| 230 | +        } else { | |
| 231 | + // if we read a file without a header we fall-back to the legacy cipher | |
| 232 | + // which was used in <=oC6 | |
| 233 | + $this->cipher = $this->crypt->getLegacyCipher(); | |
| 234 | + } | |
| 235 | + | |
| 236 | +        return array('cipher' => $this->cipher, 'signed' => 'true'); | |
| 237 | + } | |
| 238 | + | |
| 239 | + /** | |
| 240 | + * last chunk received. This is the place where you can perform some final | |
| 241 | + * operation and return some remaining data if something is left in your | |
| 242 | + * buffer. | |
| 243 | + * | |
| 244 | + * @param string $path to the file | |
| 245 | + * @param int $position | |
| 246 | + * @return string remained data which should be written to the file in case | |
| 247 | + * of a write operation | |
| 248 | + * @throws PublicKeyMissingException | |
| 249 | + * @throws \Exception | |
| 250 | + * @throws \OCA\Encryption\Exceptions\MultiKeyEncryptException | |
| 251 | + */ | |
| 252 | +    public function end($path, $position = 0) { | |
| 253 | + $result = ''; | |
| 254 | +        if ($this->isWriteOperation) { | |
| 255 | + $this->keyManager->setVersion($path, $this->version + 1, new View()); | |
| 256 | + // in case of a part file we remember the new signature versions | |
| 257 | + // the version will be set later on update. | |
| 258 | + // This way we make sure that other apps listening to the pre-hooks | |
| 259 | + // still get the old version which should be the correct value for them | |
| 260 | +            if (Scanner::isPartialFile($path)) { | |
| 261 | + self::$rememberVersion[$this->stripPartFileExtension($path)] = $this->version + 1; | |
| 262 | + } | |
| 263 | +            if (!empty($this->writeCache)) { | |
| 264 | + $result = $this->crypt->symmetricEncryptFileContent($this->writeCache, $this->fileKey, $this->version + 1, $position); | |
| 265 | + $this->writeCache = ''; | |
| 266 | + } | |
| 267 | + $publicKeys = array(); | |
| 268 | +            if ($this->useMasterPassword === true) { | |
| 269 | + $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey(); | |
| 270 | +            } else { | |
| 271 | +                foreach ($this->accessList['users'] as $uid) { | |
| 272 | +                    try { | |
| 273 | + $publicKeys[$uid] = $this->keyManager->getPublicKey($uid); | |
| 274 | +                    } catch (PublicKeyMissingException $e) { | |
| 275 | + $this->logger->warning( | |
| 276 | +                            'no public key found for user "{uid}", user will not be able to read the file', | |
| 277 | + ['app' => 'encryption', 'uid' => $uid] | |
| 278 | + ); | |
| 279 | + // if the public key of the owner is missing we should fail | |
| 280 | +                        if ($uid === $this->user) { | |
| 281 | + throw $e; | |
| 282 | + } | |
| 283 | + } | |
| 284 | + } | |
| 285 | + } | |
| 286 | + | |
| 287 | + $publicKeys = $this->keyManager->addSystemKeys($this->accessList, $publicKeys, $this->getOwner($path)); | |
| 288 | + $encryptedKeyfiles = $this->crypt->multiKeyEncrypt($this->fileKey, $publicKeys); | |
| 289 | + $this->keyManager->setAllFileKeys($this->path, $encryptedKeyfiles); | |
| 290 | + } | |
| 291 | + return $result; | |
| 292 | + } | |
| 293 | + | |
| 294 | + | |
| 295 | + | |
| 296 | + /** | |
| 297 | + * encrypt data | |
| 298 | + * | |
| 299 | + * @param string $data you want to encrypt | |
| 300 | + * @param int $position | |
| 301 | + * @return string encrypted data | |
| 302 | + */ | |
| 303 | +    public function encrypt($data, $position = 0) { | |
| 304 | + // If extra data is left over from the last round, make sure it | |
| 305 | + // is integrated into the next block | |
| 306 | +        if ($this->writeCache) { | |
| 307 | + | |
| 308 | + // Concat writeCache to start of $data | |
| 309 | + $data = $this->writeCache . $data; | |
| 310 | + | |
| 311 | + // Clear the write cache, ready for reuse - it has been | |
| 312 | + // flushed and its old contents processed | |
| 313 | + $this->writeCache = ''; | |
| 314 | + | |
| 315 | + } | |
| 316 | + | |
| 317 | + $encrypted = ''; | |
| 318 | + // While there still remains some data to be processed & written | |
| 319 | +        while (strlen($data) > 0) { | |
| 320 | + | |
| 321 | + // Remaining length for this iteration, not of the | |
| 322 | + // entire file (may be greater than 8192 bytes) | |
| 323 | + $remainingLength = strlen($data); | |
| 324 | + | |
| 325 | + // If data remaining to be written is less than the | |
| 326 | + // size of 1 6126 byte block | |
| 327 | +            if ($remainingLength < $this->unencryptedBlockSizeSigned) { | |
| 328 | + | |
| 329 | + // Set writeCache to contents of $data | |
| 330 | + // The writeCache will be carried over to the | |
| 331 | + // next write round, and added to the start of | |
| 332 | + // $data to ensure that written blocks are | |
| 333 | + // always the correct length. If there is still | |
| 334 | + // data in writeCache after the writing round | |
| 335 | + // has finished, then the data will be written | |
| 336 | + // to disk by $this->flush(). | |
| 337 | + $this->writeCache = $data; | |
| 338 | + | |
| 339 | + // Clear $data ready for next round | |
| 340 | + $data = ''; | |
| 341 | + | |
| 342 | +            } else { | |
| 343 | + | |
| 344 | + // Read the chunk from the start of $data | |
| 345 | + $chunk = substr($data, 0, $this->unencryptedBlockSizeSigned); | |
| 346 | + | |
| 347 | + $encrypted .= $this->crypt->symmetricEncryptFileContent($chunk, $this->fileKey, $this->version + 1, $position); | |
| 348 | + | |
| 349 | + // Remove the chunk we just processed from | |
| 350 | + // $data, leaving only unprocessed data in $data | |
| 351 | + // var, for handling on the next round | |
| 352 | + $data = substr($data, $this->unencryptedBlockSizeSigned); | |
| 353 | + | |
| 354 | + } | |
| 355 | + | |
| 356 | + } | |
| 357 | + | |
| 358 | + return $encrypted; | |
| 359 | + } | |
| 360 | + | |
| 361 | + /** | |
| 362 | + * decrypt data | |
| 363 | + * | |
| 364 | + * @param string $data you want to decrypt | |
| 365 | + * @param int $position | |
| 366 | + * @return string decrypted data | |
| 367 | + * @throws DecryptionFailedException | |
| 368 | + */ | |
| 369 | +    public function decrypt($data, $position = 0) { | |
| 370 | +        if (empty($this->fileKey)) { | |
| 371 | + $msg = 'Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.'; | |
| 372 | +            $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.'); | |
| 373 | + $this->logger->error($msg); | |
| 374 | + | |
| 375 | + throw new DecryptionFailedException($msg, $hint); | |
| 376 | + } | |
| 377 | + | |
| 378 | + return $this->crypt->symmetricDecryptFileContent($data, $this->fileKey, $this->cipher, $this->version, $position); | |
| 379 | + } | |
| 380 | + | |
| 381 | + /** | |
| 382 | + * update encrypted file, e.g. give additional users access to the file | |
| 383 | + * | |
| 384 | + * @param string $path path to the file which should be updated | |
| 385 | + * @param string $uid of the user who performs the operation | |
| 386 | + * @param array $accessList who has access to the file contains the key 'users' and 'public' | |
| 387 | + * @return boolean | |
| 388 | + */ | |
| 389 | +    public function update($path, $uid, array $accessList) { | |
| 390 | + | |
| 391 | +        if (empty($accessList)) { | |
| 392 | +            if (isset(self::$rememberVersion[$path])) { | |
| 393 | + $this->keyManager->setVersion($path, self::$rememberVersion[$path], new View()); | |
| 394 | + unset(self::$rememberVersion[$path]); | |
| 395 | + } | |
| 396 | + return; | |
| 397 | + } | |
| 398 | + | |
| 399 | + $fileKey = $this->keyManager->getFileKey($path, $uid); | |
| 400 | + | |
| 401 | +        if (!empty($fileKey)) { | |
| 402 | + | |
| 403 | + $publicKeys = array(); | |
| 404 | +            if ($this->useMasterPassword === true) { | |
| 405 | + $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey(); | |
| 406 | +            } else { | |
| 407 | +                foreach ($accessList['users'] as $user) { | |
| 408 | +                    try { | |
| 409 | + $publicKeys[$user] = $this->keyManager->getPublicKey($user); | |
| 410 | +                    } catch (PublicKeyMissingException $e) { | |
| 411 | +                        $this->logger->warning('Could not encrypt file for ' . $user . ': ' . $e->getMessage()); | |
| 412 | + } | |
| 413 | + } | |
| 414 | + } | |
| 415 | + | |
| 416 | + $publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $this->getOwner($path)); | |
| 417 | + | |
| 418 | + $encryptedFileKey = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys); | |
| 419 | + | |
| 420 | + $this->keyManager->deleteAllFileKeys($path); | |
| 421 | + | |
| 422 | + $this->keyManager->setAllFileKeys($path, $encryptedFileKey); | |
| 423 | + | |
| 424 | +        } else { | |
| 425 | +            $this->logger->debug('no file key found, we assume that the file "{file}" is not encrypted', | |
| 426 | +                array('file' => $path, 'app' => 'encryption')); | |
| 427 | + | |
| 428 | + return false; | |
| 429 | + } | |
| 430 | + | |
| 431 | + return true; | |
| 432 | + } | |
| 433 | + | |
| 434 | + /** | |
| 435 | + * should the file be encrypted or not | |
| 436 | + * | |
| 437 | + * @param string $path | |
| 438 | + * @return boolean | |
| 439 | + */ | |
| 440 | +    public function shouldEncrypt($path) { | |
| 441 | +        if ($this->util->shouldEncryptHomeStorage() === false) { | |
| 442 | + $storage = $this->util->getStorage($path); | |
| 443 | +            if ($storage->instanceOfStorage('\OCP\Files\IHomeStorage')) { | |
| 444 | + return false; | |
| 445 | + } | |
| 446 | + } | |
| 447 | +        $parts = explode('/', $path); | |
| 448 | +        if (count($parts) < 4) { | |
| 449 | + return false; | |
| 450 | + } | |
| 451 | + | |
| 452 | +        if ($parts[2] == 'files') { | |
| 453 | + return true; | |
| 454 | + } | |
| 455 | +        if ($parts[2] == 'files_versions') { | |
| 456 | + return true; | |
| 457 | + } | |
| 458 | +        if ($parts[2] == 'files_trashbin') { | |
| 459 | + return true; | |
| 460 | + } | |
| 461 | + | |
| 462 | + return false; | |
| 463 | + } | |
| 464 | + | |
| 465 | + /** | |
| 466 | + * get size of the unencrypted payload per block. | |
| 467 | + * Nextcloud read/write files with a block size of 8192 byte | |
| 468 | + * | |
| 469 | + * @param bool $signed | |
| 470 | + * @return int | |
| 471 | + */ | |
| 472 | +    public function getUnencryptedBlockSize($signed = false) { | |
| 473 | +        if ($signed === false) { | |
| 474 | + return $this->unencryptedBlockSize; | |
| 475 | + } | |
| 476 | + | |
| 477 | + return $this->unencryptedBlockSizeSigned; | |
| 478 | + } | |
| 479 | + | |
| 480 | + /** | |
| 481 | + * check if the encryption module is able to read the file, | |
| 482 | + * e.g. if all encryption keys exists | |
| 483 | + * | |
| 484 | + * @param string $path | |
| 485 | + * @param string $uid user for whom we want to check if he can read the file | |
| 486 | + * @return bool | |
| 487 | + * @throws DecryptionFailedException | |
| 488 | + */ | |
| 489 | +    public function isReadable($path, $uid) { | |
| 490 | + $fileKey = $this->keyManager->getFileKey($path, $uid); | |
| 491 | +        if (empty($fileKey)) { | |
| 492 | + $owner = $this->util->getOwner($path); | |
| 493 | +            if ($owner !== $uid) { | |
| 494 | + // if it is a shared file we throw a exception with a useful | |
| 495 | + // error message because in this case it means that the file was | |
| 496 | + // shared with the user at a point where the user didn't had a | |
| 497 | + // valid private/public key | |
| 498 | + $msg = 'Encryption module "' . $this->getDisplayName() . | |
| 499 | + '" is not able to read ' . $path; | |
| 500 | +                $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.'); | |
| 501 | + $this->logger->warning($msg); | |
| 502 | + throw new DecryptionFailedException($msg, $hint); | |
| 503 | + } | |
| 504 | + return false; | |
| 505 | + } | |
| 506 | + | |
| 507 | + return true; | |
| 508 | + } | |
| 509 | + | |
| 510 | + /** | |
| 511 | + * Initial encryption of all files | |
| 512 | + * | |
| 513 | + * @param InputInterface $input | |
| 514 | + * @param OutputInterface $output write some status information to the terminal during encryption | |
| 515 | + */ | |
| 516 | +    public function encryptAll(InputInterface $input, OutputInterface $output) { | |
| 517 | + $this->encryptAll->encryptAll($input, $output); | |
| 518 | + } | |
| 519 | + | |
| 520 | + /** | |
| 521 | + * prepare module to perform decrypt all operation | |
| 522 | + * | |
| 523 | + * @param InputInterface $input | |
| 524 | + * @param OutputInterface $output | |
| 525 | + * @param string $user | |
| 526 | + * @return bool | |
| 527 | + */ | |
| 528 | +    public function prepareDecryptAll(InputInterface $input, OutputInterface $output, $user = '') { | |
| 529 | + return $this->decryptAll->prepare($input, $output, $user); | |
| 530 | + } | |
| 531 | + | |
| 532 | + | |
| 533 | + /** | |
| 534 | + * @param string $path | |
| 535 | + * @return string | |
| 536 | + */ | |
| 537 | +    protected function getPathToRealFile($path) { | |
| 538 | + $realPath = $path; | |
| 539 | +        $parts = explode('/', $path); | |
| 540 | +        if ($parts[2] === 'files_versions') { | |
| 541 | +            $realPath = '/' . $parts[1] . '/files/' . implode('/', array_slice($parts, 3)); | |
| 542 | + $length = strrpos($realPath, '.'); | |
| 543 | + $realPath = substr($realPath, 0, $length); | |
| 544 | + } | |
| 545 | + | |
| 546 | + return $realPath; | |
| 547 | + } | |
| 548 | + | |
| 549 | + /** | |
| 550 | + * remove .part file extension and the ocTransferId from the file to get the | |
| 551 | + * original file name | |
| 552 | + * | |
| 553 | + * @param string $path | |
| 554 | + * @return string | |
| 555 | + */ | |
| 556 | +    protected function stripPartFileExtension($path) { | |
| 557 | +        if (pathinfo($path, PATHINFO_EXTENSION) === 'part') { | |
| 558 | + $pos = strrpos($path, '.', -6); | |
| 559 | + $path = substr($path, 0, $pos); | |
| 560 | + } | |
| 561 | + | |
| 562 | + return $path; | |
| 563 | + } | |
| 564 | + | |
| 565 | + /** | |
| 566 | + * get owner of a file | |
| 567 | + * | |
| 568 | + * @param string $path | |
| 569 | + * @return string | |
| 570 | + */ | |
| 571 | +    protected function getOwner($path) { | |
| 572 | +        if (!isset($this->owner[$path])) { | |
| 573 | + $this->owner[$path] = $this->util->getOwner($path); | |
| 574 | + } | |
| 575 | + return $this->owner[$path]; | |
| 576 | + } | |
| 577 | + | |
| 578 | + /** | |
| 579 | + * Check if the module is ready to be used by that specific user. | |
| 580 | + * In case a module is not ready - because e.g. key pairs have not been generated | |
| 581 | + * upon login this method can return false before any operation starts and might | |
| 582 | + * cause issues during operations. | |
| 583 | + * | |
| 584 | + * @param string $user | |
| 585 | + * @return boolean | |
| 586 | + * @since 9.1.0 | |
| 587 | + */ | |
| 588 | +    public function isReadyForUser($user) { | |
| 589 | + return $this->keyManager->userHasKeys($user); | |
| 590 | + } | |
| 591 | 591 | } | 
| @@ -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,676 +38,676 @@ | ||
| 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 | - $masterKey = $this->getPublicMasterKey(); | |
| 183 | -		if (empty($masterKey)) { | |
| 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 | - | |
| 198 | - /** | |
| 199 | - * @return bool | |
| 200 | - */ | |
| 201 | -	public function recoveryKeyExists() { | |
| 202 | - $key = $this->getRecoveryKey(); | |
| 203 | - return (!empty($key)); | |
| 204 | - } | |
| 205 | - | |
| 206 | - /** | |
| 207 | - * get recovery key | |
| 208 | - * | |
| 209 | - * @return string | |
| 210 | - */ | |
| 211 | -	public function getRecoveryKey() { | |
| 212 | - return $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.publicKey', Encryption::ID); | |
| 213 | - } | |
| 214 | - | |
| 215 | - /** | |
| 216 | - * get recovery key ID | |
| 217 | - * | |
| 218 | - * @return string | |
| 219 | - */ | |
| 220 | -	public function getRecoveryKeyId() { | |
| 221 | - return $this->recoveryKeyId; | |
| 222 | - } | |
| 223 | - | |
| 224 | - /** | |
| 225 | - * @param string $password | |
| 226 | - * @return bool | |
| 227 | - */ | |
| 228 | -	public function checkRecoveryPassword($password) { | |
| 229 | - $recoveryKey = $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.privateKey', Encryption::ID); | |
| 230 | - $decryptedRecoveryKey = $this->crypt->decryptPrivateKey($recoveryKey, $password); | |
| 231 | - | |
| 232 | -		if ($decryptedRecoveryKey) { | |
| 233 | - return true; | |
| 234 | - } | |
| 235 | - return false; | |
| 236 | - } | |
| 237 | - | |
| 238 | - /** | |
| 239 | - * @param string $uid | |
| 240 | - * @param string $password | |
| 241 | - * @param string $keyPair | |
| 242 | - * @return bool | |
| 243 | - */ | |
| 244 | -	public function storeKeyPair($uid, $password, $keyPair) { | |
| 245 | - // Save Public Key | |
| 246 | - $this->setPublicKey($uid, $keyPair['publicKey']); | |
| 247 | - | |
| 248 | - $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $password, $uid); | |
| 249 | - | |
| 250 | - $header = $this->crypt->generateHeader(); | |
| 251 | - | |
| 252 | -		if ($encryptedKey) { | |
| 253 | - $this->setPrivateKey($uid, $header . $encryptedKey); | |
| 254 | - return true; | |
| 255 | - } | |
| 256 | - return false; | |
| 257 | - } | |
| 258 | - | |
| 259 | - /** | |
| 260 | - * @param string $password | |
| 261 | - * @param array $keyPair | |
| 262 | - * @return bool | |
| 263 | - */ | |
| 264 | -	public function setRecoveryKey($password, $keyPair) { | |
| 265 | - // Save Public Key | |
| 266 | - $this->keyStorage->setSystemUserKey($this->getRecoveryKeyId(). | |
| 267 | - '.publicKey', | |
| 268 | - $keyPair['publicKey'], | |
| 269 | - Encryption::ID); | |
| 270 | - | |
| 271 | - $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $password); | |
| 272 | - $header = $this->crypt->generateHeader(); | |
| 273 | - | |
| 274 | -		if ($encryptedKey) { | |
| 275 | - $this->setSystemPrivateKey($this->getRecoveryKeyId(), $header . $encryptedKey); | |
| 276 | - return true; | |
| 277 | - } | |
| 278 | - return false; | |
| 279 | - } | |
| 280 | - | |
| 281 | - /** | |
| 282 | - * @param $userId | |
| 283 | - * @param $key | |
| 284 | - * @return bool | |
| 285 | - */ | |
| 286 | -	public function setPublicKey($userId, $key) { | |
| 287 | - return $this->keyStorage->setUserKey($userId, $this->publicKeyId, $key, Encryption::ID); | |
| 288 | - } | |
| 289 | - | |
| 290 | - /** | |
| 291 | - * @param $userId | |
| 292 | - * @param string $key | |
| 293 | - * @return bool | |
| 294 | - */ | |
| 295 | -	public function setPrivateKey($userId, $key) { | |
| 296 | - return $this->keyStorage->setUserKey($userId, | |
| 297 | - $this->privateKeyId, | |
| 298 | - $key, | |
| 299 | - Encryption::ID); | |
| 300 | - } | |
| 301 | - | |
| 302 | - /** | |
| 303 | - * write file key to key storage | |
| 304 | - * | |
| 305 | - * @param string $path | |
| 306 | - * @param string $key | |
| 307 | - * @return boolean | |
| 308 | - */ | |
| 309 | -	public function setFileKey($path, $key) { | |
| 310 | - return $this->keyStorage->setFileKey($path, $this->fileKeyId, $key, Encryption::ID); | |
| 311 | - } | |
| 312 | - | |
| 313 | - /** | |
| 314 | - * set all file keys (the file key and the corresponding share keys) | |
| 315 | - * | |
| 316 | - * @param string $path | |
| 317 | - * @param array $keys | |
| 318 | - */ | |
| 319 | -	public function setAllFileKeys($path, $keys) { | |
| 320 | - $this->setFileKey($path, $keys['data']); | |
| 321 | -		foreach ($keys['keys'] as $uid => $keyFile) { | |
| 322 | - $this->setShareKey($path, $uid, $keyFile); | |
| 323 | - } | |
| 324 | - } | |
| 325 | - | |
| 326 | - /** | |
| 327 | - * write share key to the key storage | |
| 328 | - * | |
| 329 | - * @param string $path | |
| 330 | - * @param string $uid | |
| 331 | - * @param string $key | |
| 332 | - * @return boolean | |
| 333 | - */ | |
| 334 | -	public function setShareKey($path, $uid, $key) { | |
| 335 | - $keyId = $uid . '.' . $this->shareKeyId; | |
| 336 | - return $this->keyStorage->setFileKey($path, $keyId, $key, Encryption::ID); | |
| 337 | - } | |
| 338 | - | |
| 339 | - /** | |
| 340 | - * Decrypt private key and store it | |
| 341 | - * | |
| 342 | - * @param string $uid user id | |
| 343 | - * @param string $passPhrase users password | |
| 344 | - * @return boolean | |
| 345 | - */ | |
| 346 | -	public function init($uid, $passPhrase) { | |
| 347 | - | |
| 348 | - $this->session->setStatus(Session::INIT_EXECUTED); | |
| 349 | - | |
| 350 | -		try { | |
| 351 | -			if($this->util->isMasterKeyEnabled()) { | |
| 352 | - $uid = $this->getMasterKeyId(); | |
| 353 | - $passPhrase = $this->getMasterKeyPassword(); | |
| 354 | - $privateKey = $this->getSystemPrivateKey($uid); | |
| 355 | -			} else { | |
| 356 | - $privateKey = $this->getPrivateKey($uid); | |
| 357 | - } | |
| 358 | - $privateKey = $this->crypt->decryptPrivateKey($privateKey, $passPhrase, $uid); | |
| 359 | -		} catch (PrivateKeyMissingException $e) { | |
| 360 | - return false; | |
| 361 | -		} catch (DecryptionFailedException $e) { | |
| 362 | - return false; | |
| 363 | -		} catch (\Exception $e) { | |
| 364 | - $this->log->warning( | |
| 365 | - 'Could not decrypt the private key from user "' . $uid . '"" during login. ' . | |
| 366 | - 'Assume password change on the user back-end. Error message: ' | |
| 367 | - . $e->getMessage() | |
| 368 | - ); | |
| 369 | - return false; | |
| 370 | - } | |
| 371 | - | |
| 372 | -		if ($privateKey) { | |
| 373 | - $this->session->setPrivateKey($privateKey); | |
| 374 | - $this->session->setStatus(Session::INIT_SUCCESSFUL); | |
| 375 | - return true; | |
| 376 | - } | |
| 377 | - | |
| 378 | - return false; | |
| 379 | - } | |
| 380 | - | |
| 381 | - /** | |
| 382 | - * @param $userId | |
| 383 | - * @return string | |
| 384 | - * @throws PrivateKeyMissingException | |
| 385 | - */ | |
| 386 | -	public function getPrivateKey($userId) { | |
| 387 | - $privateKey = $this->keyStorage->getUserKey($userId, | |
| 388 | - $this->privateKeyId, Encryption::ID); | |
| 389 | - | |
| 390 | -		if (strlen($privateKey) !== 0) { | |
| 391 | - return $privateKey; | |
| 392 | - } | |
| 393 | - throw new PrivateKeyMissingException($userId); | |
| 394 | - } | |
| 395 | - | |
| 396 | - /** | |
| 397 | - * @param string $path | |
| 398 | - * @param $uid | |
| 399 | - * @return string | |
| 400 | - */ | |
| 401 | -	public function getFileKey($path, $uid) { | |
| 402 | -		if ($uid === '') { | |
| 403 | - $uid = null; | |
| 404 | - } | |
| 405 | - $publicAccess = is_null($uid); | |
| 406 | - $encryptedFileKey = $this->keyStorage->getFileKey($path, $this->fileKeyId, Encryption::ID); | |
| 407 | - | |
| 408 | -		if (empty($encryptedFileKey)) { | |
| 409 | - return ''; | |
| 410 | - } | |
| 411 | - | |
| 412 | -		if ($this->util->isMasterKeyEnabled()) { | |
| 413 | - $uid = $this->getMasterKeyId(); | |
| 414 | - $shareKey = $this->getShareKey($path, $uid); | |
| 415 | -			if ($publicAccess) { | |
| 416 | - $privateKey = $this->getSystemPrivateKey($uid); | |
| 417 | - $privateKey = $this->crypt->decryptPrivateKey($privateKey, $this->getMasterKeyPassword(), $uid); | |
| 418 | -			} else { | |
| 419 | - // when logged in, the master key is already decrypted in the session | |
| 420 | - $privateKey = $this->session->getPrivateKey(); | |
| 421 | - } | |
| 422 | -		} else if ($publicAccess) { | |
| 423 | - // use public share key for public links | |
| 424 | - $uid = $this->getPublicShareKeyId(); | |
| 425 | - $shareKey = $this->getShareKey($path, $uid); | |
| 426 | - $privateKey = $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.privateKey', Encryption::ID); | |
| 427 | - $privateKey = $this->crypt->decryptPrivateKey($privateKey); | |
| 428 | -		} else { | |
| 429 | - $shareKey = $this->getShareKey($path, $uid); | |
| 430 | - $privateKey = $this->session->getPrivateKey(); | |
| 431 | - } | |
| 432 | - | |
| 433 | -		if ($encryptedFileKey && $shareKey && $privateKey) { | |
| 434 | - return $this->crypt->multiKeyDecrypt($encryptedFileKey, | |
| 435 | - $shareKey, | |
| 436 | - $privateKey); | |
| 437 | - } | |
| 438 | - | |
| 439 | - return ''; | |
| 440 | - } | |
| 441 | - | |
| 442 | - /** | |
| 443 | - * Get the current version of a file | |
| 444 | - * | |
| 445 | - * @param string $path | |
| 446 | - * @param View $view | |
| 447 | - * @return int | |
| 448 | - */ | |
| 449 | -	public function getVersion($path, View $view) { | |
| 450 | - $fileInfo = $view->getFileInfo($path); | |
| 451 | -		if($fileInfo === false) { | |
| 452 | - return 0; | |
| 453 | - } | |
| 454 | - return $fileInfo->getEncryptedVersion(); | |
| 455 | - } | |
| 456 | - | |
| 457 | - /** | |
| 458 | - * Set the current version of a file | |
| 459 | - * | |
| 460 | - * @param string $path | |
| 461 | - * @param int $version | |
| 462 | - * @param View $view | |
| 463 | - */ | |
| 464 | -	public function setVersion($path, $version, View $view) { | |
| 465 | - $fileInfo= $view->getFileInfo($path); | |
| 466 | - | |
| 467 | -		if($fileInfo !== false) { | |
| 468 | - $cache = $fileInfo->getStorage()->getCache(); | |
| 469 | - $cache->update($fileInfo->getId(), ['encrypted' => $version, 'encryptedVersion' => $version]); | |
| 470 | - } | |
| 471 | - } | |
| 472 | - | |
| 473 | - /** | |
| 474 | - * get the encrypted file key | |
| 475 | - * | |
| 476 | - * @param string $path | |
| 477 | - * @return string | |
| 478 | - */ | |
| 479 | -	public function getEncryptedFileKey($path) { | |
| 480 | - $encryptedFileKey = $this->keyStorage->getFileKey($path, | |
| 481 | - $this->fileKeyId, Encryption::ID); | |
| 482 | - | |
| 483 | - return $encryptedFileKey; | |
| 484 | - } | |
| 485 | - | |
| 486 | - /** | |
| 487 | - * delete share key | |
| 488 | - * | |
| 489 | - * @param string $path | |
| 490 | - * @param string $keyId | |
| 491 | - * @return boolean | |
| 492 | - */ | |
| 493 | -	public function deleteShareKey($path, $keyId) { | |
| 494 | - return $this->keyStorage->deleteFileKey( | |
| 495 | - $path, | |
| 496 | - $keyId . '.' . $this->shareKeyId, | |
| 497 | - Encryption::ID); | |
| 498 | - } | |
| 499 | - | |
| 500 | - | |
| 501 | - /** | |
| 502 | - * @param $path | |
| 503 | - * @param $uid | |
| 504 | - * @return mixed | |
| 505 | - */ | |
| 506 | -	public function getShareKey($path, $uid) { | |
| 507 | - $keyId = $uid . '.' . $this->shareKeyId; | |
| 508 | - return $this->keyStorage->getFileKey($path, $keyId, Encryption::ID); | |
| 509 | - } | |
| 510 | - | |
| 511 | - /** | |
| 512 | - * check if user has a private and a public key | |
| 513 | - * | |
| 514 | - * @param string $userId | |
| 515 | - * @return bool | |
| 516 | - * @throws PrivateKeyMissingException | |
| 517 | - * @throws PublicKeyMissingException | |
| 518 | - */ | |
| 519 | -	public function userHasKeys($userId) { | |
| 520 | - $privateKey = $publicKey = true; | |
| 521 | - $exception = null; | |
| 522 | - | |
| 523 | -		try { | |
| 524 | - $this->getPrivateKey($userId); | |
| 525 | -		} catch (PrivateKeyMissingException $e) { | |
| 526 | - $privateKey = false; | |
| 527 | - $exception = $e; | |
| 528 | - } | |
| 529 | -		try { | |
| 530 | - $this->getPublicKey($userId); | |
| 531 | -		} catch (PublicKeyMissingException $e) { | |
| 532 | - $publicKey = false; | |
| 533 | - $exception = $e; | |
| 534 | - } | |
| 535 | - | |
| 536 | -		if ($privateKey && $publicKey) { | |
| 537 | - return true; | |
| 538 | -		} elseif (!$privateKey && !$publicKey) { | |
| 539 | - return false; | |
| 540 | -		} else { | |
| 541 | - throw $exception; | |
| 542 | - } | |
| 543 | - } | |
| 544 | - | |
| 545 | - /** | |
| 546 | - * @param $userId | |
| 547 | - * @return mixed | |
| 548 | - * @throws PublicKeyMissingException | |
| 549 | - */ | |
| 550 | -	public function getPublicKey($userId) { | |
| 551 | - $publicKey = $this->keyStorage->getUserKey($userId, $this->publicKeyId, Encryption::ID); | |
| 552 | - | |
| 553 | -		if (strlen($publicKey) !== 0) { | |
| 554 | - return $publicKey; | |
| 555 | - } | |
| 556 | - throw new PublicKeyMissingException($userId); | |
| 557 | - } | |
| 558 | - | |
| 559 | -	public function getPublicShareKeyId() { | |
| 560 | - return $this->publicShareKeyId; | |
| 561 | - } | |
| 562 | - | |
| 563 | - /** | |
| 564 | - * get public key for public link shares | |
| 565 | - * | |
| 566 | - * @return string | |
| 567 | - */ | |
| 568 | -	public function getPublicShareKey() { | |
| 569 | - return $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.publicKey', Encryption::ID); | |
| 570 | - } | |
| 571 | - | |
| 572 | - /** | |
| 573 | - * @param string $purpose | |
| 574 | - * @param string $uid | |
| 575 | - */ | |
| 576 | -	public function backupUserKeys($purpose, $uid) { | |
| 577 | - $this->keyStorage->backupUserKeys(Encryption::ID, $purpose, $uid); | |
| 578 | - } | |
| 579 | - | |
| 580 | - /** | |
| 581 | - * creat a backup of the users private and public key and then delete it | |
| 582 | - * | |
| 583 | - * @param string $uid | |
| 584 | - */ | |
| 585 | -	public function deleteUserKeys($uid) { | |
| 586 | - $this->deletePublicKey($uid); | |
| 587 | - $this->deletePrivateKey($uid); | |
| 588 | - } | |
| 589 | - | |
| 590 | - /** | |
| 591 | - * @param $uid | |
| 592 | - * @return bool | |
| 593 | - */ | |
| 594 | -	public function deletePublicKey($uid) { | |
| 595 | - return $this->keyStorage->deleteUserKey($uid, $this->publicKeyId, Encryption::ID); | |
| 596 | - } | |
| 597 | - | |
| 598 | - /** | |
| 599 | - * @param string $uid | |
| 600 | - * @return bool | |
| 601 | - */ | |
| 602 | -	private function deletePrivateKey($uid) { | |
| 603 | - return $this->keyStorage->deleteUserKey($uid, $this->privateKeyId, Encryption::ID); | |
| 604 | - } | |
| 605 | - | |
| 606 | - /** | |
| 607 | - * @param string $path | |
| 608 | - * @return bool | |
| 609 | - */ | |
| 610 | -	public function deleteAllFileKeys($path) { | |
| 611 | - return $this->keyStorage->deleteAllFileKeys($path); | |
| 612 | - } | |
| 613 | - | |
| 614 | - /** | |
| 615 | - * @param array $userIds | |
| 616 | - * @return array | |
| 617 | - * @throws PublicKeyMissingException | |
| 618 | - */ | |
| 619 | -	public function getPublicKeys(array $userIds) { | |
| 620 | - $keys = []; | |
| 621 | - | |
| 622 | -		foreach ($userIds as $userId) { | |
| 623 | -			try { | |
| 624 | - $keys[$userId] = $this->getPublicKey($userId); | |
| 625 | -			} catch (PublicKeyMissingException $e) { | |
| 626 | - continue; | |
| 627 | - } | |
| 628 | - } | |
| 629 | - | |
| 630 | - return $keys; | |
| 631 | - | |
| 632 | - } | |
| 633 | - | |
| 634 | - /** | |
| 635 | - * @param string $keyId | |
| 636 | - * @return string returns openssl key | |
| 637 | - */ | |
| 638 | -	public function getSystemPrivateKey($keyId) { | |
| 639 | - return $this->keyStorage->getSystemUserKey($keyId . '.' . $this->privateKeyId, Encryption::ID); | |
| 640 | - } | |
| 641 | - | |
| 642 | - /** | |
| 643 | - * @param string $keyId | |
| 644 | - * @param string $key | |
| 645 | - * @return string returns openssl key | |
| 646 | - */ | |
| 647 | -	public function setSystemPrivateKey($keyId, $key) { | |
| 648 | - return $this->keyStorage->setSystemUserKey( | |
| 649 | - $keyId . '.' . $this->privateKeyId, | |
| 650 | - $key, | |
| 651 | - Encryption::ID); | |
| 652 | - } | |
| 653 | - | |
| 654 | - /** | |
| 655 | - * add system keys such as the public share key and the recovery key | |
| 656 | - * | |
| 657 | - * @param array $accessList | |
| 658 | - * @param array $publicKeys | |
| 659 | - * @param string $uid | |
| 660 | - * @return array | |
| 661 | - * @throws PublicKeyMissingException | |
| 662 | - */ | |
| 663 | -	public function addSystemKeys(array $accessList, array $publicKeys, $uid) { | |
| 664 | -		if (!empty($accessList['public'])) { | |
| 665 | - $publicShareKey = $this->getPublicShareKey(); | |
| 666 | -			if (empty($publicShareKey)) { | |
| 667 | - throw new PublicKeyMissingException($this->getPublicShareKeyId()); | |
| 668 | - } | |
| 669 | - $publicKeys[$this->getPublicShareKeyId()] = $publicShareKey; | |
| 670 | - } | |
| 671 | - | |
| 672 | - if ($this->recoveryKeyExists() && | |
| 673 | -			$this->util->isRecoveryEnabledForUser($uid)) { | |
| 674 | - | |
| 675 | - $publicKeys[$this->getRecoveryKeyId()] = $this->getRecoveryKey(); | |
| 676 | - } | |
| 677 | - | |
| 678 | - return $publicKeys; | |
| 679 | - } | |
| 680 | - | |
| 681 | - /** | |
| 682 | - * get master key password | |
| 683 | - * | |
| 684 | - * @return string | |
| 685 | - * @throws \Exception | |
| 686 | - */ | |
| 687 | -	public function getMasterKeyPassword() { | |
| 688 | -		$password = $this->config->getSystemValue('secret'); | |
| 689 | -		if (empty($password)){ | |
| 690 | -			throw new \Exception('Can not get secret from Nextcloud instance'); | |
| 691 | - } | |
| 692 | - | |
| 693 | - return $password; | |
| 694 | - } | |
| 695 | - | |
| 696 | - /** | |
| 697 | - * return master key id | |
| 698 | - * | |
| 699 | - * @return string | |
| 700 | - */ | |
| 701 | -	public function getMasterKeyId() { | |
| 702 | - return $this->masterKeyId; | |
| 703 | - } | |
| 704 | - | |
| 705 | - /** | |
| 706 | - * get public master key | |
| 707 | - * | |
| 708 | - * @return string | |
| 709 | - */ | |
| 710 | -	public function getPublicMasterKey() { | |
| 711 | - return $this->keyStorage->getSystemUserKey($this->masterKeyId . '.publicKey', Encryption::ID); | |
| 712 | - } | |
| 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 | + $masterKey = $this->getPublicMasterKey(); | |
| 183 | +        if (empty($masterKey)) { | |
| 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 | + | |
| 198 | + /** | |
| 199 | + * @return bool | |
| 200 | + */ | |
| 201 | +    public function recoveryKeyExists() { | |
| 202 | + $key = $this->getRecoveryKey(); | |
| 203 | + return (!empty($key)); | |
| 204 | + } | |
| 205 | + | |
| 206 | + /** | |
| 207 | + * get recovery key | |
| 208 | + * | |
| 209 | + * @return string | |
| 210 | + */ | |
| 211 | +    public function getRecoveryKey() { | |
| 212 | + return $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.publicKey', Encryption::ID); | |
| 213 | + } | |
| 214 | + | |
| 215 | + /** | |
| 216 | + * get recovery key ID | |
| 217 | + * | |
| 218 | + * @return string | |
| 219 | + */ | |
| 220 | +    public function getRecoveryKeyId() { | |
| 221 | + return $this->recoveryKeyId; | |
| 222 | + } | |
| 223 | + | |
| 224 | + /** | |
| 225 | + * @param string $password | |
| 226 | + * @return bool | |
| 227 | + */ | |
| 228 | +    public function checkRecoveryPassword($password) { | |
| 229 | + $recoveryKey = $this->keyStorage->getSystemUserKey($this->recoveryKeyId . '.privateKey', Encryption::ID); | |
| 230 | + $decryptedRecoveryKey = $this->crypt->decryptPrivateKey($recoveryKey, $password); | |
| 231 | + | |
| 232 | +        if ($decryptedRecoveryKey) { | |
| 233 | + return true; | |
| 234 | + } | |
| 235 | + return false; | |
| 236 | + } | |
| 237 | + | |
| 238 | + /** | |
| 239 | + * @param string $uid | |
| 240 | + * @param string $password | |
| 241 | + * @param string $keyPair | |
| 242 | + * @return bool | |
| 243 | + */ | |
| 244 | +    public function storeKeyPair($uid, $password, $keyPair) { | |
| 245 | + // Save Public Key | |
| 246 | + $this->setPublicKey($uid, $keyPair['publicKey']); | |
| 247 | + | |
| 248 | + $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $password, $uid); | |
| 249 | + | |
| 250 | + $header = $this->crypt->generateHeader(); | |
| 251 | + | |
| 252 | +        if ($encryptedKey) { | |
| 253 | + $this->setPrivateKey($uid, $header . $encryptedKey); | |
| 254 | + return true; | |
| 255 | + } | |
| 256 | + return false; | |
| 257 | + } | |
| 258 | + | |
| 259 | + /** | |
| 260 | + * @param string $password | |
| 261 | + * @param array $keyPair | |
| 262 | + * @return bool | |
| 263 | + */ | |
| 264 | +    public function setRecoveryKey($password, $keyPair) { | |
| 265 | + // Save Public Key | |
| 266 | + $this->keyStorage->setSystemUserKey($this->getRecoveryKeyId(). | |
| 267 | + '.publicKey', | |
| 268 | + $keyPair['publicKey'], | |
| 269 | + Encryption::ID); | |
| 270 | + | |
| 271 | + $encryptedKey = $this->crypt->encryptPrivateKey($keyPair['privateKey'], $password); | |
| 272 | + $header = $this->crypt->generateHeader(); | |
| 273 | + | |
| 274 | +        if ($encryptedKey) { | |
| 275 | + $this->setSystemPrivateKey($this->getRecoveryKeyId(), $header . $encryptedKey); | |
| 276 | + return true; | |
| 277 | + } | |
| 278 | + return false; | |
| 279 | + } | |
| 280 | + | |
| 281 | + /** | |
| 282 | + * @param $userId | |
| 283 | + * @param $key | |
| 284 | + * @return bool | |
| 285 | + */ | |
| 286 | +    public function setPublicKey($userId, $key) { | |
| 287 | + return $this->keyStorage->setUserKey($userId, $this->publicKeyId, $key, Encryption::ID); | |
| 288 | + } | |
| 289 | + | |
| 290 | + /** | |
| 291 | + * @param $userId | |
| 292 | + * @param string $key | |
| 293 | + * @return bool | |
| 294 | + */ | |
| 295 | +    public function setPrivateKey($userId, $key) { | |
| 296 | + return $this->keyStorage->setUserKey($userId, | |
| 297 | + $this->privateKeyId, | |
| 298 | + $key, | |
| 299 | + Encryption::ID); | |
| 300 | + } | |
| 301 | + | |
| 302 | + /** | |
| 303 | + * write file key to key storage | |
| 304 | + * | |
| 305 | + * @param string $path | |
| 306 | + * @param string $key | |
| 307 | + * @return boolean | |
| 308 | + */ | |
| 309 | +    public function setFileKey($path, $key) { | |
| 310 | + return $this->keyStorage->setFileKey($path, $this->fileKeyId, $key, Encryption::ID); | |
| 311 | + } | |
| 312 | + | |
| 313 | + /** | |
| 314 | + * set all file keys (the file key and the corresponding share keys) | |
| 315 | + * | |
| 316 | + * @param string $path | |
| 317 | + * @param array $keys | |
| 318 | + */ | |
| 319 | +    public function setAllFileKeys($path, $keys) { | |
| 320 | + $this->setFileKey($path, $keys['data']); | |
| 321 | +        foreach ($keys['keys'] as $uid => $keyFile) { | |
| 322 | + $this->setShareKey($path, $uid, $keyFile); | |
| 323 | + } | |
| 324 | + } | |
| 325 | + | |
| 326 | + /** | |
| 327 | + * write share key to the key storage | |
| 328 | + * | |
| 329 | + * @param string $path | |
| 330 | + * @param string $uid | |
| 331 | + * @param string $key | |
| 332 | + * @return boolean | |
| 333 | + */ | |
| 334 | +    public function setShareKey($path, $uid, $key) { | |
| 335 | + $keyId = $uid . '.' . $this->shareKeyId; | |
| 336 | + return $this->keyStorage->setFileKey($path, $keyId, $key, Encryption::ID); | |
| 337 | + } | |
| 338 | + | |
| 339 | + /** | |
| 340 | + * Decrypt private key and store it | |
| 341 | + * | |
| 342 | + * @param string $uid user id | |
| 343 | + * @param string $passPhrase users password | |
| 344 | + * @return boolean | |
| 345 | + */ | |
| 346 | +    public function init($uid, $passPhrase) { | |
| 347 | + | |
| 348 | + $this->session->setStatus(Session::INIT_EXECUTED); | |
| 349 | + | |
| 350 | +        try { | |
| 351 | +            if($this->util->isMasterKeyEnabled()) { | |
| 352 | + $uid = $this->getMasterKeyId(); | |
| 353 | + $passPhrase = $this->getMasterKeyPassword(); | |
| 354 | + $privateKey = $this->getSystemPrivateKey($uid); | |
| 355 | +            } else { | |
| 356 | + $privateKey = $this->getPrivateKey($uid); | |
| 357 | + } | |
| 358 | + $privateKey = $this->crypt->decryptPrivateKey($privateKey, $passPhrase, $uid); | |
| 359 | +        } catch (PrivateKeyMissingException $e) { | |
| 360 | + return false; | |
| 361 | +        } catch (DecryptionFailedException $e) { | |
| 362 | + return false; | |
| 363 | +        } catch (\Exception $e) { | |
| 364 | + $this->log->warning( | |
| 365 | + 'Could not decrypt the private key from user "' . $uid . '"" during login. ' . | |
| 366 | + 'Assume password change on the user back-end. Error message: ' | |
| 367 | + . $e->getMessage() | |
| 368 | + ); | |
| 369 | + return false; | |
| 370 | + } | |
| 371 | + | |
| 372 | +        if ($privateKey) { | |
| 373 | + $this->session->setPrivateKey($privateKey); | |
| 374 | + $this->session->setStatus(Session::INIT_SUCCESSFUL); | |
| 375 | + return true; | |
| 376 | + } | |
| 377 | + | |
| 378 | + return false; | |
| 379 | + } | |
| 380 | + | |
| 381 | + /** | |
| 382 | + * @param $userId | |
| 383 | + * @return string | |
| 384 | + * @throws PrivateKeyMissingException | |
| 385 | + */ | |
| 386 | +    public function getPrivateKey($userId) { | |
| 387 | + $privateKey = $this->keyStorage->getUserKey($userId, | |
| 388 | + $this->privateKeyId, Encryption::ID); | |
| 389 | + | |
| 390 | +        if (strlen($privateKey) !== 0) { | |
| 391 | + return $privateKey; | |
| 392 | + } | |
| 393 | + throw new PrivateKeyMissingException($userId); | |
| 394 | + } | |
| 395 | + | |
| 396 | + /** | |
| 397 | + * @param string $path | |
| 398 | + * @param $uid | |
| 399 | + * @return string | |
| 400 | + */ | |
| 401 | +    public function getFileKey($path, $uid) { | |
| 402 | +        if ($uid === '') { | |
| 403 | + $uid = null; | |
| 404 | + } | |
| 405 | + $publicAccess = is_null($uid); | |
| 406 | + $encryptedFileKey = $this->keyStorage->getFileKey($path, $this->fileKeyId, Encryption::ID); | |
| 407 | + | |
| 408 | +        if (empty($encryptedFileKey)) { | |
| 409 | + return ''; | |
| 410 | + } | |
| 411 | + | |
| 412 | +        if ($this->util->isMasterKeyEnabled()) { | |
| 413 | + $uid = $this->getMasterKeyId(); | |
| 414 | + $shareKey = $this->getShareKey($path, $uid); | |
| 415 | +            if ($publicAccess) { | |
| 416 | + $privateKey = $this->getSystemPrivateKey($uid); | |
| 417 | + $privateKey = $this->crypt->decryptPrivateKey($privateKey, $this->getMasterKeyPassword(), $uid); | |
| 418 | +            } else { | |
| 419 | + // when logged in, the master key is already decrypted in the session | |
| 420 | + $privateKey = $this->session->getPrivateKey(); | |
| 421 | + } | |
| 422 | +        } else if ($publicAccess) { | |
| 423 | + // use public share key for public links | |
| 424 | + $uid = $this->getPublicShareKeyId(); | |
| 425 | + $shareKey = $this->getShareKey($path, $uid); | |
| 426 | + $privateKey = $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.privateKey', Encryption::ID); | |
| 427 | + $privateKey = $this->crypt->decryptPrivateKey($privateKey); | |
| 428 | +        } else { | |
| 429 | + $shareKey = $this->getShareKey($path, $uid); | |
| 430 | + $privateKey = $this->session->getPrivateKey(); | |
| 431 | + } | |
| 432 | + | |
| 433 | +        if ($encryptedFileKey && $shareKey && $privateKey) { | |
| 434 | + return $this->crypt->multiKeyDecrypt($encryptedFileKey, | |
| 435 | + $shareKey, | |
| 436 | + $privateKey); | |
| 437 | + } | |
| 438 | + | |
| 439 | + return ''; | |
| 440 | + } | |
| 441 | + | |
| 442 | + /** | |
| 443 | + * Get the current version of a file | |
| 444 | + * | |
| 445 | + * @param string $path | |
| 446 | + * @param View $view | |
| 447 | + * @return int | |
| 448 | + */ | |
| 449 | +    public function getVersion($path, View $view) { | |
| 450 | + $fileInfo = $view->getFileInfo($path); | |
| 451 | +        if($fileInfo === false) { | |
| 452 | + return 0; | |
| 453 | + } | |
| 454 | + return $fileInfo->getEncryptedVersion(); | |
| 455 | + } | |
| 456 | + | |
| 457 | + /** | |
| 458 | + * Set the current version of a file | |
| 459 | + * | |
| 460 | + * @param string $path | |
| 461 | + * @param int $version | |
| 462 | + * @param View $view | |
| 463 | + */ | |
| 464 | +    public function setVersion($path, $version, View $view) { | |
| 465 | + $fileInfo= $view->getFileInfo($path); | |
| 466 | + | |
| 467 | +        if($fileInfo !== false) { | |
| 468 | + $cache = $fileInfo->getStorage()->getCache(); | |
| 469 | + $cache->update($fileInfo->getId(), ['encrypted' => $version, 'encryptedVersion' => $version]); | |
| 470 | + } | |
| 471 | + } | |
| 472 | + | |
| 473 | + /** | |
| 474 | + * get the encrypted file key | |
| 475 | + * | |
| 476 | + * @param string $path | |
| 477 | + * @return string | |
| 478 | + */ | |
| 479 | +    public function getEncryptedFileKey($path) { | |
| 480 | + $encryptedFileKey = $this->keyStorage->getFileKey($path, | |
| 481 | + $this->fileKeyId, Encryption::ID); | |
| 482 | + | |
| 483 | + return $encryptedFileKey; | |
| 484 | + } | |
| 485 | + | |
| 486 | + /** | |
| 487 | + * delete share key | |
| 488 | + * | |
| 489 | + * @param string $path | |
| 490 | + * @param string $keyId | |
| 491 | + * @return boolean | |
| 492 | + */ | |
| 493 | +    public function deleteShareKey($path, $keyId) { | |
| 494 | + return $this->keyStorage->deleteFileKey( | |
| 495 | + $path, | |
| 496 | + $keyId . '.' . $this->shareKeyId, | |
| 497 | + Encryption::ID); | |
| 498 | + } | |
| 499 | + | |
| 500 | + | |
| 501 | + /** | |
| 502 | + * @param $path | |
| 503 | + * @param $uid | |
| 504 | + * @return mixed | |
| 505 | + */ | |
| 506 | +    public function getShareKey($path, $uid) { | |
| 507 | + $keyId = $uid . '.' . $this->shareKeyId; | |
| 508 | + return $this->keyStorage->getFileKey($path, $keyId, Encryption::ID); | |
| 509 | + } | |
| 510 | + | |
| 511 | + /** | |
| 512 | + * check if user has a private and a public key | |
| 513 | + * | |
| 514 | + * @param string $userId | |
| 515 | + * @return bool | |
| 516 | + * @throws PrivateKeyMissingException | |
| 517 | + * @throws PublicKeyMissingException | |
| 518 | + */ | |
| 519 | +    public function userHasKeys($userId) { | |
| 520 | + $privateKey = $publicKey = true; | |
| 521 | + $exception = null; | |
| 522 | + | |
| 523 | +        try { | |
| 524 | + $this->getPrivateKey($userId); | |
| 525 | +        } catch (PrivateKeyMissingException $e) { | |
| 526 | + $privateKey = false; | |
| 527 | + $exception = $e; | |
| 528 | + } | |
| 529 | +        try { | |
| 530 | + $this->getPublicKey($userId); | |
| 531 | +        } catch (PublicKeyMissingException $e) { | |
| 532 | + $publicKey = false; | |
| 533 | + $exception = $e; | |
| 534 | + } | |
| 535 | + | |
| 536 | +        if ($privateKey && $publicKey) { | |
| 537 | + return true; | |
| 538 | +        } elseif (!$privateKey && !$publicKey) { | |
| 539 | + return false; | |
| 540 | +        } else { | |
| 541 | + throw $exception; | |
| 542 | + } | |
| 543 | + } | |
| 544 | + | |
| 545 | + /** | |
| 546 | + * @param $userId | |
| 547 | + * @return mixed | |
| 548 | + * @throws PublicKeyMissingException | |
| 549 | + */ | |
| 550 | +    public function getPublicKey($userId) { | |
| 551 | + $publicKey = $this->keyStorage->getUserKey($userId, $this->publicKeyId, Encryption::ID); | |
| 552 | + | |
| 553 | +        if (strlen($publicKey) !== 0) { | |
| 554 | + return $publicKey; | |
| 555 | + } | |
| 556 | + throw new PublicKeyMissingException($userId); | |
| 557 | + } | |
| 558 | + | |
| 559 | +    public function getPublicShareKeyId() { | |
| 560 | + return $this->publicShareKeyId; | |
| 561 | + } | |
| 562 | + | |
| 563 | + /** | |
| 564 | + * get public key for public link shares | |
| 565 | + * | |
| 566 | + * @return string | |
| 567 | + */ | |
| 568 | +    public function getPublicShareKey() { | |
| 569 | + return $this->keyStorage->getSystemUserKey($this->publicShareKeyId . '.publicKey', Encryption::ID); | |
| 570 | + } | |
| 571 | + | |
| 572 | + /** | |
| 573 | + * @param string $purpose | |
| 574 | + * @param string $uid | |
| 575 | + */ | |
| 576 | +    public function backupUserKeys($purpose, $uid) { | |
| 577 | + $this->keyStorage->backupUserKeys(Encryption::ID, $purpose, $uid); | |
| 578 | + } | |
| 579 | + | |
| 580 | + /** | |
| 581 | + * creat a backup of the users private and public key and then delete it | |
| 582 | + * | |
| 583 | + * @param string $uid | |
| 584 | + */ | |
| 585 | +    public function deleteUserKeys($uid) { | |
| 586 | + $this->deletePublicKey($uid); | |
| 587 | + $this->deletePrivateKey($uid); | |
| 588 | + } | |
| 589 | + | |
| 590 | + /** | |
| 591 | + * @param $uid | |
| 592 | + * @return bool | |
| 593 | + */ | |
| 594 | +    public function deletePublicKey($uid) { | |
| 595 | + return $this->keyStorage->deleteUserKey($uid, $this->publicKeyId, Encryption::ID); | |
| 596 | + } | |
| 597 | + | |
| 598 | + /** | |
| 599 | + * @param string $uid | |
| 600 | + * @return bool | |
| 601 | + */ | |
| 602 | +    private function deletePrivateKey($uid) { | |
| 603 | + return $this->keyStorage->deleteUserKey($uid, $this->privateKeyId, Encryption::ID); | |
| 604 | + } | |
| 605 | + | |
| 606 | + /** | |
| 607 | + * @param string $path | |
| 608 | + * @return bool | |
| 609 | + */ | |
| 610 | +    public function deleteAllFileKeys($path) { | |
| 611 | + return $this->keyStorage->deleteAllFileKeys($path); | |
| 612 | + } | |
| 613 | + | |
| 614 | + /** | |
| 615 | + * @param array $userIds | |
| 616 | + * @return array | |
| 617 | + * @throws PublicKeyMissingException | |
| 618 | + */ | |
| 619 | +    public function getPublicKeys(array $userIds) { | |
| 620 | + $keys = []; | |
| 621 | + | |
| 622 | +        foreach ($userIds as $userId) { | |
| 623 | +            try { | |
| 624 | + $keys[$userId] = $this->getPublicKey($userId); | |
| 625 | +            } catch (PublicKeyMissingException $e) { | |
| 626 | + continue; | |
| 627 | + } | |
| 628 | + } | |
| 629 | + | |
| 630 | + return $keys; | |
| 631 | + | |
| 632 | + } | |
| 633 | + | |
| 634 | + /** | |
| 635 | + * @param string $keyId | |
| 636 | + * @return string returns openssl key | |
| 637 | + */ | |
| 638 | +    public function getSystemPrivateKey($keyId) { | |
| 639 | + return $this->keyStorage->getSystemUserKey($keyId . '.' . $this->privateKeyId, Encryption::ID); | |
| 640 | + } | |
| 641 | + | |
| 642 | + /** | |
| 643 | + * @param string $keyId | |
| 644 | + * @param string $key | |
| 645 | + * @return string returns openssl key | |
| 646 | + */ | |
| 647 | +    public function setSystemPrivateKey($keyId, $key) { | |
| 648 | + return $this->keyStorage->setSystemUserKey( | |
| 649 | + $keyId . '.' . $this->privateKeyId, | |
| 650 | + $key, | |
| 651 | + Encryption::ID); | |
| 652 | + } | |
| 653 | + | |
| 654 | + /** | |
| 655 | + * add system keys such as the public share key and the recovery key | |
| 656 | + * | |
| 657 | + * @param array $accessList | |
| 658 | + * @param array $publicKeys | |
| 659 | + * @param string $uid | |
| 660 | + * @return array | |
| 661 | + * @throws PublicKeyMissingException | |
| 662 | + */ | |
| 663 | +    public function addSystemKeys(array $accessList, array $publicKeys, $uid) { | |
| 664 | +        if (!empty($accessList['public'])) { | |
| 665 | + $publicShareKey = $this->getPublicShareKey(); | |
| 666 | +            if (empty($publicShareKey)) { | |
| 667 | + throw new PublicKeyMissingException($this->getPublicShareKeyId()); | |
| 668 | + } | |
| 669 | + $publicKeys[$this->getPublicShareKeyId()] = $publicShareKey; | |
| 670 | + } | |
| 671 | + | |
| 672 | + if ($this->recoveryKeyExists() && | |
| 673 | +            $this->util->isRecoveryEnabledForUser($uid)) { | |
| 674 | + | |
| 675 | + $publicKeys[$this->getRecoveryKeyId()] = $this->getRecoveryKey(); | |
| 676 | + } | |
| 677 | + | |
| 678 | + return $publicKeys; | |
| 679 | + } | |
| 680 | + | |
| 681 | + /** | |
| 682 | + * get master key password | |
| 683 | + * | |
| 684 | + * @return string | |
| 685 | + * @throws \Exception | |
| 686 | + */ | |
| 687 | +    public function getMasterKeyPassword() { | |
| 688 | +        $password = $this->config->getSystemValue('secret'); | |
| 689 | +        if (empty($password)){ | |
| 690 | +            throw new \Exception('Can not get secret from Nextcloud instance'); | |
| 691 | + } | |
| 692 | + | |
| 693 | + return $password; | |
| 694 | + } | |
| 695 | + | |
| 696 | + /** | |
| 697 | + * return master key id | |
| 698 | + * | |
| 699 | + * @return string | |
| 700 | + */ | |
| 701 | +    public function getMasterKeyId() { | |
| 702 | + return $this->masterKeyId; | |
| 703 | + } | |
| 704 | + | |
| 705 | + /** | |
| 706 | + * get public master key | |
| 707 | + * | |
| 708 | + * @return string | |
| 709 | + */ | |
| 710 | +    public function getPublicMasterKey() { | |
| 711 | + return $this->keyStorage->getSystemUserKey($this->masterKeyId . '.publicKey', Encryption::ID); | |
| 712 | + } | |
| 713 | 713 | } |