Completed
Pull Request — stable10 (#5732)
by Morris
14:18
created
lib/private/App/Platform.php 2 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -23,7 +23,6 @@
 block discarded – undo
23 23
 
24 24
 namespace OC\App;
25 25
 
26
-use OC_Util;
27 26
 use OCP\IConfig;
28 27
 
29 28
 /**
Please login to merge, or discard this patch.
Indentation   +54 added lines, -54 removed lines patch added patch discarded remove patch
@@ -36,66 +36,66 @@
 block discarded – undo
36 36
  */
37 37
 class Platform {
38 38
 
39
-	/**
40
-	 * @param IConfig $config
41
-	 */
42
-	function __construct(IConfig $config) {
43
-		$this->config = $config;
44
-	}
39
+    /**
40
+     * @param IConfig $config
41
+     */
42
+    function __construct(IConfig $config) {
43
+        $this->config = $config;
44
+    }
45 45
 
46
-	/**
47
-	 * @return string
48
-	 */
49
-	public function getPhpVersion() {
50
-		return phpversion();
51
-	}
46
+    /**
47
+     * @return string
48
+     */
49
+    public function getPhpVersion() {
50
+        return phpversion();
51
+    }
52 52
 
53
-	/**
54
-	 * @return int
55
-	 */
56
-	public function getIntSize() {
57
-		return PHP_INT_SIZE;
58
-	}
53
+    /**
54
+     * @return int
55
+     */
56
+    public function getIntSize() {
57
+        return PHP_INT_SIZE;
58
+    }
59 59
 
60
-	/**
61
-	 * @return string
62
-	 */
63
-	public function getOcVersion() {
64
-		$v = \OCP\Util::getVersion();
65
-		return join('.', $v);
66
-	}
60
+    /**
61
+     * @return string
62
+     */
63
+    public function getOcVersion() {
64
+        $v = \OCP\Util::getVersion();
65
+        return join('.', $v);
66
+    }
67 67
 
68
-	/**
69
-	 * @return string
70
-	 */
71
-	public function getDatabase() {
72
-		$dbType = $this->config->getSystemValue('dbtype', 'sqlite');
73
-		if ($dbType === 'sqlite3') {
74
-			$dbType = 'sqlite';
75
-		}
68
+    /**
69
+     * @return string
70
+     */
71
+    public function getDatabase() {
72
+        $dbType = $this->config->getSystemValue('dbtype', 'sqlite');
73
+        if ($dbType === 'sqlite3') {
74
+            $dbType = 'sqlite';
75
+        }
76 76
 
77
-		return $dbType;
78
-	}
77
+        return $dbType;
78
+    }
79 79
 
80
-	/**
81
-	 * @return string
82
-	 */
83
-	public function getOS() {
84
-		return php_uname('s');
85
-	}
80
+    /**
81
+     * @return string
82
+     */
83
+    public function getOS() {
84
+        return php_uname('s');
85
+    }
86 86
 
87
-	/**
88
-	 * @param $command
89
-	 * @return bool
90
-	 */
91
-	public function isCommandKnown($command) {
92
-		$path = \OC_Helper::findBinaryPath($command);
93
-		return ($path !== null);
94
-	}
87
+    /**
88
+     * @param $command
89
+     * @return bool
90
+     */
91
+    public function isCommandKnown($command) {
92
+        $path = \OC_Helper::findBinaryPath($command);
93
+        return ($path !== null);
94
+    }
95 95
 
96
-	public function getLibraryVersion($name) {
97
-		$repo = new PlatformRepository();
98
-		$lib = $repo->findLibrary($name);
99
-		return $lib;
100
-	}
96
+    public function getLibraryVersion($name) {
97
+        $repo = new PlatformRepository();
98
+        $lib = $repo->findLibrary($name);
99
+        return $lib;
100
+    }
101 101
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/Http.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -110,7 +110,7 @@
 block discarded – undo
110 110
 
111 111
 	/**
112 112
 	 * Gets the correct header
113
-	 * @param Http::CONSTANT $status the constant from the Http class
113
+	 * @param integer $status the constant from the Http class
114 114
 	 * @param \DateTime $lastModified formatted last modified date
115 115
 	 * @param string $ETag the etag
116 116
 	 * @return string
Please login to merge, or discard this patch.
Indentation   +115 added lines, -115 removed lines patch added patch discarded remove patch
@@ -33,121 +33,121 @@
 block discarded – undo
33 33
 
34 34
 class Http extends BaseHttp {
35 35
 
36
-	private $server;
37
-	private $protocolVersion;
38
-	protected $headers;
39
-
40
-	/**
41
-	 * @param array $server $_SERVER
42
-	 * @param string $protocolVersion the http version to use defaults to HTTP/1.1
43
-	 */
44
-	public function __construct($server, $protocolVersion='HTTP/1.1') {
45
-		$this->server = $server;
46
-		$this->protocolVersion = $protocolVersion;
47
-
48
-		$this->headers = array(
49
-			self::STATUS_CONTINUE => 'Continue',
50
-			self::STATUS_SWITCHING_PROTOCOLS => 'Switching Protocols',
51
-			self::STATUS_PROCESSING => 'Processing',
52
-			self::STATUS_OK => 'OK',
53
-			self::STATUS_CREATED => 'Created',
54
-			self::STATUS_ACCEPTED => 'Accepted',
55
-			self::STATUS_NON_AUTHORATIVE_INFORMATION => 'Non-Authorative Information',
56
-			self::STATUS_NO_CONTENT => 'No Content',
57
-			self::STATUS_RESET_CONTENT => 'Reset Content',
58
-			self::STATUS_PARTIAL_CONTENT => 'Partial Content',
59
-			self::STATUS_MULTI_STATUS => 'Multi-Status', // RFC 4918
60
-			self::STATUS_ALREADY_REPORTED => 'Already Reported', // RFC 5842
61
-			self::STATUS_IM_USED => 'IM Used', // RFC 3229
62
-			self::STATUS_MULTIPLE_CHOICES => 'Multiple Choices',
63
-			self::STATUS_MOVED_PERMANENTLY => 'Moved Permanently',
64
-			self::STATUS_FOUND => 'Found',
65
-			self::STATUS_SEE_OTHER => 'See Other',
66
-			self::STATUS_NOT_MODIFIED => 'Not Modified',
67
-			self::STATUS_USE_PROXY => 'Use Proxy',
68
-			self::STATUS_RESERVED => 'Reserved',
69
-			self::STATUS_TEMPORARY_REDIRECT => 'Temporary Redirect',
70
-			self::STATUS_BAD_REQUEST => 'Bad request',
71
-			self::STATUS_UNAUTHORIZED => 'Unauthorized',
72
-			self::STATUS_PAYMENT_REQUIRED => 'Payment Required',
73
-			self::STATUS_FORBIDDEN => 'Forbidden',
74
-			self::STATUS_NOT_FOUND => 'Not Found',
75
-			self::STATUS_METHOD_NOT_ALLOWED => 'Method Not Allowed',
76
-			self::STATUS_NOT_ACCEPTABLE => 'Not Acceptable',
77
-			self::STATUS_PROXY_AUTHENTICATION_REQUIRED => 'Proxy Authentication Required',
78
-			self::STATUS_REQUEST_TIMEOUT => 'Request Timeout',
79
-			self::STATUS_CONFLICT => 'Conflict',
80
-			self::STATUS_GONE => 'Gone',
81
-			self::STATUS_LENGTH_REQUIRED => 'Length Required',
82
-			self::STATUS_PRECONDITION_FAILED => 'Precondition failed',
83
-			self::STATUS_REQUEST_ENTITY_TOO_LARGE => 'Request Entity Too Large',
84
-			self::STATUS_REQUEST_URI_TOO_LONG => 'Request-URI Too Long',
85
-			self::STATUS_UNSUPPORTED_MEDIA_TYPE => 'Unsupported Media Type',
86
-			self::STATUS_REQUEST_RANGE_NOT_SATISFIABLE => 'Requested Range Not Satisfiable',
87
-			self::STATUS_EXPECTATION_FAILED => 'Expectation Failed',
88
-			self::STATUS_IM_A_TEAPOT => 'I\'m a teapot', // RFC 2324
89
-			self::STATUS_UNPROCESSABLE_ENTITY => 'Unprocessable Entity', // RFC 4918
90
-			self::STATUS_LOCKED => 'Locked', // RFC 4918
91
-			self::STATUS_FAILED_DEPENDENCY => 'Failed Dependency', // RFC 4918
92
-			self::STATUS_UPGRADE_REQUIRED => 'Upgrade required',
93
-			self::STATUS_PRECONDITION_REQUIRED => 'Precondition required', // draft-nottingham-http-new-status
94
-			self::STATUS_TOO_MANY_REQUESTS => 'Too Many Requests', // draft-nottingham-http-new-status
95
-			self::STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE => 'Request Header Fields Too Large', // draft-nottingham-http-new-status
96
-			self::STATUS_INTERNAL_SERVER_ERROR => 'Internal Server Error',
97
-			self::STATUS_NOT_IMPLEMENTED => 'Not Implemented',
98
-			self::STATUS_BAD_GATEWAY => 'Bad Gateway',
99
-			self::STATUS_SERVICE_UNAVAILABLE => 'Service Unavailable',
100
-			self::STATUS_GATEWAY_TIMEOUT => 'Gateway Timeout',
101
-			self::STATUS_HTTP_VERSION_NOT_SUPPORTED => 'HTTP Version not supported',
102
-			self::STATUS_VARIANT_ALSO_NEGOTIATES => 'Variant Also Negotiates',
103
-			self::STATUS_INSUFFICIENT_STORAGE => 'Insufficient Storage', // RFC 4918
104
-			self::STATUS_LOOP_DETECTED => 'Loop Detected', // RFC 5842
105
-			self::STATUS_BANDWIDTH_LIMIT_EXCEEDED => 'Bandwidth Limit Exceeded', // non-standard
106
-			self::STATUS_NOT_EXTENDED => 'Not extended',
107
-			self::STATUS_NETWORK_AUTHENTICATION_REQUIRED => 'Network Authentication Required', // draft-nottingham-http-new-status
108
-		);
109
-	}
110
-
111
-
112
-	/**
113
-	 * Gets the correct header
114
-	 * @param Http::CONSTANT $status the constant from the Http class
115
-	 * @param \DateTime $lastModified formatted last modified date
116
-	 * @param string $ETag the etag
117
-	 * @return string
118
-	 */
119
-	public function getStatusHeader($status, \DateTime $lastModified=null, 
120
-	                                $ETag=null) {
121
-
122
-		if(!is_null($lastModified)) {
123
-			$lastModified = $lastModified->format(\DateTime::RFC2822);
124
-		}
125
-
126
-		// if etag or lastmodified have not changed, return a not modified
127
-		if ((isset($this->server['HTTP_IF_NONE_MATCH'])
128
-			&& trim(trim($this->server['HTTP_IF_NONE_MATCH']), '"') === (string)$ETag)
129
-
130
-			||
131
-
132
-			(isset($this->server['HTTP_IF_MODIFIED_SINCE'])
133
-			&& trim($this->server['HTTP_IF_MODIFIED_SINCE']) === 
134
-				$lastModified)) {
135
-
136
-			$status = self::STATUS_NOT_MODIFIED;
137
-		}
138
-
139
-		// we have one change currently for the http 1.0 header that differs
140
-		// from 1.1: STATUS_TEMPORARY_REDIRECT should be STATUS_FOUND
141
-		// if this differs any more, we want to create childclasses for this
142
-		if($status === self::STATUS_TEMPORARY_REDIRECT 
143
-			&& $this->protocolVersion === 'HTTP/1.0') {
144
-
145
-			$status = self::STATUS_FOUND;
146
-		}
147
-
148
-		return $this->protocolVersion . ' ' . $status . ' ' . 
149
-			$this->headers[$status];
150
-	}
36
+    private $server;
37
+    private $protocolVersion;
38
+    protected $headers;
39
+
40
+    /**
41
+     * @param array $server $_SERVER
42
+     * @param string $protocolVersion the http version to use defaults to HTTP/1.1
43
+     */
44
+    public function __construct($server, $protocolVersion='HTTP/1.1') {
45
+        $this->server = $server;
46
+        $this->protocolVersion = $protocolVersion;
47
+
48
+        $this->headers = array(
49
+            self::STATUS_CONTINUE => 'Continue',
50
+            self::STATUS_SWITCHING_PROTOCOLS => 'Switching Protocols',
51
+            self::STATUS_PROCESSING => 'Processing',
52
+            self::STATUS_OK => 'OK',
53
+            self::STATUS_CREATED => 'Created',
54
+            self::STATUS_ACCEPTED => 'Accepted',
55
+            self::STATUS_NON_AUTHORATIVE_INFORMATION => 'Non-Authorative Information',
56
+            self::STATUS_NO_CONTENT => 'No Content',
57
+            self::STATUS_RESET_CONTENT => 'Reset Content',
58
+            self::STATUS_PARTIAL_CONTENT => 'Partial Content',
59
+            self::STATUS_MULTI_STATUS => 'Multi-Status', // RFC 4918
60
+            self::STATUS_ALREADY_REPORTED => 'Already Reported', // RFC 5842
61
+            self::STATUS_IM_USED => 'IM Used', // RFC 3229
62
+            self::STATUS_MULTIPLE_CHOICES => 'Multiple Choices',
63
+            self::STATUS_MOVED_PERMANENTLY => 'Moved Permanently',
64
+            self::STATUS_FOUND => 'Found',
65
+            self::STATUS_SEE_OTHER => 'See Other',
66
+            self::STATUS_NOT_MODIFIED => 'Not Modified',
67
+            self::STATUS_USE_PROXY => 'Use Proxy',
68
+            self::STATUS_RESERVED => 'Reserved',
69
+            self::STATUS_TEMPORARY_REDIRECT => 'Temporary Redirect',
70
+            self::STATUS_BAD_REQUEST => 'Bad request',
71
+            self::STATUS_UNAUTHORIZED => 'Unauthorized',
72
+            self::STATUS_PAYMENT_REQUIRED => 'Payment Required',
73
+            self::STATUS_FORBIDDEN => 'Forbidden',
74
+            self::STATUS_NOT_FOUND => 'Not Found',
75
+            self::STATUS_METHOD_NOT_ALLOWED => 'Method Not Allowed',
76
+            self::STATUS_NOT_ACCEPTABLE => 'Not Acceptable',
77
+            self::STATUS_PROXY_AUTHENTICATION_REQUIRED => 'Proxy Authentication Required',
78
+            self::STATUS_REQUEST_TIMEOUT => 'Request Timeout',
79
+            self::STATUS_CONFLICT => 'Conflict',
80
+            self::STATUS_GONE => 'Gone',
81
+            self::STATUS_LENGTH_REQUIRED => 'Length Required',
82
+            self::STATUS_PRECONDITION_FAILED => 'Precondition failed',
83
+            self::STATUS_REQUEST_ENTITY_TOO_LARGE => 'Request Entity Too Large',
84
+            self::STATUS_REQUEST_URI_TOO_LONG => 'Request-URI Too Long',
85
+            self::STATUS_UNSUPPORTED_MEDIA_TYPE => 'Unsupported Media Type',
86
+            self::STATUS_REQUEST_RANGE_NOT_SATISFIABLE => 'Requested Range Not Satisfiable',
87
+            self::STATUS_EXPECTATION_FAILED => 'Expectation Failed',
88
+            self::STATUS_IM_A_TEAPOT => 'I\'m a teapot', // RFC 2324
89
+            self::STATUS_UNPROCESSABLE_ENTITY => 'Unprocessable Entity', // RFC 4918
90
+            self::STATUS_LOCKED => 'Locked', // RFC 4918
91
+            self::STATUS_FAILED_DEPENDENCY => 'Failed Dependency', // RFC 4918
92
+            self::STATUS_UPGRADE_REQUIRED => 'Upgrade required',
93
+            self::STATUS_PRECONDITION_REQUIRED => 'Precondition required', // draft-nottingham-http-new-status
94
+            self::STATUS_TOO_MANY_REQUESTS => 'Too Many Requests', // draft-nottingham-http-new-status
95
+            self::STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE => 'Request Header Fields Too Large', // draft-nottingham-http-new-status
96
+            self::STATUS_INTERNAL_SERVER_ERROR => 'Internal Server Error',
97
+            self::STATUS_NOT_IMPLEMENTED => 'Not Implemented',
98
+            self::STATUS_BAD_GATEWAY => 'Bad Gateway',
99
+            self::STATUS_SERVICE_UNAVAILABLE => 'Service Unavailable',
100
+            self::STATUS_GATEWAY_TIMEOUT => 'Gateway Timeout',
101
+            self::STATUS_HTTP_VERSION_NOT_SUPPORTED => 'HTTP Version not supported',
102
+            self::STATUS_VARIANT_ALSO_NEGOTIATES => 'Variant Also Negotiates',
103
+            self::STATUS_INSUFFICIENT_STORAGE => 'Insufficient Storage', // RFC 4918
104
+            self::STATUS_LOOP_DETECTED => 'Loop Detected', // RFC 5842
105
+            self::STATUS_BANDWIDTH_LIMIT_EXCEEDED => 'Bandwidth Limit Exceeded', // non-standard
106
+            self::STATUS_NOT_EXTENDED => 'Not extended',
107
+            self::STATUS_NETWORK_AUTHENTICATION_REQUIRED => 'Network Authentication Required', // draft-nottingham-http-new-status
108
+        );
109
+    }
110
+
111
+
112
+    /**
113
+     * Gets the correct header
114
+     * @param Http::CONSTANT $status the constant from the Http class
115
+     * @param \DateTime $lastModified formatted last modified date
116
+     * @param string $ETag the etag
117
+     * @return string
118
+     */
119
+    public function getStatusHeader($status, \DateTime $lastModified=null, 
120
+                                    $ETag=null) {
121
+
122
+        if(!is_null($lastModified)) {
123
+            $lastModified = $lastModified->format(\DateTime::RFC2822);
124
+        }
125
+
126
+        // if etag or lastmodified have not changed, return a not modified
127
+        if ((isset($this->server['HTTP_IF_NONE_MATCH'])
128
+            && trim(trim($this->server['HTTP_IF_NONE_MATCH']), '"') === (string)$ETag)
129
+
130
+            ||
131
+
132
+            (isset($this->server['HTTP_IF_MODIFIED_SINCE'])
133
+            && trim($this->server['HTTP_IF_MODIFIED_SINCE']) === 
134
+                $lastModified)) {
135
+
136
+            $status = self::STATUS_NOT_MODIFIED;
137
+        }
138
+
139
+        // we have one change currently for the http 1.0 header that differs
140
+        // from 1.1: STATUS_TEMPORARY_REDIRECT should be STATUS_FOUND
141
+        // if this differs any more, we want to create childclasses for this
142
+        if($status === self::STATUS_TEMPORARY_REDIRECT 
143
+            && $this->protocolVersion === 'HTTP/1.0') {
144
+
145
+            $status = self::STATUS_FOUND;
146
+        }
147
+
148
+        return $this->protocolVersion . ' ' . $status . ' ' . 
149
+            $this->headers[$status];
150
+    }
151 151
 
152 152
 
153 153
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -41,7 +41,7 @@  discard block
 block discarded – undo
41 41
 	 * @param array $server $_SERVER
42 42
 	 * @param string $protocolVersion the http version to use defaults to HTTP/1.1
43 43
 	 */
44
-	public function __construct($server, $protocolVersion='HTTP/1.1') {
44
+	public function __construct($server, $protocolVersion = 'HTTP/1.1') {
45 45
 		$this->server = $server;
46 46
 		$this->protocolVersion = $protocolVersion;
47 47
 
@@ -116,16 +116,16 @@  discard block
 block discarded – undo
116 116
 	 * @param string $ETag the etag
117 117
 	 * @return string
118 118
 	 */
119
-	public function getStatusHeader($status, \DateTime $lastModified=null, 
120
-	                                $ETag=null) {
119
+	public function getStatusHeader($status, \DateTime $lastModified = null, 
120
+	                                $ETag = null) {
121 121
 
122
-		if(!is_null($lastModified)) {
122
+		if (!is_null($lastModified)) {
123 123
 			$lastModified = $lastModified->format(\DateTime::RFC2822);
124 124
 		}
125 125
 
126 126
 		// if etag or lastmodified have not changed, return a not modified
127 127
 		if ((isset($this->server['HTTP_IF_NONE_MATCH'])
128
-			&& trim(trim($this->server['HTTP_IF_NONE_MATCH']), '"') === (string)$ETag)
128
+			&& trim(trim($this->server['HTTP_IF_NONE_MATCH']), '"') === (string) $ETag)
129 129
 
130 130
 			||
131 131
 
@@ -139,13 +139,13 @@  discard block
 block discarded – undo
139 139
 		// we have one change currently for the http 1.0 header that differs
140 140
 		// from 1.1: STATUS_TEMPORARY_REDIRECT should be STATUS_FOUND
141 141
 		// if this differs any more, we want to create childclasses for this
142
-		if($status === self::STATUS_TEMPORARY_REDIRECT 
142
+		if ($status === self::STATUS_TEMPORARY_REDIRECT 
143 143
 			&& $this->protocolVersion === 'HTTP/1.0') {
144 144
 
145 145
 			$status = self::STATUS_FOUND;
146 146
 		}
147 147
 
148
-		return $this->protocolVersion . ' ' . $status . ' ' . 
148
+		return $this->protocolVersion.' '.$status.' '. 
149 149
 			$this->headers[$status];
150 150
 	}
151 151
 
Please login to merge, or discard this patch.
lib/private/AppFramework/Utility/ControllerMethodReflector.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -46,7 +46,7 @@
 block discarded – undo
46 46
 
47 47
 
48 48
 	/**
49
-	 * @param object $object an object or classname
49
+	 * @param \OCP\AppFramework\Controller $object an object or classname
50 50
 	 * @param string $method the method which we want to inspect
51 51
 	 */
52 52
 	public function reflect($object, $method){
Please login to merge, or discard this patch.
Indentation   +79 added lines, -79 removed lines patch added patch discarded remove patch
@@ -35,85 +35,85 @@
 block discarded – undo
35 35
  */
36 36
 class ControllerMethodReflector implements IControllerMethodReflector{
37 37
 
38
-	private $annotations;
39
-	private $types;
40
-	private $parameters;
41
-
42
-	public function __construct() {
43
-		$this->types = array();
44
-		$this->parameters = array();
45
-		$this->annotations = array();
46
-	}
47
-
48
-
49
-	/**
50
-	 * @param object $object an object or classname
51
-	 * @param string $method the method which we want to inspect
52
-	 */
53
-	public function reflect($object, $method){
54
-		$reflection = new \ReflectionMethod($object, $method);
55
-		$docs = $reflection->getDocComment();
56
-
57
-		// extract everything prefixed by @ and first letter uppercase
58
-		preg_match_all('/@([A-Z]\w+)/', $docs, $matches);
59
-		$this->annotations = $matches[1];
60
-
61
-		// extract type parameter information
62
-		preg_match_all('/@param\h+(?P<type>\w+)\h+\$(?P<var>\w+)/', $docs, $matches);
63
-		$this->types = array_combine($matches['var'], $matches['type']);
64
-
65
-		foreach ($reflection->getParameters() as $param) {
66
-			// extract type information from PHP 7 scalar types and prefer them
67
-			// over phpdoc annotations
68
-			if (method_exists($param, 'getType')) {
69
-				$type = $param->getType();
70
-				if ($type !== null) {
71
-					$this->types[$param->getName()] = (string) $type;
72
-				}
73
-			}
74
-
75
-			if($param->isOptional()) {
76
-				$default = $param->getDefaultValue();
77
-			} else {
78
-				$default = null;
79
-			}
80
-			$this->parameters[$param->name] = $default;
81
-		}
82
-	}
83
-
84
-
85
-	/**
86
-	 * Inspects the PHPDoc parameters for types
87
-	 * @param string $parameter the parameter whose type comments should be
88
-	 * parsed
89
-	 * @return string|null type in the type parameters (@param int $something)
90
-	 * would return int or null if not existing
91
-	 */
92
-	public function getType($parameter) {
93
-		if(array_key_exists($parameter, $this->types)) {
94
-			return $this->types[$parameter];
95
-		} else {
96
-			return null;
97
-		}
98
-	}
99
-
100
-
101
-	/**
102
-	 * @return array the arguments of the method with key => default value
103
-	 */
104
-	public function getParameters() {
105
-		return $this->parameters;
106
-	}
107
-
108
-
109
-	/**
110
-	 * Check if a method contains an annotation
111
-	 * @param string $name the name of the annotation
112
-	 * @return bool true if the annotation is found
113
-	 */
114
-	public function hasAnnotation($name){
115
-		return in_array($name, $this->annotations);
116
-	}
38
+    private $annotations;
39
+    private $types;
40
+    private $parameters;
41
+
42
+    public function __construct() {
43
+        $this->types = array();
44
+        $this->parameters = array();
45
+        $this->annotations = array();
46
+    }
47
+
48
+
49
+    /**
50
+     * @param object $object an object or classname
51
+     * @param string $method the method which we want to inspect
52
+     */
53
+    public function reflect($object, $method){
54
+        $reflection = new \ReflectionMethod($object, $method);
55
+        $docs = $reflection->getDocComment();
56
+
57
+        // extract everything prefixed by @ and first letter uppercase
58
+        preg_match_all('/@([A-Z]\w+)/', $docs, $matches);
59
+        $this->annotations = $matches[1];
60
+
61
+        // extract type parameter information
62
+        preg_match_all('/@param\h+(?P<type>\w+)\h+\$(?P<var>\w+)/', $docs, $matches);
63
+        $this->types = array_combine($matches['var'], $matches['type']);
64
+
65
+        foreach ($reflection->getParameters() as $param) {
66
+            // extract type information from PHP 7 scalar types and prefer them
67
+            // over phpdoc annotations
68
+            if (method_exists($param, 'getType')) {
69
+                $type = $param->getType();
70
+                if ($type !== null) {
71
+                    $this->types[$param->getName()] = (string) $type;
72
+                }
73
+            }
74
+
75
+            if($param->isOptional()) {
76
+                $default = $param->getDefaultValue();
77
+            } else {
78
+                $default = null;
79
+            }
80
+            $this->parameters[$param->name] = $default;
81
+        }
82
+    }
83
+
84
+
85
+    /**
86
+     * Inspects the PHPDoc parameters for types
87
+     * @param string $parameter the parameter whose type comments should be
88
+     * parsed
89
+     * @return string|null type in the type parameters (@param int $something)
90
+     * would return int or null if not existing
91
+     */
92
+    public function getType($parameter) {
93
+        if(array_key_exists($parameter, $this->types)) {
94
+            return $this->types[$parameter];
95
+        } else {
96
+            return null;
97
+        }
98
+    }
99
+
100
+
101
+    /**
102
+     * @return array the arguments of the method with key => default value
103
+     */
104
+    public function getParameters() {
105
+        return $this->parameters;
106
+    }
107
+
108
+
109
+    /**
110
+     * Check if a method contains an annotation
111
+     * @param string $name the name of the annotation
112
+     * @return bool true if the annotation is found
113
+     */
114
+    public function hasAnnotation($name){
115
+        return in_array($name, $this->annotations);
116
+    }
117 117
 
118 118
 
119 119
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -33,7 +33,7 @@  discard block
 block discarded – undo
33 33
 /**
34 34
  * Reads and parses annotations from doc comments
35 35
  */
36
-class ControllerMethodReflector implements IControllerMethodReflector{
36
+class ControllerMethodReflector implements IControllerMethodReflector {
37 37
 
38 38
 	private $annotations;
39 39
 	private $types;
@@ -50,7 +50,7 @@  discard block
 block discarded – undo
50 50
 	 * @param object $object an object or classname
51 51
 	 * @param string $method the method which we want to inspect
52 52
 	 */
53
-	public function reflect($object, $method){
53
+	public function reflect($object, $method) {
54 54
 		$reflection = new \ReflectionMethod($object, $method);
55 55
 		$docs = $reflection->getDocComment();
56 56
 
@@ -72,7 +72,7 @@  discard block
 block discarded – undo
72 72
 				}
73 73
 			}
74 74
 
75
-			if($param->isOptional()) {
75
+			if ($param->isOptional()) {
76 76
 				$default = $param->getDefaultValue();
77 77
 			} else {
78 78
 				$default = null;
@@ -90,7 +90,7 @@  discard block
 block discarded – undo
90 90
 	 * would return int or null if not existing
91 91
 	 */
92 92
 	public function getType($parameter) {
93
-		if(array_key_exists($parameter, $this->types)) {
93
+		if (array_key_exists($parameter, $this->types)) {
94 94
 			return $this->types[$parameter];
95 95
 		} else {
96 96
 			return null;
@@ -111,7 +111,7 @@  discard block
 block discarded – undo
111 111
 	 * @param string $name the name of the annotation
112 112
 	 * @return bool true if the annotation is found
113 113
 	 */
114
-	public function hasAnnotation($name){
114
+	public function hasAnnotation($name) {
115 115
 		return in_array($name, $this->annotations);
116 116
 	}
117 117
 
Please login to merge, or discard this patch.
lib/private/Cache/File.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -92,9 +92,9 @@
 block discarded – undo
92 92
 
93 93
 	/**
94 94
 	 * @param string $key
95
-	 * @param mixed $value
95
+	 * @param string|null $value
96 96
 	 * @param int $ttl
97
-	 * @return bool|mixed
97
+	 * @return boolean
98 98
 	 * @throws \OC\ForbiddenException
99 99
 	 */
100 100
 	public function set($key, $value, $ttl = 0) {
Please login to merge, or discard this patch.
Indentation   +157 added lines, -157 removed lines patch added patch discarded remove patch
@@ -33,170 +33,170 @@
 block discarded – undo
33 33
 
34 34
 class File implements ICache {
35 35
 
36
-	/** @var View */
37
-	protected $storage;
36
+    /** @var View */
37
+    protected $storage;
38 38
 
39
-	/**
40
-	 * Returns the cache storage for the logged in user
41
-	 *
42
-	 * @return \OC\Files\View cache storage
43
-	 * @throws \OC\ForbiddenException
44
-	 * @throws \OC\User\NoUserException
45
-	 */
46
-	protected function getStorage() {
47
-		if (isset($this->storage)) {
48
-			return $this->storage;
49
-		}
50
-		if (\OC_User::isLoggedIn()) {
51
-			$rootView = new View();
52
-			$user = \OC::$server->getUserSession()->getUser();
53
-			Filesystem::initMountPoints($user->getUID());
54
-			if (!$rootView->file_exists('/' . $user->getUID() . '/cache')) {
55
-				$rootView->mkdir('/' . $user->getUID() . '/cache');
56
-			}
57
-			$this->storage = new View('/' . $user->getUID() . '/cache');
58
-			return $this->storage;
59
-		} else {
60
-			\OCP\Util::writeLog('core', 'Can\'t get cache storage, user not logged in', \OCP\Util::ERROR);
61
-			throw new \OC\ForbiddenException('Can\t get cache storage, user not logged in');
62
-		}
63
-	}
39
+    /**
40
+     * Returns the cache storage for the logged in user
41
+     *
42
+     * @return \OC\Files\View cache storage
43
+     * @throws \OC\ForbiddenException
44
+     * @throws \OC\User\NoUserException
45
+     */
46
+    protected function getStorage() {
47
+        if (isset($this->storage)) {
48
+            return $this->storage;
49
+        }
50
+        if (\OC_User::isLoggedIn()) {
51
+            $rootView = new View();
52
+            $user = \OC::$server->getUserSession()->getUser();
53
+            Filesystem::initMountPoints($user->getUID());
54
+            if (!$rootView->file_exists('/' . $user->getUID() . '/cache')) {
55
+                $rootView->mkdir('/' . $user->getUID() . '/cache');
56
+            }
57
+            $this->storage = new View('/' . $user->getUID() . '/cache');
58
+            return $this->storage;
59
+        } else {
60
+            \OCP\Util::writeLog('core', 'Can\'t get cache storage, user not logged in', \OCP\Util::ERROR);
61
+            throw new \OC\ForbiddenException('Can\t get cache storage, user not logged in');
62
+        }
63
+    }
64 64
 
65
-	/**
66
-	 * @param string $key
67
-	 * @return mixed|null
68
-	 * @throws \OC\ForbiddenException
69
-	 */
70
-	public function get($key) {
71
-		$result = null;
72
-		if ($this->hasKey($key)) {
73
-			$storage = $this->getStorage();
74
-			$result = $storage->file_get_contents($key);
75
-		}
76
-		return $result;
77
-	}
65
+    /**
66
+     * @param string $key
67
+     * @return mixed|null
68
+     * @throws \OC\ForbiddenException
69
+     */
70
+    public function get($key) {
71
+        $result = null;
72
+        if ($this->hasKey($key)) {
73
+            $storage = $this->getStorage();
74
+            $result = $storage->file_get_contents($key);
75
+        }
76
+        return $result;
77
+    }
78 78
 
79
-	/**
80
-	 * Returns the size of the stored/cached data
81
-	 *
82
-	 * @param string $key
83
-	 * @return int
84
-	 */
85
-	public function size($key) {
86
-		$result = 0;
87
-		if ($this->hasKey($key)) {
88
-			$storage = $this->getStorage();
89
-			$result = $storage->filesize($key);
90
-		}
91
-		return $result;
92
-	}
79
+    /**
80
+     * Returns the size of the stored/cached data
81
+     *
82
+     * @param string $key
83
+     * @return int
84
+     */
85
+    public function size($key) {
86
+        $result = 0;
87
+        if ($this->hasKey($key)) {
88
+            $storage = $this->getStorage();
89
+            $result = $storage->filesize($key);
90
+        }
91
+        return $result;
92
+    }
93 93
 
94
-	/**
95
-	 * @param string $key
96
-	 * @param mixed $value
97
-	 * @param int $ttl
98
-	 * @return bool|mixed
99
-	 * @throws \OC\ForbiddenException
100
-	 */
101
-	public function set($key, $value, $ttl = 0) {
102
-		$storage = $this->getStorage();
103
-		$result = false;
104
-		// unique id to avoid chunk collision, just in case
105
-		$uniqueId = \OC::$server->getSecureRandom()->generate(
106
-			16,
107
-			ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER
108
-		);
94
+    /**
95
+     * @param string $key
96
+     * @param mixed $value
97
+     * @param int $ttl
98
+     * @return bool|mixed
99
+     * @throws \OC\ForbiddenException
100
+     */
101
+    public function set($key, $value, $ttl = 0) {
102
+        $storage = $this->getStorage();
103
+        $result = false;
104
+        // unique id to avoid chunk collision, just in case
105
+        $uniqueId = \OC::$server->getSecureRandom()->generate(
106
+            16,
107
+            ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER
108
+        );
109 109
 
110
-		// use part file to prevent hasKey() to find the key
111
-		// while it is being written
112
-		$keyPart = $key . '.' . $uniqueId . '.part';
113
-		if ($storage and $storage->file_put_contents($keyPart, $value)) {
114
-			if ($ttl === 0) {
115
-				$ttl = 86400; // 60*60*24
116
-			}
117
-			$result = $storage->touch($keyPart, time() + $ttl);
118
-			$result &= $storage->rename($keyPart, $key);
119
-		}
120
-		return $result;
121
-	}
110
+        // use part file to prevent hasKey() to find the key
111
+        // while it is being written
112
+        $keyPart = $key . '.' . $uniqueId . '.part';
113
+        if ($storage and $storage->file_put_contents($keyPart, $value)) {
114
+            if ($ttl === 0) {
115
+                $ttl = 86400; // 60*60*24
116
+            }
117
+            $result = $storage->touch($keyPart, time() + $ttl);
118
+            $result &= $storage->rename($keyPart, $key);
119
+        }
120
+        return $result;
121
+    }
122 122
 
123
-	/**
124
-	 * @param string $key
125
-	 * @return bool
126
-	 * @throws \OC\ForbiddenException
127
-	 */
128
-	public function hasKey($key) {
129
-		$storage = $this->getStorage();
130
-		if ($storage && $storage->is_file($key) && $storage->isReadable($key)) {
131
-			return true;
132
-		}
133
-		return false;
134
-	}
123
+    /**
124
+     * @param string $key
125
+     * @return bool
126
+     * @throws \OC\ForbiddenException
127
+     */
128
+    public function hasKey($key) {
129
+        $storage = $this->getStorage();
130
+        if ($storage && $storage->is_file($key) && $storage->isReadable($key)) {
131
+            return true;
132
+        }
133
+        return false;
134
+    }
135 135
 
136
-	/**
137
-	 * @param string $key
138
-	 * @return bool|mixed
139
-	 * @throws \OC\ForbiddenException
140
-	 */
141
-	public function remove($key) {
142
-		$storage = $this->getStorage();
143
-		if (!$storage) {
144
-			return false;
145
-		}
146
-		return $storage->unlink($key);
147
-	}
136
+    /**
137
+     * @param string $key
138
+     * @return bool|mixed
139
+     * @throws \OC\ForbiddenException
140
+     */
141
+    public function remove($key) {
142
+        $storage = $this->getStorage();
143
+        if (!$storage) {
144
+            return false;
145
+        }
146
+        return $storage->unlink($key);
147
+    }
148 148
 
149
-	/**
150
-	 * @param string $prefix
151
-	 * @return bool
152
-	 * @throws \OC\ForbiddenException
153
-	 */
154
-	public function clear($prefix = '') {
155
-		$storage = $this->getStorage();
156
-		if ($storage and $storage->is_dir('/')) {
157
-			$dh = $storage->opendir('/');
158
-			if (is_resource($dh)) {
159
-				while (($file = readdir($dh)) !== false) {
160
-					if ($file != '.' and $file != '..' and ($prefix === '' || strpos($file, $prefix) === 0)) {
161
-						$storage->unlink('/' . $file);
162
-					}
163
-				}
164
-			}
165
-		}
166
-		return true;
167
-	}
149
+    /**
150
+     * @param string $prefix
151
+     * @return bool
152
+     * @throws \OC\ForbiddenException
153
+     */
154
+    public function clear($prefix = '') {
155
+        $storage = $this->getStorage();
156
+        if ($storage and $storage->is_dir('/')) {
157
+            $dh = $storage->opendir('/');
158
+            if (is_resource($dh)) {
159
+                while (($file = readdir($dh)) !== false) {
160
+                    if ($file != '.' and $file != '..' and ($prefix === '' || strpos($file, $prefix) === 0)) {
161
+                        $storage->unlink('/' . $file);
162
+                    }
163
+                }
164
+            }
165
+        }
166
+        return true;
167
+    }
168 168
 
169
-	/**
170
-	 * Runs GC
171
-	 * @throws \OC\ForbiddenException
172
-	 */
173
-	public function gc() {
174
-		$storage = $this->getStorage();
175
-		if ($storage and $storage->is_dir('/')) {
176
-			// extra hour safety, in case of stray part chunks that take longer to write,
177
-			// because touch() is only called after the chunk was finished
178
-			$now = time() - 3600;
179
-			$dh = $storage->opendir('/');
180
-			if (!is_resource($dh)) {
181
-				return null;
182
-			}
183
-			while (($file = readdir($dh)) !== false) {
184
-				if ($file != '.' and $file != '..') {
185
-					try {
186
-						$mtime = $storage->filemtime('/' . $file);
187
-						if ($mtime < $now) {
188
-							$storage->unlink('/' . $file);
189
-						}
190
-					} catch (\OCP\Lock\LockedException $e) {
191
-						// ignore locked chunks
192
-						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
193
-					} catch (\OCP\Files\ForbiddenException $e) {
194
-						\OC::$server->getLogger()->debug('Could not cleanup forbidden chunk "' . $file . '"', array('app' => 'core'));
195
-					} catch (\OCP\Files\LockNotAcquiredException $e) {
196
-						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
197
-					}
198
-				}
199
-			}
200
-		}
201
-	}
169
+    /**
170
+     * Runs GC
171
+     * @throws \OC\ForbiddenException
172
+     */
173
+    public function gc() {
174
+        $storage = $this->getStorage();
175
+        if ($storage and $storage->is_dir('/')) {
176
+            // extra hour safety, in case of stray part chunks that take longer to write,
177
+            // because touch() is only called after the chunk was finished
178
+            $now = time() - 3600;
179
+            $dh = $storage->opendir('/');
180
+            if (!is_resource($dh)) {
181
+                return null;
182
+            }
183
+            while (($file = readdir($dh)) !== false) {
184
+                if ($file != '.' and $file != '..') {
185
+                    try {
186
+                        $mtime = $storage->filemtime('/' . $file);
187
+                        if ($mtime < $now) {
188
+                            $storage->unlink('/' . $file);
189
+                        }
190
+                    } catch (\OCP\Lock\LockedException $e) {
191
+                        // ignore locked chunks
192
+                        \OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
193
+                    } catch (\OCP\Files\ForbiddenException $e) {
194
+                        \OC::$server->getLogger()->debug('Could not cleanup forbidden chunk "' . $file . '"', array('app' => 'core'));
195
+                    } catch (\OCP\Files\LockNotAcquiredException $e) {
196
+                        \OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
197
+                    }
198
+                }
199
+            }
200
+        }
201
+    }
202 202
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -51,10 +51,10 @@  discard block
 block discarded – undo
51 51
 			$rootView = new View();
52 52
 			$user = \OC::$server->getUserSession()->getUser();
53 53
 			Filesystem::initMountPoints($user->getUID());
54
-			if (!$rootView->file_exists('/' . $user->getUID() . '/cache')) {
55
-				$rootView->mkdir('/' . $user->getUID() . '/cache');
54
+			if (!$rootView->file_exists('/'.$user->getUID().'/cache')) {
55
+				$rootView->mkdir('/'.$user->getUID().'/cache');
56 56
 			}
57
-			$this->storage = new View('/' . $user->getUID() . '/cache');
57
+			$this->storage = new View('/'.$user->getUID().'/cache');
58 58
 			return $this->storage;
59 59
 		} else {
60 60
 			\OCP\Util::writeLog('core', 'Can\'t get cache storage, user not logged in', \OCP\Util::ERROR);
@@ -104,12 +104,12 @@  discard block
 block discarded – undo
104 104
 		// unique id to avoid chunk collision, just in case
105 105
 		$uniqueId = \OC::$server->getSecureRandom()->generate(
106 106
 			16,
107
-			ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER
107
+			ISecureRandom::CHAR_DIGITS.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_UPPER
108 108
 		);
109 109
 
110 110
 		// use part file to prevent hasKey() to find the key
111 111
 		// while it is being written
112
-		$keyPart = $key . '.' . $uniqueId . '.part';
112
+		$keyPart = $key.'.'.$uniqueId.'.part';
113 113
 		if ($storage and $storage->file_put_contents($keyPart, $value)) {
114 114
 			if ($ttl === 0) {
115 115
 				$ttl = 86400; // 60*60*24
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
 			if (is_resource($dh)) {
159 159
 				while (($file = readdir($dh)) !== false) {
160 160
 					if ($file != '.' and $file != '..' and ($prefix === '' || strpos($file, $prefix) === 0)) {
161
-						$storage->unlink('/' . $file);
161
+						$storage->unlink('/'.$file);
162 162
 					}
163 163
 				}
164 164
 			}
@@ -183,17 +183,17 @@  discard block
 block discarded – undo
183 183
 			while (($file = readdir($dh)) !== false) {
184 184
 				if ($file != '.' and $file != '..') {
185 185
 					try {
186
-						$mtime = $storage->filemtime('/' . $file);
186
+						$mtime = $storage->filemtime('/'.$file);
187 187
 						if ($mtime < $now) {
188
-							$storage->unlink('/' . $file);
188
+							$storage->unlink('/'.$file);
189 189
 						}
190 190
 					} catch (\OCP\Lock\LockedException $e) {
191 191
 						// ignore locked chunks
192
-						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
192
+						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "'.$file.'"', array('app' => 'core'));
193 193
 					} catch (\OCP\Files\ForbiddenException $e) {
194
-						\OC::$server->getLogger()->debug('Could not cleanup forbidden chunk "' . $file . '"', array('app' => 'core'));
194
+						\OC::$server->getLogger()->debug('Could not cleanup forbidden chunk "'.$file.'"', array('app' => 'core'));
195 195
 					} catch (\OCP\Files\LockNotAcquiredException $e) {
196
-						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
196
+						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "'.$file.'"', array('app' => 'core'));
197 197
 					}
198 198
 				}
199 199
 			}
Please login to merge, or discard this patch.
lib/private/Comments/Manager.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -205,7 +205,7 @@
 block discarded – undo
205 205
 	/**
206 206
 	 * removes an entry from the comments run time cache
207 207
 	 *
208
-	 * @param mixed $id the comment's id
208
+	 * @param string $id the comment's id
209 209
 	 */
210 210
 	protected function uncache($id) {
211 211
 		$id = strval($id);
Please login to merge, or discard this patch.
Indentation   +714 added lines, -714 removed lines patch added patch discarded remove patch
@@ -37,718 +37,718 @@
 block discarded – undo
37 37
 
38 38
 class Manager implements ICommentsManager {
39 39
 
40
-	/** @var  IDBConnection */
41
-	protected $dbConn;
42
-
43
-	/** @var  ILogger */
44
-	protected $logger;
45
-
46
-	/** @var IConfig */
47
-	protected $config;
48
-
49
-	/** @var EventDispatcherInterface */
50
-	protected $dispatcher;
51
-
52
-	/** @var IComment[]  */
53
-	protected $commentsCache = [];
54
-
55
-	/**
56
-	 * Manager constructor.
57
-	 *
58
-	 * @param IDBConnection $dbConn
59
-	 * @param ILogger $logger
60
-	 * @param IConfig $config
61
-	 * @param EventDispatcherInterface $dispatcher
62
-	 */
63
-	public function __construct(
64
-		IDBConnection $dbConn,
65
-		ILogger $logger,
66
-		IConfig $config,
67
-		EventDispatcherInterface $dispatcher
68
-	) {
69
-		$this->dbConn = $dbConn;
70
-		$this->logger = $logger;
71
-		$this->config = $config;
72
-		$this->dispatcher = $dispatcher;
73
-	}
74
-
75
-	/**
76
-	 * converts data base data into PHP native, proper types as defined by
77
-	 * IComment interface.
78
-	 *
79
-	 * @param array $data
80
-	 * @return array
81
-	 */
82
-	protected function normalizeDatabaseData(array $data) {
83
-		$data['id'] = strval($data['id']);
84
-		$data['parent_id'] = strval($data['parent_id']);
85
-		$data['topmost_parent_id'] = strval($data['topmost_parent_id']);
86
-		$data['creation_timestamp'] = new \DateTime($data['creation_timestamp']);
87
-		if (!is_null($data['latest_child_timestamp'])) {
88
-			$data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']);
89
-		}
90
-		$data['children_count'] = intval($data['children_count']);
91
-		return $data;
92
-	}
93
-
94
-	/**
95
-	 * prepares a comment for an insert or update operation after making sure
96
-	 * all necessary fields have a value assigned.
97
-	 *
98
-	 * @param IComment $comment
99
-	 * @return IComment returns the same updated IComment instance as provided
100
-	 *                  by parameter for convenience
101
-	 * @throws \UnexpectedValueException
102
-	 */
103
-	protected function prepareCommentForDatabaseWrite(IComment $comment) {
104
-		if(    !$comment->getActorType()
105
-			|| !$comment->getActorId()
106
-			|| !$comment->getObjectType()
107
-			|| !$comment->getObjectId()
108
-			|| !$comment->getVerb()
109
-		) {
110
-			throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving');
111
-		}
112
-
113
-		if($comment->getId() === '') {
114
-			$comment->setChildrenCount(0);
115
-			$comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC')));
116
-			$comment->setLatestChildDateTime(null);
117
-		}
118
-
119
-		if(is_null($comment->getCreationDateTime())) {
120
-			$comment->setCreationDateTime(new \DateTime());
121
-		}
122
-
123
-		if($comment->getParentId() !== '0') {
124
-			$comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId()));
125
-		} else {
126
-			$comment->setTopmostParentId('0');
127
-		}
128
-
129
-		$this->cache($comment);
130
-
131
-		return $comment;
132
-	}
133
-
134
-	/**
135
-	 * returns the topmost parent id of a given comment identified by ID
136
-	 *
137
-	 * @param string $id
138
-	 * @return string
139
-	 * @throws NotFoundException
140
-	 */
141
-	protected function determineTopmostParentId($id) {
142
-		$comment = $this->get($id);
143
-		if($comment->getParentId() === '0') {
144
-			return $comment->getId();
145
-		} else {
146
-			return $this->determineTopmostParentId($comment->getId());
147
-		}
148
-	}
149
-
150
-	/**
151
-	 * updates child information of a comment
152
-	 *
153
-	 * @param string	$id
154
-	 * @param \DateTime	$cDateTime	the date time of the most recent child
155
-	 * @throws NotFoundException
156
-	 */
157
-	protected function updateChildrenInformation($id, \DateTime $cDateTime) {
158
-		$qb = $this->dbConn->getQueryBuilder();
159
-		$query = $qb->select($qb->createFunction('COUNT(`id`)'))
160
-				->from('comments')
161
-				->where($qb->expr()->eq('parent_id', $qb->createParameter('id')))
162
-				->setParameter('id', $id);
163
-
164
-		$resultStatement = $query->execute();
165
-		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
166
-		$resultStatement->closeCursor();
167
-		$children = intval($data[0]);
168
-
169
-		$comment = $this->get($id);
170
-		$comment->setChildrenCount($children);
171
-		$comment->setLatestChildDateTime($cDateTime);
172
-		$this->save($comment);
173
-	}
174
-
175
-	/**
176
-	 * Tests whether actor or object type and id parameters are acceptable.
177
-	 * Throws exception if not.
178
-	 *
179
-	 * @param string $role
180
-	 * @param string $type
181
-	 * @param string $id
182
-	 * @throws \InvalidArgumentException
183
-	 */
184
-	protected function checkRoleParameters($role, $type, $id) {
185
-		if(
186
-			   !is_string($type) || empty($type)
187
-			|| !is_string($id) || empty($id)
188
-		) {
189
-			throw new \InvalidArgumentException($role . ' parameters must be string and not empty');
190
-		}
191
-	}
192
-
193
-	/**
194
-	 * run-time caches a comment
195
-	 *
196
-	 * @param IComment $comment
197
-	 */
198
-	protected function cache(IComment $comment) {
199
-		$id = $comment->getId();
200
-		if(empty($id)) {
201
-			return;
202
-		}
203
-		$this->commentsCache[strval($id)] = $comment;
204
-	}
205
-
206
-	/**
207
-	 * removes an entry from the comments run time cache
208
-	 *
209
-	 * @param mixed $id the comment's id
210
-	 */
211
-	protected function uncache($id) {
212
-		$id = strval($id);
213
-		if (isset($this->commentsCache[$id])) {
214
-			unset($this->commentsCache[$id]);
215
-		}
216
-	}
217
-
218
-	/**
219
-	 * returns a comment instance
220
-	 *
221
-	 * @param string $id the ID of the comment
222
-	 * @return IComment
223
-	 * @throws NotFoundException
224
-	 * @throws \InvalidArgumentException
225
-	 * @since 9.0.0
226
-	 */
227
-	public function get($id) {
228
-		if(intval($id) === 0) {
229
-			throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.');
230
-		}
231
-
232
-		if(isset($this->commentsCache[$id])) {
233
-			return $this->commentsCache[$id];
234
-		}
235
-
236
-		$qb = $this->dbConn->getQueryBuilder();
237
-		$resultStatement = $qb->select('*')
238
-			->from('comments')
239
-			->where($qb->expr()->eq('id', $qb->createParameter('id')))
240
-			->setParameter('id', $id, IQueryBuilder::PARAM_INT)
241
-			->execute();
242
-
243
-		$data = $resultStatement->fetch();
244
-		$resultStatement->closeCursor();
245
-		if(!$data) {
246
-			throw new NotFoundException();
247
-		}
248
-
249
-		$comment = new Comment($this->normalizeDatabaseData($data));
250
-		$this->cache($comment);
251
-		return $comment;
252
-	}
253
-
254
-	/**
255
-	 * returns the comment specified by the id and all it's child comments.
256
-	 * At this point of time, we do only support one level depth.
257
-	 *
258
-	 * @param string $id
259
-	 * @param int $limit max number of entries to return, 0 returns all
260
-	 * @param int $offset the start entry
261
-	 * @return array
262
-	 * @since 9.0.0
263
-	 *
264
-	 * The return array looks like this
265
-	 * [
266
-	 *   'comment' => IComment, // root comment
267
-	 *   'replies' =>
268
-	 *   [
269
-	 *     0 =>
270
-	 *     [
271
-	 *       'comment' => IComment,
272
-	 *       'replies' => []
273
-	 *     ]
274
-	 *     1 =>
275
-	 *     [
276
-	 *       'comment' => IComment,
277
-	 *       'replies'=> []
278
-	 *     ],
279
-	 *     …
280
-	 *   ]
281
-	 * ]
282
-	 */
283
-	public function getTree($id, $limit = 0, $offset = 0) {
284
-		$tree = [];
285
-		$tree['comment'] = $this->get($id);
286
-		$tree['replies'] = [];
287
-
288
-		$qb = $this->dbConn->getQueryBuilder();
289
-		$query = $qb->select('*')
290
-				->from('comments')
291
-				->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id')))
292
-				->orderBy('creation_timestamp', 'DESC')
293
-				->setParameter('id', $id);
294
-
295
-		if($limit > 0) {
296
-			$query->setMaxResults($limit);
297
-		}
298
-		if($offset > 0) {
299
-			$query->setFirstResult($offset);
300
-		}
301
-
302
-		$resultStatement = $query->execute();
303
-		while($data = $resultStatement->fetch()) {
304
-			$comment = new Comment($this->normalizeDatabaseData($data));
305
-			$this->cache($comment);
306
-			$tree['replies'][] = [
307
-				'comment' => $comment,
308
-				'replies' => []
309
-			];
310
-		}
311
-		$resultStatement->closeCursor();
312
-
313
-		return $tree;
314
-	}
315
-
316
-	/**
317
-	 * returns comments for a specific object (e.g. a file).
318
-	 *
319
-	 * The sort order is always newest to oldest.
320
-	 *
321
-	 * @param string $objectType the object type, e.g. 'files'
322
-	 * @param string $objectId the id of the object
323
-	 * @param int $limit optional, number of maximum comments to be returned. if
324
-	 * not specified, all comments are returned.
325
-	 * @param int $offset optional, starting point
326
-	 * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
327
-	 * that may be returned
328
-	 * @return IComment[]
329
-	 * @since 9.0.0
330
-	 */
331
-	public function getForObject(
332
-			$objectType,
333
-			$objectId,
334
-			$limit = 0,
335
-			$offset = 0,
336
-			\DateTime $notOlderThan = null
337
-	) {
338
-		$comments = [];
339
-
340
-		$qb = $this->dbConn->getQueryBuilder();
341
-		$query = $qb->select('*')
342
-				->from('comments')
343
-				->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
344
-				->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
345
-				->orderBy('creation_timestamp', 'DESC')
346
-				->setParameter('type', $objectType)
347
-				->setParameter('id', $objectId);
348
-
349
-		if($limit > 0) {
350
-			$query->setMaxResults($limit);
351
-		}
352
-		if($offset > 0) {
353
-			$query->setFirstResult($offset);
354
-		}
355
-		if(!is_null($notOlderThan)) {
356
-			$query
357
-				->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
358
-				->setParameter('notOlderThan', $notOlderThan, 'datetime');
359
-		}
360
-
361
-		$resultStatement = $query->execute();
362
-		while($data = $resultStatement->fetch()) {
363
-			$comment = new Comment($this->normalizeDatabaseData($data));
364
-			$this->cache($comment);
365
-			$comments[] = $comment;
366
-		}
367
-		$resultStatement->closeCursor();
368
-
369
-		return $comments;
370
-	}
371
-
372
-	/**
373
-	 * @param $objectType string the object type, e.g. 'files'
374
-	 * @param $objectId string the id of the object
375
-	 * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
376
-	 * that may be returned
377
-	 * @return Int
378
-	 * @since 9.0.0
379
-	 */
380
-	public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null) {
381
-		$qb = $this->dbConn->getQueryBuilder();
382
-		$query = $qb->select($qb->createFunction('COUNT(`id`)'))
383
-				->from('comments')
384
-				->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
385
-				->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
386
-				->setParameter('type', $objectType)
387
-				->setParameter('id', $objectId);
388
-
389
-		if(!is_null($notOlderThan)) {
390
-			$query
391
-				->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
392
-				->setParameter('notOlderThan', $notOlderThan, 'datetime');
393
-		}
394
-
395
-		$resultStatement = $query->execute();
396
-		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
397
-		$resultStatement->closeCursor();
398
-		return intval($data[0]);
399
-	}
400
-
401
-	/**
402
-	 * creates a new comment and returns it. At this point of time, it is not
403
-	 * saved in the used data storage. Use save() after setting other fields
404
-	 * of the comment (e.g. message or verb).
405
-	 *
406
-	 * @param string $actorType the actor type (e.g. 'users')
407
-	 * @param string $actorId a user id
408
-	 * @param string $objectType the object type the comment is attached to
409
-	 * @param string $objectId the object id the comment is attached to
410
-	 * @return IComment
411
-	 * @since 9.0.0
412
-	 */
413
-	public function create($actorType, $actorId, $objectType, $objectId) {
414
-		$comment = new Comment();
415
-		$comment
416
-			->setActor($actorType, $actorId)
417
-			->setObject($objectType, $objectId);
418
-		return $comment;
419
-	}
420
-
421
-	/**
422
-	 * permanently deletes the comment specified by the ID
423
-	 *
424
-	 * When the comment has child comments, their parent ID will be changed to
425
-	 * the parent ID of the item that is to be deleted.
426
-	 *
427
-	 * @param string $id
428
-	 * @return bool
429
-	 * @throws \InvalidArgumentException
430
-	 * @since 9.0.0
431
-	 */
432
-	public function delete($id) {
433
-		if(!is_string($id)) {
434
-			throw new \InvalidArgumentException('Parameter must be string');
435
-		}
436
-
437
-		try {
438
-			$comment = $this->get($id);
439
-		} catch (\Exception $e) {
440
-			// Ignore exceptions, we just don't fire a hook then
441
-			$comment = null;
442
-		}
443
-
444
-		$qb = $this->dbConn->getQueryBuilder();
445
-		$query = $qb->delete('comments')
446
-			->where($qb->expr()->eq('id', $qb->createParameter('id')))
447
-			->setParameter('id', $id);
448
-
449
-		try {
450
-			$affectedRows = $query->execute();
451
-			$this->uncache($id);
452
-		} catch (DriverException $e) {
453
-			$this->logger->logException($e, ['app' => 'core_comments']);
454
-			return false;
455
-		}
456
-
457
-		if ($affectedRows > 0 && $comment instanceof IComment) {
458
-			$this->dispatcher->dispatch(CommentsEvent::EVENT_DELETE, new CommentsEvent(
459
-				CommentsEvent::EVENT_DELETE,
460
-				$comment
461
-			));
462
-		}
463
-
464
-		return ($affectedRows > 0);
465
-	}
466
-
467
-	/**
468
-	 * saves the comment permanently
469
-	 *
470
-	 * if the supplied comment has an empty ID, a new entry comment will be
471
-	 * saved and the instance updated with the new ID.
472
-	 *
473
-	 * Otherwise, an existing comment will be updated.
474
-	 *
475
-	 * Throws NotFoundException when a comment that is to be updated does not
476
-	 * exist anymore at this point of time.
477
-	 *
478
-	 * @param IComment $comment
479
-	 * @return bool
480
-	 * @throws NotFoundException
481
-	 * @since 9.0.0
482
-	 */
483
-	public function save(IComment $comment) {
484
-		if($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
485
-			$result = $this->insert($comment);
486
-		} else {
487
-			$result = $this->update($comment);
488
-		}
489
-
490
-		if($result && !!$comment->getParentId()) {
491
-			$this->updateChildrenInformation(
492
-					$comment->getParentId(),
493
-					$comment->getCreationDateTime()
494
-			);
495
-			$this->cache($comment);
496
-		}
497
-
498
-		return $result;
499
-	}
500
-
501
-	/**
502
-	 * inserts the provided comment in the database
503
-	 *
504
-	 * @param IComment $comment
505
-	 * @return bool
506
-	 */
507
-	protected function insert(IComment &$comment) {
508
-		$qb = $this->dbConn->getQueryBuilder();
509
-		$affectedRows = $qb
510
-			->insert('comments')
511
-			->values([
512
-				'parent_id'					=> $qb->createNamedParameter($comment->getParentId()),
513
-				'topmost_parent_id' 		=> $qb->createNamedParameter($comment->getTopmostParentId()),
514
-				'children_count' 			=> $qb->createNamedParameter($comment->getChildrenCount()),
515
-				'actor_type' 				=> $qb->createNamedParameter($comment->getActorType()),
516
-				'actor_id' 					=> $qb->createNamedParameter($comment->getActorId()),
517
-				'message' 					=> $qb->createNamedParameter($comment->getMessage()),
518
-				'verb' 						=> $qb->createNamedParameter($comment->getVerb()),
519
-				'creation_timestamp' 		=> $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'),
520
-				'latest_child_timestamp'	=> $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'),
521
-				'object_type' 				=> $qb->createNamedParameter($comment->getObjectType()),
522
-				'object_id' 				=> $qb->createNamedParameter($comment->getObjectId()),
523
-			])
524
-			->execute();
525
-
526
-		if ($affectedRows > 0) {
527
-			$comment->setId(strval($qb->getLastInsertId()));
528
-		}
529
-
530
-		$this->dispatcher->dispatch(CommentsEvent::EVENT_ADD, new CommentsEvent(
531
-			CommentsEvent::EVENT_ADD,
532
-			$comment
533
-		));
534
-
535
-		return $affectedRows > 0;
536
-	}
537
-
538
-	/**
539
-	 * updates a Comment data row
540
-	 *
541
-	 * @param IComment $comment
542
-	 * @return bool
543
-	 * @throws NotFoundException
544
-	 */
545
-	protected function update(IComment $comment) {
546
-		$qb = $this->dbConn->getQueryBuilder();
547
-		$affectedRows = $qb
548
-			->update('comments')
549
-				->set('parent_id',				$qb->createNamedParameter($comment->getParentId()))
550
-				->set('topmost_parent_id', 		$qb->createNamedParameter($comment->getTopmostParentId()))
551
-				->set('children_count',			$qb->createNamedParameter($comment->getChildrenCount()))
552
-				->set('actor_type', 			$qb->createNamedParameter($comment->getActorType()))
553
-				->set('actor_id', 				$qb->createNamedParameter($comment->getActorId()))
554
-				->set('message',				$qb->createNamedParameter($comment->getMessage()))
555
-				->set('verb',					$qb->createNamedParameter($comment->getVerb()))
556
-				->set('creation_timestamp',		$qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
557
-				->set('latest_child_timestamp',	$qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
558
-				->set('object_type',			$qb->createNamedParameter($comment->getObjectType()))
559
-				->set('object_id',				$qb->createNamedParameter($comment->getObjectId()))
560
-			->where($qb->expr()->eq('id', $qb->createParameter('id')))
561
-			->setParameter('id', $comment->getId())
562
-			->execute();
563
-
564
-		if($affectedRows === 0) {
565
-			throw new NotFoundException('Comment to update does ceased to exist');
566
-		}
567
-
568
-		$this->dispatcher->dispatch(CommentsEvent::EVENT_UPDATE, new CommentsEvent(
569
-			CommentsEvent::EVENT_UPDATE,
570
-			$comment
571
-		));
572
-
573
-		return $affectedRows > 0;
574
-	}
575
-
576
-	/**
577
-	 * removes references to specific actor (e.g. on user delete) of a comment.
578
-	 * The comment itself must not get lost/deleted.
579
-	 *
580
-	 * @param string $actorType the actor type (e.g. 'users')
581
-	 * @param string $actorId a user id
582
-	 * @return boolean
583
-	 * @since 9.0.0
584
-	 */
585
-	public function deleteReferencesOfActor($actorType, $actorId) {
586
-		$this->checkRoleParameters('Actor', $actorType, $actorId);
587
-
588
-		$qb = $this->dbConn->getQueryBuilder();
589
-		$affectedRows = $qb
590
-			->update('comments')
591
-			->set('actor_type',	$qb->createNamedParameter(ICommentsManager::DELETED_USER))
592
-			->set('actor_id',	$qb->createNamedParameter(ICommentsManager::DELETED_USER))
593
-			->where($qb->expr()->eq('actor_type', $qb->createParameter('type')))
594
-			->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id')))
595
-			->setParameter('type', $actorType)
596
-			->setParameter('id', $actorId)
597
-			->execute();
598
-
599
-		$this->commentsCache = [];
600
-
601
-		return is_int($affectedRows);
602
-	}
603
-
604
-	/**
605
-	 * deletes all comments made of a specific object (e.g. on file delete)
606
-	 *
607
-	 * @param string $objectType the object type (e.g. 'files')
608
-	 * @param string $objectId e.g. the file id
609
-	 * @return boolean
610
-	 * @since 9.0.0
611
-	 */
612
-	public function deleteCommentsAtObject($objectType, $objectId) {
613
-		$this->checkRoleParameters('Object', $objectType, $objectId);
614
-
615
-		$qb = $this->dbConn->getQueryBuilder();
616
-		$affectedRows = $qb
617
-			->delete('comments')
618
-			->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
619
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
620
-			->setParameter('type', $objectType)
621
-			->setParameter('id', $objectId)
622
-			->execute();
623
-
624
-		$this->commentsCache = [];
625
-
626
-		return is_int($affectedRows);
627
-	}
628
-
629
-	/**
630
-	 * deletes the read markers for the specified user
631
-	 *
632
-	 * @param \OCP\IUser $user
633
-	 * @return bool
634
-	 * @since 9.0.0
635
-	 */
636
-	public function deleteReadMarksFromUser(IUser $user) {
637
-		$qb = $this->dbConn->getQueryBuilder();
638
-		$query = $qb->delete('comments_read_markers')
639
-			->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
640
-			->setParameter('user_id', $user->getUID());
641
-
642
-		try {
643
-			$affectedRows = $query->execute();
644
-		} catch (DriverException $e) {
645
-			$this->logger->logException($e, ['app' => 'core_comments']);
646
-			return false;
647
-		}
648
-		return ($affectedRows > 0);
649
-	}
650
-
651
-	/**
652
-	 * sets the read marker for a given file to the specified date for the
653
-	 * provided user
654
-	 *
655
-	 * @param string $objectType
656
-	 * @param string $objectId
657
-	 * @param \DateTime $dateTime
658
-	 * @param IUser $user
659
-	 * @since 9.0.0
660
-	 */
661
-	public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) {
662
-		$this->checkRoleParameters('Object', $objectType, $objectId);
663
-
664
-		$qb = $this->dbConn->getQueryBuilder();
665
-		$values = [
666
-			'user_id'         => $qb->createNamedParameter($user->getUID()),
667
-			'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'),
668
-			'object_type'     => $qb->createNamedParameter($objectType),
669
-			'object_id'       => $qb->createNamedParameter($objectId),
670
-		];
671
-
672
-		// Strategy: try to update, if this does not return affected rows, do an insert.
673
-		$affectedRows = $qb
674
-			->update('comments_read_markers')
675
-			->set('user_id',         $values['user_id'])
676
-			->set('marker_datetime', $values['marker_datetime'])
677
-			->set('object_type',     $values['object_type'])
678
-			->set('object_id',       $values['object_id'])
679
-			->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
680
-			->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
681
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
682
-			->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
683
-			->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
684
-			->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
685
-			->execute();
686
-
687
-		if ($affectedRows > 0) {
688
-			return;
689
-		}
690
-
691
-		$qb->insert('comments_read_markers')
692
-			->values($values)
693
-			->execute();
694
-	}
695
-
696
-	/**
697
-	 * returns the read marker for a given file to the specified date for the
698
-	 * provided user. It returns null, when the marker is not present, i.e.
699
-	 * no comments were marked as read.
700
-	 *
701
-	 * @param string $objectType
702
-	 * @param string $objectId
703
-	 * @param IUser $user
704
-	 * @return \DateTime|null
705
-	 * @since 9.0.0
706
-	 */
707
-	public function getReadMark($objectType, $objectId, IUser $user) {
708
-		$qb = $this->dbConn->getQueryBuilder();
709
-		$resultStatement = $qb->select('marker_datetime')
710
-			->from('comments_read_markers')
711
-			->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
712
-			->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
713
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
714
-			->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
715
-			->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
716
-			->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
717
-			->execute();
718
-
719
-		$data = $resultStatement->fetch();
720
-		$resultStatement->closeCursor();
721
-		if(!$data || is_null($data['marker_datetime'])) {
722
-			return null;
723
-		}
724
-
725
-		return new \DateTime($data['marker_datetime']);
726
-	}
727
-
728
-	/**
729
-	 * deletes the read markers on the specified object
730
-	 *
731
-	 * @param string $objectType
732
-	 * @param string $objectId
733
-	 * @return bool
734
-	 * @since 9.0.0
735
-	 */
736
-	public function deleteReadMarksOnObject($objectType, $objectId) {
737
-		$this->checkRoleParameters('Object', $objectType, $objectId);
738
-
739
-		$qb = $this->dbConn->getQueryBuilder();
740
-		$query = $qb->delete('comments_read_markers')
741
-			->where($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
742
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
743
-			->setParameter('object_type', $objectType)
744
-			->setParameter('object_id', $objectId);
745
-
746
-		try {
747
-			$affectedRows = $query->execute();
748
-		} catch (DriverException $e) {
749
-			$this->logger->logException($e, ['app' => 'core_comments']);
750
-			return false;
751
-		}
752
-		return ($affectedRows > 0);
753
-	}
40
+    /** @var  IDBConnection */
41
+    protected $dbConn;
42
+
43
+    /** @var  ILogger */
44
+    protected $logger;
45
+
46
+    /** @var IConfig */
47
+    protected $config;
48
+
49
+    /** @var EventDispatcherInterface */
50
+    protected $dispatcher;
51
+
52
+    /** @var IComment[]  */
53
+    protected $commentsCache = [];
54
+
55
+    /**
56
+     * Manager constructor.
57
+     *
58
+     * @param IDBConnection $dbConn
59
+     * @param ILogger $logger
60
+     * @param IConfig $config
61
+     * @param EventDispatcherInterface $dispatcher
62
+     */
63
+    public function __construct(
64
+        IDBConnection $dbConn,
65
+        ILogger $logger,
66
+        IConfig $config,
67
+        EventDispatcherInterface $dispatcher
68
+    ) {
69
+        $this->dbConn = $dbConn;
70
+        $this->logger = $logger;
71
+        $this->config = $config;
72
+        $this->dispatcher = $dispatcher;
73
+    }
74
+
75
+    /**
76
+     * converts data base data into PHP native, proper types as defined by
77
+     * IComment interface.
78
+     *
79
+     * @param array $data
80
+     * @return array
81
+     */
82
+    protected function normalizeDatabaseData(array $data) {
83
+        $data['id'] = strval($data['id']);
84
+        $data['parent_id'] = strval($data['parent_id']);
85
+        $data['topmost_parent_id'] = strval($data['topmost_parent_id']);
86
+        $data['creation_timestamp'] = new \DateTime($data['creation_timestamp']);
87
+        if (!is_null($data['latest_child_timestamp'])) {
88
+            $data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']);
89
+        }
90
+        $data['children_count'] = intval($data['children_count']);
91
+        return $data;
92
+    }
93
+
94
+    /**
95
+     * prepares a comment for an insert or update operation after making sure
96
+     * all necessary fields have a value assigned.
97
+     *
98
+     * @param IComment $comment
99
+     * @return IComment returns the same updated IComment instance as provided
100
+     *                  by parameter for convenience
101
+     * @throws \UnexpectedValueException
102
+     */
103
+    protected function prepareCommentForDatabaseWrite(IComment $comment) {
104
+        if(    !$comment->getActorType()
105
+            || !$comment->getActorId()
106
+            || !$comment->getObjectType()
107
+            || !$comment->getObjectId()
108
+            || !$comment->getVerb()
109
+        ) {
110
+            throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving');
111
+        }
112
+
113
+        if($comment->getId() === '') {
114
+            $comment->setChildrenCount(0);
115
+            $comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC')));
116
+            $comment->setLatestChildDateTime(null);
117
+        }
118
+
119
+        if(is_null($comment->getCreationDateTime())) {
120
+            $comment->setCreationDateTime(new \DateTime());
121
+        }
122
+
123
+        if($comment->getParentId() !== '0') {
124
+            $comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId()));
125
+        } else {
126
+            $comment->setTopmostParentId('0');
127
+        }
128
+
129
+        $this->cache($comment);
130
+
131
+        return $comment;
132
+    }
133
+
134
+    /**
135
+     * returns the topmost parent id of a given comment identified by ID
136
+     *
137
+     * @param string $id
138
+     * @return string
139
+     * @throws NotFoundException
140
+     */
141
+    protected function determineTopmostParentId($id) {
142
+        $comment = $this->get($id);
143
+        if($comment->getParentId() === '0') {
144
+            return $comment->getId();
145
+        } else {
146
+            return $this->determineTopmostParentId($comment->getId());
147
+        }
148
+    }
149
+
150
+    /**
151
+     * updates child information of a comment
152
+     *
153
+     * @param string	$id
154
+     * @param \DateTime	$cDateTime	the date time of the most recent child
155
+     * @throws NotFoundException
156
+     */
157
+    protected function updateChildrenInformation($id, \DateTime $cDateTime) {
158
+        $qb = $this->dbConn->getQueryBuilder();
159
+        $query = $qb->select($qb->createFunction('COUNT(`id`)'))
160
+                ->from('comments')
161
+                ->where($qb->expr()->eq('parent_id', $qb->createParameter('id')))
162
+                ->setParameter('id', $id);
163
+
164
+        $resultStatement = $query->execute();
165
+        $data = $resultStatement->fetch(\PDO::FETCH_NUM);
166
+        $resultStatement->closeCursor();
167
+        $children = intval($data[0]);
168
+
169
+        $comment = $this->get($id);
170
+        $comment->setChildrenCount($children);
171
+        $comment->setLatestChildDateTime($cDateTime);
172
+        $this->save($comment);
173
+    }
174
+
175
+    /**
176
+     * Tests whether actor or object type and id parameters are acceptable.
177
+     * Throws exception if not.
178
+     *
179
+     * @param string $role
180
+     * @param string $type
181
+     * @param string $id
182
+     * @throws \InvalidArgumentException
183
+     */
184
+    protected function checkRoleParameters($role, $type, $id) {
185
+        if(
186
+                !is_string($type) || empty($type)
187
+            || !is_string($id) || empty($id)
188
+        ) {
189
+            throw new \InvalidArgumentException($role . ' parameters must be string and not empty');
190
+        }
191
+    }
192
+
193
+    /**
194
+     * run-time caches a comment
195
+     *
196
+     * @param IComment $comment
197
+     */
198
+    protected function cache(IComment $comment) {
199
+        $id = $comment->getId();
200
+        if(empty($id)) {
201
+            return;
202
+        }
203
+        $this->commentsCache[strval($id)] = $comment;
204
+    }
205
+
206
+    /**
207
+     * removes an entry from the comments run time cache
208
+     *
209
+     * @param mixed $id the comment's id
210
+     */
211
+    protected function uncache($id) {
212
+        $id = strval($id);
213
+        if (isset($this->commentsCache[$id])) {
214
+            unset($this->commentsCache[$id]);
215
+        }
216
+    }
217
+
218
+    /**
219
+     * returns a comment instance
220
+     *
221
+     * @param string $id the ID of the comment
222
+     * @return IComment
223
+     * @throws NotFoundException
224
+     * @throws \InvalidArgumentException
225
+     * @since 9.0.0
226
+     */
227
+    public function get($id) {
228
+        if(intval($id) === 0) {
229
+            throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.');
230
+        }
231
+
232
+        if(isset($this->commentsCache[$id])) {
233
+            return $this->commentsCache[$id];
234
+        }
235
+
236
+        $qb = $this->dbConn->getQueryBuilder();
237
+        $resultStatement = $qb->select('*')
238
+            ->from('comments')
239
+            ->where($qb->expr()->eq('id', $qb->createParameter('id')))
240
+            ->setParameter('id', $id, IQueryBuilder::PARAM_INT)
241
+            ->execute();
242
+
243
+        $data = $resultStatement->fetch();
244
+        $resultStatement->closeCursor();
245
+        if(!$data) {
246
+            throw new NotFoundException();
247
+        }
248
+
249
+        $comment = new Comment($this->normalizeDatabaseData($data));
250
+        $this->cache($comment);
251
+        return $comment;
252
+    }
253
+
254
+    /**
255
+     * returns the comment specified by the id and all it's child comments.
256
+     * At this point of time, we do only support one level depth.
257
+     *
258
+     * @param string $id
259
+     * @param int $limit max number of entries to return, 0 returns all
260
+     * @param int $offset the start entry
261
+     * @return array
262
+     * @since 9.0.0
263
+     *
264
+     * The return array looks like this
265
+     * [
266
+     *   'comment' => IComment, // root comment
267
+     *   'replies' =>
268
+     *   [
269
+     *     0 =>
270
+     *     [
271
+     *       'comment' => IComment,
272
+     *       'replies' => []
273
+     *     ]
274
+     *     1 =>
275
+     *     [
276
+     *       'comment' => IComment,
277
+     *       'replies'=> []
278
+     *     ],
279
+     *     …
280
+     *   ]
281
+     * ]
282
+     */
283
+    public function getTree($id, $limit = 0, $offset = 0) {
284
+        $tree = [];
285
+        $tree['comment'] = $this->get($id);
286
+        $tree['replies'] = [];
287
+
288
+        $qb = $this->dbConn->getQueryBuilder();
289
+        $query = $qb->select('*')
290
+                ->from('comments')
291
+                ->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id')))
292
+                ->orderBy('creation_timestamp', 'DESC')
293
+                ->setParameter('id', $id);
294
+
295
+        if($limit > 0) {
296
+            $query->setMaxResults($limit);
297
+        }
298
+        if($offset > 0) {
299
+            $query->setFirstResult($offset);
300
+        }
301
+
302
+        $resultStatement = $query->execute();
303
+        while($data = $resultStatement->fetch()) {
304
+            $comment = new Comment($this->normalizeDatabaseData($data));
305
+            $this->cache($comment);
306
+            $tree['replies'][] = [
307
+                'comment' => $comment,
308
+                'replies' => []
309
+            ];
310
+        }
311
+        $resultStatement->closeCursor();
312
+
313
+        return $tree;
314
+    }
315
+
316
+    /**
317
+     * returns comments for a specific object (e.g. a file).
318
+     *
319
+     * The sort order is always newest to oldest.
320
+     *
321
+     * @param string $objectType the object type, e.g. 'files'
322
+     * @param string $objectId the id of the object
323
+     * @param int $limit optional, number of maximum comments to be returned. if
324
+     * not specified, all comments are returned.
325
+     * @param int $offset optional, starting point
326
+     * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
327
+     * that may be returned
328
+     * @return IComment[]
329
+     * @since 9.0.0
330
+     */
331
+    public function getForObject(
332
+            $objectType,
333
+            $objectId,
334
+            $limit = 0,
335
+            $offset = 0,
336
+            \DateTime $notOlderThan = null
337
+    ) {
338
+        $comments = [];
339
+
340
+        $qb = $this->dbConn->getQueryBuilder();
341
+        $query = $qb->select('*')
342
+                ->from('comments')
343
+                ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
344
+                ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
345
+                ->orderBy('creation_timestamp', 'DESC')
346
+                ->setParameter('type', $objectType)
347
+                ->setParameter('id', $objectId);
348
+
349
+        if($limit > 0) {
350
+            $query->setMaxResults($limit);
351
+        }
352
+        if($offset > 0) {
353
+            $query->setFirstResult($offset);
354
+        }
355
+        if(!is_null($notOlderThan)) {
356
+            $query
357
+                ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
358
+                ->setParameter('notOlderThan', $notOlderThan, 'datetime');
359
+        }
360
+
361
+        $resultStatement = $query->execute();
362
+        while($data = $resultStatement->fetch()) {
363
+            $comment = new Comment($this->normalizeDatabaseData($data));
364
+            $this->cache($comment);
365
+            $comments[] = $comment;
366
+        }
367
+        $resultStatement->closeCursor();
368
+
369
+        return $comments;
370
+    }
371
+
372
+    /**
373
+     * @param $objectType string the object type, e.g. 'files'
374
+     * @param $objectId string the id of the object
375
+     * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
376
+     * that may be returned
377
+     * @return Int
378
+     * @since 9.0.0
379
+     */
380
+    public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null) {
381
+        $qb = $this->dbConn->getQueryBuilder();
382
+        $query = $qb->select($qb->createFunction('COUNT(`id`)'))
383
+                ->from('comments')
384
+                ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
385
+                ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
386
+                ->setParameter('type', $objectType)
387
+                ->setParameter('id', $objectId);
388
+
389
+        if(!is_null($notOlderThan)) {
390
+            $query
391
+                ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
392
+                ->setParameter('notOlderThan', $notOlderThan, 'datetime');
393
+        }
394
+
395
+        $resultStatement = $query->execute();
396
+        $data = $resultStatement->fetch(\PDO::FETCH_NUM);
397
+        $resultStatement->closeCursor();
398
+        return intval($data[0]);
399
+    }
400
+
401
+    /**
402
+     * creates a new comment and returns it. At this point of time, it is not
403
+     * saved in the used data storage. Use save() after setting other fields
404
+     * of the comment (e.g. message or verb).
405
+     *
406
+     * @param string $actorType the actor type (e.g. 'users')
407
+     * @param string $actorId a user id
408
+     * @param string $objectType the object type the comment is attached to
409
+     * @param string $objectId the object id the comment is attached to
410
+     * @return IComment
411
+     * @since 9.0.0
412
+     */
413
+    public function create($actorType, $actorId, $objectType, $objectId) {
414
+        $comment = new Comment();
415
+        $comment
416
+            ->setActor($actorType, $actorId)
417
+            ->setObject($objectType, $objectId);
418
+        return $comment;
419
+    }
420
+
421
+    /**
422
+     * permanently deletes the comment specified by the ID
423
+     *
424
+     * When the comment has child comments, their parent ID will be changed to
425
+     * the parent ID of the item that is to be deleted.
426
+     *
427
+     * @param string $id
428
+     * @return bool
429
+     * @throws \InvalidArgumentException
430
+     * @since 9.0.0
431
+     */
432
+    public function delete($id) {
433
+        if(!is_string($id)) {
434
+            throw new \InvalidArgumentException('Parameter must be string');
435
+        }
436
+
437
+        try {
438
+            $comment = $this->get($id);
439
+        } catch (\Exception $e) {
440
+            // Ignore exceptions, we just don't fire a hook then
441
+            $comment = null;
442
+        }
443
+
444
+        $qb = $this->dbConn->getQueryBuilder();
445
+        $query = $qb->delete('comments')
446
+            ->where($qb->expr()->eq('id', $qb->createParameter('id')))
447
+            ->setParameter('id', $id);
448
+
449
+        try {
450
+            $affectedRows = $query->execute();
451
+            $this->uncache($id);
452
+        } catch (DriverException $e) {
453
+            $this->logger->logException($e, ['app' => 'core_comments']);
454
+            return false;
455
+        }
456
+
457
+        if ($affectedRows > 0 && $comment instanceof IComment) {
458
+            $this->dispatcher->dispatch(CommentsEvent::EVENT_DELETE, new CommentsEvent(
459
+                CommentsEvent::EVENT_DELETE,
460
+                $comment
461
+            ));
462
+        }
463
+
464
+        return ($affectedRows > 0);
465
+    }
466
+
467
+    /**
468
+     * saves the comment permanently
469
+     *
470
+     * if the supplied comment has an empty ID, a new entry comment will be
471
+     * saved and the instance updated with the new ID.
472
+     *
473
+     * Otherwise, an existing comment will be updated.
474
+     *
475
+     * Throws NotFoundException when a comment that is to be updated does not
476
+     * exist anymore at this point of time.
477
+     *
478
+     * @param IComment $comment
479
+     * @return bool
480
+     * @throws NotFoundException
481
+     * @since 9.0.0
482
+     */
483
+    public function save(IComment $comment) {
484
+        if($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
485
+            $result = $this->insert($comment);
486
+        } else {
487
+            $result = $this->update($comment);
488
+        }
489
+
490
+        if($result && !!$comment->getParentId()) {
491
+            $this->updateChildrenInformation(
492
+                    $comment->getParentId(),
493
+                    $comment->getCreationDateTime()
494
+            );
495
+            $this->cache($comment);
496
+        }
497
+
498
+        return $result;
499
+    }
500
+
501
+    /**
502
+     * inserts the provided comment in the database
503
+     *
504
+     * @param IComment $comment
505
+     * @return bool
506
+     */
507
+    protected function insert(IComment &$comment) {
508
+        $qb = $this->dbConn->getQueryBuilder();
509
+        $affectedRows = $qb
510
+            ->insert('comments')
511
+            ->values([
512
+                'parent_id'					=> $qb->createNamedParameter($comment->getParentId()),
513
+                'topmost_parent_id' 		=> $qb->createNamedParameter($comment->getTopmostParentId()),
514
+                'children_count' 			=> $qb->createNamedParameter($comment->getChildrenCount()),
515
+                'actor_type' 				=> $qb->createNamedParameter($comment->getActorType()),
516
+                'actor_id' 					=> $qb->createNamedParameter($comment->getActorId()),
517
+                'message' 					=> $qb->createNamedParameter($comment->getMessage()),
518
+                'verb' 						=> $qb->createNamedParameter($comment->getVerb()),
519
+                'creation_timestamp' 		=> $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'),
520
+                'latest_child_timestamp'	=> $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'),
521
+                'object_type' 				=> $qb->createNamedParameter($comment->getObjectType()),
522
+                'object_id' 				=> $qb->createNamedParameter($comment->getObjectId()),
523
+            ])
524
+            ->execute();
525
+
526
+        if ($affectedRows > 0) {
527
+            $comment->setId(strval($qb->getLastInsertId()));
528
+        }
529
+
530
+        $this->dispatcher->dispatch(CommentsEvent::EVENT_ADD, new CommentsEvent(
531
+            CommentsEvent::EVENT_ADD,
532
+            $comment
533
+        ));
534
+
535
+        return $affectedRows > 0;
536
+    }
537
+
538
+    /**
539
+     * updates a Comment data row
540
+     *
541
+     * @param IComment $comment
542
+     * @return bool
543
+     * @throws NotFoundException
544
+     */
545
+    protected function update(IComment $comment) {
546
+        $qb = $this->dbConn->getQueryBuilder();
547
+        $affectedRows = $qb
548
+            ->update('comments')
549
+                ->set('parent_id',				$qb->createNamedParameter($comment->getParentId()))
550
+                ->set('topmost_parent_id', 		$qb->createNamedParameter($comment->getTopmostParentId()))
551
+                ->set('children_count',			$qb->createNamedParameter($comment->getChildrenCount()))
552
+                ->set('actor_type', 			$qb->createNamedParameter($comment->getActorType()))
553
+                ->set('actor_id', 				$qb->createNamedParameter($comment->getActorId()))
554
+                ->set('message',				$qb->createNamedParameter($comment->getMessage()))
555
+                ->set('verb',					$qb->createNamedParameter($comment->getVerb()))
556
+                ->set('creation_timestamp',		$qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
557
+                ->set('latest_child_timestamp',	$qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
558
+                ->set('object_type',			$qb->createNamedParameter($comment->getObjectType()))
559
+                ->set('object_id',				$qb->createNamedParameter($comment->getObjectId()))
560
+            ->where($qb->expr()->eq('id', $qb->createParameter('id')))
561
+            ->setParameter('id', $comment->getId())
562
+            ->execute();
563
+
564
+        if($affectedRows === 0) {
565
+            throw new NotFoundException('Comment to update does ceased to exist');
566
+        }
567
+
568
+        $this->dispatcher->dispatch(CommentsEvent::EVENT_UPDATE, new CommentsEvent(
569
+            CommentsEvent::EVENT_UPDATE,
570
+            $comment
571
+        ));
572
+
573
+        return $affectedRows > 0;
574
+    }
575
+
576
+    /**
577
+     * removes references to specific actor (e.g. on user delete) of a comment.
578
+     * The comment itself must not get lost/deleted.
579
+     *
580
+     * @param string $actorType the actor type (e.g. 'users')
581
+     * @param string $actorId a user id
582
+     * @return boolean
583
+     * @since 9.0.0
584
+     */
585
+    public function deleteReferencesOfActor($actorType, $actorId) {
586
+        $this->checkRoleParameters('Actor', $actorType, $actorId);
587
+
588
+        $qb = $this->dbConn->getQueryBuilder();
589
+        $affectedRows = $qb
590
+            ->update('comments')
591
+            ->set('actor_type',	$qb->createNamedParameter(ICommentsManager::DELETED_USER))
592
+            ->set('actor_id',	$qb->createNamedParameter(ICommentsManager::DELETED_USER))
593
+            ->where($qb->expr()->eq('actor_type', $qb->createParameter('type')))
594
+            ->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id')))
595
+            ->setParameter('type', $actorType)
596
+            ->setParameter('id', $actorId)
597
+            ->execute();
598
+
599
+        $this->commentsCache = [];
600
+
601
+        return is_int($affectedRows);
602
+    }
603
+
604
+    /**
605
+     * deletes all comments made of a specific object (e.g. on file delete)
606
+     *
607
+     * @param string $objectType the object type (e.g. 'files')
608
+     * @param string $objectId e.g. the file id
609
+     * @return boolean
610
+     * @since 9.0.0
611
+     */
612
+    public function deleteCommentsAtObject($objectType, $objectId) {
613
+        $this->checkRoleParameters('Object', $objectType, $objectId);
614
+
615
+        $qb = $this->dbConn->getQueryBuilder();
616
+        $affectedRows = $qb
617
+            ->delete('comments')
618
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
619
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
620
+            ->setParameter('type', $objectType)
621
+            ->setParameter('id', $objectId)
622
+            ->execute();
623
+
624
+        $this->commentsCache = [];
625
+
626
+        return is_int($affectedRows);
627
+    }
628
+
629
+    /**
630
+     * deletes the read markers for the specified user
631
+     *
632
+     * @param \OCP\IUser $user
633
+     * @return bool
634
+     * @since 9.0.0
635
+     */
636
+    public function deleteReadMarksFromUser(IUser $user) {
637
+        $qb = $this->dbConn->getQueryBuilder();
638
+        $query = $qb->delete('comments_read_markers')
639
+            ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
640
+            ->setParameter('user_id', $user->getUID());
641
+
642
+        try {
643
+            $affectedRows = $query->execute();
644
+        } catch (DriverException $e) {
645
+            $this->logger->logException($e, ['app' => 'core_comments']);
646
+            return false;
647
+        }
648
+        return ($affectedRows > 0);
649
+    }
650
+
651
+    /**
652
+     * sets the read marker for a given file to the specified date for the
653
+     * provided user
654
+     *
655
+     * @param string $objectType
656
+     * @param string $objectId
657
+     * @param \DateTime $dateTime
658
+     * @param IUser $user
659
+     * @since 9.0.0
660
+     */
661
+    public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) {
662
+        $this->checkRoleParameters('Object', $objectType, $objectId);
663
+
664
+        $qb = $this->dbConn->getQueryBuilder();
665
+        $values = [
666
+            'user_id'         => $qb->createNamedParameter($user->getUID()),
667
+            'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'),
668
+            'object_type'     => $qb->createNamedParameter($objectType),
669
+            'object_id'       => $qb->createNamedParameter($objectId),
670
+        ];
671
+
672
+        // Strategy: try to update, if this does not return affected rows, do an insert.
673
+        $affectedRows = $qb
674
+            ->update('comments_read_markers')
675
+            ->set('user_id',         $values['user_id'])
676
+            ->set('marker_datetime', $values['marker_datetime'])
677
+            ->set('object_type',     $values['object_type'])
678
+            ->set('object_id',       $values['object_id'])
679
+            ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
680
+            ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
681
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
682
+            ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
683
+            ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
684
+            ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
685
+            ->execute();
686
+
687
+        if ($affectedRows > 0) {
688
+            return;
689
+        }
690
+
691
+        $qb->insert('comments_read_markers')
692
+            ->values($values)
693
+            ->execute();
694
+    }
695
+
696
+    /**
697
+     * returns the read marker for a given file to the specified date for the
698
+     * provided user. It returns null, when the marker is not present, i.e.
699
+     * no comments were marked as read.
700
+     *
701
+     * @param string $objectType
702
+     * @param string $objectId
703
+     * @param IUser $user
704
+     * @return \DateTime|null
705
+     * @since 9.0.0
706
+     */
707
+    public function getReadMark($objectType, $objectId, IUser $user) {
708
+        $qb = $this->dbConn->getQueryBuilder();
709
+        $resultStatement = $qb->select('marker_datetime')
710
+            ->from('comments_read_markers')
711
+            ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
712
+            ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
713
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
714
+            ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
715
+            ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
716
+            ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
717
+            ->execute();
718
+
719
+        $data = $resultStatement->fetch();
720
+        $resultStatement->closeCursor();
721
+        if(!$data || is_null($data['marker_datetime'])) {
722
+            return null;
723
+        }
724
+
725
+        return new \DateTime($data['marker_datetime']);
726
+    }
727
+
728
+    /**
729
+     * deletes the read markers on the specified object
730
+     *
731
+     * @param string $objectType
732
+     * @param string $objectId
733
+     * @return bool
734
+     * @since 9.0.0
735
+     */
736
+    public function deleteReadMarksOnObject($objectType, $objectId) {
737
+        $this->checkRoleParameters('Object', $objectType, $objectId);
738
+
739
+        $qb = $this->dbConn->getQueryBuilder();
740
+        $query = $qb->delete('comments_read_markers')
741
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
742
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
743
+            ->setParameter('object_type', $objectType)
744
+            ->setParameter('object_id', $objectId);
745
+
746
+        try {
747
+            $affectedRows = $query->execute();
748
+        } catch (DriverException $e) {
749
+            $this->logger->logException($e, ['app' => 'core_comments']);
750
+            return false;
751
+        }
752
+        return ($affectedRows > 0);
753
+    }
754 754
 }
Please login to merge, or discard this patch.
Spacing   +41 added lines, -41 removed lines patch added patch discarded remove patch
@@ -101,7 +101,7 @@  discard block
 block discarded – undo
101 101
 	 * @throws \UnexpectedValueException
102 102
 	 */
103 103
 	protected function prepareCommentForDatabaseWrite(IComment $comment) {
104
-		if(    !$comment->getActorType()
104
+		if (!$comment->getActorType()
105 105
 			|| !$comment->getActorId()
106 106
 			|| !$comment->getObjectType()
107 107
 			|| !$comment->getObjectId()
@@ -110,17 +110,17 @@  discard block
 block discarded – undo
110 110
 			throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving');
111 111
 		}
112 112
 
113
-		if($comment->getId() === '') {
113
+		if ($comment->getId() === '') {
114 114
 			$comment->setChildrenCount(0);
115 115
 			$comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC')));
116 116
 			$comment->setLatestChildDateTime(null);
117 117
 		}
118 118
 
119
-		if(is_null($comment->getCreationDateTime())) {
119
+		if (is_null($comment->getCreationDateTime())) {
120 120
 			$comment->setCreationDateTime(new \DateTime());
121 121
 		}
122 122
 
123
-		if($comment->getParentId() !== '0') {
123
+		if ($comment->getParentId() !== '0') {
124 124
 			$comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId()));
125 125
 		} else {
126 126
 			$comment->setTopmostParentId('0');
@@ -140,7 +140,7 @@  discard block
 block discarded – undo
140 140
 	 */
141 141
 	protected function determineTopmostParentId($id) {
142 142
 		$comment = $this->get($id);
143
-		if($comment->getParentId() === '0') {
143
+		if ($comment->getParentId() === '0') {
144 144
 			return $comment->getId();
145 145
 		} else {
146 146
 			return $this->determineTopmostParentId($comment->getId());
@@ -182,11 +182,11 @@  discard block
 block discarded – undo
182 182
 	 * @throws \InvalidArgumentException
183 183
 	 */
184 184
 	protected function checkRoleParameters($role, $type, $id) {
185
-		if(
185
+		if (
186 186
 			   !is_string($type) || empty($type)
187 187
 			|| !is_string($id) || empty($id)
188 188
 		) {
189
-			throw new \InvalidArgumentException($role . ' parameters must be string and not empty');
189
+			throw new \InvalidArgumentException($role.' parameters must be string and not empty');
190 190
 		}
191 191
 	}
192 192
 
@@ -197,7 +197,7 @@  discard block
 block discarded – undo
197 197
 	 */
198 198
 	protected function cache(IComment $comment) {
199 199
 		$id = $comment->getId();
200
-		if(empty($id)) {
200
+		if (empty($id)) {
201 201
 			return;
202 202
 		}
203 203
 		$this->commentsCache[strval($id)] = $comment;
@@ -225,11 +225,11 @@  discard block
 block discarded – undo
225 225
 	 * @since 9.0.0
226 226
 	 */
227 227
 	public function get($id) {
228
-		if(intval($id) === 0) {
228
+		if (intval($id) === 0) {
229 229
 			throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.');
230 230
 		}
231 231
 
232
-		if(isset($this->commentsCache[$id])) {
232
+		if (isset($this->commentsCache[$id])) {
233 233
 			return $this->commentsCache[$id];
234 234
 		}
235 235
 
@@ -242,7 +242,7 @@  discard block
 block discarded – undo
242 242
 
243 243
 		$data = $resultStatement->fetch();
244 244
 		$resultStatement->closeCursor();
245
-		if(!$data) {
245
+		if (!$data) {
246 246
 			throw new NotFoundException();
247 247
 		}
248 248
 
@@ -292,15 +292,15 @@  discard block
 block discarded – undo
292 292
 				->orderBy('creation_timestamp', 'DESC')
293 293
 				->setParameter('id', $id);
294 294
 
295
-		if($limit > 0) {
295
+		if ($limit > 0) {
296 296
 			$query->setMaxResults($limit);
297 297
 		}
298
-		if($offset > 0) {
298
+		if ($offset > 0) {
299 299
 			$query->setFirstResult($offset);
300 300
 		}
301 301
 
302 302
 		$resultStatement = $query->execute();
303
-		while($data = $resultStatement->fetch()) {
303
+		while ($data = $resultStatement->fetch()) {
304 304
 			$comment = new Comment($this->normalizeDatabaseData($data));
305 305
 			$this->cache($comment);
306 306
 			$tree['replies'][] = [
@@ -346,20 +346,20 @@  discard block
 block discarded – undo
346 346
 				->setParameter('type', $objectType)
347 347
 				->setParameter('id', $objectId);
348 348
 
349
-		if($limit > 0) {
349
+		if ($limit > 0) {
350 350
 			$query->setMaxResults($limit);
351 351
 		}
352
-		if($offset > 0) {
352
+		if ($offset > 0) {
353 353
 			$query->setFirstResult($offset);
354 354
 		}
355
-		if(!is_null($notOlderThan)) {
355
+		if (!is_null($notOlderThan)) {
356 356
 			$query
357 357
 				->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
358 358
 				->setParameter('notOlderThan', $notOlderThan, 'datetime');
359 359
 		}
360 360
 
361 361
 		$resultStatement = $query->execute();
362
-		while($data = $resultStatement->fetch()) {
362
+		while ($data = $resultStatement->fetch()) {
363 363
 			$comment = new Comment($this->normalizeDatabaseData($data));
364 364
 			$this->cache($comment);
365 365
 			$comments[] = $comment;
@@ -386,7 +386,7 @@  discard block
 block discarded – undo
386 386
 				->setParameter('type', $objectType)
387 387
 				->setParameter('id', $objectId);
388 388
 
389
-		if(!is_null($notOlderThan)) {
389
+		if (!is_null($notOlderThan)) {
390 390
 			$query
391 391
 				->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
392 392
 				->setParameter('notOlderThan', $notOlderThan, 'datetime');
@@ -430,7 +430,7 @@  discard block
 block discarded – undo
430 430
 	 * @since 9.0.0
431 431
 	 */
432 432
 	public function delete($id) {
433
-		if(!is_string($id)) {
433
+		if (!is_string($id)) {
434 434
 			throw new \InvalidArgumentException('Parameter must be string');
435 435
 		}
436 436
 
@@ -481,13 +481,13 @@  discard block
 block discarded – undo
481 481
 	 * @since 9.0.0
482 482
 	 */
483 483
 	public function save(IComment $comment) {
484
-		if($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
484
+		if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
485 485
 			$result = $this->insert($comment);
486 486
 		} else {
487 487
 			$result = $this->update($comment);
488 488
 		}
489 489
 
490
-		if($result && !!$comment->getParentId()) {
490
+		if ($result && !!$comment->getParentId()) {
491 491
 			$this->updateChildrenInformation(
492 492
 					$comment->getParentId(),
493 493
 					$comment->getCreationDateTime()
@@ -504,7 +504,7 @@  discard block
 block discarded – undo
504 504
 	 * @param IComment $comment
505 505
 	 * @return bool
506 506
 	 */
507
-	protected function insert(IComment &$comment) {
507
+	protected function insert(IComment & $comment) {
508 508
 		$qb = $this->dbConn->getQueryBuilder();
509 509
 		$affectedRows = $qb
510 510
 			->insert('comments')
@@ -546,22 +546,22 @@  discard block
 block discarded – undo
546 546
 		$qb = $this->dbConn->getQueryBuilder();
547 547
 		$affectedRows = $qb
548 548
 			->update('comments')
549
-				->set('parent_id',				$qb->createNamedParameter($comment->getParentId()))
550
-				->set('topmost_parent_id', 		$qb->createNamedParameter($comment->getTopmostParentId()))
551
-				->set('children_count',			$qb->createNamedParameter($comment->getChildrenCount()))
552
-				->set('actor_type', 			$qb->createNamedParameter($comment->getActorType()))
553
-				->set('actor_id', 				$qb->createNamedParameter($comment->getActorId()))
554
-				->set('message',				$qb->createNamedParameter($comment->getMessage()))
555
-				->set('verb',					$qb->createNamedParameter($comment->getVerb()))
556
-				->set('creation_timestamp',		$qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
557
-				->set('latest_child_timestamp',	$qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
558
-				->set('object_type',			$qb->createNamedParameter($comment->getObjectType()))
559
-				->set('object_id',				$qb->createNamedParameter($comment->getObjectId()))
549
+				->set('parent_id', $qb->createNamedParameter($comment->getParentId()))
550
+				->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId()))
551
+				->set('children_count', $qb->createNamedParameter($comment->getChildrenCount()))
552
+				->set('actor_type', $qb->createNamedParameter($comment->getActorType()))
553
+				->set('actor_id', $qb->createNamedParameter($comment->getActorId()))
554
+				->set('message', $qb->createNamedParameter($comment->getMessage()))
555
+				->set('verb', $qb->createNamedParameter($comment->getVerb()))
556
+				->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
557
+				->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
558
+				->set('object_type', $qb->createNamedParameter($comment->getObjectType()))
559
+				->set('object_id', $qb->createNamedParameter($comment->getObjectId()))
560 560
 			->where($qb->expr()->eq('id', $qb->createParameter('id')))
561 561
 			->setParameter('id', $comment->getId())
562 562
 			->execute();
563 563
 
564
-		if($affectedRows === 0) {
564
+		if ($affectedRows === 0) {
565 565
 			throw new NotFoundException('Comment to update does ceased to exist');
566 566
 		}
567 567
 
@@ -588,8 +588,8 @@  discard block
 block discarded – undo
588 588
 		$qb = $this->dbConn->getQueryBuilder();
589 589
 		$affectedRows = $qb
590 590
 			->update('comments')
591
-			->set('actor_type',	$qb->createNamedParameter(ICommentsManager::DELETED_USER))
592
-			->set('actor_id',	$qb->createNamedParameter(ICommentsManager::DELETED_USER))
591
+			->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
592
+			->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
593 593
 			->where($qb->expr()->eq('actor_type', $qb->createParameter('type')))
594 594
 			->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id')))
595 595
 			->setParameter('type', $actorType)
@@ -672,10 +672,10 @@  discard block
 block discarded – undo
672 672
 		// Strategy: try to update, if this does not return affected rows, do an insert.
673 673
 		$affectedRows = $qb
674 674
 			->update('comments_read_markers')
675
-			->set('user_id',         $values['user_id'])
675
+			->set('user_id', $values['user_id'])
676 676
 			->set('marker_datetime', $values['marker_datetime'])
677
-			->set('object_type',     $values['object_type'])
678
-			->set('object_id',       $values['object_id'])
677
+			->set('object_type', $values['object_type'])
678
+			->set('object_id', $values['object_id'])
679 679
 			->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
680 680
 			->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
681 681
 			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
@@ -718,7 +718,7 @@  discard block
 block discarded – undo
718 718
 
719 719
 		$data = $resultStatement->fetch();
720 720
 		$resultStatement->closeCursor();
721
-		if(!$data || is_null($data['marker_datetime'])) {
721
+		if (!$data || is_null($data['marker_datetime'])) {
722 722
 			return null;
723 723
 		}
724 724
 
Please login to merge, or discard this patch.
lib/private/DateTimeFormatter.php 3 patches
Doc Comments   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -93,7 +93,7 @@  discard block
 block discarded – undo
93 93
 	/**
94 94
 	 * Formats the date of the given timestamp
95 95
 	 *
96
-	 * @param int|\DateTime	$timestamp	Either a Unix timestamp or DateTime object
96
+	 * @param integer	$timestamp	Either a Unix timestamp or DateTime object
97 97
 	 * @param string	$format			Either 'full', 'long', 'medium' or 'short'
98 98
 	 * 				full:	e.g. 'EEEE, MMMM d, y'	=> 'Wednesday, August 20, 2014'
99 99
 	 * 				long:	e.g. 'MMMM d, y'		=> 'August 20, 2014'
@@ -192,7 +192,7 @@  discard block
 block discarded – undo
192 192
 	/**
193 193
 	 * Gives the relative past time of the timestamp
194 194
 	 *
195
-	 * @param int|\DateTime	$timestamp	Either a Unix timestamp or DateTime object
195
+	 * @param integer	$timestamp	Either a Unix timestamp or DateTime object
196 196
 	 * @param int|\DateTime	$baseTimestamp	Timestamp to compare $timestamp against, defaults to current time
197 197
 	 * @return string	Dates returned are:
198 198
 	 * 				< 60 sec	=> seconds ago
@@ -228,7 +228,7 @@  discard block
 block discarded – undo
228 228
 	/**
229 229
 	 * Formats the date and time of the given timestamp
230 230
 	 *
231
-	 * @param int|\DateTime $timestamp	Either a Unix timestamp or DateTime object
231
+	 * @param integer $timestamp	Either a Unix timestamp or DateTime object
232 232
 	 * @param string		$formatDate		See formatDate() for description
233 233
 	 * @param string		$formatTime		See formatTime() for description
234 234
 	 * @param \DateTimeZone	$timeZone	The timezone to use
Please login to merge, or discard this patch.
Indentation   +232 added lines, -232 removed lines patch added patch discarded remove patch
@@ -25,257 +25,257 @@
 block discarded – undo
25 25
 namespace OC;
26 26
 
27 27
 class DateTimeFormatter implements \OCP\IDateTimeFormatter {
28
-	/** @var \DateTimeZone */
29
-	protected $defaultTimeZone;
28
+    /** @var \DateTimeZone */
29
+    protected $defaultTimeZone;
30 30
 
31
-	/** @var \OCP\IL10N */
32
-	protected $defaultL10N;
31
+    /** @var \OCP\IL10N */
32
+    protected $defaultL10N;
33 33
 
34
-	/**
35
-	 * Constructor
36
-	 *
37
-	 * @param \DateTimeZone $defaultTimeZone Set the timezone for the format
38
-	 * @param \OCP\IL10N $defaultL10N Set the language for the format
39
-	 */
40
-	public function __construct(\DateTimeZone $defaultTimeZone, \OCP\IL10N $defaultL10N) {
41
-		$this->defaultTimeZone = $defaultTimeZone;
42
-		$this->defaultL10N = $defaultL10N;
43
-	}
34
+    /**
35
+     * Constructor
36
+     *
37
+     * @param \DateTimeZone $defaultTimeZone Set the timezone for the format
38
+     * @param \OCP\IL10N $defaultL10N Set the language for the format
39
+     */
40
+    public function __construct(\DateTimeZone $defaultTimeZone, \OCP\IL10N $defaultL10N) {
41
+        $this->defaultTimeZone = $defaultTimeZone;
42
+        $this->defaultL10N = $defaultL10N;
43
+    }
44 44
 
45
-	/**
46
-	 * Get TimeZone to use
47
-	 *
48
-	 * @param \DateTimeZone $timeZone	The timezone to use
49
-	 * @return \DateTimeZone		The timezone to use, falling back to the current user's timezone
50
-	 */
51
-	protected function getTimeZone($timeZone = null) {
52
-		if ($timeZone === null) {
53
-			$timeZone = $this->defaultTimeZone;
54
-		}
45
+    /**
46
+     * Get TimeZone to use
47
+     *
48
+     * @param \DateTimeZone $timeZone	The timezone to use
49
+     * @return \DateTimeZone		The timezone to use, falling back to the current user's timezone
50
+     */
51
+    protected function getTimeZone($timeZone = null) {
52
+        if ($timeZone === null) {
53
+            $timeZone = $this->defaultTimeZone;
54
+        }
55 55
 
56
-		return $timeZone;
57
-	}
56
+        return $timeZone;
57
+    }
58 58
 
59
-	/**
60
-	 * Get \OCP\IL10N to use
61
-	 *
62
-	 * @param \OCP\IL10N $l	The locale to use
63
-	 * @return \OCP\IL10N		The locale to use, falling back to the current user's locale
64
-	 */
65
-	protected function getLocale($l = null) {
66
-		if ($l === null) {
67
-			$l = $this->defaultL10N;
68
-		}
59
+    /**
60
+     * Get \OCP\IL10N to use
61
+     *
62
+     * @param \OCP\IL10N $l	The locale to use
63
+     * @return \OCP\IL10N		The locale to use, falling back to the current user's locale
64
+     */
65
+    protected function getLocale($l = null) {
66
+        if ($l === null) {
67
+            $l = $this->defaultL10N;
68
+        }
69 69
 
70
-		return $l;
71
-	}
70
+        return $l;
71
+    }
72 72
 
73
-	/**
74
-	 * Generates a DateTime object with the given timestamp and TimeZone
75
-	 *
76
-	 * @param mixed $timestamp
77
-	 * @param \DateTimeZone $timeZone	The timezone to use
78
-	 * @return \DateTime
79
-	 */
80
-	protected function getDateTime($timestamp, \DateTimeZone $timeZone = null) {
81
-		if ($timestamp === null) {
82
-			return new \DateTime('now', $timeZone);
83
-		} else if (!$timestamp instanceof \DateTime) {
84
-			$dateTime = new \DateTime('now', $timeZone);
85
-			$dateTime->setTimestamp($timestamp);
86
-			return $dateTime;
87
-		}
88
-		if ($timeZone) {
89
-			$timestamp->setTimezone($timeZone);
90
-		}
91
-		return $timestamp;
92
-	}
73
+    /**
74
+     * Generates a DateTime object with the given timestamp and TimeZone
75
+     *
76
+     * @param mixed $timestamp
77
+     * @param \DateTimeZone $timeZone	The timezone to use
78
+     * @return \DateTime
79
+     */
80
+    protected function getDateTime($timestamp, \DateTimeZone $timeZone = null) {
81
+        if ($timestamp === null) {
82
+            return new \DateTime('now', $timeZone);
83
+        } else if (!$timestamp instanceof \DateTime) {
84
+            $dateTime = new \DateTime('now', $timeZone);
85
+            $dateTime->setTimestamp($timestamp);
86
+            return $dateTime;
87
+        }
88
+        if ($timeZone) {
89
+            $timestamp->setTimezone($timeZone);
90
+        }
91
+        return $timestamp;
92
+    }
93 93
 
94
-	/**
95
-	 * Formats the date of the given timestamp
96
-	 *
97
-	 * @param int|\DateTime	$timestamp	Either a Unix timestamp or DateTime object
98
-	 * @param string	$format			Either 'full', 'long', 'medium' or 'short'
99
-	 * 				full:	e.g. 'EEEE, MMMM d, y'	=> 'Wednesday, August 20, 2014'
100
-	 * 				long:	e.g. 'MMMM d, y'		=> 'August 20, 2014'
101
-	 * 				medium:	e.g. 'MMM d, y'			=> 'Aug 20, 2014'
102
-	 * 				short:	e.g. 'M/d/yy'			=> '8/20/14'
103
-	 * 				The exact format is dependent on the language
104
-	 * @param \DateTimeZone	$timeZone	The timezone to use
105
-	 * @param \OCP\IL10N	$l			The locale to use
106
-	 * @return string Formatted date string
107
-	 */
108
-	public function formatDate($timestamp, $format = 'long', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) {
109
-		return $this->format($timestamp, 'date', $format, $timeZone, $l);
110
-	}
94
+    /**
95
+     * Formats the date of the given timestamp
96
+     *
97
+     * @param int|\DateTime	$timestamp	Either a Unix timestamp or DateTime object
98
+     * @param string	$format			Either 'full', 'long', 'medium' or 'short'
99
+     * 				full:	e.g. 'EEEE, MMMM d, y'	=> 'Wednesday, August 20, 2014'
100
+     * 				long:	e.g. 'MMMM d, y'		=> 'August 20, 2014'
101
+     * 				medium:	e.g. 'MMM d, y'			=> 'Aug 20, 2014'
102
+     * 				short:	e.g. 'M/d/yy'			=> '8/20/14'
103
+     * 				The exact format is dependent on the language
104
+     * @param \DateTimeZone	$timeZone	The timezone to use
105
+     * @param \OCP\IL10N	$l			The locale to use
106
+     * @return string Formatted date string
107
+     */
108
+    public function formatDate($timestamp, $format = 'long', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) {
109
+        return $this->format($timestamp, 'date', $format, $timeZone, $l);
110
+    }
111 111
 
112
-	/**
113
-	 * Formats the date of the given timestamp
114
-	 *
115
-	 * @param int|\DateTime	$timestamp	Either a Unix timestamp or DateTime object
116
-	 * @param string	$format			Either 'full', 'long', 'medium' or 'short'
117
-	 * 				full:	e.g. 'EEEE, MMMM d, y'	=> 'Wednesday, August 20, 2014'
118
-	 * 				long:	e.g. 'MMMM d, y'		=> 'August 20, 2014'
119
-	 * 				medium:	e.g. 'MMM d, y'			=> 'Aug 20, 2014'
120
-	 * 				short:	e.g. 'M/d/yy'			=> '8/20/14'
121
-	 * 				The exact format is dependent on the language
122
-	 * 					Uses 'Today', 'Yesterday' and 'Tomorrow' when applicable
123
-	 * @param \DateTimeZone	$timeZone	The timezone to use
124
-	 * @param \OCP\IL10N	$l			The locale to use
125
-	 * @return string Formatted relative date string
126
-	 */
127
-	public function formatDateRelativeDay($timestamp, $format = 'long', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) {
128
-		if (substr($format, -1) !== '*' && substr($format, -1) !== '*') {
129
-			$format .= '^';
130
-		}
112
+    /**
113
+     * Formats the date of the given timestamp
114
+     *
115
+     * @param int|\DateTime	$timestamp	Either a Unix timestamp or DateTime object
116
+     * @param string	$format			Either 'full', 'long', 'medium' or 'short'
117
+     * 				full:	e.g. 'EEEE, MMMM d, y'	=> 'Wednesday, August 20, 2014'
118
+     * 				long:	e.g. 'MMMM d, y'		=> 'August 20, 2014'
119
+     * 				medium:	e.g. 'MMM d, y'			=> 'Aug 20, 2014'
120
+     * 				short:	e.g. 'M/d/yy'			=> '8/20/14'
121
+     * 				The exact format is dependent on the language
122
+     * 					Uses 'Today', 'Yesterday' and 'Tomorrow' when applicable
123
+     * @param \DateTimeZone	$timeZone	The timezone to use
124
+     * @param \OCP\IL10N	$l			The locale to use
125
+     * @return string Formatted relative date string
126
+     */
127
+    public function formatDateRelativeDay($timestamp, $format = 'long', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) {
128
+        if (substr($format, -1) !== '*' && substr($format, -1) !== '*') {
129
+            $format .= '^';
130
+        }
131 131
 
132
-		return $this->format($timestamp, 'date', $format, $timeZone, $l);
133
-	}
132
+        return $this->format($timestamp, 'date', $format, $timeZone, $l);
133
+    }
134 134
 
135
-	/**
136
-	 * Gives the relative date of the timestamp
137
-	 * Only works for past dates
138
-	 *
139
-	 * @param int|\DateTime	$timestamp	Either a Unix timestamp or DateTime object
140
-	 * @param int|\DateTime	$baseTimestamp	Timestamp to compare $timestamp against, defaults to current time
141
-	 * @return string	Dates returned are:
142
-	 * 				<  1 month	=> Today, Yesterday, n days ago
143
-	 * 				< 13 month	=> last month, n months ago
144
-	 * 				>= 13 month	=> last year, n years ago
145
-	 * @param \OCP\IL10N	$l			The locale to use
146
-	 * @return string Formatted date span
147
-	 */
148
-	public function formatDateSpan($timestamp, $baseTimestamp = null, \OCP\IL10N $l = null) {
149
-		$l = $this->getLocale($l);
150
-		$timestamp = $this->getDateTime($timestamp);
151
-		$timestamp->setTime(0, 0, 0);
152
-		if ($baseTimestamp === null) {
153
-			$baseTimestamp = time();
154
-		}
155
-		$baseTimestamp = $this->getDateTime($baseTimestamp);
156
-		$baseTimestamp->setTime(0, 0, 0);
157
-		$dateInterval = $timestamp->diff($baseTimestamp);
135
+    /**
136
+     * Gives the relative date of the timestamp
137
+     * Only works for past dates
138
+     *
139
+     * @param int|\DateTime	$timestamp	Either a Unix timestamp or DateTime object
140
+     * @param int|\DateTime	$baseTimestamp	Timestamp to compare $timestamp against, defaults to current time
141
+     * @return string	Dates returned are:
142
+     * 				<  1 month	=> Today, Yesterday, n days ago
143
+     * 				< 13 month	=> last month, n months ago
144
+     * 				>= 13 month	=> last year, n years ago
145
+     * @param \OCP\IL10N	$l			The locale to use
146
+     * @return string Formatted date span
147
+     */
148
+    public function formatDateSpan($timestamp, $baseTimestamp = null, \OCP\IL10N $l = null) {
149
+        $l = $this->getLocale($l);
150
+        $timestamp = $this->getDateTime($timestamp);
151
+        $timestamp->setTime(0, 0, 0);
152
+        if ($baseTimestamp === null) {
153
+            $baseTimestamp = time();
154
+        }
155
+        $baseTimestamp = $this->getDateTime($baseTimestamp);
156
+        $baseTimestamp->setTime(0, 0, 0);
157
+        $dateInterval = $timestamp->diff($baseTimestamp);
158 158
 
159
-		if ($dateInterval->y == 0 && $dateInterval->m == 0 && $dateInterval->d == 0) {
160
-			return (string) $l->t('today');
161
-		} else if ($dateInterval->y == 0 && $dateInterval->m == 0 && $dateInterval->d == 1) {
162
-			return (string) $l->t('yesterday');
163
-		} else if ($dateInterval->y == 0 && $dateInterval->m == 0) {
164
-			return (string) $l->n('%n day ago', '%n days ago', $dateInterval->d);
165
-		} else if ($dateInterval->y == 0 && $dateInterval->m == 1) {
166
-			return (string) $l->t('last month');
167
-		} else if ($dateInterval->y == 0) {
168
-			return (string) $l->n('%n month ago', '%n months ago', $dateInterval->m);
169
-		} else if ($dateInterval->y == 1) {
170
-			return (string) $l->t('last year');
171
-		}
172
-		return (string) $l->n('%n year ago', '%n years ago', $dateInterval->y);
173
-	}
159
+        if ($dateInterval->y == 0 && $dateInterval->m == 0 && $dateInterval->d == 0) {
160
+            return (string) $l->t('today');
161
+        } else if ($dateInterval->y == 0 && $dateInterval->m == 0 && $dateInterval->d == 1) {
162
+            return (string) $l->t('yesterday');
163
+        } else if ($dateInterval->y == 0 && $dateInterval->m == 0) {
164
+            return (string) $l->n('%n day ago', '%n days ago', $dateInterval->d);
165
+        } else if ($dateInterval->y == 0 && $dateInterval->m == 1) {
166
+            return (string) $l->t('last month');
167
+        } else if ($dateInterval->y == 0) {
168
+            return (string) $l->n('%n month ago', '%n months ago', $dateInterval->m);
169
+        } else if ($dateInterval->y == 1) {
170
+            return (string) $l->t('last year');
171
+        }
172
+        return (string) $l->n('%n year ago', '%n years ago', $dateInterval->y);
173
+    }
174 174
 
175
-	/**
176
-	 * Formats the time of the given timestamp
177
-	 *
178
-	 * @param int|\DateTime	$timestamp	Either a Unix timestamp or DateTime object
179
-	 * @param string	$format			Either 'full', 'long', 'medium' or 'short'
180
-	 * 				full:	e.g. 'h:mm:ss a zzzz'	=> '11:42:13 AM GMT+0:00'
181
-	 * 				long:	e.g. 'h:mm:ss a z'		=> '11:42:13 AM GMT'
182
-	 * 				medium:	e.g. 'h:mm:ss a'		=> '11:42:13 AM'
183
-	 * 				short:	e.g. 'h:mm a'			=> '11:42 AM'
184
-	 * 				The exact format is dependent on the language
185
-	 * @param \DateTimeZone	$timeZone	The timezone to use
186
-	 * @param \OCP\IL10N	$l			The locale to use
187
-	 * @return string Formatted time string
188
-	 */
189
-	public function formatTime($timestamp, $format = 'medium', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) {
190
-		return $this->format($timestamp, 'time', $format, $timeZone, $l);
191
-	}
175
+    /**
176
+     * Formats the time of the given timestamp
177
+     *
178
+     * @param int|\DateTime	$timestamp	Either a Unix timestamp or DateTime object
179
+     * @param string	$format			Either 'full', 'long', 'medium' or 'short'
180
+     * 				full:	e.g. 'h:mm:ss a zzzz'	=> '11:42:13 AM GMT+0:00'
181
+     * 				long:	e.g. 'h:mm:ss a z'		=> '11:42:13 AM GMT'
182
+     * 				medium:	e.g. 'h:mm:ss a'		=> '11:42:13 AM'
183
+     * 				short:	e.g. 'h:mm a'			=> '11:42 AM'
184
+     * 				The exact format is dependent on the language
185
+     * @param \DateTimeZone	$timeZone	The timezone to use
186
+     * @param \OCP\IL10N	$l			The locale to use
187
+     * @return string Formatted time string
188
+     */
189
+    public function formatTime($timestamp, $format = 'medium', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) {
190
+        return $this->format($timestamp, 'time', $format, $timeZone, $l);
191
+    }
192 192
 
193
-	/**
194
-	 * Gives the relative past time of the timestamp
195
-	 *
196
-	 * @param int|\DateTime	$timestamp	Either a Unix timestamp or DateTime object
197
-	 * @param int|\DateTime	$baseTimestamp	Timestamp to compare $timestamp against, defaults to current time
198
-	 * @return string	Dates returned are:
199
-	 * 				< 60 sec	=> seconds ago
200
-	 * 				<  1 hour	=> n minutes ago
201
-	 * 				<  1 day	=> n hours ago
202
-	 * 				<  1 month	=> Yesterday, n days ago
203
-	 * 				< 13 month	=> last month, n months ago
204
-	 * 				>= 13 month	=> last year, n years ago
205
-	 * @param \OCP\IL10N	$l			The locale to use
206
-	 * @return string Formatted time span
207
-	 */
208
-	public function formatTimeSpan($timestamp, $baseTimestamp = null, \OCP\IL10N $l = null) {
209
-		$l = $this->getLocale($l);
210
-		$timestamp = $this->getDateTime($timestamp);
211
-		if ($baseTimestamp === null) {
212
-			$baseTimestamp = time();
213
-		}
214
-		$baseTimestamp = $this->getDateTime($baseTimestamp);
193
+    /**
194
+     * Gives the relative past time of the timestamp
195
+     *
196
+     * @param int|\DateTime	$timestamp	Either a Unix timestamp or DateTime object
197
+     * @param int|\DateTime	$baseTimestamp	Timestamp to compare $timestamp against, defaults to current time
198
+     * @return string	Dates returned are:
199
+     * 				< 60 sec	=> seconds ago
200
+     * 				<  1 hour	=> n minutes ago
201
+     * 				<  1 day	=> n hours ago
202
+     * 				<  1 month	=> Yesterday, n days ago
203
+     * 				< 13 month	=> last month, n months ago
204
+     * 				>= 13 month	=> last year, n years ago
205
+     * @param \OCP\IL10N	$l			The locale to use
206
+     * @return string Formatted time span
207
+     */
208
+    public function formatTimeSpan($timestamp, $baseTimestamp = null, \OCP\IL10N $l = null) {
209
+        $l = $this->getLocale($l);
210
+        $timestamp = $this->getDateTime($timestamp);
211
+        if ($baseTimestamp === null) {
212
+            $baseTimestamp = time();
213
+        }
214
+        $baseTimestamp = $this->getDateTime($baseTimestamp);
215 215
 
216
-		$diff = $timestamp->diff($baseTimestamp);
217
-		if ($diff->y > 0 || $diff->m > 0 || $diff->d > 0) {
218
-			return (string) $this->formatDateSpan($timestamp, $baseTimestamp, $l);
219
-		}
216
+        $diff = $timestamp->diff($baseTimestamp);
217
+        if ($diff->y > 0 || $diff->m > 0 || $diff->d > 0) {
218
+            return (string) $this->formatDateSpan($timestamp, $baseTimestamp, $l);
219
+        }
220 220
 
221
-		if ($diff->h > 0) {
222
-			return (string) $l->n('%n hour ago', '%n hours ago', $diff->h);
223
-		} else if ($diff->i > 0) {
224
-			return (string) $l->n('%n minute ago', '%n minutes ago', $diff->i);
225
-		}
226
-		return (string) $l->t('seconds ago');
227
-	}
221
+        if ($diff->h > 0) {
222
+            return (string) $l->n('%n hour ago', '%n hours ago', $diff->h);
223
+        } else if ($diff->i > 0) {
224
+            return (string) $l->n('%n minute ago', '%n minutes ago', $diff->i);
225
+        }
226
+        return (string) $l->t('seconds ago');
227
+    }
228 228
 
229
-	/**
230
-	 * Formats the date and time of the given timestamp
231
-	 *
232
-	 * @param int|\DateTime $timestamp	Either a Unix timestamp or DateTime object
233
-	 * @param string		$formatDate		See formatDate() for description
234
-	 * @param string		$formatTime		See formatTime() for description
235
-	 * @param \DateTimeZone	$timeZone	The timezone to use
236
-	 * @param \OCP\IL10N	$l			The locale to use
237
-	 * @return string Formatted date and time string
238
-	 */
239
-	public function formatDateTime($timestamp, $formatDate = 'long', $formatTime = 'medium', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) {
240
-		return $this->format($timestamp, 'datetime', $formatDate . '|' . $formatTime, $timeZone, $l);
241
-	}
229
+    /**
230
+     * Formats the date and time of the given timestamp
231
+     *
232
+     * @param int|\DateTime $timestamp	Either a Unix timestamp or DateTime object
233
+     * @param string		$formatDate		See formatDate() for description
234
+     * @param string		$formatTime		See formatTime() for description
235
+     * @param \DateTimeZone	$timeZone	The timezone to use
236
+     * @param \OCP\IL10N	$l			The locale to use
237
+     * @return string Formatted date and time string
238
+     */
239
+    public function formatDateTime($timestamp, $formatDate = 'long', $formatTime = 'medium', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) {
240
+        return $this->format($timestamp, 'datetime', $formatDate . '|' . $formatTime, $timeZone, $l);
241
+    }
242 242
 
243
-	/**
244
-	 * Formats the date and time of the given timestamp
245
-	 *
246
-	 * @param int|\DateTime $timestamp	Either a Unix timestamp or DateTime object
247
-	 * @param string	$formatDate		See formatDate() for description
248
-	 * 					Uses 'Today', 'Yesterday' and 'Tomorrow' when applicable
249
-	 * @param string	$formatTime		See formatTime() for description
250
-	 * @param \DateTimeZone	$timeZone	The timezone to use
251
-	 * @param \OCP\IL10N	$l			The locale to use
252
-	 * @return string Formatted relative date and time string
253
-	 */
254
-	public function formatDateTimeRelativeDay($timestamp, $formatDate = 'long', $formatTime = 'medium', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) {
255
-		if (substr($formatDate, -1) !== '^' && substr($formatDate, -1) !== '*') {
256
-			$formatDate .= '^';
257
-		}
243
+    /**
244
+     * Formats the date and time of the given timestamp
245
+     *
246
+     * @param int|\DateTime $timestamp	Either a Unix timestamp or DateTime object
247
+     * @param string	$formatDate		See formatDate() for description
248
+     * 					Uses 'Today', 'Yesterday' and 'Tomorrow' when applicable
249
+     * @param string	$formatTime		See formatTime() for description
250
+     * @param \DateTimeZone	$timeZone	The timezone to use
251
+     * @param \OCP\IL10N	$l			The locale to use
252
+     * @return string Formatted relative date and time string
253
+     */
254
+    public function formatDateTimeRelativeDay($timestamp, $formatDate = 'long', $formatTime = 'medium', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) {
255
+        if (substr($formatDate, -1) !== '^' && substr($formatDate, -1) !== '*') {
256
+            $formatDate .= '^';
257
+        }
258 258
 
259
-		return $this->format($timestamp, 'datetime', $formatDate . '|' . $formatTime, $timeZone, $l);
260
-	}
259
+        return $this->format($timestamp, 'datetime', $formatDate . '|' . $formatTime, $timeZone, $l);
260
+    }
261 261
 
262
-	/**
263
-	 * Formats the date and time of the given timestamp
264
-	 *
265
-	 * @param int|\DateTime $timestamp	Either a Unix timestamp or DateTime object
266
-	 * @param string		$type		One of 'date', 'datetime' or 'time'
267
-	 * @param string		$format		Format string
268
-	 * @param \DateTimeZone	$timeZone	The timezone to use
269
-	 * @param \OCP\IL10N	$l			The locale to use
270
-	 * @return string Formatted date and time string
271
-	 */
272
-	protected function format($timestamp, $type, $format, \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) {
273
-		$l = $this->getLocale($l);
274
-		$timeZone = $this->getTimeZone($timeZone);
275
-		$timestamp = $this->getDateTime($timestamp, $timeZone);
262
+    /**
263
+     * Formats the date and time of the given timestamp
264
+     *
265
+     * @param int|\DateTime $timestamp	Either a Unix timestamp or DateTime object
266
+     * @param string		$type		One of 'date', 'datetime' or 'time'
267
+     * @param string		$format		Format string
268
+     * @param \DateTimeZone	$timeZone	The timezone to use
269
+     * @param \OCP\IL10N	$l			The locale to use
270
+     * @return string Formatted date and time string
271
+     */
272
+    protected function format($timestamp, $type, $format, \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) {
273
+        $l = $this->getLocale($l);
274
+        $timeZone = $this->getTimeZone($timeZone);
275
+        $timestamp = $this->getDateTime($timestamp, $timeZone);
276 276
 
277
-		return (string) $l->l($type, $timestamp, array(
278
-			'width' => $format,
279
-		));
280
-	}
277
+        return (string) $l->l($type, $timestamp, array(
278
+            'width' => $format,
279
+        ));
280
+    }
281 281
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -237,7 +237,7 @@  discard block
 block discarded – undo
237 237
 	 * @return string Formatted date and time string
238 238
 	 */
239 239
 	public function formatDateTime($timestamp, $formatDate = 'long', $formatTime = 'medium', \DateTimeZone $timeZone = null, \OCP\IL10N $l = null) {
240
-		return $this->format($timestamp, 'datetime', $formatDate . '|' . $formatTime, $timeZone, $l);
240
+		return $this->format($timestamp, 'datetime', $formatDate.'|'.$formatTime, $timeZone, $l);
241 241
 	}
242 242
 
243 243
 	/**
@@ -256,7 +256,7 @@  discard block
 block discarded – undo
256 256
 			$formatDate .= '^';
257 257
 		}
258 258
 
259
-		return $this->format($timestamp, 'datetime', $formatDate . '|' . $formatTime, $timeZone, $l);
259
+		return $this->format($timestamp, 'datetime', $formatDate.'|'.$formatTime, $timeZone, $l);
260 260
 	}
261 261
 
262 262
 	/**
Please login to merge, or discard this patch.
lib/private/DB/Connection.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
 	 * If an SQLLogger is configured, the execution is logged.
174 174
 	 *
175 175
 	 * @param string                                      $query  The SQL query to execute.
176
-	 * @param array                                       $params The parameters to bind to the query, if any.
176
+	 * @param string[]                                       $params The parameters to bind to the query, if any.
177 177
 	 * @param array                                       $types  The types the previous parameters are in.
178 178
 	 * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp    The query cache profile, optional.
179 179
 	 *
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
 	 * columns or sequences.
219 219
 	 *
220 220
 	 * @param string $seqName Name of the sequence object from which the ID should be returned.
221
-	 * @return string A string representation of the last inserted ID.
221
+	 * @return integer A string representation of the last inserted ID.
222 222
 	 */
223 223
 	public function lastInsertId($seqName = null) {
224 224
 		if ($seqName) {
Please login to merge, or discard this patch.
Indentation   +363 added lines, -363 removed lines patch added patch discarded remove patch
@@ -39,367 +39,367 @@
 block discarded – undo
39 39
 use OCP\PreConditionNotMetException;
40 40
 
41 41
 class Connection extends \Doctrine\DBAL\Connection implements IDBConnection {
42
-	/**
43
-	 * @var string $tablePrefix
44
-	 */
45
-	protected $tablePrefix;
46
-
47
-	/**
48
-	 * @var \OC\DB\Adapter $adapter
49
-	 */
50
-	protected $adapter;
51
-
52
-	protected $lockedTable = null;
53
-
54
-	public function connect() {
55
-		try {
56
-			return parent::connect();
57
-		} catch (DBALException $e) {
58
-			// throw a new exception to prevent leaking info from the stacktrace
59
-			throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
60
-		}
61
-	}
62
-
63
-	/**
64
-	 * Returns a QueryBuilder for the connection.
65
-	 *
66
-	 * @return \OCP\DB\QueryBuilder\IQueryBuilder
67
-	 */
68
-	public function getQueryBuilder() {
69
-		return new QueryBuilder($this);
70
-	}
71
-
72
-	/**
73
-	 * Gets the QueryBuilder for the connection.
74
-	 *
75
-	 * @return \Doctrine\DBAL\Query\QueryBuilder
76
-	 * @deprecated please use $this->getQueryBuilder() instead
77
-	 */
78
-	public function createQueryBuilder() {
79
-		$backtrace = $this->getCallerBacktrace();
80
-		\OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
81
-		return parent::createQueryBuilder();
82
-	}
83
-
84
-	/**
85
-	 * Gets the ExpressionBuilder for the connection.
86
-	 *
87
-	 * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
88
-	 * @deprecated please use $this->getQueryBuilder()->expr() instead
89
-	 */
90
-	public function getExpressionBuilder() {
91
-		$backtrace = $this->getCallerBacktrace();
92
-		\OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
93
-		return parent::getExpressionBuilder();
94
-	}
95
-
96
-	/**
97
-	 * Get the file and line that called the method where `getCallerBacktrace()` was used
98
-	 *
99
-	 * @return string
100
-	 */
101
-	protected function getCallerBacktrace() {
102
-		$traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
103
-
104
-		// 0 is the method where we use `getCallerBacktrace`
105
-		// 1 is the target method which uses the method we want to log
106
-		if (isset($traces[1])) {
107
-			return $traces[1]['file'] . ':' . $traces[1]['line'];
108
-		}
109
-
110
-		return '';
111
-	}
112
-
113
-	/**
114
-	 * @return string
115
-	 */
116
-	public function getPrefix() {
117
-		return $this->tablePrefix;
118
-	}
119
-
120
-	/**
121
-	 * Initializes a new instance of the Connection class.
122
-	 *
123
-	 * @param array $params  The connection parameters.
124
-	 * @param \Doctrine\DBAL\Driver $driver
125
-	 * @param \Doctrine\DBAL\Configuration $config
126
-	 * @param \Doctrine\Common\EventManager $eventManager
127
-	 * @throws \Exception
128
-	 */
129
-	public function __construct(array $params, Driver $driver, Configuration $config = null,
130
-		EventManager $eventManager = null)
131
-	{
132
-		if (!isset($params['adapter'])) {
133
-			throw new \Exception('adapter not set');
134
-		}
135
-		if (!isset($params['tablePrefix'])) {
136
-			throw new \Exception('tablePrefix not set');
137
-		}
138
-		parent::__construct($params, $driver, $config, $eventManager);
139
-		$this->adapter = new $params['adapter']($this);
140
-		$this->tablePrefix = $params['tablePrefix'];
141
-
142
-		parent::setTransactionIsolation(parent::TRANSACTION_READ_COMMITTED);
143
-	}
144
-
145
-	/**
146
-	 * Prepares an SQL statement.
147
-	 *
148
-	 * @param string $statement The SQL statement to prepare.
149
-	 * @param int $limit
150
-	 * @param int $offset
151
-	 * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
152
-	 */
153
-	public function prepare( $statement, $limit=null, $offset=null ) {
154
-		if ($limit === -1) {
155
-			$limit = null;
156
-		}
157
-		if (!is_null($limit)) {
158
-			$platform = $this->getDatabasePlatform();
159
-			$statement = $platform->modifyLimitQuery($statement, $limit, $offset);
160
-		}
161
-		$statement = $this->replaceTablePrefix($statement);
162
-		$statement = $this->adapter->fixupStatement($statement);
163
-
164
-		if(\OC::$server->getSystemConfig()->getValue( 'log_query', false)) {
165
-			\OCP\Util::writeLog('core', 'DB prepare : '.$statement, \OCP\Util::DEBUG);
166
-		}
167
-		return parent::prepare($statement);
168
-	}
169
-
170
-	/**
171
-	 * Executes an, optionally parametrized, SQL query.
172
-	 *
173
-	 * If the query is parametrized, a prepared statement is used.
174
-	 * If an SQLLogger is configured, the execution is logged.
175
-	 *
176
-	 * @param string                                      $query  The SQL query to execute.
177
-	 * @param array                                       $params The parameters to bind to the query, if any.
178
-	 * @param array                                       $types  The types the previous parameters are in.
179
-	 * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp    The query cache profile, optional.
180
-	 *
181
-	 * @return \Doctrine\DBAL\Driver\Statement The executed statement.
182
-	 *
183
-	 * @throws \Doctrine\DBAL\DBALException
184
-	 */
185
-	public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null)
186
-	{
187
-		$query = $this->replaceTablePrefix($query);
188
-		$query = $this->adapter->fixupStatement($query);
189
-		return parent::executeQuery($query, $params, $types, $qcp);
190
-	}
191
-
192
-	/**
193
-	 * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
194
-	 * and returns the number of affected rows.
195
-	 *
196
-	 * This method supports PDO binding types as well as DBAL mapping types.
197
-	 *
198
-	 * @param string $query  The SQL query.
199
-	 * @param array  $params The query parameters.
200
-	 * @param array  $types  The parameter types.
201
-	 *
202
-	 * @return integer The number of affected rows.
203
-	 *
204
-	 * @throws \Doctrine\DBAL\DBALException
205
-	 */
206
-	public function executeUpdate($query, array $params = array(), array $types = array())
207
-	{
208
-		$query = $this->replaceTablePrefix($query);
209
-		$query = $this->adapter->fixupStatement($query);
210
-		return parent::executeUpdate($query, $params, $types);
211
-	}
212
-
213
-	/**
214
-	 * Returns the ID of the last inserted row, or the last value from a sequence object,
215
-	 * depending on the underlying driver.
216
-	 *
217
-	 * Note: This method may not return a meaningful or consistent result across different drivers,
218
-	 * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
219
-	 * columns or sequences.
220
-	 *
221
-	 * @param string $seqName Name of the sequence object from which the ID should be returned.
222
-	 * @return string A string representation of the last inserted ID.
223
-	 */
224
-	public function lastInsertId($seqName = null) {
225
-		if ($seqName) {
226
-			$seqName = $this->replaceTablePrefix($seqName);
227
-		}
228
-		return $this->adapter->lastInsertId($seqName);
229
-	}
230
-
231
-	// internal use
232
-	public function realLastInsertId($seqName = null) {
233
-		return parent::lastInsertId($seqName);
234
-	}
235
-
236
-	/**
237
-	 * Insert a row if the matching row does not exists.
238
-	 *
239
-	 * @param string $table The table name (will replace *PREFIX* with the actual prefix)
240
-	 * @param array $input data that should be inserted into the table  (column name => value)
241
-	 * @param array|null $compare List of values that should be checked for "if not exists"
242
-	 *				If this is null or an empty array, all keys of $input will be compared
243
-	 *				Please note: text fields (clob) must not be used in the compare array
244
-	 * @return int number of inserted rows
245
-	 * @throws \Doctrine\DBAL\DBALException
246
-	 */
247
-	public function insertIfNotExist($table, $input, array $compare = null) {
248
-		return $this->adapter->insertIfNotExist($table, $input, $compare);
249
-	}
250
-
251
-	private function getType($value) {
252
-		if (is_bool($value)) {
253
-			return IQueryBuilder::PARAM_BOOL;
254
-		} else if (is_int($value)) {
255
-			return IQueryBuilder::PARAM_INT;
256
-		} else {
257
-			return IQueryBuilder::PARAM_STR;
258
-		}
259
-	}
260
-
261
-	/**
262
-	 * Insert or update a row value
263
-	 *
264
-	 * @param string $table
265
-	 * @param array $keys (column name => value)
266
-	 * @param array $values (column name => value)
267
-	 * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
268
-	 * @return int number of new rows
269
-	 * @throws \Doctrine\DBAL\DBALException
270
-	 * @throws PreConditionNotMetException
271
-	 */
272
-	public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) {
273
-		try {
274
-			$insertQb = $this->getQueryBuilder();
275
-			$insertQb->insert($table)
276
-				->values(
277
-					array_map(function($value) use ($insertQb) {
278
-						return $insertQb->createNamedParameter($value, $this->getType($value));
279
-					}, array_merge($keys, $values))
280
-				);
281
-			return $insertQb->execute();
282
-		} catch (\Doctrine\DBAL\Exception\ConstraintViolationException $e) {
283
-			// value already exists, try update
284
-			$updateQb = $this->getQueryBuilder();
285
-			$updateQb->update($table);
286
-			foreach ($values as $name => $value) {
287
-				$updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
288
-			}
289
-			$where = $updateQb->expr()->andX();
290
-			$whereValues = array_merge($keys, $updatePreconditionValues);
291
-			foreach ($whereValues as $name => $value) {
292
-				$where->add($updateQb->expr()->eq(
293
-					$name,
294
-					$updateQb->createNamedParameter($value, $this->getType($value)),
295
-					$this->getType($value)
296
-				));
297
-			}
298
-			$updateQb->where($where);
299
-			$affected = $updateQb->execute();
300
-
301
-			if ($affected === 0 && !empty($updatePreconditionValues)) {
302
-				throw new PreConditionNotMetException();
303
-			}
304
-
305
-			return 0;
306
-		}
307
-	}
308
-
309
-	/**
310
-	 * Create an exclusive read+write lock on a table
311
-	 *
312
-	 * @param string $tableName
313
-	 * @throws \BadMethodCallException When trying to acquire a second lock
314
-	 * @since 9.1.0
315
-	 */
316
-	public function lockTable($tableName) {
317
-		if ($this->lockedTable !== null) {
318
-			throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
319
-		}
320
-
321
-		$tableName = $this->tablePrefix . $tableName;
322
-		$this->lockedTable = $tableName;
323
-		$this->adapter->lockTable($tableName);
324
-	}
325
-
326
-	/**
327
-	 * Release a previous acquired lock again
328
-	 *
329
-	 * @since 9.1.0
330
-	 */
331
-	public function unlockTable() {
332
-		$this->adapter->unlockTable();
333
-		$this->lockedTable = null;
334
-	}
335
-
336
-	/**
337
-	 * returns the error code and message as a string for logging
338
-	 * works with DoctrineException
339
-	 * @return string
340
-	 */
341
-	public function getError() {
342
-		$msg = $this->errorCode() . ': ';
343
-		$errorInfo = $this->errorInfo();
344
-		if (is_array($errorInfo)) {
345
-			$msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
346
-			$msg .= 'Driver Code = '.$errorInfo[1] . ', ';
347
-			$msg .= 'Driver Message = '.$errorInfo[2];
348
-		}
349
-		return $msg;
350
-	}
351
-
352
-	/**
353
-	 * Drop a table from the database if it exists
354
-	 *
355
-	 * @param string $table table name without the prefix
356
-	 */
357
-	public function dropTable($table) {
358
-		$table = $this->tablePrefix . trim($table);
359
-		$schema = $this->getSchemaManager();
360
-		if($schema->tablesExist(array($table))) {
361
-			$schema->dropTable($table);
362
-		}
363
-	}
364
-
365
-	/**
366
-	 * Check if a table exists
367
-	 *
368
-	 * @param string $table table name without the prefix
369
-	 * @return bool
370
-	 */
371
-	public function tableExists($table){
372
-		$table = $this->tablePrefix . trim($table);
373
-		$schema = $this->getSchemaManager();
374
-		return $schema->tablesExist(array($table));
375
-	}
376
-
377
-	// internal use
378
-	/**
379
-	 * @param string $statement
380
-	 * @return string
381
-	 */
382
-	protected function replaceTablePrefix($statement) {
383
-		return str_replace( '*PREFIX*', $this->tablePrefix, $statement );
384
-	}
385
-
386
-	/**
387
-	 * Check if a transaction is active
388
-	 *
389
-	 * @return bool
390
-	 * @since 8.2.0
391
-	 */
392
-	public function inTransaction() {
393
-		return $this->getTransactionNestingLevel() > 0;
394
-	}
395
-
396
-	/**
397
-	 * Espace a parameter to be used in a LIKE query
398
-	 *
399
-	 * @param string $param
400
-	 * @return string
401
-	 */
402
-	public function escapeLikeParameter($param) {
403
-		return addcslashes($param, '\\_%');
404
-	}
42
+    /**
43
+     * @var string $tablePrefix
44
+     */
45
+    protected $tablePrefix;
46
+
47
+    /**
48
+     * @var \OC\DB\Adapter $adapter
49
+     */
50
+    protected $adapter;
51
+
52
+    protected $lockedTable = null;
53
+
54
+    public function connect() {
55
+        try {
56
+            return parent::connect();
57
+        } catch (DBALException $e) {
58
+            // throw a new exception to prevent leaking info from the stacktrace
59
+            throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
60
+        }
61
+    }
62
+
63
+    /**
64
+     * Returns a QueryBuilder for the connection.
65
+     *
66
+     * @return \OCP\DB\QueryBuilder\IQueryBuilder
67
+     */
68
+    public function getQueryBuilder() {
69
+        return new QueryBuilder($this);
70
+    }
71
+
72
+    /**
73
+     * Gets the QueryBuilder for the connection.
74
+     *
75
+     * @return \Doctrine\DBAL\Query\QueryBuilder
76
+     * @deprecated please use $this->getQueryBuilder() instead
77
+     */
78
+    public function createQueryBuilder() {
79
+        $backtrace = $this->getCallerBacktrace();
80
+        \OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
81
+        return parent::createQueryBuilder();
82
+    }
83
+
84
+    /**
85
+     * Gets the ExpressionBuilder for the connection.
86
+     *
87
+     * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
88
+     * @deprecated please use $this->getQueryBuilder()->expr() instead
89
+     */
90
+    public function getExpressionBuilder() {
91
+        $backtrace = $this->getCallerBacktrace();
92
+        \OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
93
+        return parent::getExpressionBuilder();
94
+    }
95
+
96
+    /**
97
+     * Get the file and line that called the method where `getCallerBacktrace()` was used
98
+     *
99
+     * @return string
100
+     */
101
+    protected function getCallerBacktrace() {
102
+        $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
103
+
104
+        // 0 is the method where we use `getCallerBacktrace`
105
+        // 1 is the target method which uses the method we want to log
106
+        if (isset($traces[1])) {
107
+            return $traces[1]['file'] . ':' . $traces[1]['line'];
108
+        }
109
+
110
+        return '';
111
+    }
112
+
113
+    /**
114
+     * @return string
115
+     */
116
+    public function getPrefix() {
117
+        return $this->tablePrefix;
118
+    }
119
+
120
+    /**
121
+     * Initializes a new instance of the Connection class.
122
+     *
123
+     * @param array $params  The connection parameters.
124
+     * @param \Doctrine\DBAL\Driver $driver
125
+     * @param \Doctrine\DBAL\Configuration $config
126
+     * @param \Doctrine\Common\EventManager $eventManager
127
+     * @throws \Exception
128
+     */
129
+    public function __construct(array $params, Driver $driver, Configuration $config = null,
130
+        EventManager $eventManager = null)
131
+    {
132
+        if (!isset($params['adapter'])) {
133
+            throw new \Exception('adapter not set');
134
+        }
135
+        if (!isset($params['tablePrefix'])) {
136
+            throw new \Exception('tablePrefix not set');
137
+        }
138
+        parent::__construct($params, $driver, $config, $eventManager);
139
+        $this->adapter = new $params['adapter']($this);
140
+        $this->tablePrefix = $params['tablePrefix'];
141
+
142
+        parent::setTransactionIsolation(parent::TRANSACTION_READ_COMMITTED);
143
+    }
144
+
145
+    /**
146
+     * Prepares an SQL statement.
147
+     *
148
+     * @param string $statement The SQL statement to prepare.
149
+     * @param int $limit
150
+     * @param int $offset
151
+     * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
152
+     */
153
+    public function prepare( $statement, $limit=null, $offset=null ) {
154
+        if ($limit === -1) {
155
+            $limit = null;
156
+        }
157
+        if (!is_null($limit)) {
158
+            $platform = $this->getDatabasePlatform();
159
+            $statement = $platform->modifyLimitQuery($statement, $limit, $offset);
160
+        }
161
+        $statement = $this->replaceTablePrefix($statement);
162
+        $statement = $this->adapter->fixupStatement($statement);
163
+
164
+        if(\OC::$server->getSystemConfig()->getValue( 'log_query', false)) {
165
+            \OCP\Util::writeLog('core', 'DB prepare : '.$statement, \OCP\Util::DEBUG);
166
+        }
167
+        return parent::prepare($statement);
168
+    }
169
+
170
+    /**
171
+     * Executes an, optionally parametrized, SQL query.
172
+     *
173
+     * If the query is parametrized, a prepared statement is used.
174
+     * If an SQLLogger is configured, the execution is logged.
175
+     *
176
+     * @param string                                      $query  The SQL query to execute.
177
+     * @param array                                       $params The parameters to bind to the query, if any.
178
+     * @param array                                       $types  The types the previous parameters are in.
179
+     * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp    The query cache profile, optional.
180
+     *
181
+     * @return \Doctrine\DBAL\Driver\Statement The executed statement.
182
+     *
183
+     * @throws \Doctrine\DBAL\DBALException
184
+     */
185
+    public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null)
186
+    {
187
+        $query = $this->replaceTablePrefix($query);
188
+        $query = $this->adapter->fixupStatement($query);
189
+        return parent::executeQuery($query, $params, $types, $qcp);
190
+    }
191
+
192
+    /**
193
+     * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
194
+     * and returns the number of affected rows.
195
+     *
196
+     * This method supports PDO binding types as well as DBAL mapping types.
197
+     *
198
+     * @param string $query  The SQL query.
199
+     * @param array  $params The query parameters.
200
+     * @param array  $types  The parameter types.
201
+     *
202
+     * @return integer The number of affected rows.
203
+     *
204
+     * @throws \Doctrine\DBAL\DBALException
205
+     */
206
+    public function executeUpdate($query, array $params = array(), array $types = array())
207
+    {
208
+        $query = $this->replaceTablePrefix($query);
209
+        $query = $this->adapter->fixupStatement($query);
210
+        return parent::executeUpdate($query, $params, $types);
211
+    }
212
+
213
+    /**
214
+     * Returns the ID of the last inserted row, or the last value from a sequence object,
215
+     * depending on the underlying driver.
216
+     *
217
+     * Note: This method may not return a meaningful or consistent result across different drivers,
218
+     * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
219
+     * columns or sequences.
220
+     *
221
+     * @param string $seqName Name of the sequence object from which the ID should be returned.
222
+     * @return string A string representation of the last inserted ID.
223
+     */
224
+    public function lastInsertId($seqName = null) {
225
+        if ($seqName) {
226
+            $seqName = $this->replaceTablePrefix($seqName);
227
+        }
228
+        return $this->adapter->lastInsertId($seqName);
229
+    }
230
+
231
+    // internal use
232
+    public function realLastInsertId($seqName = null) {
233
+        return parent::lastInsertId($seqName);
234
+    }
235
+
236
+    /**
237
+     * Insert a row if the matching row does not exists.
238
+     *
239
+     * @param string $table The table name (will replace *PREFIX* with the actual prefix)
240
+     * @param array $input data that should be inserted into the table  (column name => value)
241
+     * @param array|null $compare List of values that should be checked for "if not exists"
242
+     *				If this is null or an empty array, all keys of $input will be compared
243
+     *				Please note: text fields (clob) must not be used in the compare array
244
+     * @return int number of inserted rows
245
+     * @throws \Doctrine\DBAL\DBALException
246
+     */
247
+    public function insertIfNotExist($table, $input, array $compare = null) {
248
+        return $this->adapter->insertIfNotExist($table, $input, $compare);
249
+    }
250
+
251
+    private function getType($value) {
252
+        if (is_bool($value)) {
253
+            return IQueryBuilder::PARAM_BOOL;
254
+        } else if (is_int($value)) {
255
+            return IQueryBuilder::PARAM_INT;
256
+        } else {
257
+            return IQueryBuilder::PARAM_STR;
258
+        }
259
+    }
260
+
261
+    /**
262
+     * Insert or update a row value
263
+     *
264
+     * @param string $table
265
+     * @param array $keys (column name => value)
266
+     * @param array $values (column name => value)
267
+     * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
268
+     * @return int number of new rows
269
+     * @throws \Doctrine\DBAL\DBALException
270
+     * @throws PreConditionNotMetException
271
+     */
272
+    public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) {
273
+        try {
274
+            $insertQb = $this->getQueryBuilder();
275
+            $insertQb->insert($table)
276
+                ->values(
277
+                    array_map(function($value) use ($insertQb) {
278
+                        return $insertQb->createNamedParameter($value, $this->getType($value));
279
+                    }, array_merge($keys, $values))
280
+                );
281
+            return $insertQb->execute();
282
+        } catch (\Doctrine\DBAL\Exception\ConstraintViolationException $e) {
283
+            // value already exists, try update
284
+            $updateQb = $this->getQueryBuilder();
285
+            $updateQb->update($table);
286
+            foreach ($values as $name => $value) {
287
+                $updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
288
+            }
289
+            $where = $updateQb->expr()->andX();
290
+            $whereValues = array_merge($keys, $updatePreconditionValues);
291
+            foreach ($whereValues as $name => $value) {
292
+                $where->add($updateQb->expr()->eq(
293
+                    $name,
294
+                    $updateQb->createNamedParameter($value, $this->getType($value)),
295
+                    $this->getType($value)
296
+                ));
297
+            }
298
+            $updateQb->where($where);
299
+            $affected = $updateQb->execute();
300
+
301
+            if ($affected === 0 && !empty($updatePreconditionValues)) {
302
+                throw new PreConditionNotMetException();
303
+            }
304
+
305
+            return 0;
306
+        }
307
+    }
308
+
309
+    /**
310
+     * Create an exclusive read+write lock on a table
311
+     *
312
+     * @param string $tableName
313
+     * @throws \BadMethodCallException When trying to acquire a second lock
314
+     * @since 9.1.0
315
+     */
316
+    public function lockTable($tableName) {
317
+        if ($this->lockedTable !== null) {
318
+            throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
319
+        }
320
+
321
+        $tableName = $this->tablePrefix . $tableName;
322
+        $this->lockedTable = $tableName;
323
+        $this->adapter->lockTable($tableName);
324
+    }
325
+
326
+    /**
327
+     * Release a previous acquired lock again
328
+     *
329
+     * @since 9.1.0
330
+     */
331
+    public function unlockTable() {
332
+        $this->adapter->unlockTable();
333
+        $this->lockedTable = null;
334
+    }
335
+
336
+    /**
337
+     * returns the error code and message as a string for logging
338
+     * works with DoctrineException
339
+     * @return string
340
+     */
341
+    public function getError() {
342
+        $msg = $this->errorCode() . ': ';
343
+        $errorInfo = $this->errorInfo();
344
+        if (is_array($errorInfo)) {
345
+            $msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
346
+            $msg .= 'Driver Code = '.$errorInfo[1] . ', ';
347
+            $msg .= 'Driver Message = '.$errorInfo[2];
348
+        }
349
+        return $msg;
350
+    }
351
+
352
+    /**
353
+     * Drop a table from the database if it exists
354
+     *
355
+     * @param string $table table name without the prefix
356
+     */
357
+    public function dropTable($table) {
358
+        $table = $this->tablePrefix . trim($table);
359
+        $schema = $this->getSchemaManager();
360
+        if($schema->tablesExist(array($table))) {
361
+            $schema->dropTable($table);
362
+        }
363
+    }
364
+
365
+    /**
366
+     * Check if a table exists
367
+     *
368
+     * @param string $table table name without the prefix
369
+     * @return bool
370
+     */
371
+    public function tableExists($table){
372
+        $table = $this->tablePrefix . trim($table);
373
+        $schema = $this->getSchemaManager();
374
+        return $schema->tablesExist(array($table));
375
+    }
376
+
377
+    // internal use
378
+    /**
379
+     * @param string $statement
380
+     * @return string
381
+     */
382
+    protected function replaceTablePrefix($statement) {
383
+        return str_replace( '*PREFIX*', $this->tablePrefix, $statement );
384
+    }
385
+
386
+    /**
387
+     * Check if a transaction is active
388
+     *
389
+     * @return bool
390
+     * @since 8.2.0
391
+     */
392
+    public function inTransaction() {
393
+        return $this->getTransactionNestingLevel() > 0;
394
+    }
395
+
396
+    /**
397
+     * Espace a parameter to be used in a LIKE query
398
+     *
399
+     * @param string $param
400
+     * @return string
401
+     */
402
+    public function escapeLikeParameter($param) {
403
+        return addcslashes($param, '\\_%');
404
+    }
405 405
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
 			return parent::connect();
57 57
 		} catch (DBALException $e) {
58 58
 			// throw a new exception to prevent leaking info from the stacktrace
59
-			throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
59
+			throw new DBALException('Failed to connect to the database: '.$e->getMessage(), $e->getCode());
60 60
 		}
61 61
 	}
62 62
 
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 		// 0 is the method where we use `getCallerBacktrace`
105 105
 		// 1 is the target method which uses the method we want to log
106 106
 		if (isset($traces[1])) {
107
-			return $traces[1]['file'] . ':' . $traces[1]['line'];
107
+			return $traces[1]['file'].':'.$traces[1]['line'];
108 108
 		}
109 109
 
110 110
 		return '';
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
 	 * @param int $offset
151 151
 	 * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
152 152
 	 */
153
-	public function prepare( $statement, $limit=null, $offset=null ) {
153
+	public function prepare($statement, $limit = null, $offset = null) {
154 154
 		if ($limit === -1) {
155 155
 			$limit = null;
156 156
 		}
@@ -161,7 +161,7 @@  discard block
 block discarded – undo
161 161
 		$statement = $this->replaceTablePrefix($statement);
162 162
 		$statement = $this->adapter->fixupStatement($statement);
163 163
 
164
-		if(\OC::$server->getSystemConfig()->getValue( 'log_query', false)) {
164
+		if (\OC::$server->getSystemConfig()->getValue('log_query', false)) {
165 165
 			\OCP\Util::writeLog('core', 'DB prepare : '.$statement, \OCP\Util::DEBUG);
166 166
 		}
167 167
 		return parent::prepare($statement);
@@ -318,7 +318,7 @@  discard block
 block discarded – undo
318 318
 			throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
319 319
 		}
320 320
 
321
-		$tableName = $this->tablePrefix . $tableName;
321
+		$tableName = $this->tablePrefix.$tableName;
322 322
 		$this->lockedTable = $tableName;
323 323
 		$this->adapter->lockTable($tableName);
324 324
 	}
@@ -339,11 +339,11 @@  discard block
 block discarded – undo
339 339
 	 * @return string
340 340
 	 */
341 341
 	public function getError() {
342
-		$msg = $this->errorCode() . ': ';
342
+		$msg = $this->errorCode().': ';
343 343
 		$errorInfo = $this->errorInfo();
344 344
 		if (is_array($errorInfo)) {
345
-			$msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
346
-			$msg .= 'Driver Code = '.$errorInfo[1] . ', ';
345
+			$msg .= 'SQLSTATE = '.$errorInfo[0].', ';
346
+			$msg .= 'Driver Code = '.$errorInfo[1].', ';
347 347
 			$msg .= 'Driver Message = '.$errorInfo[2];
348 348
 		}
349 349
 		return $msg;
@@ -355,9 +355,9 @@  discard block
 block discarded – undo
355 355
 	 * @param string $table table name without the prefix
356 356
 	 */
357 357
 	public function dropTable($table) {
358
-		$table = $this->tablePrefix . trim($table);
358
+		$table = $this->tablePrefix.trim($table);
359 359
 		$schema = $this->getSchemaManager();
360
-		if($schema->tablesExist(array($table))) {
360
+		if ($schema->tablesExist(array($table))) {
361 361
 			$schema->dropTable($table);
362 362
 		}
363 363
 	}
@@ -368,8 +368,8 @@  discard block
 block discarded – undo
368 368
 	 * @param string $table table name without the prefix
369 369
 	 * @return bool
370 370
 	 */
371
-	public function tableExists($table){
372
-		$table = $this->tablePrefix . trim($table);
371
+	public function tableExists($table) {
372
+		$table = $this->tablePrefix.trim($table);
373 373
 		$schema = $this->getSchemaManager();
374 374
 		return $schema->tablesExist(array($table));
375 375
 	}
@@ -380,7 +380,7 @@  discard block
 block discarded – undo
380 380
 	 * @return string
381 381
 	 */
382 382
 	protected function replaceTablePrefix($statement) {
383
-		return str_replace( '*PREFIX*', $this->tablePrefix, $statement );
383
+		return str_replace('*PREFIX*', $this->tablePrefix, $statement);
384 384
 	}
385 385
 
386 386
 	/**
Please login to merge, or discard this patch.
lib/private/Encryption/Util.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -30,7 +30,6 @@
 block discarded – undo
30 30
 use OC\Files\Filesystem;
31 31
 use OC\Files\View;
32 32
 use OCP\Encryption\IEncryptionModule;
33
-use OCP\Files\Storage;
34 33
 use OCP\IConfig;
35 34
 
36 35
 class Util {
Please login to merge, or discard this patch.
Indentation   +354 added lines, -354 removed lines patch added patch discarded remove patch
@@ -36,359 +36,359 @@
 block discarded – undo
36 36
 
37 37
 class Util {
38 38
 
39
-	const HEADER_START = 'HBEGIN';
40
-	const HEADER_END = 'HEND';
41
-	const HEADER_PADDING_CHAR = '-';
42
-
43
-	const HEADER_ENCRYPTION_MODULE_KEY = 'oc_encryption_module';
44
-
45
-	/**
46
-	 * block size will always be 8192 for a PHP stream
47
-	 * @see https://bugs.php.net/bug.php?id=21641
48
-	 * @var integer
49
-	 */
50
-	protected $headerSize = 8192;
51
-
52
-	/**
53
-	 * block size will always be 8192 for a PHP stream
54
-	 * @see https://bugs.php.net/bug.php?id=21641
55
-	 * @var integer
56
-	 */
57
-	protected $blockSize = 8192;
58
-
59
-	/** @var View */
60
-	protected $rootView;
61
-
62
-	/** @var array */
63
-	protected $ocHeaderKeys;
64
-
65
-	/** @var \OC\User\Manager */
66
-	protected $userManager;
67
-
68
-	/** @var IConfig */
69
-	protected $config;
70
-
71
-	/** @var array paths excluded from encryption */
72
-	protected $excludedPaths;
73
-
74
-	/** @var \OC\Group\Manager $manager */
75
-	protected $groupManager;
76
-
77
-	/**
78
-	 *
79
-	 * @param View $rootView
80
-	 * @param \OC\User\Manager $userManager
81
-	 * @param \OC\Group\Manager $groupManager
82
-	 * @param IConfig $config
83
-	 */
84
-	public function __construct(
85
-		View $rootView,
86
-		\OC\User\Manager $userManager,
87
-		\OC\Group\Manager $groupManager,
88
-		IConfig $config) {
89
-
90
-		$this->ocHeaderKeys = [
91
-			self::HEADER_ENCRYPTION_MODULE_KEY
92
-		];
93
-
94
-		$this->rootView = $rootView;
95
-		$this->userManager = $userManager;
96
-		$this->groupManager = $groupManager;
97
-		$this->config = $config;
98
-
99
-		$this->excludedPaths[] = 'files_encryption';
100
-	}
101
-
102
-	/**
103
-	 * read encryption module ID from header
104
-	 *
105
-	 * @param array $header
106
-	 * @return string
107
-	 * @throws ModuleDoesNotExistsException
108
-	 */
109
-	public function getEncryptionModuleId(array $header = null) {
110
-		$id = '';
111
-		$encryptionModuleKey = self::HEADER_ENCRYPTION_MODULE_KEY;
112
-
113
-		if (isset($header[$encryptionModuleKey])) {
114
-			$id = $header[$encryptionModuleKey];
115
-		} elseif (isset($header['cipher'])) {
116
-			if (class_exists('\OCA\Encryption\Crypto\Encryption')) {
117
-				// fall back to default encryption if the user migrated from
118
-				// ownCloud <= 8.0 with the old encryption
119
-				$id = \OCA\Encryption\Crypto\Encryption::ID;
120
-			} else {
121
-				throw new ModuleDoesNotExistsException('Default encryption module missing');
122
-			}
123
-		}
124
-
125
-		return $id;
126
-	}
127
-
128
-	/**
129
-	 * create header for encrypted file
130
-	 *
131
-	 * @param array $headerData
132
-	 * @param IEncryptionModule $encryptionModule
133
-	 * @return string
134
-	 * @throws EncryptionHeaderToLargeException if header has to many arguments
135
-	 * @throws EncryptionHeaderKeyExistsException if header key is already in use
136
-	 */
137
-	public function createHeader(array $headerData, IEncryptionModule $encryptionModule) {
138
-		$header = self::HEADER_START . ':' . self::HEADER_ENCRYPTION_MODULE_KEY . ':' . $encryptionModule->getId() . ':';
139
-		foreach ($headerData as $key => $value) {
140
-			if (in_array($key, $this->ocHeaderKeys)) {
141
-				throw new EncryptionHeaderKeyExistsException($key);
142
-			}
143
-			$header .= $key . ':' . $value . ':';
144
-		}
145
-		$header .= self::HEADER_END;
146
-
147
-		if (strlen($header) > $this->getHeaderSize()) {
148
-			throw new EncryptionHeaderToLargeException();
149
-		}
150
-
151
-		$paddedHeader = str_pad($header, $this->headerSize, self::HEADER_PADDING_CHAR, STR_PAD_RIGHT);
152
-
153
-		return $paddedHeader;
154
-	}
155
-
156
-	/**
157
-	 * go recursively through a dir and collect all files and sub files.
158
-	 *
159
-	 * @param string $dir relative to the users files folder
160
-	 * @return array with list of files relative to the users files folder
161
-	 */
162
-	public function getAllFiles($dir) {
163
-		$result = array();
164
-		$dirList = array($dir);
165
-
166
-		while ($dirList) {
167
-			$dir = array_pop($dirList);
168
-			$content = $this->rootView->getDirectoryContent($dir);
169
-
170
-			foreach ($content as $c) {
171
-				if ($c->getType() === 'dir') {
172
-					$dirList[] = $c->getPath();
173
-				} else {
174
-					$result[] =  $c->getPath();
175
-				}
176
-			}
177
-
178
-		}
179
-
180
-		return $result;
181
-	}
182
-
183
-	/**
184
-	 * check if it is a file uploaded by the user stored in data/user/files
185
-	 * or a metadata file
186
-	 *
187
-	 * @param string $path relative to the data/ folder
188
-	 * @return boolean
189
-	 */
190
-	public function isFile($path) {
191
-		$parts = explode('/', Filesystem::normalizePath($path), 4);
192
-		if (isset($parts[2]) && $parts[2] === 'files') {
193
-			return true;
194
-		}
195
-		return false;
196
-	}
197
-
198
-	/**
199
-	 * return size of encryption header
200
-	 *
201
-	 * @return integer
202
-	 */
203
-	public function getHeaderSize() {
204
-		return $this->headerSize;
205
-	}
206
-
207
-	/**
208
-	 * return size of block read by a PHP stream
209
-	 *
210
-	 * @return integer
211
-	 */
212
-	public function getBlockSize() {
213
-		return $this->blockSize;
214
-	}
215
-
216
-	/**
217
-	 * get the owner and the path for the file relative to the owners files folder
218
-	 *
219
-	 * @param string $path
220
-	 * @return array
221
-	 * @throws \BadMethodCallException
222
-	 */
223
-	public function getUidAndFilename($path) {
224
-
225
-		$parts = explode('/', $path);
226
-		$uid = '';
227
-		if (count($parts) > 2) {
228
-			$uid = $parts[1];
229
-		}
230
-		if (!$this->userManager->userExists($uid)) {
231
-			throw new \BadMethodCallException(
232
-				'path needs to be relative to the system wide data folder and point to a user specific file'
233
-			);
234
-		}
235
-
236
-		$ownerPath = implode('/', array_slice($parts, 2));
237
-
238
-		return array($uid, Filesystem::normalizePath($ownerPath));
239
-
240
-	}
241
-
242
-	/**
243
-	 * Remove .path extension from a file path
244
-	 * @param string $path Path that may identify a .part file
245
-	 * @return string File path without .part extension
246
-	 * @note this is needed for reusing keys
247
-	 */
248
-	public function stripPartialFileExtension($path) {
249
-		$extension = pathinfo($path, PATHINFO_EXTENSION);
250
-
251
-		if ( $extension === 'part') {
252
-
253
-			$newLength = strlen($path) - 5; // 5 = strlen(".part")
254
-			$fPath = substr($path, 0, $newLength);
255
-
256
-			// if path also contains a transaction id, we remove it too
257
-			$extension = pathinfo($fPath, PATHINFO_EXTENSION);
258
-			if(substr($extension, 0, 12) === 'ocTransferId') { // 12 = strlen("ocTransferId")
259
-				$newLength = strlen($fPath) - strlen($extension) -1;
260
-				$fPath = substr($fPath, 0, $newLength);
261
-			}
262
-			return $fPath;
263
-
264
-		} else {
265
-			return $path;
266
-		}
267
-	}
268
-
269
-	public function getUserWithAccessToMountPoint($users, $groups) {
270
-		$result = array();
271
-		if (in_array('all', $users)) {
272
-			$result = \OCP\User::getUsers();
273
-		} else {
274
-			$result = array_merge($result, $users);
275
-			foreach ($groups as $group) {
276
-				$result = array_merge($result, \OC_Group::usersInGroup($group));
277
-			}
278
-		}
279
-
280
-		return $result;
281
-	}
282
-
283
-	/**
284
-	 * check if the file is stored on a system wide mount point
285
-	 * @param string $path relative to /data/user with leading '/'
286
-	 * @param string $uid
287
-	 * @return boolean
288
-	 */
289
-	public function isSystemWideMountPoint($path, $uid) {
290
-		if (\OCP\App::isEnabled("files_external")) {
291
-			$mounts = \OC_Mount_Config::getSystemMountPoints();
292
-			foreach ($mounts as $mount) {
293
-				if (strpos($path, '/files/' . $mount['mountpoint']) === 0) {
294
-					if ($this->isMountPointApplicableToUser($mount, $uid)) {
295
-						return true;
296
-					}
297
-				}
298
-			}
299
-		}
300
-		return false;
301
-	}
302
-
303
-	/**
304
-	 * check if mount point is applicable to user
305
-	 *
306
-	 * @param array $mount contains $mount['applicable']['users'], $mount['applicable']['groups']
307
-	 * @param string $uid
308
-	 * @return boolean
309
-	 */
310
-	private function isMountPointApplicableToUser($mount, $uid) {
311
-		$acceptedUids = array('all', $uid);
312
-		// check if mount point is applicable for the user
313
-		$intersection = array_intersect($acceptedUids, $mount['applicable']['users']);
314
-		if (!empty($intersection)) {
315
-			return true;
316
-		}
317
-		// check if mount point is applicable for group where the user is a member
318
-		foreach ($mount['applicable']['groups'] as $gid) {
319
-			if ($this->groupManager->isInGroup($uid, $gid)) {
320
-				return true;
321
-			}
322
-		}
323
-		return false;
324
-	}
325
-
326
-	/**
327
-	 * check if it is a path which is excluded by ownCloud from encryption
328
-	 *
329
-	 * @param string $path
330
-	 * @return boolean
331
-	 */
332
-	public function isExcluded($path) {
333
-		$normalizedPath = Filesystem::normalizePath($path);
334
-		$root = explode('/', $normalizedPath, 4);
335
-		if (count($root) > 1) {
336
-
337
-			// detect alternative key storage root
338
-			$rootDir = $this->getKeyStorageRoot();
339
-			if ($rootDir !== '' &&
340
-				0 === strpos(
341
-					Filesystem::normalizePath($path),
342
-					Filesystem::normalizePath($rootDir)
343
-				)
344
-			) {
345
-				return true;
346
-			}
347
-
348
-
349
-			//detect system wide folders
350
-			if (in_array($root[1], $this->excludedPaths)) {
351
-				return true;
352
-			}
353
-
354
-			// detect user specific folders
355
-			if ($this->userManager->userExists($root[1])
356
-				&& in_array($root[2], $this->excludedPaths)) {
357
-
358
-				return true;
359
-			}
360
-		}
361
-		return false;
362
-	}
363
-
364
-	/**
365
-	 * check if recovery key is enabled for user
366
-	 *
367
-	 * @param string $uid
368
-	 * @return boolean
369
-	 */
370
-	public function recoveryEnabled($uid) {
371
-		$enabled = $this->config->getUserValue($uid, 'encryption', 'recovery_enabled', '0');
372
-
373
-		return ($enabled === '1') ? true : false;
374
-	}
375
-
376
-	/**
377
-	 * set new key storage root
378
-	 *
379
-	 * @param string $root new key store root relative to the data folder
380
-	 */
381
-	public function setKeyStorageRoot($root) {
382
-		$this->config->setAppValue('core', 'encryption_key_storage_root', $root);
383
-	}
384
-
385
-	/**
386
-	 * get key storage root
387
-	 *
388
-	 * @return string key storage root
389
-	 */
390
-	public function getKeyStorageRoot() {
391
-		return $this->config->getAppValue('core', 'encryption_key_storage_root', '');
392
-	}
39
+    const HEADER_START = 'HBEGIN';
40
+    const HEADER_END = 'HEND';
41
+    const HEADER_PADDING_CHAR = '-';
42
+
43
+    const HEADER_ENCRYPTION_MODULE_KEY = 'oc_encryption_module';
44
+
45
+    /**
46
+     * block size will always be 8192 for a PHP stream
47
+     * @see https://bugs.php.net/bug.php?id=21641
48
+     * @var integer
49
+     */
50
+    protected $headerSize = 8192;
51
+
52
+    /**
53
+     * block size will always be 8192 for a PHP stream
54
+     * @see https://bugs.php.net/bug.php?id=21641
55
+     * @var integer
56
+     */
57
+    protected $blockSize = 8192;
58
+
59
+    /** @var View */
60
+    protected $rootView;
61
+
62
+    /** @var array */
63
+    protected $ocHeaderKeys;
64
+
65
+    /** @var \OC\User\Manager */
66
+    protected $userManager;
67
+
68
+    /** @var IConfig */
69
+    protected $config;
70
+
71
+    /** @var array paths excluded from encryption */
72
+    protected $excludedPaths;
73
+
74
+    /** @var \OC\Group\Manager $manager */
75
+    protected $groupManager;
76
+
77
+    /**
78
+     *
79
+     * @param View $rootView
80
+     * @param \OC\User\Manager $userManager
81
+     * @param \OC\Group\Manager $groupManager
82
+     * @param IConfig $config
83
+     */
84
+    public function __construct(
85
+        View $rootView,
86
+        \OC\User\Manager $userManager,
87
+        \OC\Group\Manager $groupManager,
88
+        IConfig $config) {
89
+
90
+        $this->ocHeaderKeys = [
91
+            self::HEADER_ENCRYPTION_MODULE_KEY
92
+        ];
93
+
94
+        $this->rootView = $rootView;
95
+        $this->userManager = $userManager;
96
+        $this->groupManager = $groupManager;
97
+        $this->config = $config;
98
+
99
+        $this->excludedPaths[] = 'files_encryption';
100
+    }
101
+
102
+    /**
103
+     * read encryption module ID from header
104
+     *
105
+     * @param array $header
106
+     * @return string
107
+     * @throws ModuleDoesNotExistsException
108
+     */
109
+    public function getEncryptionModuleId(array $header = null) {
110
+        $id = '';
111
+        $encryptionModuleKey = self::HEADER_ENCRYPTION_MODULE_KEY;
112
+
113
+        if (isset($header[$encryptionModuleKey])) {
114
+            $id = $header[$encryptionModuleKey];
115
+        } elseif (isset($header['cipher'])) {
116
+            if (class_exists('\OCA\Encryption\Crypto\Encryption')) {
117
+                // fall back to default encryption if the user migrated from
118
+                // ownCloud <= 8.0 with the old encryption
119
+                $id = \OCA\Encryption\Crypto\Encryption::ID;
120
+            } else {
121
+                throw new ModuleDoesNotExistsException('Default encryption module missing');
122
+            }
123
+        }
124
+
125
+        return $id;
126
+    }
127
+
128
+    /**
129
+     * create header for encrypted file
130
+     *
131
+     * @param array $headerData
132
+     * @param IEncryptionModule $encryptionModule
133
+     * @return string
134
+     * @throws EncryptionHeaderToLargeException if header has to many arguments
135
+     * @throws EncryptionHeaderKeyExistsException if header key is already in use
136
+     */
137
+    public function createHeader(array $headerData, IEncryptionModule $encryptionModule) {
138
+        $header = self::HEADER_START . ':' . self::HEADER_ENCRYPTION_MODULE_KEY . ':' . $encryptionModule->getId() . ':';
139
+        foreach ($headerData as $key => $value) {
140
+            if (in_array($key, $this->ocHeaderKeys)) {
141
+                throw new EncryptionHeaderKeyExistsException($key);
142
+            }
143
+            $header .= $key . ':' . $value . ':';
144
+        }
145
+        $header .= self::HEADER_END;
146
+
147
+        if (strlen($header) > $this->getHeaderSize()) {
148
+            throw new EncryptionHeaderToLargeException();
149
+        }
150
+
151
+        $paddedHeader = str_pad($header, $this->headerSize, self::HEADER_PADDING_CHAR, STR_PAD_RIGHT);
152
+
153
+        return $paddedHeader;
154
+    }
155
+
156
+    /**
157
+     * go recursively through a dir and collect all files and sub files.
158
+     *
159
+     * @param string $dir relative to the users files folder
160
+     * @return array with list of files relative to the users files folder
161
+     */
162
+    public function getAllFiles($dir) {
163
+        $result = array();
164
+        $dirList = array($dir);
165
+
166
+        while ($dirList) {
167
+            $dir = array_pop($dirList);
168
+            $content = $this->rootView->getDirectoryContent($dir);
169
+
170
+            foreach ($content as $c) {
171
+                if ($c->getType() === 'dir') {
172
+                    $dirList[] = $c->getPath();
173
+                } else {
174
+                    $result[] =  $c->getPath();
175
+                }
176
+            }
177
+
178
+        }
179
+
180
+        return $result;
181
+    }
182
+
183
+    /**
184
+     * check if it is a file uploaded by the user stored in data/user/files
185
+     * or a metadata file
186
+     *
187
+     * @param string $path relative to the data/ folder
188
+     * @return boolean
189
+     */
190
+    public function isFile($path) {
191
+        $parts = explode('/', Filesystem::normalizePath($path), 4);
192
+        if (isset($parts[2]) && $parts[2] === 'files') {
193
+            return true;
194
+        }
195
+        return false;
196
+    }
197
+
198
+    /**
199
+     * return size of encryption header
200
+     *
201
+     * @return integer
202
+     */
203
+    public function getHeaderSize() {
204
+        return $this->headerSize;
205
+    }
206
+
207
+    /**
208
+     * return size of block read by a PHP stream
209
+     *
210
+     * @return integer
211
+     */
212
+    public function getBlockSize() {
213
+        return $this->blockSize;
214
+    }
215
+
216
+    /**
217
+     * get the owner and the path for the file relative to the owners files folder
218
+     *
219
+     * @param string $path
220
+     * @return array
221
+     * @throws \BadMethodCallException
222
+     */
223
+    public function getUidAndFilename($path) {
224
+
225
+        $parts = explode('/', $path);
226
+        $uid = '';
227
+        if (count($parts) > 2) {
228
+            $uid = $parts[1];
229
+        }
230
+        if (!$this->userManager->userExists($uid)) {
231
+            throw new \BadMethodCallException(
232
+                'path needs to be relative to the system wide data folder and point to a user specific file'
233
+            );
234
+        }
235
+
236
+        $ownerPath = implode('/', array_slice($parts, 2));
237
+
238
+        return array($uid, Filesystem::normalizePath($ownerPath));
239
+
240
+    }
241
+
242
+    /**
243
+     * Remove .path extension from a file path
244
+     * @param string $path Path that may identify a .part file
245
+     * @return string File path without .part extension
246
+     * @note this is needed for reusing keys
247
+     */
248
+    public function stripPartialFileExtension($path) {
249
+        $extension = pathinfo($path, PATHINFO_EXTENSION);
250
+
251
+        if ( $extension === 'part') {
252
+
253
+            $newLength = strlen($path) - 5; // 5 = strlen(".part")
254
+            $fPath = substr($path, 0, $newLength);
255
+
256
+            // if path also contains a transaction id, we remove it too
257
+            $extension = pathinfo($fPath, PATHINFO_EXTENSION);
258
+            if(substr($extension, 0, 12) === 'ocTransferId') { // 12 = strlen("ocTransferId")
259
+                $newLength = strlen($fPath) - strlen($extension) -1;
260
+                $fPath = substr($fPath, 0, $newLength);
261
+            }
262
+            return $fPath;
263
+
264
+        } else {
265
+            return $path;
266
+        }
267
+    }
268
+
269
+    public function getUserWithAccessToMountPoint($users, $groups) {
270
+        $result = array();
271
+        if (in_array('all', $users)) {
272
+            $result = \OCP\User::getUsers();
273
+        } else {
274
+            $result = array_merge($result, $users);
275
+            foreach ($groups as $group) {
276
+                $result = array_merge($result, \OC_Group::usersInGroup($group));
277
+            }
278
+        }
279
+
280
+        return $result;
281
+    }
282
+
283
+    /**
284
+     * check if the file is stored on a system wide mount point
285
+     * @param string $path relative to /data/user with leading '/'
286
+     * @param string $uid
287
+     * @return boolean
288
+     */
289
+    public function isSystemWideMountPoint($path, $uid) {
290
+        if (\OCP\App::isEnabled("files_external")) {
291
+            $mounts = \OC_Mount_Config::getSystemMountPoints();
292
+            foreach ($mounts as $mount) {
293
+                if (strpos($path, '/files/' . $mount['mountpoint']) === 0) {
294
+                    if ($this->isMountPointApplicableToUser($mount, $uid)) {
295
+                        return true;
296
+                    }
297
+                }
298
+            }
299
+        }
300
+        return false;
301
+    }
302
+
303
+    /**
304
+     * check if mount point is applicable to user
305
+     *
306
+     * @param array $mount contains $mount['applicable']['users'], $mount['applicable']['groups']
307
+     * @param string $uid
308
+     * @return boolean
309
+     */
310
+    private function isMountPointApplicableToUser($mount, $uid) {
311
+        $acceptedUids = array('all', $uid);
312
+        // check if mount point is applicable for the user
313
+        $intersection = array_intersect($acceptedUids, $mount['applicable']['users']);
314
+        if (!empty($intersection)) {
315
+            return true;
316
+        }
317
+        // check if mount point is applicable for group where the user is a member
318
+        foreach ($mount['applicable']['groups'] as $gid) {
319
+            if ($this->groupManager->isInGroup($uid, $gid)) {
320
+                return true;
321
+            }
322
+        }
323
+        return false;
324
+    }
325
+
326
+    /**
327
+     * check if it is a path which is excluded by ownCloud from encryption
328
+     *
329
+     * @param string $path
330
+     * @return boolean
331
+     */
332
+    public function isExcluded($path) {
333
+        $normalizedPath = Filesystem::normalizePath($path);
334
+        $root = explode('/', $normalizedPath, 4);
335
+        if (count($root) > 1) {
336
+
337
+            // detect alternative key storage root
338
+            $rootDir = $this->getKeyStorageRoot();
339
+            if ($rootDir !== '' &&
340
+                0 === strpos(
341
+                    Filesystem::normalizePath($path),
342
+                    Filesystem::normalizePath($rootDir)
343
+                )
344
+            ) {
345
+                return true;
346
+            }
347
+
348
+
349
+            //detect system wide folders
350
+            if (in_array($root[1], $this->excludedPaths)) {
351
+                return true;
352
+            }
353
+
354
+            // detect user specific folders
355
+            if ($this->userManager->userExists($root[1])
356
+                && in_array($root[2], $this->excludedPaths)) {
357
+
358
+                return true;
359
+            }
360
+        }
361
+        return false;
362
+    }
363
+
364
+    /**
365
+     * check if recovery key is enabled for user
366
+     *
367
+     * @param string $uid
368
+     * @return boolean
369
+     */
370
+    public function recoveryEnabled($uid) {
371
+        $enabled = $this->config->getUserValue($uid, 'encryption', 'recovery_enabled', '0');
372
+
373
+        return ($enabled === '1') ? true : false;
374
+    }
375
+
376
+    /**
377
+     * set new key storage root
378
+     *
379
+     * @param string $root new key store root relative to the data folder
380
+     */
381
+    public function setKeyStorageRoot($root) {
382
+        $this->config->setAppValue('core', 'encryption_key_storage_root', $root);
383
+    }
384
+
385
+    /**
386
+     * get key storage root
387
+     *
388
+     * @return string key storage root
389
+     */
390
+    public function getKeyStorageRoot() {
391
+        return $this->config->getAppValue('core', 'encryption_key_storage_root', '');
392
+    }
393 393
 
394 394
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -135,12 +135,12 @@  discard block
 block discarded – undo
135 135
 	 * @throws EncryptionHeaderKeyExistsException if header key is already in use
136 136
 	 */
137 137
 	public function createHeader(array $headerData, IEncryptionModule $encryptionModule) {
138
-		$header = self::HEADER_START . ':' . self::HEADER_ENCRYPTION_MODULE_KEY . ':' . $encryptionModule->getId() . ':';
138
+		$header = self::HEADER_START.':'.self::HEADER_ENCRYPTION_MODULE_KEY.':'.$encryptionModule->getId().':';
139 139
 		foreach ($headerData as $key => $value) {
140 140
 			if (in_array($key, $this->ocHeaderKeys)) {
141 141
 				throw new EncryptionHeaderKeyExistsException($key);
142 142
 			}
143
-			$header .= $key . ':' . $value . ':';
143
+			$header .= $key.':'.$value.':';
144 144
 		}
145 145
 		$header .= self::HEADER_END;
146 146
 
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
 				if ($c->getType() === 'dir') {
172 172
 					$dirList[] = $c->getPath();
173 173
 				} else {
174
-					$result[] =  $c->getPath();
174
+					$result[] = $c->getPath();
175 175
 				}
176 176
 			}
177 177
 
@@ -248,15 +248,15 @@  discard block
 block discarded – undo
248 248
 	public function stripPartialFileExtension($path) {
249 249
 		$extension = pathinfo($path, PATHINFO_EXTENSION);
250 250
 
251
-		if ( $extension === 'part') {
251
+		if ($extension === 'part') {
252 252
 
253 253
 			$newLength = strlen($path) - 5; // 5 = strlen(".part")
254 254
 			$fPath = substr($path, 0, $newLength);
255 255
 
256 256
 			// if path also contains a transaction id, we remove it too
257 257
 			$extension = pathinfo($fPath, PATHINFO_EXTENSION);
258
-			if(substr($extension, 0, 12) === 'ocTransferId') { // 12 = strlen("ocTransferId")
259
-				$newLength = strlen($fPath) - strlen($extension) -1;
258
+			if (substr($extension, 0, 12) === 'ocTransferId') { // 12 = strlen("ocTransferId")
259
+				$newLength = strlen($fPath) - strlen($extension) - 1;
260 260
 				$fPath = substr($fPath, 0, $newLength);
261 261
 			}
262 262
 			return $fPath;
@@ -290,7 +290,7 @@  discard block
 block discarded – undo
290 290
 		if (\OCP\App::isEnabled("files_external")) {
291 291
 			$mounts = \OC_Mount_Config::getSystemMountPoints();
292 292
 			foreach ($mounts as $mount) {
293
-				if (strpos($path, '/files/' . $mount['mountpoint']) === 0) {
293
+				if (strpos($path, '/files/'.$mount['mountpoint']) === 0) {
294 294
 					if ($this->isMountPointApplicableToUser($mount, $uid)) {
295 295
 						return true;
296 296
 					}
Please login to merge, or discard this patch.
lib/private/Files/Cache/Cache.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -402,6 +402,9 @@
 block discarded – undo
402 402
 		}
403 403
 	}
404 404
 
405
+	/**
406
+	 * @param string $path
407
+	 */
405 408
 	private function getParentPath($path) {
406 409
 		$parent = dirname($path);
407 410
 		if ($parent === '.') {
Please login to merge, or discard this patch.
Indentation   +773 added lines, -773 removed lines patch added patch discarded remove patch
@@ -52,787 +52,787 @@
 block discarded – undo
52 52
  * - ChangePropagator: updates the mtime and etags of parent folders whenever a change to the cache is made to the cache by the updater
53 53
  */
54 54
 class Cache implements ICache {
55
-	use MoveFromCacheTrait {
56
-		MoveFromCacheTrait::moveFromCache as moveFromCacheFallback;
57
-	}
58
-
59
-	/**
60
-	 * @var array partial data for the cache
61
-	 */
62
-	protected $partial = array();
63
-
64
-	/**
65
-	 * @var string
66
-	 */
67
-	protected $storageId;
68
-
69
-	/**
70
-	 * @var Storage $storageCache
71
-	 */
72
-	protected $storageCache;
73
-
74
-	/** @var IMimeTypeLoader */
75
-	protected $mimetypeLoader;
76
-
77
-	/**
78
-	 * @var IDBConnection
79
-	 */
80
-	protected $connection;
81
-
82
-	/**
83
-	 * @param \OC\Files\Storage\Storage|string $storage
84
-	 */
85
-	public function __construct($storage) {
86
-		if ($storage instanceof \OC\Files\Storage\Storage) {
87
-			$this->storageId = $storage->getId();
88
-		} else {
89
-			$this->storageId = $storage;
90
-		}
91
-		if (strlen($this->storageId) > 64) {
92
-			$this->storageId = md5($this->storageId);
93
-		}
94
-
95
-		$this->storageCache = new Storage($storage);
96
-		$this->mimetypeLoader = \OC::$server->getMimeTypeLoader();
97
-		$this->connection = \OC::$server->getDatabaseConnection();
98
-	}
99
-
100
-	/**
101
-	 * Get the numeric storage id for this cache's storage
102
-	 *
103
-	 * @return int
104
-	 */
105
-	public function getNumericStorageId() {
106
-		return $this->storageCache->getNumericId();
107
-	}
108
-
109
-	/**
110
-	 * get the stored metadata of a file or folder
111
-	 *
112
-	 * @param string | int $file either the path of a file or folder or the file id for a file or folder
113
-	 * @return ICacheEntry|false the cache entry as array of false if the file is not found in the cache
114
-	 */
115
-	public function get($file) {
116
-		if (is_string($file) or $file == '') {
117
-			// normalize file
118
-			$file = $this->normalize($file);
119
-
120
-			$where = 'WHERE `storage` = ? AND `path_hash` = ?';
121
-			$params = array($this->getNumericStorageId(), md5($file));
122
-		} else { //file id
123
-			$where = 'WHERE `fileid` = ?';
124
-			$params = array($file);
125
-		}
126
-		$sql = 'SELECT `fileid`, `storage`, `path`, `parent`, `name`, `mimetype`, `mimepart`, `size`, `mtime`,
55
+    use MoveFromCacheTrait {
56
+        MoveFromCacheTrait::moveFromCache as moveFromCacheFallback;
57
+    }
58
+
59
+    /**
60
+     * @var array partial data for the cache
61
+     */
62
+    protected $partial = array();
63
+
64
+    /**
65
+     * @var string
66
+     */
67
+    protected $storageId;
68
+
69
+    /**
70
+     * @var Storage $storageCache
71
+     */
72
+    protected $storageCache;
73
+
74
+    /** @var IMimeTypeLoader */
75
+    protected $mimetypeLoader;
76
+
77
+    /**
78
+     * @var IDBConnection
79
+     */
80
+    protected $connection;
81
+
82
+    /**
83
+     * @param \OC\Files\Storage\Storage|string $storage
84
+     */
85
+    public function __construct($storage) {
86
+        if ($storage instanceof \OC\Files\Storage\Storage) {
87
+            $this->storageId = $storage->getId();
88
+        } else {
89
+            $this->storageId = $storage;
90
+        }
91
+        if (strlen($this->storageId) > 64) {
92
+            $this->storageId = md5($this->storageId);
93
+        }
94
+
95
+        $this->storageCache = new Storage($storage);
96
+        $this->mimetypeLoader = \OC::$server->getMimeTypeLoader();
97
+        $this->connection = \OC::$server->getDatabaseConnection();
98
+    }
99
+
100
+    /**
101
+     * Get the numeric storage id for this cache's storage
102
+     *
103
+     * @return int
104
+     */
105
+    public function getNumericStorageId() {
106
+        return $this->storageCache->getNumericId();
107
+    }
108
+
109
+    /**
110
+     * get the stored metadata of a file or folder
111
+     *
112
+     * @param string | int $file either the path of a file or folder or the file id for a file or folder
113
+     * @return ICacheEntry|false the cache entry as array of false if the file is not found in the cache
114
+     */
115
+    public function get($file) {
116
+        if (is_string($file) or $file == '') {
117
+            // normalize file
118
+            $file = $this->normalize($file);
119
+
120
+            $where = 'WHERE `storage` = ? AND `path_hash` = ?';
121
+            $params = array($this->getNumericStorageId(), md5($file));
122
+        } else { //file id
123
+            $where = 'WHERE `fileid` = ?';
124
+            $params = array($file);
125
+        }
126
+        $sql = 'SELECT `fileid`, `storage`, `path`, `parent`, `name`, `mimetype`, `mimepart`, `size`, `mtime`,
127 127
 					   `storage_mtime`, `encrypted`, `etag`, `permissions`, `checksum`
128 128
 				FROM `*PREFIX*filecache` ' . $where;
129
-		$result = $this->connection->executeQuery($sql, $params);
130
-		$data = $result->fetch();
131
-
132
-		//FIXME hide this HACK in the next database layer, or just use doctrine and get rid of MDB2 and PDO
133
-		//PDO returns false, MDB2 returns null, oracle always uses MDB2, so convert null to false
134
-		if ($data === null) {
135
-			$data = false;
136
-		}
137
-
138
-		//merge partial data
139
-		if (!$data and is_string($file)) {
140
-			if (isset($this->partial[$file])) {
141
-				$data = $this->partial[$file];
142
-			}
143
-			return $data;
144
-		} else {
145
-			//fix types
146
-			$data['fileid'] = (int)$data['fileid'];
147
-			$data['parent'] = (int)$data['parent'];
148
-			$data['size'] = 0 + $data['size'];
149
-			$data['mtime'] = (int)$data['mtime'];
150
-			$data['storage_mtime'] = (int)$data['storage_mtime'];
151
-			$data['encryptedVersion'] = (int)$data['encrypted'];
152
-			$data['encrypted'] = (bool)$data['encrypted'];
153
-			$data['storage'] = $this->storageId;
154
-			$data['mimetype'] = $this->mimetypeLoader->getMimetypeById($data['mimetype']);
155
-			$data['mimepart'] = $this->mimetypeLoader->getMimetypeById($data['mimepart']);
156
-			if ($data['storage_mtime'] == 0) {
157
-				$data['storage_mtime'] = $data['mtime'];
158
-			}
159
-			$data['permissions'] = (int)$data['permissions'];
160
-			return new CacheEntry($data);
161
-		}
162
-	}
163
-
164
-	/**
165
-	 * get the metadata of all files stored in $folder
166
-	 *
167
-	 * @param string $folder
168
-	 * @return ICacheEntry[]
169
-	 */
170
-	public function getFolderContents($folder) {
171
-		$fileId = $this->getId($folder);
172
-		return $this->getFolderContentsById($fileId);
173
-	}
174
-
175
-	/**
176
-	 * get the metadata of all files stored in $folder
177
-	 *
178
-	 * @param int $fileId the file id of the folder
179
-	 * @return ICacheEntry[]
180
-	 */
181
-	public function getFolderContentsById($fileId) {
182
-		if ($fileId > -1) {
183
-			$sql = 'SELECT `fileid`, `storage`, `path`, `parent`, `name`, `mimetype`, `mimepart`, `size`, `mtime`,
129
+        $result = $this->connection->executeQuery($sql, $params);
130
+        $data = $result->fetch();
131
+
132
+        //FIXME hide this HACK in the next database layer, or just use doctrine and get rid of MDB2 and PDO
133
+        //PDO returns false, MDB2 returns null, oracle always uses MDB2, so convert null to false
134
+        if ($data === null) {
135
+            $data = false;
136
+        }
137
+
138
+        //merge partial data
139
+        if (!$data and is_string($file)) {
140
+            if (isset($this->partial[$file])) {
141
+                $data = $this->partial[$file];
142
+            }
143
+            return $data;
144
+        } else {
145
+            //fix types
146
+            $data['fileid'] = (int)$data['fileid'];
147
+            $data['parent'] = (int)$data['parent'];
148
+            $data['size'] = 0 + $data['size'];
149
+            $data['mtime'] = (int)$data['mtime'];
150
+            $data['storage_mtime'] = (int)$data['storage_mtime'];
151
+            $data['encryptedVersion'] = (int)$data['encrypted'];
152
+            $data['encrypted'] = (bool)$data['encrypted'];
153
+            $data['storage'] = $this->storageId;
154
+            $data['mimetype'] = $this->mimetypeLoader->getMimetypeById($data['mimetype']);
155
+            $data['mimepart'] = $this->mimetypeLoader->getMimetypeById($data['mimepart']);
156
+            if ($data['storage_mtime'] == 0) {
157
+                $data['storage_mtime'] = $data['mtime'];
158
+            }
159
+            $data['permissions'] = (int)$data['permissions'];
160
+            return new CacheEntry($data);
161
+        }
162
+    }
163
+
164
+    /**
165
+     * get the metadata of all files stored in $folder
166
+     *
167
+     * @param string $folder
168
+     * @return ICacheEntry[]
169
+     */
170
+    public function getFolderContents($folder) {
171
+        $fileId = $this->getId($folder);
172
+        return $this->getFolderContentsById($fileId);
173
+    }
174
+
175
+    /**
176
+     * get the metadata of all files stored in $folder
177
+     *
178
+     * @param int $fileId the file id of the folder
179
+     * @return ICacheEntry[]
180
+     */
181
+    public function getFolderContentsById($fileId) {
182
+        if ($fileId > -1) {
183
+            $sql = 'SELECT `fileid`, `storage`, `path`, `parent`, `name`, `mimetype`, `mimepart`, `size`, `mtime`,
184 184
 						   `storage_mtime`, `encrypted`, `etag`, `permissions`, `checksum`
185 185
 					FROM `*PREFIX*filecache` WHERE `parent` = ? ORDER BY `name` ASC';
186
-			$result = $this->connection->executeQuery($sql, [$fileId]);
187
-			$files = $result->fetchAll();
188
-			foreach ($files as &$file) {
189
-				$file['mimetype'] = $this->mimetypeLoader->getMimetypeById($file['mimetype']);
190
-				$file['mimepart'] = $this->mimetypeLoader->getMimetypeById($file['mimepart']);
191
-				if ($file['storage_mtime'] == 0) {
192
-					$file['storage_mtime'] = $file['mtime'];
193
-				}
194
-				$file['permissions'] = (int)$file['permissions'];
195
-				$file['mtime'] = (int)$file['mtime'];
196
-				$file['storage_mtime'] = (int)$file['storage_mtime'];
197
-				$file['size'] = 0 + $file['size'];
198
-			}
199
-			return array_map(function (array $data) {
200
-				return new CacheEntry($data);
201
-			}, $files);
202
-		} else {
203
-			return array();
204
-		}
205
-	}
206
-
207
-	/**
208
-	 * insert or update meta data for a file or folder
209
-	 *
210
-	 * @param string $file
211
-	 * @param array $data
212
-	 *
213
-	 * @return int file id
214
-	 * @throws \RuntimeException
215
-	 */
216
-	public function put($file, array $data) {
217
-		if (($id = $this->getId($file)) > -1) {
218
-			$this->update($id, $data);
219
-			return $id;
220
-		} else {
221
-			return $this->insert($file, $data);
222
-		}
223
-	}
224
-
225
-	/**
226
-	 * insert meta data for a new file or folder
227
-	 *
228
-	 * @param string $file
229
-	 * @param array $data
230
-	 *
231
-	 * @return int file id
232
-	 * @throws \RuntimeException
233
-	 */
234
-	public function insert($file, array $data) {
235
-		// normalize file
236
-		$file = $this->normalize($file);
237
-
238
-		if (isset($this->partial[$file])) { //add any saved partial data
239
-			$data = array_merge($this->partial[$file], $data);
240
-			unset($this->partial[$file]);
241
-		}
242
-
243
-		$requiredFields = array('size', 'mtime', 'mimetype');
244
-		foreach ($requiredFields as $field) {
245
-			if (!isset($data[$field])) { //data not complete save as partial and return
246
-				$this->partial[$file] = $data;
247
-				return -1;
248
-			}
249
-		}
250
-
251
-		$data['path'] = $file;
252
-		$data['parent'] = $this->getParentId($file);
253
-		$data['name'] = \OC_Util::basename($file);
254
-
255
-		list($queryParts, $params) = $this->buildParts($data);
256
-		$queryParts[] = '`storage`';
257
-		$params[] = $this->getNumericStorageId();
258
-
259
-		$queryParts = array_map(function ($item) {
260
-			return trim($item, "`");
261
-		}, $queryParts);
262
-		$values = array_combine($queryParts, $params);
263
-		if (\OC::$server->getDatabaseConnection()->insertIfNotExist('*PREFIX*filecache', $values, [
264
-			'storage',
265
-			'path_hash',
266
-		])
267
-		) {
268
-			return (int)$this->connection->lastInsertId('*PREFIX*filecache');
269
-		}
270
-
271
-		// The file was created in the mean time
272
-		if (($id = $this->getId($file)) > -1) {
273
-			$this->update($id, $data);
274
-			return $id;
275
-		} else {
276
-			throw new \RuntimeException('File entry could not be inserted with insertIfNotExist() but could also not be selected with getId() in order to perform an update. Please try again.');
277
-		}
278
-	}
279
-
280
-	/**
281
-	 * update the metadata of an existing file or folder in the cache
282
-	 *
283
-	 * @param int $id the fileid of the existing file or folder
284
-	 * @param array $data [$key => $value] the metadata to update, only the fields provided in the array will be updated, non-provided values will remain unchanged
285
-	 */
286
-	public function update($id, array $data) {
287
-
288
-		if (isset($data['path'])) {
289
-			// normalize path
290
-			$data['path'] = $this->normalize($data['path']);
291
-		}
292
-
293
-		if (isset($data['name'])) {
294
-			// normalize path
295
-			$data['name'] = $this->normalize($data['name']);
296
-		}
297
-
298
-		list($queryParts, $params) = $this->buildParts($data);
299
-		// duplicate $params because we need the parts twice in the SQL statement
300
-		// once for the SET part, once in the WHERE clause
301
-		$params = array_merge($params, $params);
302
-		$params[] = $id;
303
-
304
-		// don't update if the data we try to set is the same as the one in the record
305
-		// some databases (Postgres) don't like superfluous updates
306
-		$sql = 'UPDATE `*PREFIX*filecache` SET ' . implode(' = ?, ', $queryParts) . '=? ' .
307
-			'WHERE (' .
308
-			implode(' <> ? OR ', $queryParts) . ' <> ? OR ' .
309
-			implode(' IS NULL OR ', $queryParts) . ' IS NULL' .
310
-			') AND `fileid` = ? ';
311
-		$this->connection->executeQuery($sql, $params);
312
-
313
-	}
314
-
315
-	/**
316
-	 * extract query parts and params array from data array
317
-	 *
318
-	 * @param array $data
319
-	 * @return array [$queryParts, $params]
320
-	 *        $queryParts: string[], the (escaped) column names to be set in the query
321
-	 *        $params: mixed[], the new values for the columns, to be passed as params to the query
322
-	 */
323
-	protected function buildParts(array $data) {
324
-		$fields = array(
325
-			'path', 'parent', 'name', 'mimetype', 'size', 'mtime', 'storage_mtime', 'encrypted',
326
-			'etag', 'permissions', 'checksum');
327
-
328
-		$doNotCopyStorageMTime = false;
329
-		if (array_key_exists('mtime', $data) && $data['mtime'] === null) {
330
-			// this horrific magic tells it to not copy storage_mtime to mtime
331
-			unset($data['mtime']);
332
-			$doNotCopyStorageMTime = true;
333
-		}
334
-
335
-		$params = array();
336
-		$queryParts = array();
337
-		foreach ($data as $name => $value) {
338
-			if (array_search($name, $fields) !== false) {
339
-				if ($name === 'path') {
340
-					$params[] = md5($value);
341
-					$queryParts[] = '`path_hash`';
342
-				} elseif ($name === 'mimetype') {
343
-					$params[] = $this->mimetypeLoader->getId(substr($value, 0, strpos($value, '/')));
344
-					$queryParts[] = '`mimepart`';
345
-					$value = $this->mimetypeLoader->getId($value);
346
-				} elseif ($name === 'storage_mtime') {
347
-					if (!$doNotCopyStorageMTime && !isset($data['mtime'])) {
348
-						$params[] = $value;
349
-						$queryParts[] = '`mtime`';
350
-					}
351
-				} elseif ($name === 'encrypted') {
352
-					if(isset($data['encryptedVersion'])) {
353
-						$value = $data['encryptedVersion'];
354
-					} else {
355
-						// Boolean to integer conversion
356
-						$value = $value ? 1 : 0;
357
-					}
358
-				}
359
-				$params[] = $value;
360
-				$queryParts[] = '`' . $name . '`';
361
-			}
362
-		}
363
-		return array($queryParts, $params);
364
-	}
365
-
366
-	/**
367
-	 * get the file id for a file
368
-	 *
369
-	 * A file id is a numeric id for a file or folder that's unique within an owncloud instance which stays the same for the lifetime of a file
370
-	 *
371
-	 * File ids are easiest way for apps to store references to a file since unlike paths they are not affected by renames or sharing
372
-	 *
373
-	 * @param string $file
374
-	 * @return int
375
-	 */
376
-	public function getId($file) {
377
-		// normalize file
378
-		$file = $this->normalize($file);
379
-
380
-		$pathHash = md5($file);
381
-
382
-		$sql = 'SELECT `fileid` FROM `*PREFIX*filecache` WHERE `storage` = ? AND `path_hash` = ?';
383
-		$result = $this->connection->executeQuery($sql, array($this->getNumericStorageId(), $pathHash));
384
-		if ($row = $result->fetch()) {
385
-			return $row['fileid'];
386
-		} else {
387
-			return -1;
388
-		}
389
-	}
390
-
391
-	/**
392
-	 * get the id of the parent folder of a file
393
-	 *
394
-	 * @param string $file
395
-	 * @return int
396
-	 */
397
-	public function getParentId($file) {
398
-		if ($file === '') {
399
-			return -1;
400
-		} else {
401
-			$parent = $this->getParentPath($file);
402
-			return (int)$this->getId($parent);
403
-		}
404
-	}
405
-
406
-	private function getParentPath($path) {
407
-		$parent = dirname($path);
408
-		if ($parent === '.') {
409
-			$parent = '';
410
-		}
411
-		return $parent;
412
-	}
413
-
414
-	/**
415
-	 * check if a file is available in the cache
416
-	 *
417
-	 * @param string $file
418
-	 * @return bool
419
-	 */
420
-	public function inCache($file) {
421
-		return $this->getId($file) != -1;
422
-	}
423
-
424
-	/**
425
-	 * remove a file or folder from the cache
426
-	 *
427
-	 * when removing a folder from the cache all files and folders inside the folder will be removed as well
428
-	 *
429
-	 * @param string $file
430
-	 */
431
-	public function remove($file) {
432
-		$entry = $this->get($file);
433
-		$sql = 'DELETE FROM `*PREFIX*filecache` WHERE `fileid` = ?';
434
-		$this->connection->executeQuery($sql, array($entry['fileid']));
435
-		if ($entry['mimetype'] === 'httpd/unix-directory') {
436
-			$this->removeChildren($entry);
437
-		}
438
-	}
439
-
440
-	/**
441
-	 * Get all sub folders of a folder
442
-	 *
443
-	 * @param array $entry the cache entry of the folder to get the subfolders for
444
-	 * @return array[] the cache entries for the subfolders
445
-	 */
446
-	private function getSubFolders($entry) {
447
-		$children = $this->getFolderContentsById($entry['fileid']);
448
-		return array_filter($children, function ($child) {
449
-			return $child['mimetype'] === 'httpd/unix-directory';
450
-		});
451
-	}
452
-
453
-	/**
454
-	 * Recursively remove all children of a folder
455
-	 *
456
-	 * @param array $entry the cache entry of the folder to remove the children of
457
-	 * @throws \OC\DatabaseException
458
-	 */
459
-	private function removeChildren($entry) {
460
-		$subFolders = $this->getSubFolders($entry);
461
-		foreach ($subFolders as $folder) {
462
-			$this->removeChildren($folder);
463
-		}
464
-		$sql = 'DELETE FROM `*PREFIX*filecache` WHERE `parent` = ?';
465
-		$this->connection->executeQuery($sql, array($entry['fileid']));
466
-	}
467
-
468
-	/**
469
-	 * Move a file or folder in the cache
470
-	 *
471
-	 * @param string $source
472
-	 * @param string $target
473
-	 */
474
-	public function move($source, $target) {
475
-		$this->moveFromCache($this, $source, $target);
476
-	}
477
-
478
-	/**
479
-	 * Get the storage id and path needed for a move
480
-	 *
481
-	 * @param string $path
482
-	 * @return array [$storageId, $internalPath]
483
-	 */
484
-	protected function getMoveInfo($path) {
485
-		return [$this->getNumericStorageId(), $path];
486
-	}
487
-
488
-	/**
489
-	 * Move a file or folder in the cache
490
-	 *
491
-	 * @param \OCP\Files\Cache\ICache $sourceCache
492
-	 * @param string $sourcePath
493
-	 * @param string $targetPath
494
-	 * @throws \OC\DatabaseException
495
-	 */
496
-	public function moveFromCache(ICache $sourceCache, $sourcePath, $targetPath) {
497
-		if ($sourceCache instanceof Cache) {
498
-			// normalize source and target
499
-			$sourcePath = $this->normalize($sourcePath);
500
-			$targetPath = $this->normalize($targetPath);
501
-
502
-			$sourceData = $sourceCache->get($sourcePath);
503
-			$sourceId = $sourceData['fileid'];
504
-			$newParentId = $this->getParentId($targetPath);
505
-
506
-			list($sourceStorageId, $sourcePath) = $sourceCache->getMoveInfo($sourcePath);
507
-			list($targetStorageId, $targetPath) = $this->getMoveInfo($targetPath);
508
-
509
-			// sql for final update
510
-			$moveSql = 'UPDATE `*PREFIX*filecache` SET `storage` =  ?, `path` = ?, `path_hash` = ?, `name` = ?, `parent` =? WHERE `fileid` = ?';
511
-
512
-			if ($sourceData['mimetype'] === 'httpd/unix-directory') {
513
-				//find all child entries
514
-				$sql = 'SELECT `path`, `fileid` FROM `*PREFIX*filecache` WHERE `storage` = ? AND `path` LIKE ?';
515
-				$result = $this->connection->executeQuery($sql, [$sourceStorageId, $this->connection->escapeLikeParameter($sourcePath) . '/%']);
516
-				$childEntries = $result->fetchAll();
517
-				$sourceLength = strlen($sourcePath);
518
-				$this->connection->beginTransaction();
519
-				$query = $this->connection->prepare('UPDATE `*PREFIX*filecache` SET `storage` = ?, `path` = ?, `path_hash` = ? WHERE `fileid` = ?');
520
-
521
-				foreach ($childEntries as $child) {
522
-					$newTargetPath = $targetPath . substr($child['path'], $sourceLength);
523
-					$query->execute([$targetStorageId, $newTargetPath, md5($newTargetPath), $child['fileid']]);
524
-				}
525
-				$this->connection->executeQuery($moveSql, [$targetStorageId, $targetPath, md5($targetPath), basename($targetPath), $newParentId, $sourceId]);
526
-				$this->connection->commit();
527
-			} else {
528
-				$this->connection->executeQuery($moveSql, [$targetStorageId, $targetPath, md5($targetPath), basename($targetPath), $newParentId, $sourceId]);
529
-			}
530
-		} else {
531
-			$this->moveFromCacheFallback($sourceCache, $sourcePath, $targetPath);
532
-		}
533
-	}
534
-
535
-	/**
536
-	 * remove all entries for files that are stored on the storage from the cache
537
-	 */
538
-	public function clear() {
539
-		$sql = 'DELETE FROM `*PREFIX*filecache` WHERE `storage` = ?';
540
-		$this->connection->executeQuery($sql, array($this->getNumericStorageId()));
541
-
542
-		$sql = 'DELETE FROM `*PREFIX*storages` WHERE `id` = ?';
543
-		$this->connection->executeQuery($sql, array($this->storageId));
544
-	}
545
-
546
-	/**
547
-	 * Get the scan status of a file
548
-	 *
549
-	 * - Cache::NOT_FOUND: File is not in the cache
550
-	 * - Cache::PARTIAL: File is not stored in the cache but some incomplete data is known
551
-	 * - Cache::SHALLOW: The folder and it's direct children are in the cache but not all sub folders are fully scanned
552
-	 * - Cache::COMPLETE: The file or folder, with all it's children) are fully scanned
553
-	 *
554
-	 * @param string $file
555
-	 *
556
-	 * @return int Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
557
-	 */
558
-	public function getStatus($file) {
559
-		// normalize file
560
-		$file = $this->normalize($file);
561
-
562
-		$pathHash = md5($file);
563
-		$sql = 'SELECT `size` FROM `*PREFIX*filecache` WHERE `storage` = ? AND `path_hash` = ?';
564
-		$result = $this->connection->executeQuery($sql, array($this->getNumericStorageId(), $pathHash));
565
-		if ($row = $result->fetch()) {
566
-			if ((int)$row['size'] === -1) {
567
-				return self::SHALLOW;
568
-			} else {
569
-				return self::COMPLETE;
570
-			}
571
-		} else {
572
-			if (isset($this->partial[$file])) {
573
-				return self::PARTIAL;
574
-			} else {
575
-				return self::NOT_FOUND;
576
-			}
577
-		}
578
-	}
579
-
580
-	/**
581
-	 * search for files matching $pattern
582
-	 *
583
-	 * @param string $pattern the search pattern using SQL search syntax (e.g. '%searchstring%')
584
-	 * @return ICacheEntry[] an array of cache entries where the name matches the search pattern
585
-	 */
586
-	public function search($pattern) {
587
-		// normalize pattern
588
-		$pattern = $this->normalize($pattern);
589
-
590
-
591
-		$sql = '
186
+            $result = $this->connection->executeQuery($sql, [$fileId]);
187
+            $files = $result->fetchAll();
188
+            foreach ($files as &$file) {
189
+                $file['mimetype'] = $this->mimetypeLoader->getMimetypeById($file['mimetype']);
190
+                $file['mimepart'] = $this->mimetypeLoader->getMimetypeById($file['mimepart']);
191
+                if ($file['storage_mtime'] == 0) {
192
+                    $file['storage_mtime'] = $file['mtime'];
193
+                }
194
+                $file['permissions'] = (int)$file['permissions'];
195
+                $file['mtime'] = (int)$file['mtime'];
196
+                $file['storage_mtime'] = (int)$file['storage_mtime'];
197
+                $file['size'] = 0 + $file['size'];
198
+            }
199
+            return array_map(function (array $data) {
200
+                return new CacheEntry($data);
201
+            }, $files);
202
+        } else {
203
+            return array();
204
+        }
205
+    }
206
+
207
+    /**
208
+     * insert or update meta data for a file or folder
209
+     *
210
+     * @param string $file
211
+     * @param array $data
212
+     *
213
+     * @return int file id
214
+     * @throws \RuntimeException
215
+     */
216
+    public function put($file, array $data) {
217
+        if (($id = $this->getId($file)) > -1) {
218
+            $this->update($id, $data);
219
+            return $id;
220
+        } else {
221
+            return $this->insert($file, $data);
222
+        }
223
+    }
224
+
225
+    /**
226
+     * insert meta data for a new file or folder
227
+     *
228
+     * @param string $file
229
+     * @param array $data
230
+     *
231
+     * @return int file id
232
+     * @throws \RuntimeException
233
+     */
234
+    public function insert($file, array $data) {
235
+        // normalize file
236
+        $file = $this->normalize($file);
237
+
238
+        if (isset($this->partial[$file])) { //add any saved partial data
239
+            $data = array_merge($this->partial[$file], $data);
240
+            unset($this->partial[$file]);
241
+        }
242
+
243
+        $requiredFields = array('size', 'mtime', 'mimetype');
244
+        foreach ($requiredFields as $field) {
245
+            if (!isset($data[$field])) { //data not complete save as partial and return
246
+                $this->partial[$file] = $data;
247
+                return -1;
248
+            }
249
+        }
250
+
251
+        $data['path'] = $file;
252
+        $data['parent'] = $this->getParentId($file);
253
+        $data['name'] = \OC_Util::basename($file);
254
+
255
+        list($queryParts, $params) = $this->buildParts($data);
256
+        $queryParts[] = '`storage`';
257
+        $params[] = $this->getNumericStorageId();
258
+
259
+        $queryParts = array_map(function ($item) {
260
+            return trim($item, "`");
261
+        }, $queryParts);
262
+        $values = array_combine($queryParts, $params);
263
+        if (\OC::$server->getDatabaseConnection()->insertIfNotExist('*PREFIX*filecache', $values, [
264
+            'storage',
265
+            'path_hash',
266
+        ])
267
+        ) {
268
+            return (int)$this->connection->lastInsertId('*PREFIX*filecache');
269
+        }
270
+
271
+        // The file was created in the mean time
272
+        if (($id = $this->getId($file)) > -1) {
273
+            $this->update($id, $data);
274
+            return $id;
275
+        } else {
276
+            throw new \RuntimeException('File entry could not be inserted with insertIfNotExist() but could also not be selected with getId() in order to perform an update. Please try again.');
277
+        }
278
+    }
279
+
280
+    /**
281
+     * update the metadata of an existing file or folder in the cache
282
+     *
283
+     * @param int $id the fileid of the existing file or folder
284
+     * @param array $data [$key => $value] the metadata to update, only the fields provided in the array will be updated, non-provided values will remain unchanged
285
+     */
286
+    public function update($id, array $data) {
287
+
288
+        if (isset($data['path'])) {
289
+            // normalize path
290
+            $data['path'] = $this->normalize($data['path']);
291
+        }
292
+
293
+        if (isset($data['name'])) {
294
+            // normalize path
295
+            $data['name'] = $this->normalize($data['name']);
296
+        }
297
+
298
+        list($queryParts, $params) = $this->buildParts($data);
299
+        // duplicate $params because we need the parts twice in the SQL statement
300
+        // once for the SET part, once in the WHERE clause
301
+        $params = array_merge($params, $params);
302
+        $params[] = $id;
303
+
304
+        // don't update if the data we try to set is the same as the one in the record
305
+        // some databases (Postgres) don't like superfluous updates
306
+        $sql = 'UPDATE `*PREFIX*filecache` SET ' . implode(' = ?, ', $queryParts) . '=? ' .
307
+            'WHERE (' .
308
+            implode(' <> ? OR ', $queryParts) . ' <> ? OR ' .
309
+            implode(' IS NULL OR ', $queryParts) . ' IS NULL' .
310
+            ') AND `fileid` = ? ';
311
+        $this->connection->executeQuery($sql, $params);
312
+
313
+    }
314
+
315
+    /**
316
+     * extract query parts and params array from data array
317
+     *
318
+     * @param array $data
319
+     * @return array [$queryParts, $params]
320
+     *        $queryParts: string[], the (escaped) column names to be set in the query
321
+     *        $params: mixed[], the new values for the columns, to be passed as params to the query
322
+     */
323
+    protected function buildParts(array $data) {
324
+        $fields = array(
325
+            'path', 'parent', 'name', 'mimetype', 'size', 'mtime', 'storage_mtime', 'encrypted',
326
+            'etag', 'permissions', 'checksum');
327
+
328
+        $doNotCopyStorageMTime = false;
329
+        if (array_key_exists('mtime', $data) && $data['mtime'] === null) {
330
+            // this horrific magic tells it to not copy storage_mtime to mtime
331
+            unset($data['mtime']);
332
+            $doNotCopyStorageMTime = true;
333
+        }
334
+
335
+        $params = array();
336
+        $queryParts = array();
337
+        foreach ($data as $name => $value) {
338
+            if (array_search($name, $fields) !== false) {
339
+                if ($name === 'path') {
340
+                    $params[] = md5($value);
341
+                    $queryParts[] = '`path_hash`';
342
+                } elseif ($name === 'mimetype') {
343
+                    $params[] = $this->mimetypeLoader->getId(substr($value, 0, strpos($value, '/')));
344
+                    $queryParts[] = '`mimepart`';
345
+                    $value = $this->mimetypeLoader->getId($value);
346
+                } elseif ($name === 'storage_mtime') {
347
+                    if (!$doNotCopyStorageMTime && !isset($data['mtime'])) {
348
+                        $params[] = $value;
349
+                        $queryParts[] = '`mtime`';
350
+                    }
351
+                } elseif ($name === 'encrypted') {
352
+                    if(isset($data['encryptedVersion'])) {
353
+                        $value = $data['encryptedVersion'];
354
+                    } else {
355
+                        // Boolean to integer conversion
356
+                        $value = $value ? 1 : 0;
357
+                    }
358
+                }
359
+                $params[] = $value;
360
+                $queryParts[] = '`' . $name . '`';
361
+            }
362
+        }
363
+        return array($queryParts, $params);
364
+    }
365
+
366
+    /**
367
+     * get the file id for a file
368
+     *
369
+     * A file id is a numeric id for a file or folder that's unique within an owncloud instance which stays the same for the lifetime of a file
370
+     *
371
+     * File ids are easiest way for apps to store references to a file since unlike paths they are not affected by renames or sharing
372
+     *
373
+     * @param string $file
374
+     * @return int
375
+     */
376
+    public function getId($file) {
377
+        // normalize file
378
+        $file = $this->normalize($file);
379
+
380
+        $pathHash = md5($file);
381
+
382
+        $sql = 'SELECT `fileid` FROM `*PREFIX*filecache` WHERE `storage` = ? AND `path_hash` = ?';
383
+        $result = $this->connection->executeQuery($sql, array($this->getNumericStorageId(), $pathHash));
384
+        if ($row = $result->fetch()) {
385
+            return $row['fileid'];
386
+        } else {
387
+            return -1;
388
+        }
389
+    }
390
+
391
+    /**
392
+     * get the id of the parent folder of a file
393
+     *
394
+     * @param string $file
395
+     * @return int
396
+     */
397
+    public function getParentId($file) {
398
+        if ($file === '') {
399
+            return -1;
400
+        } else {
401
+            $parent = $this->getParentPath($file);
402
+            return (int)$this->getId($parent);
403
+        }
404
+    }
405
+
406
+    private function getParentPath($path) {
407
+        $parent = dirname($path);
408
+        if ($parent === '.') {
409
+            $parent = '';
410
+        }
411
+        return $parent;
412
+    }
413
+
414
+    /**
415
+     * check if a file is available in the cache
416
+     *
417
+     * @param string $file
418
+     * @return bool
419
+     */
420
+    public function inCache($file) {
421
+        return $this->getId($file) != -1;
422
+    }
423
+
424
+    /**
425
+     * remove a file or folder from the cache
426
+     *
427
+     * when removing a folder from the cache all files and folders inside the folder will be removed as well
428
+     *
429
+     * @param string $file
430
+     */
431
+    public function remove($file) {
432
+        $entry = $this->get($file);
433
+        $sql = 'DELETE FROM `*PREFIX*filecache` WHERE `fileid` = ?';
434
+        $this->connection->executeQuery($sql, array($entry['fileid']));
435
+        if ($entry['mimetype'] === 'httpd/unix-directory') {
436
+            $this->removeChildren($entry);
437
+        }
438
+    }
439
+
440
+    /**
441
+     * Get all sub folders of a folder
442
+     *
443
+     * @param array $entry the cache entry of the folder to get the subfolders for
444
+     * @return array[] the cache entries for the subfolders
445
+     */
446
+    private function getSubFolders($entry) {
447
+        $children = $this->getFolderContentsById($entry['fileid']);
448
+        return array_filter($children, function ($child) {
449
+            return $child['mimetype'] === 'httpd/unix-directory';
450
+        });
451
+    }
452
+
453
+    /**
454
+     * Recursively remove all children of a folder
455
+     *
456
+     * @param array $entry the cache entry of the folder to remove the children of
457
+     * @throws \OC\DatabaseException
458
+     */
459
+    private function removeChildren($entry) {
460
+        $subFolders = $this->getSubFolders($entry);
461
+        foreach ($subFolders as $folder) {
462
+            $this->removeChildren($folder);
463
+        }
464
+        $sql = 'DELETE FROM `*PREFIX*filecache` WHERE `parent` = ?';
465
+        $this->connection->executeQuery($sql, array($entry['fileid']));
466
+    }
467
+
468
+    /**
469
+     * Move a file or folder in the cache
470
+     *
471
+     * @param string $source
472
+     * @param string $target
473
+     */
474
+    public function move($source, $target) {
475
+        $this->moveFromCache($this, $source, $target);
476
+    }
477
+
478
+    /**
479
+     * Get the storage id and path needed for a move
480
+     *
481
+     * @param string $path
482
+     * @return array [$storageId, $internalPath]
483
+     */
484
+    protected function getMoveInfo($path) {
485
+        return [$this->getNumericStorageId(), $path];
486
+    }
487
+
488
+    /**
489
+     * Move a file or folder in the cache
490
+     *
491
+     * @param \OCP\Files\Cache\ICache $sourceCache
492
+     * @param string $sourcePath
493
+     * @param string $targetPath
494
+     * @throws \OC\DatabaseException
495
+     */
496
+    public function moveFromCache(ICache $sourceCache, $sourcePath, $targetPath) {
497
+        if ($sourceCache instanceof Cache) {
498
+            // normalize source and target
499
+            $sourcePath = $this->normalize($sourcePath);
500
+            $targetPath = $this->normalize($targetPath);
501
+
502
+            $sourceData = $sourceCache->get($sourcePath);
503
+            $sourceId = $sourceData['fileid'];
504
+            $newParentId = $this->getParentId($targetPath);
505
+
506
+            list($sourceStorageId, $sourcePath) = $sourceCache->getMoveInfo($sourcePath);
507
+            list($targetStorageId, $targetPath) = $this->getMoveInfo($targetPath);
508
+
509
+            // sql for final update
510
+            $moveSql = 'UPDATE `*PREFIX*filecache` SET `storage` =  ?, `path` = ?, `path_hash` = ?, `name` = ?, `parent` =? WHERE `fileid` = ?';
511
+
512
+            if ($sourceData['mimetype'] === 'httpd/unix-directory') {
513
+                //find all child entries
514
+                $sql = 'SELECT `path`, `fileid` FROM `*PREFIX*filecache` WHERE `storage` = ? AND `path` LIKE ?';
515
+                $result = $this->connection->executeQuery($sql, [$sourceStorageId, $this->connection->escapeLikeParameter($sourcePath) . '/%']);
516
+                $childEntries = $result->fetchAll();
517
+                $sourceLength = strlen($sourcePath);
518
+                $this->connection->beginTransaction();
519
+                $query = $this->connection->prepare('UPDATE `*PREFIX*filecache` SET `storage` = ?, `path` = ?, `path_hash` = ? WHERE `fileid` = ?');
520
+
521
+                foreach ($childEntries as $child) {
522
+                    $newTargetPath = $targetPath . substr($child['path'], $sourceLength);
523
+                    $query->execute([$targetStorageId, $newTargetPath, md5($newTargetPath), $child['fileid']]);
524
+                }
525
+                $this->connection->executeQuery($moveSql, [$targetStorageId, $targetPath, md5($targetPath), basename($targetPath), $newParentId, $sourceId]);
526
+                $this->connection->commit();
527
+            } else {
528
+                $this->connection->executeQuery($moveSql, [$targetStorageId, $targetPath, md5($targetPath), basename($targetPath), $newParentId, $sourceId]);
529
+            }
530
+        } else {
531
+            $this->moveFromCacheFallback($sourceCache, $sourcePath, $targetPath);
532
+        }
533
+    }
534
+
535
+    /**
536
+     * remove all entries for files that are stored on the storage from the cache
537
+     */
538
+    public function clear() {
539
+        $sql = 'DELETE FROM `*PREFIX*filecache` WHERE `storage` = ?';
540
+        $this->connection->executeQuery($sql, array($this->getNumericStorageId()));
541
+
542
+        $sql = 'DELETE FROM `*PREFIX*storages` WHERE `id` = ?';
543
+        $this->connection->executeQuery($sql, array($this->storageId));
544
+    }
545
+
546
+    /**
547
+     * Get the scan status of a file
548
+     *
549
+     * - Cache::NOT_FOUND: File is not in the cache
550
+     * - Cache::PARTIAL: File is not stored in the cache but some incomplete data is known
551
+     * - Cache::SHALLOW: The folder and it's direct children are in the cache but not all sub folders are fully scanned
552
+     * - Cache::COMPLETE: The file or folder, with all it's children) are fully scanned
553
+     *
554
+     * @param string $file
555
+     *
556
+     * @return int Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
557
+     */
558
+    public function getStatus($file) {
559
+        // normalize file
560
+        $file = $this->normalize($file);
561
+
562
+        $pathHash = md5($file);
563
+        $sql = 'SELECT `size` FROM `*PREFIX*filecache` WHERE `storage` = ? AND `path_hash` = ?';
564
+        $result = $this->connection->executeQuery($sql, array($this->getNumericStorageId(), $pathHash));
565
+        if ($row = $result->fetch()) {
566
+            if ((int)$row['size'] === -1) {
567
+                return self::SHALLOW;
568
+            } else {
569
+                return self::COMPLETE;
570
+            }
571
+        } else {
572
+            if (isset($this->partial[$file])) {
573
+                return self::PARTIAL;
574
+            } else {
575
+                return self::NOT_FOUND;
576
+            }
577
+        }
578
+    }
579
+
580
+    /**
581
+     * search for files matching $pattern
582
+     *
583
+     * @param string $pattern the search pattern using SQL search syntax (e.g. '%searchstring%')
584
+     * @return ICacheEntry[] an array of cache entries where the name matches the search pattern
585
+     */
586
+    public function search($pattern) {
587
+        // normalize pattern
588
+        $pattern = $this->normalize($pattern);
589
+
590
+
591
+        $sql = '
592 592
 			SELECT `fileid`, `storage`, `path`, `parent`, `name`,
593 593
 				`mimetype`, `mimepart`, `size`, `mtime`, `encrypted`,
594 594
 				`etag`, `permissions`, `checksum`
595 595
 			FROM `*PREFIX*filecache`
596 596
 			WHERE `storage` = ? AND `name` ILIKE ?';
597
-		$result = $this->connection->executeQuery($sql,
598
-			[$this->getNumericStorageId(), $pattern]
599
-		);
600
-
601
-		$files = [];
602
-		while ($row = $result->fetch()) {
603
-			$row['mimetype'] = $this->mimetypeLoader->getMimetypeById($row['mimetype']);
604
-			$row['mimepart'] = $this->mimetypeLoader->getMimetypeById($row['mimepart']);
605
-			$files[] = $row;
606
-		}
607
-		return array_map(function(array $data) {
608
-			return new CacheEntry($data);
609
-		}, $files);
610
-	}
611
-
612
-	/**
613
-	 * search for files by mimetype
614
-	 *
615
-	 * @param string $mimetype either a full mimetype to search ('text/plain') or only the first part of a mimetype ('image')
616
-	 *        where it will search for all mimetypes in the group ('image/*')
617
-	 * @return ICacheEntry[] an array of cache entries where the mimetype matches the search
618
-	 */
619
-	public function searchByMime($mimetype) {
620
-		if (strpos($mimetype, '/')) {
621
-			$where = '`mimetype` = ?';
622
-		} else {
623
-			$where = '`mimepart` = ?';
624
-		}
625
-		$sql = 'SELECT `fileid`, `storage`, `path`, `parent`, `name`, `mimetype`, `mimepart`, `size`, `mtime`, `encrypted`, `etag`, `permissions`, `checksum`
597
+        $result = $this->connection->executeQuery($sql,
598
+            [$this->getNumericStorageId(), $pattern]
599
+        );
600
+
601
+        $files = [];
602
+        while ($row = $result->fetch()) {
603
+            $row['mimetype'] = $this->mimetypeLoader->getMimetypeById($row['mimetype']);
604
+            $row['mimepart'] = $this->mimetypeLoader->getMimetypeById($row['mimepart']);
605
+            $files[] = $row;
606
+        }
607
+        return array_map(function(array $data) {
608
+            return new CacheEntry($data);
609
+        }, $files);
610
+    }
611
+
612
+    /**
613
+     * search for files by mimetype
614
+     *
615
+     * @param string $mimetype either a full mimetype to search ('text/plain') or only the first part of a mimetype ('image')
616
+     *        where it will search for all mimetypes in the group ('image/*')
617
+     * @return ICacheEntry[] an array of cache entries where the mimetype matches the search
618
+     */
619
+    public function searchByMime($mimetype) {
620
+        if (strpos($mimetype, '/')) {
621
+            $where = '`mimetype` = ?';
622
+        } else {
623
+            $where = '`mimepart` = ?';
624
+        }
625
+        $sql = 'SELECT `fileid`, `storage`, `path`, `parent`, `name`, `mimetype`, `mimepart`, `size`, `mtime`, `encrypted`, `etag`, `permissions`, `checksum`
626 626
 				FROM `*PREFIX*filecache` WHERE ' . $where . ' AND `storage` = ?';
627
-		$mimetype = $this->mimetypeLoader->getId($mimetype);
628
-		$result = $this->connection->executeQuery($sql, array($mimetype, $this->getNumericStorageId()));
629
-		$files = array();
630
-		while ($row = $result->fetch()) {
631
-			$row['mimetype'] = $this->mimetypeLoader->getMimetypeById($row['mimetype']);
632
-			$row['mimepart'] = $this->mimetypeLoader->getMimetypeById($row['mimepart']);
633
-			$files[] = $row;
634
-		}
635
-		return array_map(function (array $data) {
636
-			return new CacheEntry($data);
637
-		}, $files);
638
-	}
639
-
640
-	/**
641
-	 * Search for files by tag of a given users.
642
-	 *
643
-	 * Note that every user can tag files differently.
644
-	 *
645
-	 * @param string|int $tag name or tag id
646
-	 * @param string $userId owner of the tags
647
-	 * @return ICacheEntry[] file data
648
-	 */
649
-	public function searchByTag($tag, $userId) {
650
-		$sql = 'SELECT `fileid`, `storage`, `path`, `parent`, `name`, ' .
651
-			'`mimetype`, `mimepart`, `size`, `mtime`, ' .
652
-			'`encrypted`, `etag`, `permissions`, `checksum` ' .
653
-			'FROM `*PREFIX*filecache` `file`, ' .
654
-			'`*PREFIX*vcategory_to_object` `tagmap`, ' .
655
-			'`*PREFIX*vcategory` `tag` ' .
656
-			// JOIN filecache to vcategory_to_object
657
-			'WHERE `file`.`fileid` = `tagmap`.`objid` ' .
658
-			// JOIN vcategory_to_object to vcategory
659
-			'AND `tagmap`.`type` = `tag`.`type` ' .
660
-			'AND `tagmap`.`categoryid` = `tag`.`id` ' .
661
-			// conditions
662
-			'AND `file`.`storage` = ? ' .
663
-			'AND `tag`.`type` = \'files\' ' .
664
-			'AND `tag`.`uid` = ? ';
665
-		if (is_int($tag)) {
666
-			$sql .= 'AND `tag`.`id` = ? ';
667
-		} else {
668
-			$sql .= 'AND `tag`.`category` = ? ';
669
-		}
670
-		$result = $this->connection->executeQuery(
671
-			$sql,
672
-			[
673
-				$this->getNumericStorageId(),
674
-				$userId,
675
-				$tag
676
-			]
677
-		);
678
-		$files = array();
679
-		while ($row = $result->fetch()) {
680
-			$files[] = $row;
681
-		}
682
-		return array_map(function (array $data) {
683
-			return new CacheEntry($data);
684
-		}, $files);
685
-	}
686
-
687
-	/**
688
-	 * Re-calculate the folder size and the size of all parent folders
689
-	 *
690
-	 * @param string|boolean $path
691
-	 * @param array $data (optional) meta data of the folder
692
-	 */
693
-	public function correctFolderSize($path, $data = null) {
694
-		$this->calculateFolderSize($path, $data);
695
-		if ($path !== '') {
696
-			$parent = dirname($path);
697
-			if ($parent === '.' or $parent === '/') {
698
-				$parent = '';
699
-			}
700
-			$this->correctFolderSize($parent);
701
-		}
702
-	}
703
-
704
-	/**
705
-	 * calculate the size of a folder and set it in the cache
706
-	 *
707
-	 * @param string $path
708
-	 * @param array $entry (optional) meta data of the folder
709
-	 * @return int
710
-	 */
711
-	public function calculateFolderSize($path, $entry = null) {
712
-		$totalSize = 0;
713
-		if (is_null($entry) or !isset($entry['fileid'])) {
714
-			$entry = $this->get($path);
715
-		}
716
-		if (isset($entry['mimetype']) && $entry['mimetype'] === 'httpd/unix-directory') {
717
-			$id = $entry['fileid'];
718
-			$sql = 'SELECT SUM(`size`) AS f1, MIN(`size`) AS f2 ' .
719
-				'FROM `*PREFIX*filecache` ' .
720
-				'WHERE `parent` = ? AND `storage` = ?';
721
-			$result = $this->connection->executeQuery($sql, array($id, $this->getNumericStorageId()));
722
-			if ($row = $result->fetch()) {
723
-				$result->closeCursor();
724
-				list($sum, $min) = array_values($row);
725
-				$sum = 0 + $sum;
726
-				$min = 0 + $min;
727
-				if ($min === -1) {
728
-					$totalSize = $min;
729
-				} else {
730
-					$totalSize = $sum;
731
-				}
732
-				$update = array();
733
-				if ($entry['size'] !== $totalSize) {
734
-					$update['size'] = $totalSize;
735
-				}
736
-				if (count($update) > 0) {
737
-					$this->update($id, $update);
738
-				}
739
-			} else {
740
-				$result->closeCursor();
741
-			}
742
-		}
743
-		return $totalSize;
744
-	}
745
-
746
-	/**
747
-	 * get all file ids on the files on the storage
748
-	 *
749
-	 * @return int[]
750
-	 */
751
-	public function getAll() {
752
-		$sql = 'SELECT `fileid` FROM `*PREFIX*filecache` WHERE `storage` = ?';
753
-		$result = $this->connection->executeQuery($sql, array($this->getNumericStorageId()));
754
-		$ids = array();
755
-		while ($row = $result->fetch()) {
756
-			$ids[] = $row['fileid'];
757
-		}
758
-		return $ids;
759
-	}
760
-
761
-	/**
762
-	 * find a folder in the cache which has not been fully scanned
763
-	 *
764
-	 * If multiple incomplete folders are in the cache, the one with the highest id will be returned,
765
-	 * use the one with the highest id gives the best result with the background scanner, since that is most
766
-	 * likely the folder where we stopped scanning previously
767
-	 *
768
-	 * @return string|bool the path of the folder or false when no folder matched
769
-	 */
770
-	public function getIncomplete() {
771
-		$query = $this->connection->prepare('SELECT `path` FROM `*PREFIX*filecache`'
772
-			. ' WHERE `storage` = ? AND `size` = -1 ORDER BY `fileid` DESC', 1);
773
-		$query->execute([$this->getNumericStorageId()]);
774
-		if ($row = $query->fetch()) {
775
-			return $row['path'];
776
-		} else {
777
-			return false;
778
-		}
779
-	}
780
-
781
-	/**
782
-	 * get the path of a file on this storage by it's file id
783
-	 *
784
-	 * @param int $id the file id of the file or folder to search
785
-	 * @return string|null the path of the file (relative to the storage) or null if a file with the given id does not exists within this cache
786
-	 */
787
-	public function getPathById($id) {
788
-		$sql = 'SELECT `path` FROM `*PREFIX*filecache` WHERE `fileid` = ? AND `storage` = ?';
789
-		$result = $this->connection->executeQuery($sql, array($id, $this->getNumericStorageId()));
790
-		if ($row = $result->fetch()) {
791
-			// Oracle stores empty strings as null...
792
-			if ($row['path'] === null) {
793
-				return '';
794
-			}
795
-			return $row['path'];
796
-		} else {
797
-			return null;
798
-		}
799
-	}
800
-
801
-	/**
802
-	 * get the storage id of the storage for a file and the internal path of the file
803
-	 * unlike getPathById this does not limit the search to files on this storage and
804
-	 * instead does a global search in the cache table
805
-	 *
806
-	 * @param int $id
807
-	 * @deprecated use getPathById() instead
808
-	 * @return array first element holding the storage id, second the path
809
-	 */
810
-	static public function getById($id) {
811
-		$connection = \OC::$server->getDatabaseConnection();
812
-		$sql = 'SELECT `storage`, `path` FROM `*PREFIX*filecache` WHERE `fileid` = ?';
813
-		$result = $connection->executeQuery($sql, array($id));
814
-		if ($row = $result->fetch()) {
815
-			$numericId = $row['storage'];
816
-			$path = $row['path'];
817
-		} else {
818
-			return null;
819
-		}
820
-
821
-		if ($id = Storage::getStorageId($numericId)) {
822
-			return array($id, $path);
823
-		} else {
824
-			return null;
825
-		}
826
-	}
827
-
828
-	/**
829
-	 * normalize the given path
830
-	 *
831
-	 * @param string $path
832
-	 * @return string
833
-	 */
834
-	public function normalize($path) {
835
-
836
-		return trim(\OC_Util::normalizeUnicode($path), '/');
837
-	}
627
+        $mimetype = $this->mimetypeLoader->getId($mimetype);
628
+        $result = $this->connection->executeQuery($sql, array($mimetype, $this->getNumericStorageId()));
629
+        $files = array();
630
+        while ($row = $result->fetch()) {
631
+            $row['mimetype'] = $this->mimetypeLoader->getMimetypeById($row['mimetype']);
632
+            $row['mimepart'] = $this->mimetypeLoader->getMimetypeById($row['mimepart']);
633
+            $files[] = $row;
634
+        }
635
+        return array_map(function (array $data) {
636
+            return new CacheEntry($data);
637
+        }, $files);
638
+    }
639
+
640
+    /**
641
+     * Search for files by tag of a given users.
642
+     *
643
+     * Note that every user can tag files differently.
644
+     *
645
+     * @param string|int $tag name or tag id
646
+     * @param string $userId owner of the tags
647
+     * @return ICacheEntry[] file data
648
+     */
649
+    public function searchByTag($tag, $userId) {
650
+        $sql = 'SELECT `fileid`, `storage`, `path`, `parent`, `name`, ' .
651
+            '`mimetype`, `mimepart`, `size`, `mtime`, ' .
652
+            '`encrypted`, `etag`, `permissions`, `checksum` ' .
653
+            'FROM `*PREFIX*filecache` `file`, ' .
654
+            '`*PREFIX*vcategory_to_object` `tagmap`, ' .
655
+            '`*PREFIX*vcategory` `tag` ' .
656
+            // JOIN filecache to vcategory_to_object
657
+            'WHERE `file`.`fileid` = `tagmap`.`objid` ' .
658
+            // JOIN vcategory_to_object to vcategory
659
+            'AND `tagmap`.`type` = `tag`.`type` ' .
660
+            'AND `tagmap`.`categoryid` = `tag`.`id` ' .
661
+            // conditions
662
+            'AND `file`.`storage` = ? ' .
663
+            'AND `tag`.`type` = \'files\' ' .
664
+            'AND `tag`.`uid` = ? ';
665
+        if (is_int($tag)) {
666
+            $sql .= 'AND `tag`.`id` = ? ';
667
+        } else {
668
+            $sql .= 'AND `tag`.`category` = ? ';
669
+        }
670
+        $result = $this->connection->executeQuery(
671
+            $sql,
672
+            [
673
+                $this->getNumericStorageId(),
674
+                $userId,
675
+                $tag
676
+            ]
677
+        );
678
+        $files = array();
679
+        while ($row = $result->fetch()) {
680
+            $files[] = $row;
681
+        }
682
+        return array_map(function (array $data) {
683
+            return new CacheEntry($data);
684
+        }, $files);
685
+    }
686
+
687
+    /**
688
+     * Re-calculate the folder size and the size of all parent folders
689
+     *
690
+     * @param string|boolean $path
691
+     * @param array $data (optional) meta data of the folder
692
+     */
693
+    public function correctFolderSize($path, $data = null) {
694
+        $this->calculateFolderSize($path, $data);
695
+        if ($path !== '') {
696
+            $parent = dirname($path);
697
+            if ($parent === '.' or $parent === '/') {
698
+                $parent = '';
699
+            }
700
+            $this->correctFolderSize($parent);
701
+        }
702
+    }
703
+
704
+    /**
705
+     * calculate the size of a folder and set it in the cache
706
+     *
707
+     * @param string $path
708
+     * @param array $entry (optional) meta data of the folder
709
+     * @return int
710
+     */
711
+    public function calculateFolderSize($path, $entry = null) {
712
+        $totalSize = 0;
713
+        if (is_null($entry) or !isset($entry['fileid'])) {
714
+            $entry = $this->get($path);
715
+        }
716
+        if (isset($entry['mimetype']) && $entry['mimetype'] === 'httpd/unix-directory') {
717
+            $id = $entry['fileid'];
718
+            $sql = 'SELECT SUM(`size`) AS f1, MIN(`size`) AS f2 ' .
719
+                'FROM `*PREFIX*filecache` ' .
720
+                'WHERE `parent` = ? AND `storage` = ?';
721
+            $result = $this->connection->executeQuery($sql, array($id, $this->getNumericStorageId()));
722
+            if ($row = $result->fetch()) {
723
+                $result->closeCursor();
724
+                list($sum, $min) = array_values($row);
725
+                $sum = 0 + $sum;
726
+                $min = 0 + $min;
727
+                if ($min === -1) {
728
+                    $totalSize = $min;
729
+                } else {
730
+                    $totalSize = $sum;
731
+                }
732
+                $update = array();
733
+                if ($entry['size'] !== $totalSize) {
734
+                    $update['size'] = $totalSize;
735
+                }
736
+                if (count($update) > 0) {
737
+                    $this->update($id, $update);
738
+                }
739
+            } else {
740
+                $result->closeCursor();
741
+            }
742
+        }
743
+        return $totalSize;
744
+    }
745
+
746
+    /**
747
+     * get all file ids on the files on the storage
748
+     *
749
+     * @return int[]
750
+     */
751
+    public function getAll() {
752
+        $sql = 'SELECT `fileid` FROM `*PREFIX*filecache` WHERE `storage` = ?';
753
+        $result = $this->connection->executeQuery($sql, array($this->getNumericStorageId()));
754
+        $ids = array();
755
+        while ($row = $result->fetch()) {
756
+            $ids[] = $row['fileid'];
757
+        }
758
+        return $ids;
759
+    }
760
+
761
+    /**
762
+     * find a folder in the cache which has not been fully scanned
763
+     *
764
+     * If multiple incomplete folders are in the cache, the one with the highest id will be returned,
765
+     * use the one with the highest id gives the best result with the background scanner, since that is most
766
+     * likely the folder where we stopped scanning previously
767
+     *
768
+     * @return string|bool the path of the folder or false when no folder matched
769
+     */
770
+    public function getIncomplete() {
771
+        $query = $this->connection->prepare('SELECT `path` FROM `*PREFIX*filecache`'
772
+            . ' WHERE `storage` = ? AND `size` = -1 ORDER BY `fileid` DESC', 1);
773
+        $query->execute([$this->getNumericStorageId()]);
774
+        if ($row = $query->fetch()) {
775
+            return $row['path'];
776
+        } else {
777
+            return false;
778
+        }
779
+    }
780
+
781
+    /**
782
+     * get the path of a file on this storage by it's file id
783
+     *
784
+     * @param int $id the file id of the file or folder to search
785
+     * @return string|null the path of the file (relative to the storage) or null if a file with the given id does not exists within this cache
786
+     */
787
+    public function getPathById($id) {
788
+        $sql = 'SELECT `path` FROM `*PREFIX*filecache` WHERE `fileid` = ? AND `storage` = ?';
789
+        $result = $this->connection->executeQuery($sql, array($id, $this->getNumericStorageId()));
790
+        if ($row = $result->fetch()) {
791
+            // Oracle stores empty strings as null...
792
+            if ($row['path'] === null) {
793
+                return '';
794
+            }
795
+            return $row['path'];
796
+        } else {
797
+            return null;
798
+        }
799
+    }
800
+
801
+    /**
802
+     * get the storage id of the storage for a file and the internal path of the file
803
+     * unlike getPathById this does not limit the search to files on this storage and
804
+     * instead does a global search in the cache table
805
+     *
806
+     * @param int $id
807
+     * @deprecated use getPathById() instead
808
+     * @return array first element holding the storage id, second the path
809
+     */
810
+    static public function getById($id) {
811
+        $connection = \OC::$server->getDatabaseConnection();
812
+        $sql = 'SELECT `storage`, `path` FROM `*PREFIX*filecache` WHERE `fileid` = ?';
813
+        $result = $connection->executeQuery($sql, array($id));
814
+        if ($row = $result->fetch()) {
815
+            $numericId = $row['storage'];
816
+            $path = $row['path'];
817
+        } else {
818
+            return null;
819
+        }
820
+
821
+        if ($id = Storage::getStorageId($numericId)) {
822
+            return array($id, $path);
823
+        } else {
824
+            return null;
825
+        }
826
+    }
827
+
828
+    /**
829
+     * normalize the given path
830
+     *
831
+     * @param string $path
832
+     * @return string
833
+     */
834
+    public function normalize($path) {
835
+
836
+        return trim(\OC_Util::normalizeUnicode($path), '/');
837
+    }
838 838
 }
Please login to merge, or discard this patch.
Spacing   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -143,20 +143,20 @@  discard block
 block discarded – undo
143 143
 			return $data;
144 144
 		} else {
145 145
 			//fix types
146
-			$data['fileid'] = (int)$data['fileid'];
147
-			$data['parent'] = (int)$data['parent'];
146
+			$data['fileid'] = (int) $data['fileid'];
147
+			$data['parent'] = (int) $data['parent'];
148 148
 			$data['size'] = 0 + $data['size'];
149
-			$data['mtime'] = (int)$data['mtime'];
150
-			$data['storage_mtime'] = (int)$data['storage_mtime'];
151
-			$data['encryptedVersion'] = (int)$data['encrypted'];
152
-			$data['encrypted'] = (bool)$data['encrypted'];
149
+			$data['mtime'] = (int) $data['mtime'];
150
+			$data['storage_mtime'] = (int) $data['storage_mtime'];
151
+			$data['encryptedVersion'] = (int) $data['encrypted'];
152
+			$data['encrypted'] = (bool) $data['encrypted'];
153 153
 			$data['storage'] = $this->storageId;
154 154
 			$data['mimetype'] = $this->mimetypeLoader->getMimetypeById($data['mimetype']);
155 155
 			$data['mimepart'] = $this->mimetypeLoader->getMimetypeById($data['mimepart']);
156 156
 			if ($data['storage_mtime'] == 0) {
157 157
 				$data['storage_mtime'] = $data['mtime'];
158 158
 			}
159
-			$data['permissions'] = (int)$data['permissions'];
159
+			$data['permissions'] = (int) $data['permissions'];
160 160
 			return new CacheEntry($data);
161 161
 		}
162 162
 	}
@@ -191,12 +191,12 @@  discard block
 block discarded – undo
191 191
 				if ($file['storage_mtime'] == 0) {
192 192
 					$file['storage_mtime'] = $file['mtime'];
193 193
 				}
194
-				$file['permissions'] = (int)$file['permissions'];
195
-				$file['mtime'] = (int)$file['mtime'];
196
-				$file['storage_mtime'] = (int)$file['storage_mtime'];
194
+				$file['permissions'] = (int) $file['permissions'];
195
+				$file['mtime'] = (int) $file['mtime'];
196
+				$file['storage_mtime'] = (int) $file['storage_mtime'];
197 197
 				$file['size'] = 0 + $file['size'];
198 198
 			}
199
-			return array_map(function (array $data) {
199
+			return array_map(function(array $data) {
200 200
 				return new CacheEntry($data);
201 201
 			}, $files);
202 202
 		} else {
@@ -256,7 +256,7 @@  discard block
 block discarded – undo
256 256
 		$queryParts[] = '`storage`';
257 257
 		$params[] = $this->getNumericStorageId();
258 258
 
259
-		$queryParts = array_map(function ($item) {
259
+		$queryParts = array_map(function($item) {
260 260
 			return trim($item, "`");
261 261
 		}, $queryParts);
262 262
 		$values = array_combine($queryParts, $params);
@@ -265,7 +265,7 @@  discard block
 block discarded – undo
265 265
 			'path_hash',
266 266
 		])
267 267
 		) {
268
-			return (int)$this->connection->lastInsertId('*PREFIX*filecache');
268
+			return (int) $this->connection->lastInsertId('*PREFIX*filecache');
269 269
 		}
270 270
 
271 271
 		// The file was created in the mean time
@@ -303,10 +303,10 @@  discard block
 block discarded – undo
303 303
 
304 304
 		// don't update if the data we try to set is the same as the one in the record
305 305
 		// some databases (Postgres) don't like superfluous updates
306
-		$sql = 'UPDATE `*PREFIX*filecache` SET ' . implode(' = ?, ', $queryParts) . '=? ' .
307
-			'WHERE (' .
308
-			implode(' <> ? OR ', $queryParts) . ' <> ? OR ' .
309
-			implode(' IS NULL OR ', $queryParts) . ' IS NULL' .
306
+		$sql = 'UPDATE `*PREFIX*filecache` SET '.implode(' = ?, ', $queryParts).'=? '.
307
+			'WHERE ('.
308
+			implode(' <> ? OR ', $queryParts).' <> ? OR '.
309
+			implode(' IS NULL OR ', $queryParts).' IS NULL'.
310 310
 			') AND `fileid` = ? ';
311 311
 		$this->connection->executeQuery($sql, $params);
312 312
 
@@ -349,7 +349,7 @@  discard block
 block discarded – undo
349 349
 						$queryParts[] = '`mtime`';
350 350
 					}
351 351
 				} elseif ($name === 'encrypted') {
352
-					if(isset($data['encryptedVersion'])) {
352
+					if (isset($data['encryptedVersion'])) {
353 353
 						$value = $data['encryptedVersion'];
354 354
 					} else {
355 355
 						// Boolean to integer conversion
@@ -357,7 +357,7 @@  discard block
 block discarded – undo
357 357
 					}
358 358
 				}
359 359
 				$params[] = $value;
360
-				$queryParts[] = '`' . $name . '`';
360
+				$queryParts[] = '`'.$name.'`';
361 361
 			}
362 362
 		}
363 363
 		return array($queryParts, $params);
@@ -399,7 +399,7 @@  discard block
 block discarded – undo
399 399
 			return -1;
400 400
 		} else {
401 401
 			$parent = $this->getParentPath($file);
402
-			return (int)$this->getId($parent);
402
+			return (int) $this->getId($parent);
403 403
 		}
404 404
 	}
405 405
 
@@ -445,7 +445,7 @@  discard block
 block discarded – undo
445 445
 	 */
446 446
 	private function getSubFolders($entry) {
447 447
 		$children = $this->getFolderContentsById($entry['fileid']);
448
-		return array_filter($children, function ($child) {
448
+		return array_filter($children, function($child) {
449 449
 			return $child['mimetype'] === 'httpd/unix-directory';
450 450
 		});
451 451
 	}
@@ -512,14 +512,14 @@  discard block
 block discarded – undo
512 512
 			if ($sourceData['mimetype'] === 'httpd/unix-directory') {
513 513
 				//find all child entries
514 514
 				$sql = 'SELECT `path`, `fileid` FROM `*PREFIX*filecache` WHERE `storage` = ? AND `path` LIKE ?';
515
-				$result = $this->connection->executeQuery($sql, [$sourceStorageId, $this->connection->escapeLikeParameter($sourcePath) . '/%']);
515
+				$result = $this->connection->executeQuery($sql, [$sourceStorageId, $this->connection->escapeLikeParameter($sourcePath).'/%']);
516 516
 				$childEntries = $result->fetchAll();
517 517
 				$sourceLength = strlen($sourcePath);
518 518
 				$this->connection->beginTransaction();
519 519
 				$query = $this->connection->prepare('UPDATE `*PREFIX*filecache` SET `storage` = ?, `path` = ?, `path_hash` = ? WHERE `fileid` = ?');
520 520
 
521 521
 				foreach ($childEntries as $child) {
522
-					$newTargetPath = $targetPath . substr($child['path'], $sourceLength);
522
+					$newTargetPath = $targetPath.substr($child['path'], $sourceLength);
523 523
 					$query->execute([$targetStorageId, $newTargetPath, md5($newTargetPath), $child['fileid']]);
524 524
 				}
525 525
 				$this->connection->executeQuery($moveSql, [$targetStorageId, $targetPath, md5($targetPath), basename($targetPath), $newParentId, $sourceId]);
@@ -563,7 +563,7 @@  discard block
 block discarded – undo
563 563
 		$sql = 'SELECT `size` FROM `*PREFIX*filecache` WHERE `storage` = ? AND `path_hash` = ?';
564 564
 		$result = $this->connection->executeQuery($sql, array($this->getNumericStorageId(), $pathHash));
565 565
 		if ($row = $result->fetch()) {
566
-			if ((int)$row['size'] === -1) {
566
+			if ((int) $row['size'] === -1) {
567 567
 				return self::SHALLOW;
568 568
 			} else {
569 569
 				return self::COMPLETE;
@@ -623,7 +623,7 @@  discard block
 block discarded – undo
623 623
 			$where = '`mimepart` = ?';
624 624
 		}
625 625
 		$sql = 'SELECT `fileid`, `storage`, `path`, `parent`, `name`, `mimetype`, `mimepart`, `size`, `mtime`, `encrypted`, `etag`, `permissions`, `checksum`
626
-				FROM `*PREFIX*filecache` WHERE ' . $where . ' AND `storage` = ?';
626
+				FROM `*PREFIX*filecache` WHERE ' . $where.' AND `storage` = ?';
627 627
 		$mimetype = $this->mimetypeLoader->getId($mimetype);
628 628
 		$result = $this->connection->executeQuery($sql, array($mimetype, $this->getNumericStorageId()));
629 629
 		$files = array();
@@ -632,7 +632,7 @@  discard block
 block discarded – undo
632 632
 			$row['mimepart'] = $this->mimetypeLoader->getMimetypeById($row['mimepart']);
633 633
 			$files[] = $row;
634 634
 		}
635
-		return array_map(function (array $data) {
635
+		return array_map(function(array $data) {
636 636
 			return new CacheEntry($data);
637 637
 		}, $files);
638 638
 	}
@@ -647,20 +647,20 @@  discard block
 block discarded – undo
647 647
 	 * @return ICacheEntry[] file data
648 648
 	 */
649 649
 	public function searchByTag($tag, $userId) {
650
-		$sql = 'SELECT `fileid`, `storage`, `path`, `parent`, `name`, ' .
651
-			'`mimetype`, `mimepart`, `size`, `mtime`, ' .
652
-			'`encrypted`, `etag`, `permissions`, `checksum` ' .
653
-			'FROM `*PREFIX*filecache` `file`, ' .
654
-			'`*PREFIX*vcategory_to_object` `tagmap`, ' .
655
-			'`*PREFIX*vcategory` `tag` ' .
650
+		$sql = 'SELECT `fileid`, `storage`, `path`, `parent`, `name`, '.
651
+			'`mimetype`, `mimepart`, `size`, `mtime`, '.
652
+			'`encrypted`, `etag`, `permissions`, `checksum` '.
653
+			'FROM `*PREFIX*filecache` `file`, '.
654
+			'`*PREFIX*vcategory_to_object` `tagmap`, '.
655
+			'`*PREFIX*vcategory` `tag` '.
656 656
 			// JOIN filecache to vcategory_to_object
657
-			'WHERE `file`.`fileid` = `tagmap`.`objid` ' .
657
+			'WHERE `file`.`fileid` = `tagmap`.`objid` '.
658 658
 			// JOIN vcategory_to_object to vcategory
659
-			'AND `tagmap`.`type` = `tag`.`type` ' .
660
-			'AND `tagmap`.`categoryid` = `tag`.`id` ' .
659
+			'AND `tagmap`.`type` = `tag`.`type` '.
660
+			'AND `tagmap`.`categoryid` = `tag`.`id` '.
661 661
 			// conditions
662
-			'AND `file`.`storage` = ? ' .
663
-			'AND `tag`.`type` = \'files\' ' .
662
+			'AND `file`.`storage` = ? '.
663
+			'AND `tag`.`type` = \'files\' '.
664 664
 			'AND `tag`.`uid` = ? ';
665 665
 		if (is_int($tag)) {
666 666
 			$sql .= 'AND `tag`.`id` = ? ';
@@ -679,7 +679,7 @@  discard block
 block discarded – undo
679 679
 		while ($row = $result->fetch()) {
680 680
 			$files[] = $row;
681 681
 		}
682
-		return array_map(function (array $data) {
682
+		return array_map(function(array $data) {
683 683
 			return new CacheEntry($data);
684 684
 		}, $files);
685 685
 	}
@@ -715,8 +715,8 @@  discard block
 block discarded – undo
715 715
 		}
716 716
 		if (isset($entry['mimetype']) && $entry['mimetype'] === 'httpd/unix-directory') {
717 717
 			$id = $entry['fileid'];
718
-			$sql = 'SELECT SUM(`size`) AS f1, MIN(`size`) AS f2 ' .
719
-				'FROM `*PREFIX*filecache` ' .
718
+			$sql = 'SELECT SUM(`size`) AS f1, MIN(`size`) AS f2 '.
719
+				'FROM `*PREFIX*filecache` '.
720 720
 				'WHERE `parent` = ? AND `storage` = ?';
721 721
 			$result = $this->connection->executeQuery($sql, array($id, $this->getNumericStorageId()));
722 722
 			if ($row = $result->fetch()) {
Please login to merge, or discard this patch.