Completed
Pull Request — master (#6864)
by Julius
16:50
created
lib/public/Files/FileInfo.php 1 patch
Indentation   +199 added lines, -199 removed lines patch added patch discarded remove patch
@@ -33,229 +33,229 @@
 block discarded – undo
33 33
  * @since 7.0.0
34 34
  */
35 35
 interface FileInfo {
36
-	/**
37
-	 * @since 7.0.0
38
-	 */
39
-	const TYPE_FILE = 'file';
40
-	/**
41
-	 * @since 7.0.0
42
-	 */
43
-	const TYPE_FOLDER = 'dir';
36
+    /**
37
+     * @since 7.0.0
38
+     */
39
+    const TYPE_FILE = 'file';
40
+    /**
41
+     * @since 7.0.0
42
+     */
43
+    const TYPE_FOLDER = 'dir';
44 44
 
45
-	/**
46
-	 * @const \OCP\Files\FileInfo::SPACE_NOT_COMPUTED Return value for a not computed space value
47
-	 * @since 8.0.0
48
-	 */
49
-	const SPACE_NOT_COMPUTED = -1;
50
-	/**
51
-	 * @const \OCP\Files\FileInfo::SPACE_UNKNOWN Return value for unknown space value
52
-	 * @since 8.0.0
53
-	 */
54
-	const SPACE_UNKNOWN = -2;
55
-	/**
56
-	 * @const \OCP\Files\FileInfo::SPACE_UNLIMITED Return value for unlimited space
57
-	 * @since 8.0.0
58
-	 */
59
-	const SPACE_UNLIMITED = -3;
45
+    /**
46
+     * @const \OCP\Files\FileInfo::SPACE_NOT_COMPUTED Return value for a not computed space value
47
+     * @since 8.0.0
48
+     */
49
+    const SPACE_NOT_COMPUTED = -1;
50
+    /**
51
+     * @const \OCP\Files\FileInfo::SPACE_UNKNOWN Return value for unknown space value
52
+     * @since 8.0.0
53
+     */
54
+    const SPACE_UNKNOWN = -2;
55
+    /**
56
+     * @const \OCP\Files\FileInfo::SPACE_UNLIMITED Return value for unlimited space
57
+     * @since 8.0.0
58
+     */
59
+    const SPACE_UNLIMITED = -3;
60 60
 
61
-	/**
62
-	 * @since 9.1.0
63
-	 */
64
-	const MIMETYPE_FOLDER = 'httpd/unix-directory';
61
+    /**
62
+     * @since 9.1.0
63
+     */
64
+    const MIMETYPE_FOLDER = 'httpd/unix-directory';
65 65
 
66
-	/**
67
-	 * @const \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX Return regular expression to test filenames against (blacklisting)
68
-	 * @since 12.0.0
69
-	 */
70
-	const BLACKLIST_FILES_REGEX = '\.(part|filepart)$';
66
+    /**
67
+     * @const \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX Return regular expression to test filenames against (blacklisting)
68
+     * @since 12.0.0
69
+     */
70
+    const BLACKLIST_FILES_REGEX = '\.(part|filepart)$';
71 71
 
72
-	/**
73
-	 * Get the Etag of the file or folder
74
-	 *
75
-	 * @return string
76
-	 * @since 7.0.0
77
-	 */
78
-	public function getEtag();
72
+    /**
73
+     * Get the Etag of the file or folder
74
+     *
75
+     * @return string
76
+     * @since 7.0.0
77
+     */
78
+    public function getEtag();
79 79
 
80
-	/**
81
-	 * Get the size in bytes for the file or folder
82
-	 *
83
-	 * @return int
84
-	 * @since 7.0.0
85
-	 */
86
-	public function getSize();
80
+    /**
81
+     * Get the size in bytes for the file or folder
82
+     *
83
+     * @return int
84
+     * @since 7.0.0
85
+     */
86
+    public function getSize();
87 87
 
88
-	/**
89
-	 * Get the last modified date as timestamp for the file or folder
90
-	 *
91
-	 * @return int
92
-	 * @since 7.0.0
93
-	 */
94
-	public function getMtime();
88
+    /**
89
+     * Get the last modified date as timestamp for the file or folder
90
+     *
91
+     * @return int
92
+     * @since 7.0.0
93
+     */
94
+    public function getMtime();
95 95
 
96
-	/**
97
-	 * Get the name of the file or folder
98
-	 *
99
-	 * @return string
100
-	 * @since 7.0.0
101
-	 */
102
-	public function getName();
96
+    /**
97
+     * Get the name of the file or folder
98
+     *
99
+     * @return string
100
+     * @since 7.0.0
101
+     */
102
+    public function getName();
103 103
 
104
-	/**
105
-	 * Get the path relative to the storage
106
-	 *
107
-	 * @return string
108
-	 * @since 7.0.0
109
-	 */
110
-	public function getInternalPath();
104
+    /**
105
+     * Get the path relative to the storage
106
+     *
107
+     * @return string
108
+     * @since 7.0.0
109
+     */
110
+    public function getInternalPath();
111 111
 
112
-	/**
113
-	 * Get the absolute path
114
-	 *
115
-	 * @return string
116
-	 * @since 7.0.0
117
-	 */
118
-	public function getPath();
112
+    /**
113
+     * Get the absolute path
114
+     *
115
+     * @return string
116
+     * @since 7.0.0
117
+     */
118
+    public function getPath();
119 119
 
120
-	/**
121
-	 * Get the full mimetype of the file or folder i.e. 'image/png'
122
-	 *
123
-	 * @return string
124
-	 * @since 7.0.0
125
-	 */
126
-	public function getMimetype();
120
+    /**
121
+     * Get the full mimetype of the file or folder i.e. 'image/png'
122
+     *
123
+     * @return string
124
+     * @since 7.0.0
125
+     */
126
+    public function getMimetype();
127 127
 
128
-	/**
129
-	 * Get the first part of the mimetype of the file or folder i.e. 'image'
130
-	 *
131
-	 * @return string
132
-	 * @since 7.0.0
133
-	 */
134
-	public function getMimePart();
128
+    /**
129
+     * Get the first part of the mimetype of the file or folder i.e. 'image'
130
+     *
131
+     * @return string
132
+     * @since 7.0.0
133
+     */
134
+    public function getMimePart();
135 135
 
136
-	/**
137
-	 * Get the storage the file or folder is storage on
138
-	 *
139
-	 * @return \OCP\Files\Storage
140
-	 * @since 7.0.0
141
-	 */
142
-	public function getStorage();
136
+    /**
137
+     * Get the storage the file or folder is storage on
138
+     *
139
+     * @return \OCP\Files\Storage
140
+     * @since 7.0.0
141
+     */
142
+    public function getStorage();
143 143
 
144
-	/**
145
-	 * Get the file id of the file or folder
146
-	 *
147
-	 * @return int|null
148
-	 * @since 7.0.0
149
-	 */
150
-	public function getId();
144
+    /**
145
+     * Get the file id of the file or folder
146
+     *
147
+     * @return int|null
148
+     * @since 7.0.0
149
+     */
150
+    public function getId();
151 151
 
152
-	/**
153
-	 * Check whether the file is encrypted
154
-	 *
155
-	 * @return bool
156
-	 * @since 7.0.0
157
-	 */
158
-	public function isEncrypted();
152
+    /**
153
+     * Check whether the file is encrypted
154
+     *
155
+     * @return bool
156
+     * @since 7.0.0
157
+     */
158
+    public function isEncrypted();
159 159
 
160
-	/**
161
-	 * Get the permissions of the file or folder as bitmasked combination of the following constants
162
-	 * \OCP\Constants::PERMISSION_CREATE
163
-	 * \OCP\Constants::PERMISSION_READ
164
-	 * \OCP\Constants::PERMISSION_UPDATE
165
-	 * \OCP\Constants::PERMISSION_DELETE
166
-	 * \OCP\Constants::PERMISSION_SHARE
167
-	 * \OCP\Constants::PERMISSION_ALL
168
-	 *
169
-	 * @return int
170
-	 * @since 7.0.0 - namespace of constants has changed in 8.0.0
171
-	 */
172
-	public function getPermissions();
160
+    /**
161
+     * Get the permissions of the file or folder as bitmasked combination of the following constants
162
+     * \OCP\Constants::PERMISSION_CREATE
163
+     * \OCP\Constants::PERMISSION_READ
164
+     * \OCP\Constants::PERMISSION_UPDATE
165
+     * \OCP\Constants::PERMISSION_DELETE
166
+     * \OCP\Constants::PERMISSION_SHARE
167
+     * \OCP\Constants::PERMISSION_ALL
168
+     *
169
+     * @return int
170
+     * @since 7.0.0 - namespace of constants has changed in 8.0.0
171
+     */
172
+    public function getPermissions();
173 173
 
174
-	/**
175
-	 * Check whether this is a file or a folder
176
-	 *
177
-	 * @return string \OCP\Files\FileInfo::TYPE_FILE|\OCP\Files\FileInfo::TYPE_FOLDER
178
-	 * @since 7.0.0
179
-	 */
180
-	public function getType();
174
+    /**
175
+     * Check whether this is a file or a folder
176
+     *
177
+     * @return string \OCP\Files\FileInfo::TYPE_FILE|\OCP\Files\FileInfo::TYPE_FOLDER
178
+     * @since 7.0.0
179
+     */
180
+    public function getType();
181 181
 
182
-	/**
183
-	 * Check if the file or folder is readable
184
-	 *
185
-	 * @return bool
186
-	 * @since 7.0.0
187
-	 */
188
-	public function isReadable();
182
+    /**
183
+     * Check if the file or folder is readable
184
+     *
185
+     * @return bool
186
+     * @since 7.0.0
187
+     */
188
+    public function isReadable();
189 189
 
190
-	/**
191
-	 * Check if a file is writable
192
-	 *
193
-	 * @return bool
194
-	 * @since 7.0.0
195
-	 */
196
-	public function isUpdateable();
190
+    /**
191
+     * Check if a file is writable
192
+     *
193
+     * @return bool
194
+     * @since 7.0.0
195
+     */
196
+    public function isUpdateable();
197 197
 
198
-	/**
199
-	 * Check whether new files or folders can be created inside this folder
200
-	 *
201
-	 * @return bool
202
-	 * @since 8.0.0
203
-	 */
204
-	public function isCreatable();
198
+    /**
199
+     * Check whether new files or folders can be created inside this folder
200
+     *
201
+     * @return bool
202
+     * @since 8.0.0
203
+     */
204
+    public function isCreatable();
205 205
 
206
-	/**
207
-	 * Check if a file or folder can be deleted
208
-	 *
209
-	 * @return bool
210
-	 * @since 7.0.0
211
-	 */
212
-	public function isDeletable();
206
+    /**
207
+     * Check if a file or folder can be deleted
208
+     *
209
+     * @return bool
210
+     * @since 7.0.0
211
+     */
212
+    public function isDeletable();
213 213
 
214
-	/**
215
-	 * Check if a file or folder can be shared
216
-	 *
217
-	 * @return bool
218
-	 * @since 7.0.0
219
-	 */
220
-	public function isShareable();
214
+    /**
215
+     * Check if a file or folder can be shared
216
+     *
217
+     * @return bool
218
+     * @since 7.0.0
219
+     */
220
+    public function isShareable();
221 221
 
222
-	/**
223
-	 * Check if a file or folder is shared
224
-	 *
225
-	 * @return bool
226
-	 * @since 7.0.0
227
-	 */
228
-	public function isShared();
222
+    /**
223
+     * Check if a file or folder is shared
224
+     *
225
+     * @return bool
226
+     * @since 7.0.0
227
+     */
228
+    public function isShared();
229 229
 
230
-	/**
231
-	 * Check if a file or folder is mounted
232
-	 *
233
-	 * @return bool
234
-	 * @since 7.0.0
235
-	 */
236
-	public function isMounted();
230
+    /**
231
+     * Check if a file or folder is mounted
232
+     *
233
+     * @return bool
234
+     * @since 7.0.0
235
+     */
236
+    public function isMounted();
237 237
 
238
-	/**
239
-	 * Get the mountpoint the file belongs to
240
-	 *
241
-	 * @return \OCP\Files\Mount\IMountPoint
242
-	 * @since 8.0.0
243
-	 */
244
-	public function getMountPoint();
238
+    /**
239
+     * Get the mountpoint the file belongs to
240
+     *
241
+     * @return \OCP\Files\Mount\IMountPoint
242
+     * @since 8.0.0
243
+     */
244
+    public function getMountPoint();
245 245
 
246
-	/**
247
-	 * Get the owner of the file
248
-	 *
249
-	 * @return \OCP\IUser
250
-	 * @since 9.0.0
251
-	 */
252
-	public function getOwner();
246
+    /**
247
+     * Get the owner of the file
248
+     *
249
+     * @return \OCP\IUser
250
+     * @since 9.0.0
251
+     */
252
+    public function getOwner();
253 253
 
254
-	/**
255
-	 * Get the stored checksum for this file
256
-	 *
257
-	 * @return string
258
-	 * @since 9.0.0
259
-	 */
260
-	public function getChecksum();
254
+    /**
255
+     * Get the stored checksum for this file
256
+     *
257
+     * @return string
258
+     * @since 9.0.0
259
+     */
260
+    public function getChecksum();
261 261
 }
Please login to merge, or discard this patch.
lib/public/Util.php 1 patch
Indentation   +651 added lines, -651 removed lines patch added patch discarded remove patch
@@ -57,657 +57,657 @@
 block discarded – undo
57 57
  * @since 4.0.0
58 58
  */
59 59
 class Util {
60
-	// consts for Logging
61
-	const DEBUG=0;
62
-	const INFO=1;
63
-	const WARN=2;
64
-	const ERROR=3;
65
-	const FATAL=4;
66
-
67
-	/** \OCP\Share\IManager */
68
-	private static $shareManager;
69
-
70
-	/**
71
-	 * get the current installed version of ownCloud
72
-	 * @return array
73
-	 * @since 4.0.0
74
-	 */
75
-	public static function getVersion() {
76
-		return \OC_Util::getVersion();
77
-	}
60
+    // consts for Logging
61
+    const DEBUG=0;
62
+    const INFO=1;
63
+    const WARN=2;
64
+    const ERROR=3;
65
+    const FATAL=4;
66
+
67
+    /** \OCP\Share\IManager */
68
+    private static $shareManager;
69
+
70
+    /**
71
+     * get the current installed version of ownCloud
72
+     * @return array
73
+     * @since 4.0.0
74
+     */
75
+    public static function getVersion() {
76
+        return \OC_Util::getVersion();
77
+    }
78 78
 	
79
-	/**
80
-	 * Set current update channel
81
-	 * @param string $channel
82
-	 * @since 8.1.0
83
-	 */
84
-	public static function setChannel($channel) {
85
-		\OC::$server->getConfig()->setSystemValue('updater.release.channel', $channel);
86
-	}
79
+    /**
80
+     * Set current update channel
81
+     * @param string $channel
82
+     * @since 8.1.0
83
+     */
84
+    public static function setChannel($channel) {
85
+        \OC::$server->getConfig()->setSystemValue('updater.release.channel', $channel);
86
+    }
87 87
 	
88
-	/**
89
-	 * Get current update channel
90
-	 * @return string
91
-	 * @since 8.1.0
92
-	 */
93
-	public static function getChannel() {
94
-		return \OC_Util::getChannel();
95
-	}
96
-
97
-	/**
98
-	 * send an email
99
-	 * @param string $toaddress
100
-	 * @param string $toname
101
-	 * @param string $subject
102
-	 * @param string $mailtext
103
-	 * @param string $fromaddress
104
-	 * @param string $fromname
105
-	 * @param int $html
106
-	 * @param string $altbody
107
-	 * @param string $ccaddress
108
-	 * @param string $ccname
109
-	 * @param string $bcc
110
-	 * @deprecated 8.1.0 Use \OCP\Mail\IMailer instead
111
-	 * @since 4.0.0
112
-	 */
113
-	public static function sendMail($toaddress, $toname, $subject, $mailtext, $fromaddress, $fromname,
114
-		$html = 0, $altbody = '', $ccaddress = '', $ccname = '', $bcc = '') {
115
-		$mailer = \OC::$server->getMailer();
116
-		$message = $mailer->createMessage();
117
-		$message->setTo([$toaddress => $toname]);
118
-		$message->setSubject($subject);
119
-		$message->setPlainBody($mailtext);
120
-		$message->setFrom([$fromaddress => $fromname]);
121
-		if($html === 1) {
122
-			$message->setHtmlBody($altbody);
123
-		}
124
-
125
-		if($altbody === '') {
126
-			$message->setHtmlBody($mailtext);
127
-			$message->setPlainBody('');
128
-		} else {
129
-			$message->setHtmlBody($mailtext);
130
-			$message->setPlainBody($altbody);
131
-		}
132
-
133
-		if(!empty($ccaddress)) {
134
-			if(!empty($ccname)) {
135
-				$message->setCc([$ccaddress => $ccname]);
136
-			} else {
137
-				$message->setCc([$ccaddress]);
138
-			}
139
-		}
140
-		if(!empty($bcc)) {
141
-			$message->setBcc([$bcc]);
142
-		}
143
-
144
-		$mailer->send($message);
145
-	}
146
-
147
-	/**
148
-	 * write a message in the log
149
-	 * @param string $app
150
-	 * @param string $message
151
-	 * @param int $level
152
-	 * @since 4.0.0
153
-	 * @deprecated 13.0.0 use log of \OCP\ILogger
154
-	 */
155
-	public static function writeLog( $app, $message, $level ) {
156
-		$context = ['app' => $app];
157
-		\OC::$server->getLogger()->log($level, $message, $context);
158
-	}
159
-
160
-	/**
161
-	 * write exception into the log
162
-	 * @param string $app app name
163
-	 * @param \Exception $ex exception to log
164
-	 * @param int $level log level, defaults to \OCP\Util::FATAL
165
-	 * @since ....0.0 - parameter $level was added in 7.0.0
166
-	 * @deprecated 8.2.0 use logException of \OCP\ILogger
167
-	 */
168
-	public static function logException( $app, \Exception $ex, $level = \OCP\Util::FATAL ) {
169
-		\OC::$server->getLogger()->logException($ex, ['app' => $app]);
170
-	}
171
-
172
-	/**
173
-	 * check if sharing is disabled for the current user
174
-	 *
175
-	 * @return boolean
176
-	 * @since 7.0.0
177
-	 * @deprecated 9.1.0 Use \OC::$server->getShareManager()->sharingDisabledForUser
178
-	 */
179
-	public static function isSharingDisabledForUser() {
180
-		if (self::$shareManager === null) {
181
-			self::$shareManager = \OC::$server->getShareManager();
182
-		}
183
-
184
-		$user = \OC::$server->getUserSession()->getUser();
185
-		if ($user !== null) {
186
-			$user = $user->getUID();
187
-		}
188
-
189
-		return self::$shareManager->sharingDisabledForUser($user);
190
-	}
191
-
192
-	/**
193
-	 * get l10n object
194
-	 * @param string $application
195
-	 * @param string|null $language
196
-	 * @return \OCP\IL10N
197
-	 * @since 6.0.0 - parameter $language was added in 8.0.0
198
-	 */
199
-	public static function getL10N($application, $language = null) {
200
-		return \OC::$server->getL10N($application, $language);
201
-	}
202
-
203
-	/**
204
-	 * add a css file
205
-	 * @param string $application
206
-	 * @param string $file
207
-	 * @since 4.0.0
208
-	 */
209
-	public static function addStyle( $application, $file = null ) {
210
-		\OC_Util::addStyle( $application, $file );
211
-	}
212
-
213
-	/**
214
-	 * add a javascript file
215
-	 * @param string $application
216
-	 * @param string $file
217
-	 * @since 4.0.0
218
-	 */
219
-	public static function addScript( $application, $file = null ) {
220
-		\OC_Util::addScript( $application, $file );
221
-	}
222
-
223
-	/**
224
-	 * Add a translation JS file
225
-	 * @param string $application application id
226
-	 * @param string $languageCode language code, defaults to the current locale
227
-	 * @since 8.0.0
228
-	 */
229
-	public static function addTranslations($application, $languageCode = null) {
230
-		\OC_Util::addTranslations($application, $languageCode);
231
-	}
232
-
233
-	/**
234
-	 * Add a custom element to the header
235
-	 * If $text is null then the element will be written as empty element.
236
-	 * So use "" to get a closing tag.
237
-	 * @param string $tag tag name of the element
238
-	 * @param array $attributes array of attributes for the element
239
-	 * @param string $text the text content for the element
240
-	 * @since 4.0.0
241
-	 */
242
-	public static function addHeader($tag, $attributes, $text=null) {
243
-		\OC_Util::addHeader($tag, $attributes, $text);
244
-	}
245
-
246
-	/**
247
-	 * formats a timestamp in the "right" way
248
-	 * @param int $timestamp $timestamp
249
-	 * @param bool $dateOnly option to omit time from the result
250
-	 * @param DateTimeZone|string $timeZone where the given timestamp shall be converted to
251
-	 * @return string timestamp
252
-	 *
253
-	 * @deprecated 8.0.0 Use \OC::$server->query('DateTimeFormatter') instead
254
-	 * @since 4.0.0
255
-	 * @suppress PhanDeprecatedFunction
256
-	 */
257
-	public static function formatDate($timestamp, $dateOnly=false, $timeZone = null) {
258
-		return \OC_Util::formatDate($timestamp, $dateOnly, $timeZone);
259
-	}
260
-
261
-	/**
262
-	 * check if some encrypted files are stored
263
-	 * @return bool
264
-	 *
265
-	 * @deprecated 8.1.0 No longer required
266
-	 * @since 6.0.0
267
-	 */
268
-	public static function encryptedFiles() {
269
-		return false;
270
-	}
271
-
272
-	/**
273
-	 * Creates an absolute url to the given app and file.
274
-	 * @param string $app app
275
-	 * @param string $file file
276
-	 * @param array $args array with param=>value, will be appended to the returned url
277
-	 * 	The value of $args will be urlencoded
278
-	 * @return string the url
279
-	 * @since 4.0.0 - parameter $args was added in 4.5.0
280
-	 */
281
-	public static function linkToAbsolute( $app, $file, $args = array() ) {
282
-		$urlGenerator = \OC::$server->getURLGenerator();
283
-		return $urlGenerator->getAbsoluteURL(
284
-			$urlGenerator->linkTo($app, $file, $args)
285
-		);
286
-	}
287
-
288
-	/**
289
-	 * Creates an absolute url for remote use.
290
-	 * @param string $service id
291
-	 * @return string the url
292
-	 * @since 4.0.0
293
-	 */
294
-	public static function linkToRemote( $service ) {
295
-		$urlGenerator = \OC::$server->getURLGenerator();
296
-		$remoteBase = $urlGenerator->linkTo('', 'remote.php') . '/' . $service;
297
-		return $urlGenerator->getAbsoluteURL(
298
-			$remoteBase . (($service[strlen($service) - 1] != '/') ? '/' : '')
299
-		);
300
-	}
301
-
302
-	/**
303
-	 * Creates an absolute url for public use
304
-	 * @param string $service id
305
-	 * @return string the url
306
-	 * @since 4.5.0
307
-	 */
308
-	public static function linkToPublic($service) {
309
-		return \OC_Helper::linkToPublic($service);
310
-	}
311
-
312
-	/**
313
-	 * Creates an url using a defined route
314
-	 * @param string $route
315
-	 * @param array $parameters
316
-	 * @internal param array $args with param=>value, will be appended to the returned url
317
-	 * @return string the url
318
-	 * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->linkToRoute($route, $parameters)
319
-	 * @since 5.0.0
320
-	 */
321
-	public static function linkToRoute( $route, $parameters = array() ) {
322
-		return \OC::$server->getURLGenerator()->linkToRoute($route, $parameters);
323
-	}
324
-
325
-	/**
326
-	 * Creates an url to the given app and file
327
-	 * @param string $app app
328
-	 * @param string $file file
329
-	 * @param array $args array with param=>value, will be appended to the returned url
330
-	 * 	The value of $args will be urlencoded
331
-	 * @return string the url
332
-	 * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->linkTo($app, $file, $args)
333
-	 * @since 4.0.0 - parameter $args was added in 4.5.0
334
-	 */
335
-	public static function linkTo( $app, $file, $args = array() ) {
336
-		return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
337
-	}
338
-
339
-	/**
340
-	 * Returns the server host, even if the website uses one or more reverse proxy
341
-	 * @return string the server host
342
-	 * @deprecated 8.1.0 Use \OCP\IRequest::getServerHost
343
-	 * @since 4.0.0
344
-	 */
345
-	public static function getServerHost() {
346
-		return \OC::$server->getRequest()->getServerHost();
347
-	}
348
-
349
-	/**
350
-	 * Returns the server host name without an eventual port number
351
-	 * @return string the server hostname
352
-	 * @since 5.0.0
353
-	 */
354
-	public static function getServerHostName() {
355
-		$host_name = \OC::$server->getRequest()->getServerHost();
356
-		// strip away port number (if existing)
357
-		$colon_pos = strpos($host_name, ':');
358
-		if ($colon_pos != FALSE) {
359
-			$host_name = substr($host_name, 0, $colon_pos);
360
-		}
361
-		return $host_name;
362
-	}
363
-
364
-	/**
365
-	 * Returns the default email address
366
-	 * @param string $user_part the user part of the address
367
-	 * @return string the default email address
368
-	 *
369
-	 * Assembles a default email address (using the server hostname
370
-	 * and the given user part, and returns it
371
-	 * Example: when given lostpassword-noreply as $user_part param,
372
-	 *     and is currently accessed via http(s)://example.com/,
373
-	 *     it would return '[email protected]'
374
-	 *
375
-	 * If the configuration value 'mail_from_address' is set in
376
-	 * config.php, this value will override the $user_part that
377
-	 * is passed to this function
378
-	 * @since 5.0.0
379
-	 */
380
-	public static function getDefaultEmailAddress($user_part) {
381
-		$config = \OC::$server->getConfig();
382
-		$user_part = $config->getSystemValue('mail_from_address', $user_part);
383
-		$host_name = self::getServerHostName();
384
-		$host_name = $config->getSystemValue('mail_domain', $host_name);
385
-		$defaultEmailAddress = $user_part.'@'.$host_name;
386
-
387
-		$mailer = \OC::$server->getMailer();
388
-		if ($mailer->validateMailAddress($defaultEmailAddress)) {
389
-			return $defaultEmailAddress;
390
-		}
391
-
392
-		// in case we cannot build a valid email address from the hostname let's fallback to 'localhost.localdomain'
393
-		return $user_part.'@localhost.localdomain';
394
-	}
395
-
396
-	/**
397
-	 * Returns the server protocol. It respects reverse proxy servers and load balancers
398
-	 * @return string the server protocol
399
-	 * @deprecated 8.1.0 Use \OCP\IRequest::getServerProtocol
400
-	 * @since 4.5.0
401
-	 */
402
-	public static function getServerProtocol() {
403
-		return \OC::$server->getRequest()->getServerProtocol();
404
-	}
405
-
406
-	/**
407
-	 * Returns the request uri, even if the website uses one or more reverse proxies
408
-	 * @return string the request uri
409
-	 * @deprecated 8.1.0 Use \OCP\IRequest::getRequestUri
410
-	 * @since 5.0.0
411
-	 */
412
-	public static function getRequestUri() {
413
-		return \OC::$server->getRequest()->getRequestUri();
414
-	}
415
-
416
-	/**
417
-	 * Returns the script name, even if the website uses one or more reverse proxies
418
-	 * @return string the script name
419
-	 * @deprecated 8.1.0 Use \OCP\IRequest::getScriptName
420
-	 * @since 5.0.0
421
-	 */
422
-	public static function getScriptName() {
423
-		return \OC::$server->getRequest()->getScriptName();
424
-	}
425
-
426
-	/**
427
-	 * Creates path to an image
428
-	 * @param string $app app
429
-	 * @param string $image image name
430
-	 * @return string the url
431
-	 * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->imagePath($app, $image)
432
-	 * @since 4.0.0
433
-	 */
434
-	public static function imagePath( $app, $image ) {
435
-		return \OC::$server->getURLGenerator()->imagePath($app, $image);
436
-	}
437
-
438
-	/**
439
-	 * Make a human file size (2048 to 2 kB)
440
-	 * @param int $bytes file size in bytes
441
-	 * @return string a human readable file size
442
-	 * @since 4.0.0
443
-	 */
444
-	public static function humanFileSize($bytes) {
445
-		return \OC_Helper::humanFileSize($bytes);
446
-	}
447
-
448
-	/**
449
-	 * Make a computer file size (2 kB to 2048)
450
-	 * @param string $str file size in a fancy format
451
-	 * @return float a file size in bytes
452
-	 *
453
-	 * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
454
-	 * @since 4.0.0
455
-	 */
456
-	public static function computerFileSize($str) {
457
-		return \OC_Helper::computerFileSize($str);
458
-	}
459
-
460
-	/**
461
-	 * connects a function to a hook
462
-	 *
463
-	 * @param string $signalClass class name of emitter
464
-	 * @param string $signalName name of signal
465
-	 * @param string|object $slotClass class name of slot
466
-	 * @param string $slotName name of slot
467
-	 * @return bool
468
-	 *
469
-	 * This function makes it very easy to connect to use hooks.
470
-	 *
471
-	 * TODO: write example
472
-	 * @since 4.0.0
473
-	 */
474
-	static public function connectHook($signalClass, $signalName, $slotClass, $slotName) {
475
-		return \OC_Hook::connect($signalClass, $signalName, $slotClass, $slotName);
476
-	}
477
-
478
-	/**
479
-	 * Emits a signal. To get data from the slot use references!
480
-	 * @param string $signalclass class name of emitter
481
-	 * @param string $signalname name of signal
482
-	 * @param array $params default: array() array with additional data
483
-	 * @return bool true if slots exists or false if not
484
-	 *
485
-	 * TODO: write example
486
-	 * @since 4.0.0
487
-	 */
488
-	static public function emitHook($signalclass, $signalname, $params = array()) {
489
-		return \OC_Hook::emit($signalclass, $signalname, $params);
490
-	}
491
-
492
-	/**
493
-	 * Cached encrypted CSRF token. Some static unit-tests of ownCloud compare
494
-	 * multiple OC_Template elements which invoke `callRegister`. If the value
495
-	 * would not be cached these unit-tests would fail.
496
-	 * @var string
497
-	 */
498
-	private static $token = '';
499
-
500
-	/**
501
-	 * Register an get/post call. This is important to prevent CSRF attacks
502
-	 * @since 4.5.0
503
-	 */
504
-	public static function callRegister() {
505
-		if(self::$token === '') {
506
-			self::$token = \OC::$server->getCsrfTokenManager()->getToken()->getEncryptedValue();
507
-		}
508
-		return self::$token;
509
-	}
510
-
511
-	/**
512
-	 * Check an ajax get/post call if the request token is valid. exit if not.
513
-	 * @since 4.5.0
514
-	 * @deprecated 9.0.0 Use annotations based on the app framework.
515
-	 */
516
-	public static function callCheck() {
517
-		if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
518
-			header('Location: '.\OC::$WEBROOT);
519
-			exit();
520
-		}
521
-
522
-		if (!\OC::$server->getRequest()->passesCSRFCheck()) {
523
-			exit();
524
-		}
525
-	}
526
-
527
-	/**
528
-	 * Used to sanitize HTML
529
-	 *
530
-	 * This function is used to sanitize HTML and should be applied on any
531
-	 * string or array of strings before displaying it on a web page.
532
-	 *
533
-	 * @param string|array $value
534
-	 * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
535
-	 * @since 4.5.0
536
-	 */
537
-	public static function sanitizeHTML($value) {
538
-		return \OC_Util::sanitizeHTML($value);
539
-	}
540
-
541
-	/**
542
-	 * Public function to encode url parameters
543
-	 *
544
-	 * This function is used to encode path to file before output.
545
-	 * Encoding is done according to RFC 3986 with one exception:
546
-	 * Character '/' is preserved as is.
547
-	 *
548
-	 * @param string $component part of URI to encode
549
-	 * @return string
550
-	 * @since 6.0.0
551
-	 */
552
-	public static function encodePath($component) {
553
-		return \OC_Util::encodePath($component);
554
-	}
555
-
556
-	/**
557
-	 * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
558
-	 *
559
-	 * @param array $input The array to work on
560
-	 * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
561
-	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
562
-	 * @return array
563
-	 * @since 4.5.0
564
-	 */
565
-	public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
566
-		return \OC_Helper::mb_array_change_key_case($input, $case, $encoding);
567
-	}
568
-
569
-	/**
570
-	 * replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.
571
-	 *
572
-	 * @param string $string The input string. Opposite to the PHP build-in function does not accept an array.
573
-	 * @param string $replacement The replacement string.
574
-	 * @param int $start If start is positive, the replacing will begin at the start'th offset into string. If start is negative, the replacing will begin at the start'th character from the end of string.
575
-	 * @param int $length Length of the part to be replaced
576
-	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
577
-	 * @return string
578
-	 * @since 4.5.0
579
-	 * @deprecated 8.2.0 Use substr_replace() instead.
580
-	 */
581
-	public static function mb_substr_replace($string, $replacement, $start, $length = null, $encoding = 'UTF-8') {
582
-		return substr_replace($string, $replacement, $start, $length);
583
-	}
584
-
585
-	/**
586
-	 * Replace all occurrences of the search string with the replacement string
587
-	 *
588
-	 * @param string $search The value being searched for, otherwise known as the needle. String.
589
-	 * @param string $replace The replacement string.
590
-	 * @param string $subject The string or array being searched and replaced on, otherwise known as the haystack.
591
-	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
592
-	 * @param int $count If passed, this will be set to the number of replacements performed.
593
-	 * @return string
594
-	 * @since 4.5.0
595
-	 * @deprecated 8.2.0 Use str_replace() instead.
596
-	 */
597
-	public static function mb_str_replace($search, $replace, $subject, $encoding = 'UTF-8', &$count = null) {
598
-		return str_replace($search, $replace, $subject, $count);
599
-	}
600
-
601
-	/**
602
-	 * performs a search in a nested array
603
-	 *
604
-	 * @param array $haystack the array to be searched
605
-	 * @param string $needle the search string
606
-	 * @param mixed $index optional, only search this key name
607
-	 * @return mixed the key of the matching field, otherwise false
608
-	 * @since 4.5.0
609
-	 */
610
-	public static function recursiveArraySearch($haystack, $needle, $index = null) {
611
-		return \OC_Helper::recursiveArraySearch($haystack, $needle, $index);
612
-	}
613
-
614
-	/**
615
-	 * calculates the maximum upload size respecting system settings, free space and user quota
616
-	 *
617
-	 * @param string $dir the current folder where the user currently operates
618
-	 * @param int $free the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
619
-	 * @return int number of bytes representing
620
-	 * @since 5.0.0
621
-	 */
622
-	public static function maxUploadFilesize($dir, $free = null) {
623
-		return \OC_Helper::maxUploadFilesize($dir, $free);
624
-	}
625
-
626
-	/**
627
-	 * Calculate free space left within user quota
628
-	 * @param string $dir the current folder where the user currently operates
629
-	 * @return int number of bytes representing
630
-	 * @since 7.0.0
631
-	 */
632
-	public static function freeSpace($dir) {
633
-		return \OC_Helper::freeSpace($dir);
634
-	}
635
-
636
-	/**
637
-	 * Calculate PHP upload limit
638
-	 *
639
-	 * @return int number of bytes representing
640
-	 * @since 7.0.0
641
-	 */
642
-	public static function uploadLimit() {
643
-		return \OC_Helper::uploadLimit();
644
-	}
645
-
646
-	/**
647
-	 * Returns whether the given file name is valid
648
-	 * @param string $file file name to check
649
-	 * @return bool true if the file name is valid, false otherwise
650
-	 * @deprecated 8.1.0 use \OC\Files\View::verifyPath()
651
-	 * @since 7.0.0
652
-	 * @suppress PhanDeprecatedFunction
653
-	 */
654
-	public static function isValidFileName($file) {
655
-		return \OC_Util::isValidFileName($file);
656
-	}
657
-
658
-	/**
659
-	 * Generates a cryptographic secure pseudo-random string
660
-	 * @param int $length of the random string
661
-	 * @return string
662
-	 * @deprecated 8.0.0 Use \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate($length); instead
663
-	 * @since 7.0.0
664
-	 */
665
-	public static function generateRandomBytes($length = 30) {
666
-		return \OC::$server->getSecureRandom()->generate($length, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
667
-	}
668
-
669
-	/**
670
-	 * Compare two strings to provide a natural sort
671
-	 * @param string $a first string to compare
672
-	 * @param string $b second string to compare
673
-	 * @return int -1 if $b comes before $a, 1 if $a comes before $b
674
-	 * or 0 if the strings are identical
675
-	 * @since 7.0.0
676
-	 */
677
-	public static function naturalSortCompare($a, $b) {
678
-		return \OC\NaturalSort::getInstance()->compare($a, $b);
679
-	}
680
-
681
-	/**
682
-	 * check if a password is required for each public link
683
-	 * @return boolean
684
-	 * @since 7.0.0
685
-	 */
686
-	public static function isPublicLinkPasswordRequired() {
687
-		return \OC_Util::isPublicLinkPasswordRequired();
688
-	}
689
-
690
-	/**
691
-	 * check if share API enforces a default expire date
692
-	 * @return boolean
693
-	 * @since 8.0.0
694
-	 */
695
-	public static function isDefaultExpireDateEnforced() {
696
-		return \OC_Util::isDefaultExpireDateEnforced();
697
-	}
698
-
699
-	protected static $needUpgradeCache = null;
700
-
701
-	/**
702
-	 * Checks whether the current version needs upgrade.
703
-	 *
704
-	 * @return bool true if upgrade is needed, false otherwise
705
-	 * @since 7.0.0
706
-	 */
707
-	public static function needUpgrade() {
708
-		if (!isset(self::$needUpgradeCache)) {
709
-			self::$needUpgradeCache=\OC_Util::needUpgrade(\OC::$server->getSystemConfig());
710
-		}		
711
-		return self::$needUpgradeCache;
712
-	}
88
+    /**
89
+     * Get current update channel
90
+     * @return string
91
+     * @since 8.1.0
92
+     */
93
+    public static function getChannel() {
94
+        return \OC_Util::getChannel();
95
+    }
96
+
97
+    /**
98
+     * send an email
99
+     * @param string $toaddress
100
+     * @param string $toname
101
+     * @param string $subject
102
+     * @param string $mailtext
103
+     * @param string $fromaddress
104
+     * @param string $fromname
105
+     * @param int $html
106
+     * @param string $altbody
107
+     * @param string $ccaddress
108
+     * @param string $ccname
109
+     * @param string $bcc
110
+     * @deprecated 8.1.0 Use \OCP\Mail\IMailer instead
111
+     * @since 4.0.0
112
+     */
113
+    public static function sendMail($toaddress, $toname, $subject, $mailtext, $fromaddress, $fromname,
114
+        $html = 0, $altbody = '', $ccaddress = '', $ccname = '', $bcc = '') {
115
+        $mailer = \OC::$server->getMailer();
116
+        $message = $mailer->createMessage();
117
+        $message->setTo([$toaddress => $toname]);
118
+        $message->setSubject($subject);
119
+        $message->setPlainBody($mailtext);
120
+        $message->setFrom([$fromaddress => $fromname]);
121
+        if($html === 1) {
122
+            $message->setHtmlBody($altbody);
123
+        }
124
+
125
+        if($altbody === '') {
126
+            $message->setHtmlBody($mailtext);
127
+            $message->setPlainBody('');
128
+        } else {
129
+            $message->setHtmlBody($mailtext);
130
+            $message->setPlainBody($altbody);
131
+        }
132
+
133
+        if(!empty($ccaddress)) {
134
+            if(!empty($ccname)) {
135
+                $message->setCc([$ccaddress => $ccname]);
136
+            } else {
137
+                $message->setCc([$ccaddress]);
138
+            }
139
+        }
140
+        if(!empty($bcc)) {
141
+            $message->setBcc([$bcc]);
142
+        }
143
+
144
+        $mailer->send($message);
145
+    }
146
+
147
+    /**
148
+     * write a message in the log
149
+     * @param string $app
150
+     * @param string $message
151
+     * @param int $level
152
+     * @since 4.0.0
153
+     * @deprecated 13.0.0 use log of \OCP\ILogger
154
+     */
155
+    public static function writeLog( $app, $message, $level ) {
156
+        $context = ['app' => $app];
157
+        \OC::$server->getLogger()->log($level, $message, $context);
158
+    }
159
+
160
+    /**
161
+     * write exception into the log
162
+     * @param string $app app name
163
+     * @param \Exception $ex exception to log
164
+     * @param int $level log level, defaults to \OCP\Util::FATAL
165
+     * @since ....0.0 - parameter $level was added in 7.0.0
166
+     * @deprecated 8.2.0 use logException of \OCP\ILogger
167
+     */
168
+    public static function logException( $app, \Exception $ex, $level = \OCP\Util::FATAL ) {
169
+        \OC::$server->getLogger()->logException($ex, ['app' => $app]);
170
+    }
171
+
172
+    /**
173
+     * check if sharing is disabled for the current user
174
+     *
175
+     * @return boolean
176
+     * @since 7.0.0
177
+     * @deprecated 9.1.0 Use \OC::$server->getShareManager()->sharingDisabledForUser
178
+     */
179
+    public static function isSharingDisabledForUser() {
180
+        if (self::$shareManager === null) {
181
+            self::$shareManager = \OC::$server->getShareManager();
182
+        }
183
+
184
+        $user = \OC::$server->getUserSession()->getUser();
185
+        if ($user !== null) {
186
+            $user = $user->getUID();
187
+        }
188
+
189
+        return self::$shareManager->sharingDisabledForUser($user);
190
+    }
191
+
192
+    /**
193
+     * get l10n object
194
+     * @param string $application
195
+     * @param string|null $language
196
+     * @return \OCP\IL10N
197
+     * @since 6.0.0 - parameter $language was added in 8.0.0
198
+     */
199
+    public static function getL10N($application, $language = null) {
200
+        return \OC::$server->getL10N($application, $language);
201
+    }
202
+
203
+    /**
204
+     * add a css file
205
+     * @param string $application
206
+     * @param string $file
207
+     * @since 4.0.0
208
+     */
209
+    public static function addStyle( $application, $file = null ) {
210
+        \OC_Util::addStyle( $application, $file );
211
+    }
212
+
213
+    /**
214
+     * add a javascript file
215
+     * @param string $application
216
+     * @param string $file
217
+     * @since 4.0.0
218
+     */
219
+    public static function addScript( $application, $file = null ) {
220
+        \OC_Util::addScript( $application, $file );
221
+    }
222
+
223
+    /**
224
+     * Add a translation JS file
225
+     * @param string $application application id
226
+     * @param string $languageCode language code, defaults to the current locale
227
+     * @since 8.0.0
228
+     */
229
+    public static function addTranslations($application, $languageCode = null) {
230
+        \OC_Util::addTranslations($application, $languageCode);
231
+    }
232
+
233
+    /**
234
+     * Add a custom element to the header
235
+     * If $text is null then the element will be written as empty element.
236
+     * So use "" to get a closing tag.
237
+     * @param string $tag tag name of the element
238
+     * @param array $attributes array of attributes for the element
239
+     * @param string $text the text content for the element
240
+     * @since 4.0.0
241
+     */
242
+    public static function addHeader($tag, $attributes, $text=null) {
243
+        \OC_Util::addHeader($tag, $attributes, $text);
244
+    }
245
+
246
+    /**
247
+     * formats a timestamp in the "right" way
248
+     * @param int $timestamp $timestamp
249
+     * @param bool $dateOnly option to omit time from the result
250
+     * @param DateTimeZone|string $timeZone where the given timestamp shall be converted to
251
+     * @return string timestamp
252
+     *
253
+     * @deprecated 8.0.0 Use \OC::$server->query('DateTimeFormatter') instead
254
+     * @since 4.0.0
255
+     * @suppress PhanDeprecatedFunction
256
+     */
257
+    public static function formatDate($timestamp, $dateOnly=false, $timeZone = null) {
258
+        return \OC_Util::formatDate($timestamp, $dateOnly, $timeZone);
259
+    }
260
+
261
+    /**
262
+     * check if some encrypted files are stored
263
+     * @return bool
264
+     *
265
+     * @deprecated 8.1.0 No longer required
266
+     * @since 6.0.0
267
+     */
268
+    public static function encryptedFiles() {
269
+        return false;
270
+    }
271
+
272
+    /**
273
+     * Creates an absolute url to the given app and file.
274
+     * @param string $app app
275
+     * @param string $file file
276
+     * @param array $args array with param=>value, will be appended to the returned url
277
+     * 	The value of $args will be urlencoded
278
+     * @return string the url
279
+     * @since 4.0.0 - parameter $args was added in 4.5.0
280
+     */
281
+    public static function linkToAbsolute( $app, $file, $args = array() ) {
282
+        $urlGenerator = \OC::$server->getURLGenerator();
283
+        return $urlGenerator->getAbsoluteURL(
284
+            $urlGenerator->linkTo($app, $file, $args)
285
+        );
286
+    }
287
+
288
+    /**
289
+     * Creates an absolute url for remote use.
290
+     * @param string $service id
291
+     * @return string the url
292
+     * @since 4.0.0
293
+     */
294
+    public static function linkToRemote( $service ) {
295
+        $urlGenerator = \OC::$server->getURLGenerator();
296
+        $remoteBase = $urlGenerator->linkTo('', 'remote.php') . '/' . $service;
297
+        return $urlGenerator->getAbsoluteURL(
298
+            $remoteBase . (($service[strlen($service) - 1] != '/') ? '/' : '')
299
+        );
300
+    }
301
+
302
+    /**
303
+     * Creates an absolute url for public use
304
+     * @param string $service id
305
+     * @return string the url
306
+     * @since 4.5.0
307
+     */
308
+    public static function linkToPublic($service) {
309
+        return \OC_Helper::linkToPublic($service);
310
+    }
311
+
312
+    /**
313
+     * Creates an url using a defined route
314
+     * @param string $route
315
+     * @param array $parameters
316
+     * @internal param array $args with param=>value, will be appended to the returned url
317
+     * @return string the url
318
+     * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->linkToRoute($route, $parameters)
319
+     * @since 5.0.0
320
+     */
321
+    public static function linkToRoute( $route, $parameters = array() ) {
322
+        return \OC::$server->getURLGenerator()->linkToRoute($route, $parameters);
323
+    }
324
+
325
+    /**
326
+     * Creates an url to the given app and file
327
+     * @param string $app app
328
+     * @param string $file file
329
+     * @param array $args array with param=>value, will be appended to the returned url
330
+     * 	The value of $args will be urlencoded
331
+     * @return string the url
332
+     * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->linkTo($app, $file, $args)
333
+     * @since 4.0.0 - parameter $args was added in 4.5.0
334
+     */
335
+    public static function linkTo( $app, $file, $args = array() ) {
336
+        return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
337
+    }
338
+
339
+    /**
340
+     * Returns the server host, even if the website uses one or more reverse proxy
341
+     * @return string the server host
342
+     * @deprecated 8.1.0 Use \OCP\IRequest::getServerHost
343
+     * @since 4.0.0
344
+     */
345
+    public static function getServerHost() {
346
+        return \OC::$server->getRequest()->getServerHost();
347
+    }
348
+
349
+    /**
350
+     * Returns the server host name without an eventual port number
351
+     * @return string the server hostname
352
+     * @since 5.0.0
353
+     */
354
+    public static function getServerHostName() {
355
+        $host_name = \OC::$server->getRequest()->getServerHost();
356
+        // strip away port number (if existing)
357
+        $colon_pos = strpos($host_name, ':');
358
+        if ($colon_pos != FALSE) {
359
+            $host_name = substr($host_name, 0, $colon_pos);
360
+        }
361
+        return $host_name;
362
+    }
363
+
364
+    /**
365
+     * Returns the default email address
366
+     * @param string $user_part the user part of the address
367
+     * @return string the default email address
368
+     *
369
+     * Assembles a default email address (using the server hostname
370
+     * and the given user part, and returns it
371
+     * Example: when given lostpassword-noreply as $user_part param,
372
+     *     and is currently accessed via http(s)://example.com/,
373
+     *     it would return '[email protected]'
374
+     *
375
+     * If the configuration value 'mail_from_address' is set in
376
+     * config.php, this value will override the $user_part that
377
+     * is passed to this function
378
+     * @since 5.0.0
379
+     */
380
+    public static function getDefaultEmailAddress($user_part) {
381
+        $config = \OC::$server->getConfig();
382
+        $user_part = $config->getSystemValue('mail_from_address', $user_part);
383
+        $host_name = self::getServerHostName();
384
+        $host_name = $config->getSystemValue('mail_domain', $host_name);
385
+        $defaultEmailAddress = $user_part.'@'.$host_name;
386
+
387
+        $mailer = \OC::$server->getMailer();
388
+        if ($mailer->validateMailAddress($defaultEmailAddress)) {
389
+            return $defaultEmailAddress;
390
+        }
391
+
392
+        // in case we cannot build a valid email address from the hostname let's fallback to 'localhost.localdomain'
393
+        return $user_part.'@localhost.localdomain';
394
+    }
395
+
396
+    /**
397
+     * Returns the server protocol. It respects reverse proxy servers and load balancers
398
+     * @return string the server protocol
399
+     * @deprecated 8.1.0 Use \OCP\IRequest::getServerProtocol
400
+     * @since 4.5.0
401
+     */
402
+    public static function getServerProtocol() {
403
+        return \OC::$server->getRequest()->getServerProtocol();
404
+    }
405
+
406
+    /**
407
+     * Returns the request uri, even if the website uses one or more reverse proxies
408
+     * @return string the request uri
409
+     * @deprecated 8.1.0 Use \OCP\IRequest::getRequestUri
410
+     * @since 5.0.0
411
+     */
412
+    public static function getRequestUri() {
413
+        return \OC::$server->getRequest()->getRequestUri();
414
+    }
415
+
416
+    /**
417
+     * Returns the script name, even if the website uses one or more reverse proxies
418
+     * @return string the script name
419
+     * @deprecated 8.1.0 Use \OCP\IRequest::getScriptName
420
+     * @since 5.0.0
421
+     */
422
+    public static function getScriptName() {
423
+        return \OC::$server->getRequest()->getScriptName();
424
+    }
425
+
426
+    /**
427
+     * Creates path to an image
428
+     * @param string $app app
429
+     * @param string $image image name
430
+     * @return string the url
431
+     * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->imagePath($app, $image)
432
+     * @since 4.0.0
433
+     */
434
+    public static function imagePath( $app, $image ) {
435
+        return \OC::$server->getURLGenerator()->imagePath($app, $image);
436
+    }
437
+
438
+    /**
439
+     * Make a human file size (2048 to 2 kB)
440
+     * @param int $bytes file size in bytes
441
+     * @return string a human readable file size
442
+     * @since 4.0.0
443
+     */
444
+    public static function humanFileSize($bytes) {
445
+        return \OC_Helper::humanFileSize($bytes);
446
+    }
447
+
448
+    /**
449
+     * Make a computer file size (2 kB to 2048)
450
+     * @param string $str file size in a fancy format
451
+     * @return float a file size in bytes
452
+     *
453
+     * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
454
+     * @since 4.0.0
455
+     */
456
+    public static function computerFileSize($str) {
457
+        return \OC_Helper::computerFileSize($str);
458
+    }
459
+
460
+    /**
461
+     * connects a function to a hook
462
+     *
463
+     * @param string $signalClass class name of emitter
464
+     * @param string $signalName name of signal
465
+     * @param string|object $slotClass class name of slot
466
+     * @param string $slotName name of slot
467
+     * @return bool
468
+     *
469
+     * This function makes it very easy to connect to use hooks.
470
+     *
471
+     * TODO: write example
472
+     * @since 4.0.0
473
+     */
474
+    static public function connectHook($signalClass, $signalName, $slotClass, $slotName) {
475
+        return \OC_Hook::connect($signalClass, $signalName, $slotClass, $slotName);
476
+    }
477
+
478
+    /**
479
+     * Emits a signal. To get data from the slot use references!
480
+     * @param string $signalclass class name of emitter
481
+     * @param string $signalname name of signal
482
+     * @param array $params default: array() array with additional data
483
+     * @return bool true if slots exists or false if not
484
+     *
485
+     * TODO: write example
486
+     * @since 4.0.0
487
+     */
488
+    static public function emitHook($signalclass, $signalname, $params = array()) {
489
+        return \OC_Hook::emit($signalclass, $signalname, $params);
490
+    }
491
+
492
+    /**
493
+     * Cached encrypted CSRF token. Some static unit-tests of ownCloud compare
494
+     * multiple OC_Template elements which invoke `callRegister`. If the value
495
+     * would not be cached these unit-tests would fail.
496
+     * @var string
497
+     */
498
+    private static $token = '';
499
+
500
+    /**
501
+     * Register an get/post call. This is important to prevent CSRF attacks
502
+     * @since 4.5.0
503
+     */
504
+    public static function callRegister() {
505
+        if(self::$token === '') {
506
+            self::$token = \OC::$server->getCsrfTokenManager()->getToken()->getEncryptedValue();
507
+        }
508
+        return self::$token;
509
+    }
510
+
511
+    /**
512
+     * Check an ajax get/post call if the request token is valid. exit if not.
513
+     * @since 4.5.0
514
+     * @deprecated 9.0.0 Use annotations based on the app framework.
515
+     */
516
+    public static function callCheck() {
517
+        if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
518
+            header('Location: '.\OC::$WEBROOT);
519
+            exit();
520
+        }
521
+
522
+        if (!\OC::$server->getRequest()->passesCSRFCheck()) {
523
+            exit();
524
+        }
525
+    }
526
+
527
+    /**
528
+     * Used to sanitize HTML
529
+     *
530
+     * This function is used to sanitize HTML and should be applied on any
531
+     * string or array of strings before displaying it on a web page.
532
+     *
533
+     * @param string|array $value
534
+     * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
535
+     * @since 4.5.0
536
+     */
537
+    public static function sanitizeHTML($value) {
538
+        return \OC_Util::sanitizeHTML($value);
539
+    }
540
+
541
+    /**
542
+     * Public function to encode url parameters
543
+     *
544
+     * This function is used to encode path to file before output.
545
+     * Encoding is done according to RFC 3986 with one exception:
546
+     * Character '/' is preserved as is.
547
+     *
548
+     * @param string $component part of URI to encode
549
+     * @return string
550
+     * @since 6.0.0
551
+     */
552
+    public static function encodePath($component) {
553
+        return \OC_Util::encodePath($component);
554
+    }
555
+
556
+    /**
557
+     * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
558
+     *
559
+     * @param array $input The array to work on
560
+     * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
561
+     * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
562
+     * @return array
563
+     * @since 4.5.0
564
+     */
565
+    public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
566
+        return \OC_Helper::mb_array_change_key_case($input, $case, $encoding);
567
+    }
568
+
569
+    /**
570
+     * replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.
571
+     *
572
+     * @param string $string The input string. Opposite to the PHP build-in function does not accept an array.
573
+     * @param string $replacement The replacement string.
574
+     * @param int $start If start is positive, the replacing will begin at the start'th offset into string. If start is negative, the replacing will begin at the start'th character from the end of string.
575
+     * @param int $length Length of the part to be replaced
576
+     * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
577
+     * @return string
578
+     * @since 4.5.0
579
+     * @deprecated 8.2.0 Use substr_replace() instead.
580
+     */
581
+    public static function mb_substr_replace($string, $replacement, $start, $length = null, $encoding = 'UTF-8') {
582
+        return substr_replace($string, $replacement, $start, $length);
583
+    }
584
+
585
+    /**
586
+     * Replace all occurrences of the search string with the replacement string
587
+     *
588
+     * @param string $search The value being searched for, otherwise known as the needle. String.
589
+     * @param string $replace The replacement string.
590
+     * @param string $subject The string or array being searched and replaced on, otherwise known as the haystack.
591
+     * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
592
+     * @param int $count If passed, this will be set to the number of replacements performed.
593
+     * @return string
594
+     * @since 4.5.0
595
+     * @deprecated 8.2.0 Use str_replace() instead.
596
+     */
597
+    public static function mb_str_replace($search, $replace, $subject, $encoding = 'UTF-8', &$count = null) {
598
+        return str_replace($search, $replace, $subject, $count);
599
+    }
600
+
601
+    /**
602
+     * performs a search in a nested array
603
+     *
604
+     * @param array $haystack the array to be searched
605
+     * @param string $needle the search string
606
+     * @param mixed $index optional, only search this key name
607
+     * @return mixed the key of the matching field, otherwise false
608
+     * @since 4.5.0
609
+     */
610
+    public static function recursiveArraySearch($haystack, $needle, $index = null) {
611
+        return \OC_Helper::recursiveArraySearch($haystack, $needle, $index);
612
+    }
613
+
614
+    /**
615
+     * calculates the maximum upload size respecting system settings, free space and user quota
616
+     *
617
+     * @param string $dir the current folder where the user currently operates
618
+     * @param int $free the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
619
+     * @return int number of bytes representing
620
+     * @since 5.0.0
621
+     */
622
+    public static function maxUploadFilesize($dir, $free = null) {
623
+        return \OC_Helper::maxUploadFilesize($dir, $free);
624
+    }
625
+
626
+    /**
627
+     * Calculate free space left within user quota
628
+     * @param string $dir the current folder where the user currently operates
629
+     * @return int number of bytes representing
630
+     * @since 7.0.0
631
+     */
632
+    public static function freeSpace($dir) {
633
+        return \OC_Helper::freeSpace($dir);
634
+    }
635
+
636
+    /**
637
+     * Calculate PHP upload limit
638
+     *
639
+     * @return int number of bytes representing
640
+     * @since 7.0.0
641
+     */
642
+    public static function uploadLimit() {
643
+        return \OC_Helper::uploadLimit();
644
+    }
645
+
646
+    /**
647
+     * Returns whether the given file name is valid
648
+     * @param string $file file name to check
649
+     * @return bool true if the file name is valid, false otherwise
650
+     * @deprecated 8.1.0 use \OC\Files\View::verifyPath()
651
+     * @since 7.0.0
652
+     * @suppress PhanDeprecatedFunction
653
+     */
654
+    public static function isValidFileName($file) {
655
+        return \OC_Util::isValidFileName($file);
656
+    }
657
+
658
+    /**
659
+     * Generates a cryptographic secure pseudo-random string
660
+     * @param int $length of the random string
661
+     * @return string
662
+     * @deprecated 8.0.0 Use \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate($length); instead
663
+     * @since 7.0.0
664
+     */
665
+    public static function generateRandomBytes($length = 30) {
666
+        return \OC::$server->getSecureRandom()->generate($length, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
667
+    }
668
+
669
+    /**
670
+     * Compare two strings to provide a natural sort
671
+     * @param string $a first string to compare
672
+     * @param string $b second string to compare
673
+     * @return int -1 if $b comes before $a, 1 if $a comes before $b
674
+     * or 0 if the strings are identical
675
+     * @since 7.0.0
676
+     */
677
+    public static function naturalSortCompare($a, $b) {
678
+        return \OC\NaturalSort::getInstance()->compare($a, $b);
679
+    }
680
+
681
+    /**
682
+     * check if a password is required for each public link
683
+     * @return boolean
684
+     * @since 7.0.0
685
+     */
686
+    public static function isPublicLinkPasswordRequired() {
687
+        return \OC_Util::isPublicLinkPasswordRequired();
688
+    }
689
+
690
+    /**
691
+     * check if share API enforces a default expire date
692
+     * @return boolean
693
+     * @since 8.0.0
694
+     */
695
+    public static function isDefaultExpireDateEnforced() {
696
+        return \OC_Util::isDefaultExpireDateEnforced();
697
+    }
698
+
699
+    protected static $needUpgradeCache = null;
700
+
701
+    /**
702
+     * Checks whether the current version needs upgrade.
703
+     *
704
+     * @return bool true if upgrade is needed, false otherwise
705
+     * @since 7.0.0
706
+     */
707
+    public static function needUpgrade() {
708
+        if (!isset(self::$needUpgradeCache)) {
709
+            self::$needUpgradeCache=\OC_Util::needUpgrade(\OC::$server->getSystemConfig());
710
+        }		
711
+        return self::$needUpgradeCache;
712
+    }
713 713
 }
Please login to merge, or discard this patch.
lib/public/AppFramework/Http/DataDisplayResponse.php 1 patch
Indentation   +44 added lines, -44 removed lines patch added patch discarded remove patch
@@ -33,57 +33,57 @@
 block discarded – undo
33 33
  */
34 34
 class DataDisplayResponse extends Response {
35 35
 
36
-	/**
37
-	 * response data
38
-	 * @var string
39
-	 */
40
-	protected $data;
36
+    /**
37
+     * response data
38
+     * @var string
39
+     */
40
+    protected $data;
41 41
 
42 42
 
43
-	/**
44
-	 * @param string $data the data to display
45
-	 * @param int $statusCode the Http status code, defaults to 200
46
-	 * @param array $headers additional key value based headers
47
-	 * @since 8.1.0
48
-	 */
49
-	public function __construct($data='', $statusCode=Http::STATUS_OK,
50
-	                            $headers=[]) {
51
-		$this->data = $data;
52
-		$this->setStatus($statusCode);
53
-		$this->setHeaders(array_merge($this->getHeaders(), $headers));
54
-		$this->addHeader('Content-Disposition', 'inline; filename=""');
55
-	}
43
+    /**
44
+     * @param string $data the data to display
45
+     * @param int $statusCode the Http status code, defaults to 200
46
+     * @param array $headers additional key value based headers
47
+     * @since 8.1.0
48
+     */
49
+    public function __construct($data='', $statusCode=Http::STATUS_OK,
50
+                                $headers=[]) {
51
+        $this->data = $data;
52
+        $this->setStatus($statusCode);
53
+        $this->setHeaders(array_merge($this->getHeaders(), $headers));
54
+        $this->addHeader('Content-Disposition', 'inline; filename=""');
55
+    }
56 56
 
57
-	/**
58
-	 * Outputs data. No processing is done.
59
-	 * @return string
60
-	 * @since 8.1.0
61
-	 */
62
-	public function render() {
63
-		return $this->data;
64
-	}
57
+    /**
58
+     * Outputs data. No processing is done.
59
+     * @return string
60
+     * @since 8.1.0
61
+     */
62
+    public function render() {
63
+        return $this->data;
64
+    }
65 65
 
66 66
 
67
-	/**
68
-	 * Sets values in the data
69
-	 * @param string $data the data to display
70
-	 * @return DataDisplayResponse Reference to this object
71
-	 * @since 8.1.0
72
-	 */
73
-	public function setData($data){
74
-		$this->data = $data;
67
+    /**
68
+     * Sets values in the data
69
+     * @param string $data the data to display
70
+     * @return DataDisplayResponse Reference to this object
71
+     * @since 8.1.0
72
+     */
73
+    public function setData($data){
74
+        $this->data = $data;
75 75
 
76
-		return $this;
77
-	}
76
+        return $this;
77
+    }
78 78
 
79 79
 
80
-	/**
81
-	 * Used to get the set parameters
82
-	 * @return string the data
83
-	 * @since 8.1.0
84
-	 */
85
-	public function getData(){
86
-		return $this->data;
87
-	}
80
+    /**
81
+     * Used to get the set parameters
82
+     * @return string the data
83
+     * @since 8.1.0
84
+     */
85
+    public function getData(){
86
+        return $this->data;
87
+    }
88 88
 
89 89
 }
Please login to merge, or discard this patch.
lib/private/Files/FileInfo.php 1 patch
Indentation   +352 added lines, -352 removed lines patch added patch discarded remove patch
@@ -35,356 +35,356 @@
 block discarded – undo
35 35
 use OCP\IUser;
36 36
 
37 37
 class FileInfo implements \OCP\Files\FileInfo, \ArrayAccess {
38
-	/**
39
-	 * @var array $data
40
-	 */
41
-	private $data;
42
-
43
-	/**
44
-	 * @var string $path
45
-	 */
46
-	private $path;
47
-
48
-	/**
49
-	 * @var \OC\Files\Storage\Storage $storage
50
-	 */
51
-	private $storage;
52
-
53
-	/**
54
-	 * @var string $internalPath
55
-	 */
56
-	private $internalPath;
57
-
58
-	/**
59
-	 * @var \OCP\Files\Mount\IMountPoint
60
-	 */
61
-	private $mount;
62
-
63
-	/**
64
-	 * @var IUser
65
-	 */
66
-	private $owner;
67
-
68
-	/**
69
-	 * @var string[]
70
-	 */
71
-	private $childEtags = [];
72
-
73
-	/**
74
-	 * @var IMountPoint[]
75
-	 */
76
-	private $subMounts = [];
77
-
78
-	private $subMountsUsed = false;
79
-
80
-	/**
81
-	 * @param string|boolean $path
82
-	 * @param Storage\Storage $storage
83
-	 * @param string $internalPath
84
-	 * @param array|ICacheEntry $data
85
-	 * @param \OCP\Files\Mount\IMountPoint $mount
86
-	 * @param \OCP\IUser|null $owner
87
-	 */
88
-	public function __construct($path, $storage, $internalPath, $data, $mount, $owner= null) {
89
-		$this->path = $path;
90
-		$this->storage = $storage;
91
-		$this->internalPath = $internalPath;
92
-		$this->data = $data;
93
-		$this->mount = $mount;
94
-		$this->owner = $owner;
95
-	}
96
-
97
-	public function offsetSet($offset, $value) {
98
-		$this->data[$offset] = $value;
99
-	}
100
-
101
-	public function offsetExists($offset) {
102
-		return isset($this->data[$offset]);
103
-	}
104
-
105
-	public function offsetUnset($offset) {
106
-		unset($this->data[$offset]);
107
-	}
108
-
109
-	public function offsetGet($offset) {
110
-		if ($offset === 'type') {
111
-			return $this->getType();
112
-		} else if ($offset === 'etag') {
113
-			return $this->getEtag();
114
-		} else if ($offset === 'size') {
115
-			return $this->getSize();
116
-		} else if ($offset === 'mtime') {
117
-			return $this->getMTime();
118
-		} elseif ($offset === 'permissions') {
119
-			return $this->getPermissions();
120
-		} elseif (isset($this->data[$offset])) {
121
-			return $this->data[$offset];
122
-		} else {
123
-			return null;
124
-		}
125
-	}
126
-
127
-	/**
128
-	 * @return string
129
-	 */
130
-	public function getPath() {
131
-		return $this->path;
132
-	}
133
-
134
-	/**
135
-	 * @return \OCP\Files\Storage
136
-	 */
137
-	public function getStorage() {
138
-		return $this->storage;
139
-	}
140
-
141
-	/**
142
-	 * @return string
143
-	 */
144
-	public function getInternalPath() {
145
-		return $this->internalPath;
146
-	}
147
-
148
-	/**
149
-	 * Get FileInfo ID or null in case of part file
150
-	 *
151
-	 * @return int|null
152
-	 */
153
-	public function getId() {
154
-		return isset($this->data['fileid']) ? (int)  $this->data['fileid'] : null;
155
-	}
156
-
157
-	/**
158
-	 * @return string
159
-	 */
160
-	public function getMimetype() {
161
-		return $this->data['mimetype'];
162
-	}
163
-
164
-	/**
165
-	 * @return string
166
-	 */
167
-	public function getMimePart() {
168
-		return $this->data['mimepart'];
169
-	}
170
-
171
-	/**
172
-	 * @return string
173
-	 */
174
-	public function getName() {
175
-		return basename($this->getPath());
176
-	}
177
-
178
-	/**
179
-	 * @return string
180
-	 */
181
-	public function getEtag() {
182
-		$this->updateEntryfromSubMounts();
183
-		if (count($this->childEtags) > 0) {
184
-			$combinedEtag = $this->data['etag'] . '::' . implode('::', $this->childEtags);
185
-			return md5($combinedEtag);
186
-		} else {
187
-			return $this->data['etag'];
188
-		}
189
-	}
190
-
191
-	/**
192
-	 * @return int
193
-	 */
194
-	public function getSize() {
195
-		$this->updateEntryfromSubMounts();
196
-		return isset($this->data['size']) ? 0 + $this->data['size'] : 0;
197
-	}
198
-
199
-	/**
200
-	 * @return int
201
-	 */
202
-	public function getMTime() {
203
-		$this->updateEntryfromSubMounts();
204
-		return (int) $this->data['mtime'];
205
-	}
206
-
207
-	/**
208
-	 * @return bool
209
-	 */
210
-	public function isEncrypted() {
211
-		return $this->data['encrypted'];
212
-	}
213
-
214
-	/**
215
-	 * Return the currently version used for the HMAC in the encryption app
216
-	 *
217
-	 * @return int
218
-	 */
219
-	public function getEncryptedVersion() {
220
-		return isset($this->data['encryptedVersion']) ? (int) $this->data['encryptedVersion'] : 1;
221
-	}
222
-
223
-	/**
224
-	 * @return int
225
-	 */
226
-	public function getPermissions() {
227
-		$perms = (int) $this->data['permissions'];
228
-		if (\OCP\Util::isSharingDisabledForUser() || ($this->isShared() && !\OC\Share\Share::isResharingAllowed())) {
229
-			$perms = $perms & ~\OCP\Constants::PERMISSION_SHARE;
230
-		}
231
-		return (int) $perms;
232
-	}
233
-
234
-	/**
235
-	 * @return string \OCP\Files\FileInfo::TYPE_FILE|\OCP\Files\FileInfo::TYPE_FOLDER
236
-	 */
237
-	public function getType() {
238
-		if (!isset($this->data['type'])) {
239
-			$this->data['type'] = ($this->getMimetype() === 'httpd/unix-directory') ? self::TYPE_FOLDER : self::TYPE_FILE;
240
-		}
241
-		return $this->data['type'];
242
-	}
243
-
244
-	public function getData() {
245
-		return $this->data;
246
-	}
247
-
248
-	/**
249
-	 * @param int $permissions
250
-	 * @return bool
251
-	 */
252
-	protected function checkPermissions($permissions) {
253
-		return ($this->getPermissions() & $permissions) === $permissions;
254
-	}
255
-
256
-	/**
257
-	 * @return bool
258
-	 */
259
-	public function isReadable() {
260
-		return $this->checkPermissions(\OCP\Constants::PERMISSION_READ);
261
-	}
262
-
263
-	/**
264
-	 * @return bool
265
-	 */
266
-	public function isUpdateable() {
267
-		return $this->checkPermissions(\OCP\Constants::PERMISSION_UPDATE);
268
-	}
269
-
270
-	/**
271
-	 * Check whether new files or folders can be created inside this folder
272
-	 *
273
-	 * @return bool
274
-	 */
275
-	public function isCreatable() {
276
-		return $this->checkPermissions(\OCP\Constants::PERMISSION_CREATE);
277
-	}
278
-
279
-	/**
280
-	 * @return bool
281
-	 */
282
-	public function isDeletable() {
283
-		return $this->checkPermissions(\OCP\Constants::PERMISSION_DELETE);
284
-	}
285
-
286
-	/**
287
-	 * @return bool
288
-	 */
289
-	public function isShareable() {
290
-		return $this->checkPermissions(\OCP\Constants::PERMISSION_SHARE);
291
-	}
292
-
293
-	/**
294
-	 * Check if a file or folder is shared
295
-	 *
296
-	 * @return bool
297
-	 */
298
-	public function isShared() {
299
-		$sid = $this->getStorage()->getId();
300
-		if (!is_null($sid)) {
301
-			$sid = explode(':', $sid);
302
-			return ($sid[0] === 'shared');
303
-		}
304
-
305
-		return false;
306
-	}
307
-
308
-	public function isMounted() {
309
-		$storage = $this->getStorage();
310
-		if ($storage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
311
-			return false;
312
-		}
313
-		$sid = $storage->getId();
314
-		if (!is_null($sid)) {
315
-			$sid = explode(':', $sid);
316
-			return ($sid[0] !== 'home' and $sid[0] !== 'shared');
317
-		}
318
-
319
-		return false;
320
-	}
321
-
322
-	/**
323
-	 * Get the mountpoint the file belongs to
324
-	 *
325
-	 * @return \OCP\Files\Mount\IMountPoint
326
-	 */
327
-	public function getMountPoint() {
328
-		return $this->mount;
329
-	}
330
-
331
-	/**
332
-	 * Get the owner of the file
333
-	 *
334
-	 * @return \OCP\IUser
335
-	 */
336
-	public function getOwner() {
337
-		return $this->owner;
338
-	}
339
-
340
-	/**
341
-	 * @param IMountPoint[] $mounts
342
-	 */
343
-	public function setSubMounts(array $mounts) {
344
-		$this->subMounts = $mounts;
345
-	}
346
-
347
-	private function updateEntryfromSubMounts() {
348
-		if ($this->subMountsUsed) {
349
-			return;
350
-		}
351
-		$this->subMountsUsed = true;
352
-		foreach ($this->subMounts as $mount) {
353
-			$subStorage = $mount->getStorage();
354
-			if ($subStorage) {
355
-				$subCache = $subStorage->getCache('');
356
-				$rootEntry = $subCache->get('');
357
-				$this->addSubEntry($rootEntry, $mount->getMountPoint());
358
-			}
359
-		}
360
-	}
361
-
362
-	/**
363
-	 * Add a cache entry which is the child of this folder
364
-	 *
365
-	 * Sets the size, etag and size to for cross-storage childs
366
-	 *
367
-	 * @param array|ICacheEntry $data cache entry for the child
368
-	 * @param string $entryPath full path of the child entry
369
-	 */
370
-	public function addSubEntry($data, $entryPath) {
371
-		$this->data['size'] += isset($data['size']) ? $data['size'] : 0;
372
-		if (isset($data['mtime'])) {
373
-			$this->data['mtime'] = max($this->data['mtime'], $data['mtime']);
374
-		}
375
-		if (isset($data['etag'])) {
376
-			// prefix the etag with the relative path of the subentry to propagate etag on mount moves
377
-			$relativeEntryPath = substr($entryPath, strlen($this->getPath()));
378
-			// attach the permissions to propagate etag on permision changes of submounts
379
-			$permissions = isset($data['permissions']) ? $data['permissions'] : 0;
380
-			$this->childEtags[] = $relativeEntryPath . '/' . $data['etag'] . $permissions;
381
-		}
382
-	}
383
-
384
-	/**
385
-	 * @inheritdoc
386
-	 */
387
-	public function getChecksum() {
388
-		return $this->data['checksum'];
389
-	}
38
+    /**
39
+     * @var array $data
40
+     */
41
+    private $data;
42
+
43
+    /**
44
+     * @var string $path
45
+     */
46
+    private $path;
47
+
48
+    /**
49
+     * @var \OC\Files\Storage\Storage $storage
50
+     */
51
+    private $storage;
52
+
53
+    /**
54
+     * @var string $internalPath
55
+     */
56
+    private $internalPath;
57
+
58
+    /**
59
+     * @var \OCP\Files\Mount\IMountPoint
60
+     */
61
+    private $mount;
62
+
63
+    /**
64
+     * @var IUser
65
+     */
66
+    private $owner;
67
+
68
+    /**
69
+     * @var string[]
70
+     */
71
+    private $childEtags = [];
72
+
73
+    /**
74
+     * @var IMountPoint[]
75
+     */
76
+    private $subMounts = [];
77
+
78
+    private $subMountsUsed = false;
79
+
80
+    /**
81
+     * @param string|boolean $path
82
+     * @param Storage\Storage $storage
83
+     * @param string $internalPath
84
+     * @param array|ICacheEntry $data
85
+     * @param \OCP\Files\Mount\IMountPoint $mount
86
+     * @param \OCP\IUser|null $owner
87
+     */
88
+    public function __construct($path, $storage, $internalPath, $data, $mount, $owner= null) {
89
+        $this->path = $path;
90
+        $this->storage = $storage;
91
+        $this->internalPath = $internalPath;
92
+        $this->data = $data;
93
+        $this->mount = $mount;
94
+        $this->owner = $owner;
95
+    }
96
+
97
+    public function offsetSet($offset, $value) {
98
+        $this->data[$offset] = $value;
99
+    }
100
+
101
+    public function offsetExists($offset) {
102
+        return isset($this->data[$offset]);
103
+    }
104
+
105
+    public function offsetUnset($offset) {
106
+        unset($this->data[$offset]);
107
+    }
108
+
109
+    public function offsetGet($offset) {
110
+        if ($offset === 'type') {
111
+            return $this->getType();
112
+        } else if ($offset === 'etag') {
113
+            return $this->getEtag();
114
+        } else if ($offset === 'size') {
115
+            return $this->getSize();
116
+        } else if ($offset === 'mtime') {
117
+            return $this->getMTime();
118
+        } elseif ($offset === 'permissions') {
119
+            return $this->getPermissions();
120
+        } elseif (isset($this->data[$offset])) {
121
+            return $this->data[$offset];
122
+        } else {
123
+            return null;
124
+        }
125
+    }
126
+
127
+    /**
128
+     * @return string
129
+     */
130
+    public function getPath() {
131
+        return $this->path;
132
+    }
133
+
134
+    /**
135
+     * @return \OCP\Files\Storage
136
+     */
137
+    public function getStorage() {
138
+        return $this->storage;
139
+    }
140
+
141
+    /**
142
+     * @return string
143
+     */
144
+    public function getInternalPath() {
145
+        return $this->internalPath;
146
+    }
147
+
148
+    /**
149
+     * Get FileInfo ID or null in case of part file
150
+     *
151
+     * @return int|null
152
+     */
153
+    public function getId() {
154
+        return isset($this->data['fileid']) ? (int)  $this->data['fileid'] : null;
155
+    }
156
+
157
+    /**
158
+     * @return string
159
+     */
160
+    public function getMimetype() {
161
+        return $this->data['mimetype'];
162
+    }
163
+
164
+    /**
165
+     * @return string
166
+     */
167
+    public function getMimePart() {
168
+        return $this->data['mimepart'];
169
+    }
170
+
171
+    /**
172
+     * @return string
173
+     */
174
+    public function getName() {
175
+        return basename($this->getPath());
176
+    }
177
+
178
+    /**
179
+     * @return string
180
+     */
181
+    public function getEtag() {
182
+        $this->updateEntryfromSubMounts();
183
+        if (count($this->childEtags) > 0) {
184
+            $combinedEtag = $this->data['etag'] . '::' . implode('::', $this->childEtags);
185
+            return md5($combinedEtag);
186
+        } else {
187
+            return $this->data['etag'];
188
+        }
189
+    }
190
+
191
+    /**
192
+     * @return int
193
+     */
194
+    public function getSize() {
195
+        $this->updateEntryfromSubMounts();
196
+        return isset($this->data['size']) ? 0 + $this->data['size'] : 0;
197
+    }
198
+
199
+    /**
200
+     * @return int
201
+     */
202
+    public function getMTime() {
203
+        $this->updateEntryfromSubMounts();
204
+        return (int) $this->data['mtime'];
205
+    }
206
+
207
+    /**
208
+     * @return bool
209
+     */
210
+    public function isEncrypted() {
211
+        return $this->data['encrypted'];
212
+    }
213
+
214
+    /**
215
+     * Return the currently version used for the HMAC in the encryption app
216
+     *
217
+     * @return int
218
+     */
219
+    public function getEncryptedVersion() {
220
+        return isset($this->data['encryptedVersion']) ? (int) $this->data['encryptedVersion'] : 1;
221
+    }
222
+
223
+    /**
224
+     * @return int
225
+     */
226
+    public function getPermissions() {
227
+        $perms = (int) $this->data['permissions'];
228
+        if (\OCP\Util::isSharingDisabledForUser() || ($this->isShared() && !\OC\Share\Share::isResharingAllowed())) {
229
+            $perms = $perms & ~\OCP\Constants::PERMISSION_SHARE;
230
+        }
231
+        return (int) $perms;
232
+    }
233
+
234
+    /**
235
+     * @return string \OCP\Files\FileInfo::TYPE_FILE|\OCP\Files\FileInfo::TYPE_FOLDER
236
+     */
237
+    public function getType() {
238
+        if (!isset($this->data['type'])) {
239
+            $this->data['type'] = ($this->getMimetype() === 'httpd/unix-directory') ? self::TYPE_FOLDER : self::TYPE_FILE;
240
+        }
241
+        return $this->data['type'];
242
+    }
243
+
244
+    public function getData() {
245
+        return $this->data;
246
+    }
247
+
248
+    /**
249
+     * @param int $permissions
250
+     * @return bool
251
+     */
252
+    protected function checkPermissions($permissions) {
253
+        return ($this->getPermissions() & $permissions) === $permissions;
254
+    }
255
+
256
+    /**
257
+     * @return bool
258
+     */
259
+    public function isReadable() {
260
+        return $this->checkPermissions(\OCP\Constants::PERMISSION_READ);
261
+    }
262
+
263
+    /**
264
+     * @return bool
265
+     */
266
+    public function isUpdateable() {
267
+        return $this->checkPermissions(\OCP\Constants::PERMISSION_UPDATE);
268
+    }
269
+
270
+    /**
271
+     * Check whether new files or folders can be created inside this folder
272
+     *
273
+     * @return bool
274
+     */
275
+    public function isCreatable() {
276
+        return $this->checkPermissions(\OCP\Constants::PERMISSION_CREATE);
277
+    }
278
+
279
+    /**
280
+     * @return bool
281
+     */
282
+    public function isDeletable() {
283
+        return $this->checkPermissions(\OCP\Constants::PERMISSION_DELETE);
284
+    }
285
+
286
+    /**
287
+     * @return bool
288
+     */
289
+    public function isShareable() {
290
+        return $this->checkPermissions(\OCP\Constants::PERMISSION_SHARE);
291
+    }
292
+
293
+    /**
294
+     * Check if a file or folder is shared
295
+     *
296
+     * @return bool
297
+     */
298
+    public function isShared() {
299
+        $sid = $this->getStorage()->getId();
300
+        if (!is_null($sid)) {
301
+            $sid = explode(':', $sid);
302
+            return ($sid[0] === 'shared');
303
+        }
304
+
305
+        return false;
306
+    }
307
+
308
+    public function isMounted() {
309
+        $storage = $this->getStorage();
310
+        if ($storage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
311
+            return false;
312
+        }
313
+        $sid = $storage->getId();
314
+        if (!is_null($sid)) {
315
+            $sid = explode(':', $sid);
316
+            return ($sid[0] !== 'home' and $sid[0] !== 'shared');
317
+        }
318
+
319
+        return false;
320
+    }
321
+
322
+    /**
323
+     * Get the mountpoint the file belongs to
324
+     *
325
+     * @return \OCP\Files\Mount\IMountPoint
326
+     */
327
+    public function getMountPoint() {
328
+        return $this->mount;
329
+    }
330
+
331
+    /**
332
+     * Get the owner of the file
333
+     *
334
+     * @return \OCP\IUser
335
+     */
336
+    public function getOwner() {
337
+        return $this->owner;
338
+    }
339
+
340
+    /**
341
+     * @param IMountPoint[] $mounts
342
+     */
343
+    public function setSubMounts(array $mounts) {
344
+        $this->subMounts = $mounts;
345
+    }
346
+
347
+    private function updateEntryfromSubMounts() {
348
+        if ($this->subMountsUsed) {
349
+            return;
350
+        }
351
+        $this->subMountsUsed = true;
352
+        foreach ($this->subMounts as $mount) {
353
+            $subStorage = $mount->getStorage();
354
+            if ($subStorage) {
355
+                $subCache = $subStorage->getCache('');
356
+                $rootEntry = $subCache->get('');
357
+                $this->addSubEntry($rootEntry, $mount->getMountPoint());
358
+            }
359
+        }
360
+    }
361
+
362
+    /**
363
+     * Add a cache entry which is the child of this folder
364
+     *
365
+     * Sets the size, etag and size to for cross-storage childs
366
+     *
367
+     * @param array|ICacheEntry $data cache entry for the child
368
+     * @param string $entryPath full path of the child entry
369
+     */
370
+    public function addSubEntry($data, $entryPath) {
371
+        $this->data['size'] += isset($data['size']) ? $data['size'] : 0;
372
+        if (isset($data['mtime'])) {
373
+            $this->data['mtime'] = max($this->data['mtime'], $data['mtime']);
374
+        }
375
+        if (isset($data['etag'])) {
376
+            // prefix the etag with the relative path of the subentry to propagate etag on mount moves
377
+            $relativeEntryPath = substr($entryPath, strlen($this->getPath()));
378
+            // attach the permissions to propagate etag on permision changes of submounts
379
+            $permissions = isset($data['permissions']) ? $data['permissions'] : 0;
380
+            $this->childEtags[] = $relativeEntryPath . '/' . $data['etag'] . $permissions;
381
+        }
382
+    }
383
+
384
+    /**
385
+     * @inheritdoc
386
+     */
387
+    public function getChecksum() {
388
+        return $this->data['checksum'];
389
+    }
390 390
 }
Please login to merge, or discard this patch.
lib/private/Command/QueueBus.php 1 patch
Indentation   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -26,48 +26,48 @@
 block discarded – undo
26 26
 use OCP\Command\ICommand;
27 27
 
28 28
 class QueueBus implements IBus {
29
-	/**
30
-	 * @var ICommand[]|callable[]
31
-	 */
32
-	private $queue = [];
29
+    /**
30
+     * @var ICommand[]|callable[]
31
+     */
32
+    private $queue = [];
33 33
 
34
-	/**
35
-	 * Schedule a command to be fired
36
-	 *
37
-	 * @param \OCP\Command\ICommand | callable $command
38
-	 */
39
-	public function push($command) {
40
-		$this->queue[] = $command;
41
-	}
34
+    /**
35
+     * Schedule a command to be fired
36
+     *
37
+     * @param \OCP\Command\ICommand | callable $command
38
+     */
39
+    public function push($command) {
40
+        $this->queue[] = $command;
41
+    }
42 42
 
43
-	/**
44
-	 * Require all commands using a trait to be run synchronous
45
-	 *
46
-	 * @param string $trait
47
-	 */
48
-	public function requireSync($trait) {
49
-	}
43
+    /**
44
+     * Require all commands using a trait to be run synchronous
45
+     *
46
+     * @param string $trait
47
+     */
48
+    public function requireSync($trait) {
49
+    }
50 50
 
51
-	/**
52
-	 * @param \OCP\Command\ICommand | callable $command
53
-	 */
54
-	private function runCommand($command) {
55
-		if ($command instanceof ICommand) {
56
-			// ensure the command can be serialized
57
-			$serialized = serialize($command);
58
-			if(strlen($serialized) > 4000) {
59
-				throw new \InvalidArgumentException('Trying to push a command which serialized form can not be stored in the database (>4000 character)');
60
-			}
61
-			$unserialized = unserialize($serialized);
62
-			$unserialized->handle();
63
-		} else {
64
-			$command();
65
-		}
66
-	}
51
+    /**
52
+     * @param \OCP\Command\ICommand | callable $command
53
+     */
54
+    private function runCommand($command) {
55
+        if ($command instanceof ICommand) {
56
+            // ensure the command can be serialized
57
+            $serialized = serialize($command);
58
+            if(strlen($serialized) > 4000) {
59
+                throw new \InvalidArgumentException('Trying to push a command which serialized form can not be stored in the database (>4000 character)');
60
+            }
61
+            $unserialized = unserialize($serialized);
62
+            $unserialized->handle();
63
+        } else {
64
+            $command();
65
+        }
66
+    }
67 67
 
68
-	public function run() {
69
-		while ($command = array_shift($this->queue)) {
70
-			$this->runCommand($command);
71
-		}
72
-	}
68
+    public function run() {
69
+        while ($command = array_shift($this->queue)) {
70
+            $this->runCommand($command);
71
+        }
72
+    }
73 73
 }
Please login to merge, or discard this patch.
lib/private/legacy/image.php 1 patch
Indentation   +1072 added lines, -1072 removed lines patch added patch discarded remove patch
@@ -40,565 +40,565 @@  discard block
 block discarded – undo
40 40
  * Class for basic image manipulation
41 41
  */
42 42
 class OC_Image implements \OCP\IImage {
43
-	/** @var false|resource */
44
-	protected $resource = false; // tmp resource.
45
-	/** @var int */
46
-	protected $imageType = IMAGETYPE_PNG; // Default to png if file type isn't evident.
47
-	/** @var string */
48
-	protected $mimeType = 'image/png'; // Default to png
49
-	/** @var int */
50
-	protected $bitDepth = 24;
51
-	/** @var null|string */
52
-	protected $filePath = null;
53
-	/** @var finfo */
54
-	private $fileInfo;
55
-	/** @var \OCP\ILogger */
56
-	private $logger;
57
-	/** @var \OCP\IConfig */
58
-	private $config;
59
-	/** @var array */
60
-	private $exif;
43
+    /** @var false|resource */
44
+    protected $resource = false; // tmp resource.
45
+    /** @var int */
46
+    protected $imageType = IMAGETYPE_PNG; // Default to png if file type isn't evident.
47
+    /** @var string */
48
+    protected $mimeType = 'image/png'; // Default to png
49
+    /** @var int */
50
+    protected $bitDepth = 24;
51
+    /** @var null|string */
52
+    protected $filePath = null;
53
+    /** @var finfo */
54
+    private $fileInfo;
55
+    /** @var \OCP\ILogger */
56
+    private $logger;
57
+    /** @var \OCP\IConfig */
58
+    private $config;
59
+    /** @var array */
60
+    private $exif;
61 61
 
62
-	/**
63
-	 * Get mime type for an image file.
64
-	 *
65
-	 * @param string|null $filePath The path to a local image file.
66
-	 * @return string The mime type if the it could be determined, otherwise an empty string.
67
-	 */
68
-	static public function getMimeTypeForFile($filePath) {
69
-		// exif_imagetype throws "read error!" if file is less than 12 byte
70
-		if ($filePath !== null && filesize($filePath) > 11) {
71
-			$imageType = exif_imagetype($filePath);
72
-		} else {
73
-			$imageType = false;
74
-		}
75
-		return $imageType ? image_type_to_mime_type($imageType) : '';
76
-	}
62
+    /**
63
+     * Get mime type for an image file.
64
+     *
65
+     * @param string|null $filePath The path to a local image file.
66
+     * @return string The mime type if the it could be determined, otherwise an empty string.
67
+     */
68
+    static public function getMimeTypeForFile($filePath) {
69
+        // exif_imagetype throws "read error!" if file is less than 12 byte
70
+        if ($filePath !== null && filesize($filePath) > 11) {
71
+            $imageType = exif_imagetype($filePath);
72
+        } else {
73
+            $imageType = false;
74
+        }
75
+        return $imageType ? image_type_to_mime_type($imageType) : '';
76
+    }
77 77
 
78
-	/**
79
-	 * Constructor.
80
-	 *
81
-	 * @param resource|string $imageRef The path to a local file, a base64 encoded string or a resource created by
82
-	 * an imagecreate* function.
83
-	 * @param \OCP\ILogger $logger
84
-	 * @param \OCP\IConfig $config
85
-	 */
86
-	public function __construct($imageRef = null, \OCP\ILogger $logger = null, \OCP\IConfig $config = null) {
87
-		$this->logger = $logger;
88
-		if ($logger === null) {
89
-			$this->logger = \OC::$server->getLogger();
90
-		}
91
-		$this->config = $config;
92
-		if ($config === null) {
93
-			$this->config = \OC::$server->getConfig();
94
-		}
78
+    /**
79
+     * Constructor.
80
+     *
81
+     * @param resource|string $imageRef The path to a local file, a base64 encoded string or a resource created by
82
+     * an imagecreate* function.
83
+     * @param \OCP\ILogger $logger
84
+     * @param \OCP\IConfig $config
85
+     */
86
+    public function __construct($imageRef = null, \OCP\ILogger $logger = null, \OCP\IConfig $config = null) {
87
+        $this->logger = $logger;
88
+        if ($logger === null) {
89
+            $this->logger = \OC::$server->getLogger();
90
+        }
91
+        $this->config = $config;
92
+        if ($config === null) {
93
+            $this->config = \OC::$server->getConfig();
94
+        }
95 95
 
96
-		if (\OC_Util::fileInfoLoaded()) {
97
-			$this->fileInfo = new finfo(FILEINFO_MIME_TYPE);
98
-		}
96
+        if (\OC_Util::fileInfoLoaded()) {
97
+            $this->fileInfo = new finfo(FILEINFO_MIME_TYPE);
98
+        }
99 99
 
100
-		if ($imageRef !== null) {
101
-			$this->load($imageRef);
102
-		}
103
-	}
100
+        if ($imageRef !== null) {
101
+            $this->load($imageRef);
102
+        }
103
+    }
104 104
 
105
-	/**
106
-	 * Determine whether the object contains an image resource.
107
-	 *
108
-	 * @return bool
109
-	 */
110
-	public function valid() { // apparently you can't name a method 'empty'...
111
-		return is_resource($this->resource);
112
-	}
105
+    /**
106
+     * Determine whether the object contains an image resource.
107
+     *
108
+     * @return bool
109
+     */
110
+    public function valid() { // apparently you can't name a method 'empty'...
111
+        return is_resource($this->resource);
112
+    }
113 113
 
114
-	/**
115
-	 * Returns the MIME type of the image or an empty string if no image is loaded.
116
-	 *
117
-	 * @return string
118
-	 */
119
-	public function mimeType() {
120
-		return $this->valid() ? $this->mimeType : '';
121
-	}
114
+    /**
115
+     * Returns the MIME type of the image or an empty string if no image is loaded.
116
+     *
117
+     * @return string
118
+     */
119
+    public function mimeType() {
120
+        return $this->valid() ? $this->mimeType : '';
121
+    }
122 122
 
123
-	/**
124
-	 * Returns the width of the image or -1 if no image is loaded.
125
-	 *
126
-	 * @return int
127
-	 */
128
-	public function width() {
129
-		return $this->valid() ? imagesx($this->resource) : -1;
130
-	}
123
+    /**
124
+     * Returns the width of the image or -1 if no image is loaded.
125
+     *
126
+     * @return int
127
+     */
128
+    public function width() {
129
+        return $this->valid() ? imagesx($this->resource) : -1;
130
+    }
131 131
 
132
-	/**
133
-	 * Returns the height of the image or -1 if no image is loaded.
134
-	 *
135
-	 * @return int
136
-	 */
137
-	public function height() {
138
-		return $this->valid() ? imagesy($this->resource) : -1;
139
-	}
132
+    /**
133
+     * Returns the height of the image or -1 if no image is loaded.
134
+     *
135
+     * @return int
136
+     */
137
+    public function height() {
138
+        return $this->valid() ? imagesy($this->resource) : -1;
139
+    }
140 140
 
141
-	/**
142
-	 * Returns the width when the image orientation is top-left.
143
-	 *
144
-	 * @return int
145
-	 */
146
-	public function widthTopLeft() {
147
-		$o = $this->getOrientation();
148
-		$this->logger->debug('OC_Image->widthTopLeft() Orientation: ' . $o, array('app' => 'core'));
149
-		switch ($o) {
150
-			case -1:
151
-			case 1:
152
-			case 2: // Not tested
153
-			case 3:
154
-			case 4: // Not tested
155
-				return $this->width();
156
-			case 5: // Not tested
157
-			case 6:
158
-			case 7: // Not tested
159
-			case 8:
160
-				return $this->height();
161
-		}
162
-		return $this->width();
163
-	}
141
+    /**
142
+     * Returns the width when the image orientation is top-left.
143
+     *
144
+     * @return int
145
+     */
146
+    public function widthTopLeft() {
147
+        $o = $this->getOrientation();
148
+        $this->logger->debug('OC_Image->widthTopLeft() Orientation: ' . $o, array('app' => 'core'));
149
+        switch ($o) {
150
+            case -1:
151
+            case 1:
152
+            case 2: // Not tested
153
+            case 3:
154
+            case 4: // Not tested
155
+                return $this->width();
156
+            case 5: // Not tested
157
+            case 6:
158
+            case 7: // Not tested
159
+            case 8:
160
+                return $this->height();
161
+        }
162
+        return $this->width();
163
+    }
164 164
 
165
-	/**
166
-	 * Returns the height when the image orientation is top-left.
167
-	 *
168
-	 * @return int
169
-	 */
170
-	public function heightTopLeft() {
171
-		$o = $this->getOrientation();
172
-		$this->logger->debug('OC_Image->heightTopLeft() Orientation: ' . $o, array('app' => 'core'));
173
-		switch ($o) {
174
-			case -1:
175
-			case 1:
176
-			case 2: // Not tested
177
-			case 3:
178
-			case 4: // Not tested
179
-				return $this->height();
180
-			case 5: // Not tested
181
-			case 6:
182
-			case 7: // Not tested
183
-			case 8:
184
-				return $this->width();
185
-		}
186
-		return $this->height();
187
-	}
165
+    /**
166
+     * Returns the height when the image orientation is top-left.
167
+     *
168
+     * @return int
169
+     */
170
+    public function heightTopLeft() {
171
+        $o = $this->getOrientation();
172
+        $this->logger->debug('OC_Image->heightTopLeft() Orientation: ' . $o, array('app' => 'core'));
173
+        switch ($o) {
174
+            case -1:
175
+            case 1:
176
+            case 2: // Not tested
177
+            case 3:
178
+            case 4: // Not tested
179
+                return $this->height();
180
+            case 5: // Not tested
181
+            case 6:
182
+            case 7: // Not tested
183
+            case 8:
184
+                return $this->width();
185
+        }
186
+        return $this->height();
187
+    }
188 188
 
189
-	/**
190
-	 * Outputs the image.
191
-	 *
192
-	 * @param string $mimeType
193
-	 * @return bool
194
-	 */
195
-	public function show($mimeType = null) {
196
-		if ($mimeType === null) {
197
-			$mimeType = $this->mimeType();
198
-		}
199
-		header('Content-Type: ' . $mimeType);
200
-		return $this->_output(null, $mimeType);
201
-	}
189
+    /**
190
+     * Outputs the image.
191
+     *
192
+     * @param string $mimeType
193
+     * @return bool
194
+     */
195
+    public function show($mimeType = null) {
196
+        if ($mimeType === null) {
197
+            $mimeType = $this->mimeType();
198
+        }
199
+        header('Content-Type: ' . $mimeType);
200
+        return $this->_output(null, $mimeType);
201
+    }
202 202
 
203
-	/**
204
-	 * Saves the image.
205
-	 *
206
-	 * @param string $filePath
207
-	 * @param string $mimeType
208
-	 * @return bool
209
-	 */
203
+    /**
204
+     * Saves the image.
205
+     *
206
+     * @param string $filePath
207
+     * @param string $mimeType
208
+     * @return bool
209
+     */
210 210
 
211
-	public function save($filePath = null, $mimeType = null) {
212
-		if ($mimeType === null) {
213
-			$mimeType = $this->mimeType();
214
-		}
215
-		if ($filePath === null) {
216
-			if ($this->filePath === null) {
217
-				$this->logger->error(__METHOD__ . '(): called with no path.', array('app' => 'core'));
218
-				return false;
219
-			} else {
220
-				$filePath = $this->filePath;
221
-			}
222
-		}
223
-		return $this->_output($filePath, $mimeType);
224
-	}
211
+    public function save($filePath = null, $mimeType = null) {
212
+        if ($mimeType === null) {
213
+            $mimeType = $this->mimeType();
214
+        }
215
+        if ($filePath === null) {
216
+            if ($this->filePath === null) {
217
+                $this->logger->error(__METHOD__ . '(): called with no path.', array('app' => 'core'));
218
+                return false;
219
+            } else {
220
+                $filePath = $this->filePath;
221
+            }
222
+        }
223
+        return $this->_output($filePath, $mimeType);
224
+    }
225 225
 
226
-	/**
227
-	 * Outputs/saves the image.
228
-	 *
229
-	 * @param string $filePath
230
-	 * @param string $mimeType
231
-	 * @return bool
232
-	 * @throws Exception
233
-	 */
234
-	private function _output($filePath = null, $mimeType = null) {
235
-		if ($filePath) {
236
-			if (!file_exists(dirname($filePath))) {
237
-				mkdir(dirname($filePath), 0777, true);
238
-			}
239
-			$isWritable = is_writable(dirname($filePath));
240
-			if (!$isWritable) {
241
-				$this->logger->error(__METHOD__ . '(): Directory \'' . dirname($filePath) . '\' is not writable.', array('app' => 'core'));
242
-				return false;
243
-			} elseif ($isWritable && file_exists($filePath) && !is_writable($filePath)) {
244
-				$this->logger->error(__METHOD__ . '(): File \'' . $filePath . '\' is not writable.', array('app' => 'core'));
245
-				return false;
246
-			}
247
-		}
248
-		if (!$this->valid()) {
249
-			return false;
250
-		}
226
+    /**
227
+     * Outputs/saves the image.
228
+     *
229
+     * @param string $filePath
230
+     * @param string $mimeType
231
+     * @return bool
232
+     * @throws Exception
233
+     */
234
+    private function _output($filePath = null, $mimeType = null) {
235
+        if ($filePath) {
236
+            if (!file_exists(dirname($filePath))) {
237
+                mkdir(dirname($filePath), 0777, true);
238
+            }
239
+            $isWritable = is_writable(dirname($filePath));
240
+            if (!$isWritable) {
241
+                $this->logger->error(__METHOD__ . '(): Directory \'' . dirname($filePath) . '\' is not writable.', array('app' => 'core'));
242
+                return false;
243
+            } elseif ($isWritable && file_exists($filePath) && !is_writable($filePath)) {
244
+                $this->logger->error(__METHOD__ . '(): File \'' . $filePath . '\' is not writable.', array('app' => 'core'));
245
+                return false;
246
+            }
247
+        }
248
+        if (!$this->valid()) {
249
+            return false;
250
+        }
251 251
 
252
-		$imageType = $this->imageType;
253
-		if ($mimeType !== null) {
254
-			switch ($mimeType) {
255
-				case 'image/gif':
256
-					$imageType = IMAGETYPE_GIF;
257
-					break;
258
-				case 'image/jpeg':
259
-					$imageType = IMAGETYPE_JPEG;
260
-					break;
261
-				case 'image/png':
262
-					$imageType = IMAGETYPE_PNG;
263
-					break;
264
-				case 'image/x-xbitmap':
265
-					$imageType = IMAGETYPE_XBM;
266
-					break;
267
-				case 'image/bmp':
268
-				case 'image/x-ms-bmp':
269
-					$imageType = IMAGETYPE_BMP;
270
-					break;
271
-				default:
272
-					throw new Exception('\OC_Image::_output(): "' . $mimeType . '" is not supported when forcing a specific output format');
273
-			}
274
-		}
252
+        $imageType = $this->imageType;
253
+        if ($mimeType !== null) {
254
+            switch ($mimeType) {
255
+                case 'image/gif':
256
+                    $imageType = IMAGETYPE_GIF;
257
+                    break;
258
+                case 'image/jpeg':
259
+                    $imageType = IMAGETYPE_JPEG;
260
+                    break;
261
+                case 'image/png':
262
+                    $imageType = IMAGETYPE_PNG;
263
+                    break;
264
+                case 'image/x-xbitmap':
265
+                    $imageType = IMAGETYPE_XBM;
266
+                    break;
267
+                case 'image/bmp':
268
+                case 'image/x-ms-bmp':
269
+                    $imageType = IMAGETYPE_BMP;
270
+                    break;
271
+                default:
272
+                    throw new Exception('\OC_Image::_output(): "' . $mimeType . '" is not supported when forcing a specific output format');
273
+            }
274
+        }
275 275
 
276
-		switch ($imageType) {
277
-			case IMAGETYPE_GIF:
278
-				$retVal = imagegif($this->resource, $filePath);
279
-				break;
280
-			case IMAGETYPE_JPEG:
281
-				$retVal = imagejpeg($this->resource, $filePath, $this->getJpegQuality());
282
-				break;
283
-			case IMAGETYPE_PNG:
284
-				$retVal = imagepng($this->resource, $filePath);
285
-				break;
286
-			case IMAGETYPE_XBM:
287
-				if (function_exists('imagexbm')) {
288
-					$retVal = imagexbm($this->resource, $filePath);
289
-				} else {
290
-					throw new Exception('\OC_Image::_output(): imagexbm() is not supported.');
291
-				}
276
+        switch ($imageType) {
277
+            case IMAGETYPE_GIF:
278
+                $retVal = imagegif($this->resource, $filePath);
279
+                break;
280
+            case IMAGETYPE_JPEG:
281
+                $retVal = imagejpeg($this->resource, $filePath, $this->getJpegQuality());
282
+                break;
283
+            case IMAGETYPE_PNG:
284
+                $retVal = imagepng($this->resource, $filePath);
285
+                break;
286
+            case IMAGETYPE_XBM:
287
+                if (function_exists('imagexbm')) {
288
+                    $retVal = imagexbm($this->resource, $filePath);
289
+                } else {
290
+                    throw new Exception('\OC_Image::_output(): imagexbm() is not supported.');
291
+                }
292 292
 
293
-				break;
294
-			case IMAGETYPE_WBMP:
295
-				$retVal = imagewbmp($this->resource, $filePath);
296
-				break;
297
-			case IMAGETYPE_BMP:
298
-				$retVal = imagebmp($this->resource, $filePath, $this->bitDepth);
299
-				break;
300
-			default:
301
-				$retVal = imagepng($this->resource, $filePath);
302
-		}
303
-		return $retVal;
304
-	}
293
+                break;
294
+            case IMAGETYPE_WBMP:
295
+                $retVal = imagewbmp($this->resource, $filePath);
296
+                break;
297
+            case IMAGETYPE_BMP:
298
+                $retVal = imagebmp($this->resource, $filePath, $this->bitDepth);
299
+                break;
300
+            default:
301
+                $retVal = imagepng($this->resource, $filePath);
302
+        }
303
+        return $retVal;
304
+    }
305 305
 
306
-	/**
307
-	 * Prints the image when called as $image().
308
-	 */
309
-	public function __invoke() {
310
-		return $this->show();
311
-	}
306
+    /**
307
+     * Prints the image when called as $image().
308
+     */
309
+    public function __invoke() {
310
+        return $this->show();
311
+    }
312 312
 
313
-	/**
314
-	 * @return resource Returns the image resource in any.
315
-	 */
316
-	public function resource() {
317
-		return $this->resource;
318
-	}
313
+    /**
314
+     * @return resource Returns the image resource in any.
315
+     */
316
+    public function resource() {
317
+        return $this->resource;
318
+    }
319 319
 
320
-	/**
321
-	 * @return null|string Returns the raw image data.
322
-	 */
323
-	public function data() {
324
-		if (!$this->valid()) {
325
-			return null;
326
-		}
327
-		ob_start();
328
-		switch ($this->mimeType) {
329
-			case "image/png":
330
-				$res = imagepng($this->resource);
331
-				break;
332
-			case "image/jpeg":
333
-				$quality = $this->getJpegQuality();
334
-				if ($quality !== null) {
335
-					$res = imagejpeg($this->resource, null, $quality);
336
-				} else {
337
-					$res = imagejpeg($this->resource);
338
-				}
339
-				break;
340
-			case "image/gif":
341
-				$res = imagegif($this->resource);
342
-				break;
343
-			default:
344
-				$res = imagepng($this->resource);
345
-				$this->logger->info('OC_Image->data. Could not guess mime-type, defaulting to png', array('app' => 'core'));
346
-				break;
347
-		}
348
-		if (!$res) {
349
-			$this->logger->error('OC_Image->data. Error getting image data.', array('app' => 'core'));
350
-		}
351
-		return ob_get_clean();
352
-	}
320
+    /**
321
+     * @return null|string Returns the raw image data.
322
+     */
323
+    public function data() {
324
+        if (!$this->valid()) {
325
+            return null;
326
+        }
327
+        ob_start();
328
+        switch ($this->mimeType) {
329
+            case "image/png":
330
+                $res = imagepng($this->resource);
331
+                break;
332
+            case "image/jpeg":
333
+                $quality = $this->getJpegQuality();
334
+                if ($quality !== null) {
335
+                    $res = imagejpeg($this->resource, null, $quality);
336
+                } else {
337
+                    $res = imagejpeg($this->resource);
338
+                }
339
+                break;
340
+            case "image/gif":
341
+                $res = imagegif($this->resource);
342
+                break;
343
+            default:
344
+                $res = imagepng($this->resource);
345
+                $this->logger->info('OC_Image->data. Could not guess mime-type, defaulting to png', array('app' => 'core'));
346
+                break;
347
+        }
348
+        if (!$res) {
349
+            $this->logger->error('OC_Image->data. Error getting image data.', array('app' => 'core'));
350
+        }
351
+        return ob_get_clean();
352
+    }
353 353
 
354
-	/**
355
-	 * @return string - base64 encoded, which is suitable for embedding in a VCard.
356
-	 */
357
-	public function __toString() {
358
-		return base64_encode($this->data());
359
-	}
354
+    /**
355
+     * @return string - base64 encoded, which is suitable for embedding in a VCard.
356
+     */
357
+    public function __toString() {
358
+        return base64_encode($this->data());
359
+    }
360 360
 
361
-	/**
362
-	 * @return int|null
363
-	 */
364
-	protected function getJpegQuality() {
365
-		$quality = $this->config->getAppValue('preview', 'jpeg_quality', 90);
366
-		if ($quality !== null) {
367
-			$quality = min(100, max(10, (int) $quality));
368
-		}
369
-		return $quality;
370
-	}
361
+    /**
362
+     * @return int|null
363
+     */
364
+    protected function getJpegQuality() {
365
+        $quality = $this->config->getAppValue('preview', 'jpeg_quality', 90);
366
+        if ($quality !== null) {
367
+            $quality = min(100, max(10, (int) $quality));
368
+        }
369
+        return $quality;
370
+    }
371 371
 
372
-	/**
373
-	 * (I'm open for suggestions on better method name ;)
374
-	 * Get the orientation based on EXIF data.
375
-	 *
376
-	 * @return int The orientation or -1 if no EXIF data is available.
377
-	 */
378
-	public function getOrientation() {
379
-		if ($this->exif !== null) {
380
-			return $this->exif['Orientation'];
381
-		}
372
+    /**
373
+     * (I'm open for suggestions on better method name ;)
374
+     * Get the orientation based on EXIF data.
375
+     *
376
+     * @return int The orientation or -1 if no EXIF data is available.
377
+     */
378
+    public function getOrientation() {
379
+        if ($this->exif !== null) {
380
+            return $this->exif['Orientation'];
381
+        }
382 382
 
383
-		if ($this->imageType !== IMAGETYPE_JPEG) {
384
-			$this->logger->debug('OC_Image->fixOrientation() Image is not a JPEG.', array('app' => 'core'));
385
-			return -1;
386
-		}
387
-		if (!is_callable('exif_read_data')) {
388
-			$this->logger->debug('OC_Image->fixOrientation() Exif module not enabled.', array('app' => 'core'));
389
-			return -1;
390
-		}
391
-		if (!$this->valid()) {
392
-			$this->logger->debug('OC_Image->fixOrientation() No image loaded.', array('app' => 'core'));
393
-			return -1;
394
-		}
395
-		if (is_null($this->filePath) || !is_readable($this->filePath)) {
396
-			$this->logger->debug('OC_Image->fixOrientation() No readable file path set.', array('app' => 'core'));
397
-			return -1;
398
-		}
399
-		$exif = @exif_read_data($this->filePath, 'IFD0');
400
-		if (!$exif) {
401
-			return -1;
402
-		}
403
-		if (!isset($exif['Orientation'])) {
404
-			return -1;
405
-		}
406
-		$this->exif = $exif;
407
-		return $exif['Orientation'];
408
-	}
383
+        if ($this->imageType !== IMAGETYPE_JPEG) {
384
+            $this->logger->debug('OC_Image->fixOrientation() Image is not a JPEG.', array('app' => 'core'));
385
+            return -1;
386
+        }
387
+        if (!is_callable('exif_read_data')) {
388
+            $this->logger->debug('OC_Image->fixOrientation() Exif module not enabled.', array('app' => 'core'));
389
+            return -1;
390
+        }
391
+        if (!$this->valid()) {
392
+            $this->logger->debug('OC_Image->fixOrientation() No image loaded.', array('app' => 'core'));
393
+            return -1;
394
+        }
395
+        if (is_null($this->filePath) || !is_readable($this->filePath)) {
396
+            $this->logger->debug('OC_Image->fixOrientation() No readable file path set.', array('app' => 'core'));
397
+            return -1;
398
+        }
399
+        $exif = @exif_read_data($this->filePath, 'IFD0');
400
+        if (!$exif) {
401
+            return -1;
402
+        }
403
+        if (!isset($exif['Orientation'])) {
404
+            return -1;
405
+        }
406
+        $this->exif = $exif;
407
+        return $exif['Orientation'];
408
+    }
409 409
 
410
-	public function readExif($data) {
411
-		if (!is_callable('exif_read_data')) {
412
-			$this->logger->debug('OC_Image->fixOrientation() Exif module not enabled.', array('app' => 'core'));
413
-			return;
414
-		}
415
-		if (!$this->valid()) {
416
-			$this->logger->debug('OC_Image->fixOrientation() No image loaded.', array('app' => 'core'));
417
-			return;
418
-		}
410
+    public function readExif($data) {
411
+        if (!is_callable('exif_read_data')) {
412
+            $this->logger->debug('OC_Image->fixOrientation() Exif module not enabled.', array('app' => 'core'));
413
+            return;
414
+        }
415
+        if (!$this->valid()) {
416
+            $this->logger->debug('OC_Image->fixOrientation() No image loaded.', array('app' => 'core'));
417
+            return;
418
+        }
419 419
 
420
-		$exif = @exif_read_data('data://image/jpeg;base64,' . base64_encode($data));
421
-		if (!$exif) {
422
-			return;
423
-		}
424
-		if (!isset($exif['Orientation'])) {
425
-			return;
426
-		}
427
-		$this->exif = $exif;
428
-	}
420
+        $exif = @exif_read_data('data://image/jpeg;base64,' . base64_encode($data));
421
+        if (!$exif) {
422
+            return;
423
+        }
424
+        if (!isset($exif['Orientation'])) {
425
+            return;
426
+        }
427
+        $this->exif = $exif;
428
+    }
429 429
 
430
-	/**
431
-	 * (I'm open for suggestions on better method name ;)
432
-	 * Fixes orientation based on EXIF data.
433
-	 *
434
-	 * @return bool
435
-	 */
436
-	public function fixOrientation() {
437
-		$o = $this->getOrientation();
438
-		$this->logger->debug('OC_Image->fixOrientation() Orientation: ' . $o, array('app' => 'core'));
439
-		$rotate = 0;
440
-		$flip = false;
441
-		switch ($o) {
442
-			case -1:
443
-				return false; //Nothing to fix
444
-			case 1:
445
-				$rotate = 0;
446
-				break;
447
-			case 2:
448
-				$rotate = 0;
449
-				$flip = true;
450
-				break;
451
-			case 3:
452
-				$rotate = 180;
453
-				break;
454
-			case 4:
455
-				$rotate = 180;
456
-				$flip = true;
457
-				break;
458
-			case 5:
459
-				$rotate = 90;
460
-				$flip = true;
461
-				break;
462
-			case 6:
463
-				$rotate = 270;
464
-				break;
465
-			case 7:
466
-				$rotate = 270;
467
-				$flip = true;
468
-				break;
469
-			case 8:
470
-				$rotate = 90;
471
-				break;
472
-		}
473
-		if($flip && function_exists('imageflip')) {
474
-			imageflip($this->resource, IMG_FLIP_HORIZONTAL);
475
-		}
476
-		if ($rotate) {
477
-			$res = imagerotate($this->resource, $rotate, 0);
478
-			if ($res) {
479
-				if (imagealphablending($res, true)) {
480
-					if (imagesavealpha($res, true)) {
481
-						imagedestroy($this->resource);
482
-						$this->resource = $res;
483
-						return true;
484
-					} else {
485
-						$this->logger->debug('OC_Image->fixOrientation() Error during alpha-saving', array('app' => 'core'));
486
-						return false;
487
-					}
488
-				} else {
489
-					$this->logger->debug('OC_Image->fixOrientation() Error during alpha-blending', array('app' => 'core'));
490
-					return false;
491
-				}
492
-			} else {
493
-				$this->logger->debug('OC_Image->fixOrientation() Error during orientation fixing', array('app' => 'core'));
494
-				return false;
495
-			}
496
-		}
497
-		return false;
498
-	}
430
+    /**
431
+     * (I'm open for suggestions on better method name ;)
432
+     * Fixes orientation based on EXIF data.
433
+     *
434
+     * @return bool
435
+     */
436
+    public function fixOrientation() {
437
+        $o = $this->getOrientation();
438
+        $this->logger->debug('OC_Image->fixOrientation() Orientation: ' . $o, array('app' => 'core'));
439
+        $rotate = 0;
440
+        $flip = false;
441
+        switch ($o) {
442
+            case -1:
443
+                return false; //Nothing to fix
444
+            case 1:
445
+                $rotate = 0;
446
+                break;
447
+            case 2:
448
+                $rotate = 0;
449
+                $flip = true;
450
+                break;
451
+            case 3:
452
+                $rotate = 180;
453
+                break;
454
+            case 4:
455
+                $rotate = 180;
456
+                $flip = true;
457
+                break;
458
+            case 5:
459
+                $rotate = 90;
460
+                $flip = true;
461
+                break;
462
+            case 6:
463
+                $rotate = 270;
464
+                break;
465
+            case 7:
466
+                $rotate = 270;
467
+                $flip = true;
468
+                break;
469
+            case 8:
470
+                $rotate = 90;
471
+                break;
472
+        }
473
+        if($flip && function_exists('imageflip')) {
474
+            imageflip($this->resource, IMG_FLIP_HORIZONTAL);
475
+        }
476
+        if ($rotate) {
477
+            $res = imagerotate($this->resource, $rotate, 0);
478
+            if ($res) {
479
+                if (imagealphablending($res, true)) {
480
+                    if (imagesavealpha($res, true)) {
481
+                        imagedestroy($this->resource);
482
+                        $this->resource = $res;
483
+                        return true;
484
+                    } else {
485
+                        $this->logger->debug('OC_Image->fixOrientation() Error during alpha-saving', array('app' => 'core'));
486
+                        return false;
487
+                    }
488
+                } else {
489
+                    $this->logger->debug('OC_Image->fixOrientation() Error during alpha-blending', array('app' => 'core'));
490
+                    return false;
491
+                }
492
+            } else {
493
+                $this->logger->debug('OC_Image->fixOrientation() Error during orientation fixing', array('app' => 'core'));
494
+                return false;
495
+            }
496
+        }
497
+        return false;
498
+    }
499 499
 
500
-	/**
501
-	 * Loads an image from a local file, a base64 encoded string or a resource created by an imagecreate* function.
502
-	 *
503
-	 * @param resource|string $imageRef The path to a local file, a base64 encoded string or a resource created by an imagecreate* function or a file resource (file handle    ).
504
-	 * @return resource|false An image resource or false on error
505
-	 */
506
-	public function load($imageRef) {
507
-		if (is_resource($imageRef)) {
508
-			if (get_resource_type($imageRef) === 'gd') {
509
-				$this->resource = $imageRef;
510
-				return $this->resource;
511
-			} elseif (in_array(get_resource_type($imageRef), array('file', 'stream'))) {
512
-				return $this->loadFromFileHandle($imageRef);
513
-			}
514
-		} elseif ($this->loadFromBase64($imageRef) !== false) {
515
-			return $this->resource;
516
-		} elseif ($this->loadFromFile($imageRef) !== false) {
517
-			return $this->resource;
518
-		} elseif ($this->loadFromData($imageRef) !== false) {
519
-			return $this->resource;
520
-		}
521
-		$this->logger->debug(__METHOD__ . '(): could not load anything. Giving up!', array('app' => 'core'));
522
-		return false;
523
-	}
500
+    /**
501
+     * Loads an image from a local file, a base64 encoded string or a resource created by an imagecreate* function.
502
+     *
503
+     * @param resource|string $imageRef The path to a local file, a base64 encoded string or a resource created by an imagecreate* function or a file resource (file handle    ).
504
+     * @return resource|false An image resource or false on error
505
+     */
506
+    public function load($imageRef) {
507
+        if (is_resource($imageRef)) {
508
+            if (get_resource_type($imageRef) === 'gd') {
509
+                $this->resource = $imageRef;
510
+                return $this->resource;
511
+            } elseif (in_array(get_resource_type($imageRef), array('file', 'stream'))) {
512
+                return $this->loadFromFileHandle($imageRef);
513
+            }
514
+        } elseif ($this->loadFromBase64($imageRef) !== false) {
515
+            return $this->resource;
516
+        } elseif ($this->loadFromFile($imageRef) !== false) {
517
+            return $this->resource;
518
+        } elseif ($this->loadFromData($imageRef) !== false) {
519
+            return $this->resource;
520
+        }
521
+        $this->logger->debug(__METHOD__ . '(): could not load anything. Giving up!', array('app' => 'core'));
522
+        return false;
523
+    }
524 524
 
525
-	/**
526
-	 * Loads an image from an open file handle.
527
-	 * It is the responsibility of the caller to position the pointer at the correct place and to close the handle again.
528
-	 *
529
-	 * @param resource $handle
530
-	 * @return resource|false An image resource or false on error
531
-	 */
532
-	public function loadFromFileHandle($handle) {
533
-		$contents = stream_get_contents($handle);
534
-		if ($this->loadFromData($contents)) {
535
-			return $this->resource;
536
-		}
537
-		return false;
538
-	}
525
+    /**
526
+     * Loads an image from an open file handle.
527
+     * It is the responsibility of the caller to position the pointer at the correct place and to close the handle again.
528
+     *
529
+     * @param resource $handle
530
+     * @return resource|false An image resource or false on error
531
+     */
532
+    public function loadFromFileHandle($handle) {
533
+        $contents = stream_get_contents($handle);
534
+        if ($this->loadFromData($contents)) {
535
+            return $this->resource;
536
+        }
537
+        return false;
538
+    }
539 539
 
540
-	/**
541
-	 * Loads an image from a local file.
542
-	 *
543
-	 * @param bool|string $imagePath The path to a local file.
544
-	 * @return bool|resource An image resource or false on error
545
-	 */
546
-	public function loadFromFile($imagePath = false) {
547
-		// exif_imagetype throws "read error!" if file is less than 12 byte
548
-		if (!@is_file($imagePath) || !file_exists($imagePath) || filesize($imagePath) < 12 || !is_readable($imagePath)) {
549
-			return false;
550
-		}
551
-		$iType = exif_imagetype($imagePath);
552
-		switch ($iType) {
553
-			case IMAGETYPE_GIF:
554
-				if (imagetypes() & IMG_GIF) {
555
-					$this->resource = imagecreatefromgif($imagePath);
556
-					// Preserve transparency
557
-					imagealphablending($this->resource, true);
558
-					imagesavealpha($this->resource, true);
559
-				} else {
560
-					$this->logger->debug('OC_Image->loadFromFile, GIF images not supported: ' . $imagePath, array('app' => 'core'));
561
-				}
562
-				break;
563
-			case IMAGETYPE_JPEG:
564
-				if (imagetypes() & IMG_JPG) {
565
-					if (getimagesize($imagePath) !== false) {
566
-						$this->resource = @imagecreatefromjpeg($imagePath);
567
-					} else {
568
-						$this->logger->debug('OC_Image->loadFromFile, JPG image not valid: ' . $imagePath, array('app' => 'core'));
569
-					}
570
-				} else {
571
-					$this->logger->debug('OC_Image->loadFromFile, JPG images not supported: ' . $imagePath, array('app' => 'core'));
572
-				}
573
-				break;
574
-			case IMAGETYPE_PNG:
575
-				if (imagetypes() & IMG_PNG) {
576
-					$this->resource = @imagecreatefrompng($imagePath);
577
-					// Preserve transparency
578
-					imagealphablending($this->resource, true);
579
-					imagesavealpha($this->resource, true);
580
-				} else {
581
-					$this->logger->debug('OC_Image->loadFromFile, PNG images not supported: ' . $imagePath, array('app' => 'core'));
582
-				}
583
-				break;
584
-			case IMAGETYPE_XBM:
585
-				if (imagetypes() & IMG_XPM) {
586
-					$this->resource = @imagecreatefromxbm($imagePath);
587
-				} else {
588
-					$this->logger->debug('OC_Image->loadFromFile, XBM/XPM images not supported: ' . $imagePath, array('app' => 'core'));
589
-				}
590
-				break;
591
-			case IMAGETYPE_WBMP:
592
-				if (imagetypes() & IMG_WBMP) {
593
-					$this->resource = @imagecreatefromwbmp($imagePath);
594
-				} else {
595
-					$this->logger->debug('OC_Image->loadFromFile, WBMP images not supported: ' . $imagePath, array('app' => 'core'));
596
-				}
597
-				break;
598
-			case IMAGETYPE_BMP:
599
-				$this->resource = $this->imagecreatefrombmp($imagePath);
600
-				break;
601
-			/*
540
+    /**
541
+     * Loads an image from a local file.
542
+     *
543
+     * @param bool|string $imagePath The path to a local file.
544
+     * @return bool|resource An image resource or false on error
545
+     */
546
+    public function loadFromFile($imagePath = false) {
547
+        // exif_imagetype throws "read error!" if file is less than 12 byte
548
+        if (!@is_file($imagePath) || !file_exists($imagePath) || filesize($imagePath) < 12 || !is_readable($imagePath)) {
549
+            return false;
550
+        }
551
+        $iType = exif_imagetype($imagePath);
552
+        switch ($iType) {
553
+            case IMAGETYPE_GIF:
554
+                if (imagetypes() & IMG_GIF) {
555
+                    $this->resource = imagecreatefromgif($imagePath);
556
+                    // Preserve transparency
557
+                    imagealphablending($this->resource, true);
558
+                    imagesavealpha($this->resource, true);
559
+                } else {
560
+                    $this->logger->debug('OC_Image->loadFromFile, GIF images not supported: ' . $imagePath, array('app' => 'core'));
561
+                }
562
+                break;
563
+            case IMAGETYPE_JPEG:
564
+                if (imagetypes() & IMG_JPG) {
565
+                    if (getimagesize($imagePath) !== false) {
566
+                        $this->resource = @imagecreatefromjpeg($imagePath);
567
+                    } else {
568
+                        $this->logger->debug('OC_Image->loadFromFile, JPG image not valid: ' . $imagePath, array('app' => 'core'));
569
+                    }
570
+                } else {
571
+                    $this->logger->debug('OC_Image->loadFromFile, JPG images not supported: ' . $imagePath, array('app' => 'core'));
572
+                }
573
+                break;
574
+            case IMAGETYPE_PNG:
575
+                if (imagetypes() & IMG_PNG) {
576
+                    $this->resource = @imagecreatefrompng($imagePath);
577
+                    // Preserve transparency
578
+                    imagealphablending($this->resource, true);
579
+                    imagesavealpha($this->resource, true);
580
+                } else {
581
+                    $this->logger->debug('OC_Image->loadFromFile, PNG images not supported: ' . $imagePath, array('app' => 'core'));
582
+                }
583
+                break;
584
+            case IMAGETYPE_XBM:
585
+                if (imagetypes() & IMG_XPM) {
586
+                    $this->resource = @imagecreatefromxbm($imagePath);
587
+                } else {
588
+                    $this->logger->debug('OC_Image->loadFromFile, XBM/XPM images not supported: ' . $imagePath, array('app' => 'core'));
589
+                }
590
+                break;
591
+            case IMAGETYPE_WBMP:
592
+                if (imagetypes() & IMG_WBMP) {
593
+                    $this->resource = @imagecreatefromwbmp($imagePath);
594
+                } else {
595
+                    $this->logger->debug('OC_Image->loadFromFile, WBMP images not supported: ' . $imagePath, array('app' => 'core'));
596
+                }
597
+                break;
598
+            case IMAGETYPE_BMP:
599
+                $this->resource = $this->imagecreatefrombmp($imagePath);
600
+                break;
601
+            /*
602 602
 			case IMAGETYPE_TIFF_II: // (intel byte order)
603 603
 				break;
604 604
 			case IMAGETYPE_TIFF_MM: // (motorola byte order)
@@ -622,581 +622,581 @@  discard block
 block discarded – undo
622 622
 			case IMAGETYPE_PSD:
623 623
 				break;
624 624
 			*/
625
-			default:
625
+            default:
626 626
 
627
-				// this is mostly file created from encrypted file
628
-				$this->resource = imagecreatefromstring(\OC\Files\Filesystem::file_get_contents(\OC\Files\Filesystem::getLocalPath($imagePath)));
629
-				$iType = IMAGETYPE_PNG;
630
-				$this->logger->debug('OC_Image->loadFromFile, Default', array('app' => 'core'));
631
-				break;
632
-		}
633
-		if ($this->valid()) {
634
-			$this->imageType = $iType;
635
-			$this->mimeType = image_type_to_mime_type($iType);
636
-			$this->filePath = $imagePath;
637
-		}
638
-		return $this->resource;
639
-	}
627
+                // this is mostly file created from encrypted file
628
+                $this->resource = imagecreatefromstring(\OC\Files\Filesystem::file_get_contents(\OC\Files\Filesystem::getLocalPath($imagePath)));
629
+                $iType = IMAGETYPE_PNG;
630
+                $this->logger->debug('OC_Image->loadFromFile, Default', array('app' => 'core'));
631
+                break;
632
+        }
633
+        if ($this->valid()) {
634
+            $this->imageType = $iType;
635
+            $this->mimeType = image_type_to_mime_type($iType);
636
+            $this->filePath = $imagePath;
637
+        }
638
+        return $this->resource;
639
+    }
640 640
 
641
-	/**
642
-	 * Loads an image from a string of data.
643
-	 *
644
-	 * @param string $str A string of image data as read from a file.
645
-	 * @return bool|resource An image resource or false on error
646
-	 */
647
-	public function loadFromData($str) {
648
-		if (is_resource($str)) {
649
-			return false;
650
-		}
651
-		$this->resource = @imagecreatefromstring($str);
652
-		if ($this->fileInfo) {
653
-			$this->mimeType = $this->fileInfo->buffer($str);
654
-		}
655
-		if (is_resource($this->resource)) {
656
-			imagealphablending($this->resource, false);
657
-			imagesavealpha($this->resource, true);
658
-		}
641
+    /**
642
+     * Loads an image from a string of data.
643
+     *
644
+     * @param string $str A string of image data as read from a file.
645
+     * @return bool|resource An image resource or false on error
646
+     */
647
+    public function loadFromData($str) {
648
+        if (is_resource($str)) {
649
+            return false;
650
+        }
651
+        $this->resource = @imagecreatefromstring($str);
652
+        if ($this->fileInfo) {
653
+            $this->mimeType = $this->fileInfo->buffer($str);
654
+        }
655
+        if (is_resource($this->resource)) {
656
+            imagealphablending($this->resource, false);
657
+            imagesavealpha($this->resource, true);
658
+        }
659 659
 
660
-		if (!$this->resource) {
661
-			$this->logger->debug('OC_Image->loadFromFile, could not load', array('app' => 'core'));
662
-			return false;
663
-		}
664
-		return $this->resource;
665
-	}
660
+        if (!$this->resource) {
661
+            $this->logger->debug('OC_Image->loadFromFile, could not load', array('app' => 'core'));
662
+            return false;
663
+        }
664
+        return $this->resource;
665
+    }
666 666
 
667
-	/**
668
-	 * Loads an image from a base64 encoded string.
669
-	 *
670
-	 * @param string $str A string base64 encoded string of image data.
671
-	 * @return bool|resource An image resource or false on error
672
-	 */
673
-	public function loadFromBase64($str) {
674
-		if (!is_string($str)) {
675
-			return false;
676
-		}
677
-		$data = base64_decode($str);
678
-		if ($data) { // try to load from string data
679
-			$this->resource = @imagecreatefromstring($data);
680
-			if ($this->fileInfo) {
681
-				$this->mimeType = $this->fileInfo->buffer($data);
682
-			}
683
-			if (!$this->resource) {
684
-				$this->logger->debug('OC_Image->loadFromBase64, could not load', array('app' => 'core'));
685
-				return false;
686
-			}
687
-			return $this->resource;
688
-		} else {
689
-			return false;
690
-		}
691
-	}
667
+    /**
668
+     * Loads an image from a base64 encoded string.
669
+     *
670
+     * @param string $str A string base64 encoded string of image data.
671
+     * @return bool|resource An image resource or false on error
672
+     */
673
+    public function loadFromBase64($str) {
674
+        if (!is_string($str)) {
675
+            return false;
676
+        }
677
+        $data = base64_decode($str);
678
+        if ($data) { // try to load from string data
679
+            $this->resource = @imagecreatefromstring($data);
680
+            if ($this->fileInfo) {
681
+                $this->mimeType = $this->fileInfo->buffer($data);
682
+            }
683
+            if (!$this->resource) {
684
+                $this->logger->debug('OC_Image->loadFromBase64, could not load', array('app' => 'core'));
685
+                return false;
686
+            }
687
+            return $this->resource;
688
+        } else {
689
+            return false;
690
+        }
691
+    }
692 692
 
693
-	/**
694
-	 * Create a new image from file or URL
695
-	 *
696
-	 * @link http://www.programmierer-forum.de/function-imagecreatefrombmp-laeuft-mit-allen-bitraten-t143137.htm
697
-	 * @version 1.00
698
-	 * @param string $fileName <p>
699
-	 * Path to the BMP image.
700
-	 * </p>
701
-	 * @return bool|resource an image resource identifier on success, <b>FALSE</b> on errors.
702
-	 */
703
-	private function imagecreatefrombmp($fileName) {
704
-		if (!($fh = fopen($fileName, 'rb'))) {
705
-			$this->logger->warning('imagecreatefrombmp: Can not open ' . $fileName, array('app' => 'core'));
706
-			return false;
707
-		}
708
-		// read file header
709
-		$meta = unpack('vtype/Vfilesize/Vreserved/Voffset', fread($fh, 14));
710
-		// check for bitmap
711
-		if ($meta['type'] != 19778) {
712
-			fclose($fh);
713
-			$this->logger->warning('imagecreatefrombmp: Can not open ' . $fileName . ' is not a bitmap!', array('app' => 'core'));
714
-			return false;
715
-		}
716
-		// read image header
717
-		$meta += unpack('Vheadersize/Vwidth/Vheight/vplanes/vbits/Vcompression/Vimagesize/Vxres/Vyres/Vcolors/Vimportant', fread($fh, 40));
718
-		// read additional 16bit header
719
-		if ($meta['bits'] == 16) {
720
-			$meta += unpack('VrMask/VgMask/VbMask', fread($fh, 12));
721
-		}
722
-		// set bytes and padding
723
-		$meta['bytes'] = $meta['bits'] / 8;
724
-		$this->bitDepth = $meta['bits']; //remember the bit depth for the imagebmp call
725
-		$meta['decal'] = 4 - (4 * (($meta['width'] * $meta['bytes'] / 4) - floor($meta['width'] * $meta['bytes'] / 4)));
726
-		if ($meta['decal'] == 4) {
727
-			$meta['decal'] = 0;
728
-		}
729
-		// obtain imagesize
730
-		if ($meta['imagesize'] < 1) {
731
-			$meta['imagesize'] = $meta['filesize'] - $meta['offset'];
732
-			// in rare cases filesize is equal to offset so we need to read physical size
733
-			if ($meta['imagesize'] < 1) {
734
-				$meta['imagesize'] = @filesize($fileName) - $meta['offset'];
735
-				if ($meta['imagesize'] < 1) {
736
-					fclose($fh);
737
-					$this->logger->warning('imagecreatefrombmp: Can not obtain file size of ' . $fileName . ' is not a bitmap!', array('app' => 'core'));
738
-					return false;
739
-				}
740
-			}
741
-		}
742
-		// calculate colors
743
-		$meta['colors'] = !$meta['colors'] ? pow(2, $meta['bits']) : $meta['colors'];
744
-		// read color palette
745
-		$palette = array();
746
-		if ($meta['bits'] < 16) {
747
-			$palette = unpack('l' . $meta['colors'], fread($fh, $meta['colors'] * 4));
748
-			// in rare cases the color value is signed
749
-			if ($palette[1] < 0) {
750
-				foreach ($palette as $i => $color) {
751
-					$palette[$i] = $color + 16777216;
752
-				}
753
-			}
754
-		}
755
-		// create gd image
756
-		$im = imagecreatetruecolor($meta['width'], $meta['height']);
757
-		if ($im == false) {
758
-			fclose($fh);
759
-			$this->logger->warning(
760
-				'imagecreatefrombmp: imagecreatetruecolor failed for file "' . $fileName . '" with dimensions ' . $meta['width'] . 'x' . $meta['height'],
761
-				array('app' => 'core'));
762
-			return false;
763
-		}
693
+    /**
694
+     * Create a new image from file or URL
695
+     *
696
+     * @link http://www.programmierer-forum.de/function-imagecreatefrombmp-laeuft-mit-allen-bitraten-t143137.htm
697
+     * @version 1.00
698
+     * @param string $fileName <p>
699
+     * Path to the BMP image.
700
+     * </p>
701
+     * @return bool|resource an image resource identifier on success, <b>FALSE</b> on errors.
702
+     */
703
+    private function imagecreatefrombmp($fileName) {
704
+        if (!($fh = fopen($fileName, 'rb'))) {
705
+            $this->logger->warning('imagecreatefrombmp: Can not open ' . $fileName, array('app' => 'core'));
706
+            return false;
707
+        }
708
+        // read file header
709
+        $meta = unpack('vtype/Vfilesize/Vreserved/Voffset', fread($fh, 14));
710
+        // check for bitmap
711
+        if ($meta['type'] != 19778) {
712
+            fclose($fh);
713
+            $this->logger->warning('imagecreatefrombmp: Can not open ' . $fileName . ' is not a bitmap!', array('app' => 'core'));
714
+            return false;
715
+        }
716
+        // read image header
717
+        $meta += unpack('Vheadersize/Vwidth/Vheight/vplanes/vbits/Vcompression/Vimagesize/Vxres/Vyres/Vcolors/Vimportant', fread($fh, 40));
718
+        // read additional 16bit header
719
+        if ($meta['bits'] == 16) {
720
+            $meta += unpack('VrMask/VgMask/VbMask', fread($fh, 12));
721
+        }
722
+        // set bytes and padding
723
+        $meta['bytes'] = $meta['bits'] / 8;
724
+        $this->bitDepth = $meta['bits']; //remember the bit depth for the imagebmp call
725
+        $meta['decal'] = 4 - (4 * (($meta['width'] * $meta['bytes'] / 4) - floor($meta['width'] * $meta['bytes'] / 4)));
726
+        if ($meta['decal'] == 4) {
727
+            $meta['decal'] = 0;
728
+        }
729
+        // obtain imagesize
730
+        if ($meta['imagesize'] < 1) {
731
+            $meta['imagesize'] = $meta['filesize'] - $meta['offset'];
732
+            // in rare cases filesize is equal to offset so we need to read physical size
733
+            if ($meta['imagesize'] < 1) {
734
+                $meta['imagesize'] = @filesize($fileName) - $meta['offset'];
735
+                if ($meta['imagesize'] < 1) {
736
+                    fclose($fh);
737
+                    $this->logger->warning('imagecreatefrombmp: Can not obtain file size of ' . $fileName . ' is not a bitmap!', array('app' => 'core'));
738
+                    return false;
739
+                }
740
+            }
741
+        }
742
+        // calculate colors
743
+        $meta['colors'] = !$meta['colors'] ? pow(2, $meta['bits']) : $meta['colors'];
744
+        // read color palette
745
+        $palette = array();
746
+        if ($meta['bits'] < 16) {
747
+            $palette = unpack('l' . $meta['colors'], fread($fh, $meta['colors'] * 4));
748
+            // in rare cases the color value is signed
749
+            if ($palette[1] < 0) {
750
+                foreach ($palette as $i => $color) {
751
+                    $palette[$i] = $color + 16777216;
752
+                }
753
+            }
754
+        }
755
+        // create gd image
756
+        $im = imagecreatetruecolor($meta['width'], $meta['height']);
757
+        if ($im == false) {
758
+            fclose($fh);
759
+            $this->logger->warning(
760
+                'imagecreatefrombmp: imagecreatetruecolor failed for file "' . $fileName . '" with dimensions ' . $meta['width'] . 'x' . $meta['height'],
761
+                array('app' => 'core'));
762
+            return false;
763
+        }
764 764
 
765
-		$data = fread($fh, $meta['imagesize']);
766
-		$p = 0;
767
-		$vide = chr(0);
768
-		$y = $meta['height'] - 1;
769
-		$error = 'imagecreatefrombmp: ' . $fileName . ' has not enough data!';
770
-		// loop through the image data beginning with the lower left corner
771
-		while ($y >= 0) {
772
-			$x = 0;
773
-			while ($x < $meta['width']) {
774
-				switch ($meta['bits']) {
775
-					case 32:
776
-					case 24:
777
-						if (!($part = substr($data, $p, 3))) {
778
-							$this->logger->warning($error, array('app' => 'core'));
779
-							return $im;
780
-						}
781
-						$color = @unpack('V', $part . $vide);
782
-						break;
783
-					case 16:
784
-						if (!($part = substr($data, $p, 2))) {
785
-							fclose($fh);
786
-							$this->logger->warning($error, array('app' => 'core'));
787
-							return $im;
788
-						}
789
-						$color = @unpack('v', $part);
790
-						$color[1] = (($color[1] & 0xf800) >> 8) * 65536 + (($color[1] & 0x07e0) >> 3) * 256 + (($color[1] & 0x001f) << 3);
791
-						break;
792
-					case 8:
793
-						$color = @unpack('n', $vide . substr($data, $p, 1));
794
-						$color[1] = (isset($palette[$color[1] + 1])) ? $palette[$color[1] + 1] : $palette[1];
795
-						break;
796
-					case 4:
797
-						$color = @unpack('n', $vide . substr($data, floor($p), 1));
798
-						$color[1] = ($p * 2) % 2 == 0 ? $color[1] >> 4 : $color[1] & 0x0F;
799
-						$color[1] = (isset($palette[$color[1] + 1])) ? $palette[$color[1] + 1] : $palette[1];
800
-						break;
801
-					case 1:
802
-						$color = @unpack('n', $vide . substr($data, floor($p), 1));
803
-						switch (($p * 8) % 8) {
804
-							case 0:
805
-								$color[1] = $color[1] >> 7;
806
-								break;
807
-							case 1:
808
-								$color[1] = ($color[1] & 0x40) >> 6;
809
-								break;
810
-							case 2:
811
-								$color[1] = ($color[1] & 0x20) >> 5;
812
-								break;
813
-							case 3:
814
-								$color[1] = ($color[1] & 0x10) >> 4;
815
-								break;
816
-							case 4:
817
-								$color[1] = ($color[1] & 0x8) >> 3;
818
-								break;
819
-							case 5:
820
-								$color[1] = ($color[1] & 0x4) >> 2;
821
-								break;
822
-							case 6:
823
-								$color[1] = ($color[1] & 0x2) >> 1;
824
-								break;
825
-							case 7:
826
-								$color[1] = ($color[1] & 0x1);
827
-								break;
828
-						}
829
-						$color[1] = (isset($palette[$color[1] + 1])) ? $palette[$color[1] + 1] : $palette[1];
830
-						break;
831
-					default:
832
-						fclose($fh);
833
-						$this->logger->warning('imagecreatefrombmp: ' . $fileName . ' has ' . $meta['bits'] . ' bits and this is not supported!', array('app' => 'core'));
834
-						return false;
835
-				}
836
-				imagesetpixel($im, $x, $y, $color[1]);
837
-				$x++;
838
-				$p += $meta['bytes'];
839
-			}
840
-			$y--;
841
-			$p += $meta['decal'];
842
-		}
843
-		fclose($fh);
844
-		return $im;
845
-	}
765
+        $data = fread($fh, $meta['imagesize']);
766
+        $p = 0;
767
+        $vide = chr(0);
768
+        $y = $meta['height'] - 1;
769
+        $error = 'imagecreatefrombmp: ' . $fileName . ' has not enough data!';
770
+        // loop through the image data beginning with the lower left corner
771
+        while ($y >= 0) {
772
+            $x = 0;
773
+            while ($x < $meta['width']) {
774
+                switch ($meta['bits']) {
775
+                    case 32:
776
+                    case 24:
777
+                        if (!($part = substr($data, $p, 3))) {
778
+                            $this->logger->warning($error, array('app' => 'core'));
779
+                            return $im;
780
+                        }
781
+                        $color = @unpack('V', $part . $vide);
782
+                        break;
783
+                    case 16:
784
+                        if (!($part = substr($data, $p, 2))) {
785
+                            fclose($fh);
786
+                            $this->logger->warning($error, array('app' => 'core'));
787
+                            return $im;
788
+                        }
789
+                        $color = @unpack('v', $part);
790
+                        $color[1] = (($color[1] & 0xf800) >> 8) * 65536 + (($color[1] & 0x07e0) >> 3) * 256 + (($color[1] & 0x001f) << 3);
791
+                        break;
792
+                    case 8:
793
+                        $color = @unpack('n', $vide . substr($data, $p, 1));
794
+                        $color[1] = (isset($palette[$color[1] + 1])) ? $palette[$color[1] + 1] : $palette[1];
795
+                        break;
796
+                    case 4:
797
+                        $color = @unpack('n', $vide . substr($data, floor($p), 1));
798
+                        $color[1] = ($p * 2) % 2 == 0 ? $color[1] >> 4 : $color[1] & 0x0F;
799
+                        $color[1] = (isset($palette[$color[1] + 1])) ? $palette[$color[1] + 1] : $palette[1];
800
+                        break;
801
+                    case 1:
802
+                        $color = @unpack('n', $vide . substr($data, floor($p), 1));
803
+                        switch (($p * 8) % 8) {
804
+                            case 0:
805
+                                $color[1] = $color[1] >> 7;
806
+                                break;
807
+                            case 1:
808
+                                $color[1] = ($color[1] & 0x40) >> 6;
809
+                                break;
810
+                            case 2:
811
+                                $color[1] = ($color[1] & 0x20) >> 5;
812
+                                break;
813
+                            case 3:
814
+                                $color[1] = ($color[1] & 0x10) >> 4;
815
+                                break;
816
+                            case 4:
817
+                                $color[1] = ($color[1] & 0x8) >> 3;
818
+                                break;
819
+                            case 5:
820
+                                $color[1] = ($color[1] & 0x4) >> 2;
821
+                                break;
822
+                            case 6:
823
+                                $color[1] = ($color[1] & 0x2) >> 1;
824
+                                break;
825
+                            case 7:
826
+                                $color[1] = ($color[1] & 0x1);
827
+                                break;
828
+                        }
829
+                        $color[1] = (isset($palette[$color[1] + 1])) ? $palette[$color[1] + 1] : $palette[1];
830
+                        break;
831
+                    default:
832
+                        fclose($fh);
833
+                        $this->logger->warning('imagecreatefrombmp: ' . $fileName . ' has ' . $meta['bits'] . ' bits and this is not supported!', array('app' => 'core'));
834
+                        return false;
835
+                }
836
+                imagesetpixel($im, $x, $y, $color[1]);
837
+                $x++;
838
+                $p += $meta['bytes'];
839
+            }
840
+            $y--;
841
+            $p += $meta['decal'];
842
+        }
843
+        fclose($fh);
844
+        return $im;
845
+    }
846 846
 
847
-	/**
848
-	 * Resizes the image preserving ratio.
849
-	 *
850
-	 * @param integer $maxSize The maximum size of either the width or height.
851
-	 * @return bool
852
-	 */
853
-	public function resize($maxSize) {
854
-		if (!$this->valid()) {
855
-			$this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
856
-			return false;
857
-		}
858
-		$widthOrig = imagesx($this->resource);
859
-		$heightOrig = imagesy($this->resource);
860
-		$ratioOrig = $widthOrig / $heightOrig;
847
+    /**
848
+     * Resizes the image preserving ratio.
849
+     *
850
+     * @param integer $maxSize The maximum size of either the width or height.
851
+     * @return bool
852
+     */
853
+    public function resize($maxSize) {
854
+        if (!$this->valid()) {
855
+            $this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
856
+            return false;
857
+        }
858
+        $widthOrig = imagesx($this->resource);
859
+        $heightOrig = imagesy($this->resource);
860
+        $ratioOrig = $widthOrig / $heightOrig;
861 861
 
862
-		if ($ratioOrig > 1) {
863
-			$newHeight = round($maxSize / $ratioOrig);
864
-			$newWidth = $maxSize;
865
-		} else {
866
-			$newWidth = round($maxSize * $ratioOrig);
867
-			$newHeight = $maxSize;
868
-		}
862
+        if ($ratioOrig > 1) {
863
+            $newHeight = round($maxSize / $ratioOrig);
864
+            $newWidth = $maxSize;
865
+        } else {
866
+            $newWidth = round($maxSize * $ratioOrig);
867
+            $newHeight = $maxSize;
868
+        }
869 869
 
870
-		$this->preciseResize(round($newWidth), round($newHeight));
871
-		return true;
872
-	}
870
+        $this->preciseResize(round($newWidth), round($newHeight));
871
+        return true;
872
+    }
873 873
 
874
-	/**
875
-	 * @param int $width
876
-	 * @param int $height
877
-	 * @return bool
878
-	 */
879
-	public function preciseResize($width, $height) {
880
-		if (!$this->valid()) {
881
-			$this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
882
-			return false;
883
-		}
884
-		$widthOrig = imagesx($this->resource);
885
-		$heightOrig = imagesy($this->resource);
886
-		$process = imagecreatetruecolor($width, $height);
874
+    /**
875
+     * @param int $width
876
+     * @param int $height
877
+     * @return bool
878
+     */
879
+    public function preciseResize($width, $height) {
880
+        if (!$this->valid()) {
881
+            $this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
882
+            return false;
883
+        }
884
+        $widthOrig = imagesx($this->resource);
885
+        $heightOrig = imagesy($this->resource);
886
+        $process = imagecreatetruecolor($width, $height);
887 887
 
888
-		if ($process == false) {
889
-			$this->logger->error(__METHOD__ . '(): Error creating true color image', array('app' => 'core'));
890
-			imagedestroy($process);
891
-			return false;
892
-		}
888
+        if ($process == false) {
889
+            $this->logger->error(__METHOD__ . '(): Error creating true color image', array('app' => 'core'));
890
+            imagedestroy($process);
891
+            return false;
892
+        }
893 893
 
894
-		// preserve transparency
895
-		if ($this->imageType == IMAGETYPE_GIF or $this->imageType == IMAGETYPE_PNG) {
896
-			imagecolortransparent($process, imagecolorallocatealpha($process, 0, 0, 0, 127));
897
-			imagealphablending($process, false);
898
-			imagesavealpha($process, true);
899
-		}
894
+        // preserve transparency
895
+        if ($this->imageType == IMAGETYPE_GIF or $this->imageType == IMAGETYPE_PNG) {
896
+            imagecolortransparent($process, imagecolorallocatealpha($process, 0, 0, 0, 127));
897
+            imagealphablending($process, false);
898
+            imagesavealpha($process, true);
899
+        }
900 900
 
901
-		imagecopyresampled($process, $this->resource, 0, 0, 0, 0, $width, $height, $widthOrig, $heightOrig);
902
-		if ($process == false) {
903
-			$this->logger->error(__METHOD__ . '(): Error re-sampling process image', array('app' => 'core'));
904
-			imagedestroy($process);
905
-			return false;
906
-		}
907
-		imagedestroy($this->resource);
908
-		$this->resource = $process;
909
-		return true;
910
-	}
901
+        imagecopyresampled($process, $this->resource, 0, 0, 0, 0, $width, $height, $widthOrig, $heightOrig);
902
+        if ($process == false) {
903
+            $this->logger->error(__METHOD__ . '(): Error re-sampling process image', array('app' => 'core'));
904
+            imagedestroy($process);
905
+            return false;
906
+        }
907
+        imagedestroy($this->resource);
908
+        $this->resource = $process;
909
+        return true;
910
+    }
911 911
 
912
-	/**
913
-	 * Crops the image to the middle square. If the image is already square it just returns.
914
-	 *
915
-	 * @param int $size maximum size for the result (optional)
916
-	 * @return bool for success or failure
917
-	 */
918
-	public function centerCrop($size = 0) {
919
-		if (!$this->valid()) {
920
-			$this->logger->error('OC_Image->centerCrop, No image loaded', array('app' => 'core'));
921
-			return false;
922
-		}
923
-		$widthOrig = imagesx($this->resource);
924
-		$heightOrig = imagesy($this->resource);
925
-		if ($widthOrig === $heightOrig and $size == 0) {
926
-			return true;
927
-		}
928
-		$ratioOrig = $widthOrig / $heightOrig;
929
-		$width = $height = min($widthOrig, $heightOrig);
912
+    /**
913
+     * Crops the image to the middle square. If the image is already square it just returns.
914
+     *
915
+     * @param int $size maximum size for the result (optional)
916
+     * @return bool for success or failure
917
+     */
918
+    public function centerCrop($size = 0) {
919
+        if (!$this->valid()) {
920
+            $this->logger->error('OC_Image->centerCrop, No image loaded', array('app' => 'core'));
921
+            return false;
922
+        }
923
+        $widthOrig = imagesx($this->resource);
924
+        $heightOrig = imagesy($this->resource);
925
+        if ($widthOrig === $heightOrig and $size == 0) {
926
+            return true;
927
+        }
928
+        $ratioOrig = $widthOrig / $heightOrig;
929
+        $width = $height = min($widthOrig, $heightOrig);
930 930
 
931
-		if ($ratioOrig > 1) {
932
-			$x = ($widthOrig / 2) - ($width / 2);
933
-			$y = 0;
934
-		} else {
935
-			$y = ($heightOrig / 2) - ($height / 2);
936
-			$x = 0;
937
-		}
938
-		if ($size > 0) {
939
-			$targetWidth = $size;
940
-			$targetHeight = $size;
941
-		} else {
942
-			$targetWidth = $width;
943
-			$targetHeight = $height;
944
-		}
945
-		$process = imagecreatetruecolor($targetWidth, $targetHeight);
946
-		if ($process == false) {
947
-			$this->logger->error('OC_Image->centerCrop, Error creating true color image', array('app' => 'core'));
948
-			imagedestroy($process);
949
-			return false;
950
-		}
931
+        if ($ratioOrig > 1) {
932
+            $x = ($widthOrig / 2) - ($width / 2);
933
+            $y = 0;
934
+        } else {
935
+            $y = ($heightOrig / 2) - ($height / 2);
936
+            $x = 0;
937
+        }
938
+        if ($size > 0) {
939
+            $targetWidth = $size;
940
+            $targetHeight = $size;
941
+        } else {
942
+            $targetWidth = $width;
943
+            $targetHeight = $height;
944
+        }
945
+        $process = imagecreatetruecolor($targetWidth, $targetHeight);
946
+        if ($process == false) {
947
+            $this->logger->error('OC_Image->centerCrop, Error creating true color image', array('app' => 'core'));
948
+            imagedestroy($process);
949
+            return false;
950
+        }
951 951
 
952
-		// preserve transparency
953
-		if ($this->imageType == IMAGETYPE_GIF or $this->imageType == IMAGETYPE_PNG) {
954
-			imagecolortransparent($process, imagecolorallocatealpha($process, 0, 0, 0, 127));
955
-			imagealphablending($process, false);
956
-			imagesavealpha($process, true);
957
-		}
952
+        // preserve transparency
953
+        if ($this->imageType == IMAGETYPE_GIF or $this->imageType == IMAGETYPE_PNG) {
954
+            imagecolortransparent($process, imagecolorallocatealpha($process, 0, 0, 0, 127));
955
+            imagealphablending($process, false);
956
+            imagesavealpha($process, true);
957
+        }
958 958
 
959
-		imagecopyresampled($process, $this->resource, 0, 0, $x, $y, $targetWidth, $targetHeight, $width, $height);
960
-		if ($process == false) {
961
-			$this->logger->error('OC_Image->centerCrop, Error re-sampling process image ' . $width . 'x' . $height, array('app' => 'core'));
962
-			imagedestroy($process);
963
-			return false;
964
-		}
965
-		imagedestroy($this->resource);
966
-		$this->resource = $process;
967
-		return true;
968
-	}
959
+        imagecopyresampled($process, $this->resource, 0, 0, $x, $y, $targetWidth, $targetHeight, $width, $height);
960
+        if ($process == false) {
961
+            $this->logger->error('OC_Image->centerCrop, Error re-sampling process image ' . $width . 'x' . $height, array('app' => 'core'));
962
+            imagedestroy($process);
963
+            return false;
964
+        }
965
+        imagedestroy($this->resource);
966
+        $this->resource = $process;
967
+        return true;
968
+    }
969 969
 
970
-	/**
971
-	 * Crops the image from point $x$y with dimension $wx$h.
972
-	 *
973
-	 * @param int $x Horizontal position
974
-	 * @param int $y Vertical position
975
-	 * @param int $w Width
976
-	 * @param int $h Height
977
-	 * @return bool for success or failure
978
-	 */
979
-	public function crop($x, $y, $w, $h) {
980
-		if (!$this->valid()) {
981
-			$this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
982
-			return false;
983
-		}
984
-		$process = imagecreatetruecolor($w, $h);
985
-		if ($process == false) {
986
-			$this->logger->error(__METHOD__ . '(): Error creating true color image', array('app' => 'core'));
987
-			imagedestroy($process);
988
-			return false;
989
-		}
970
+    /**
971
+     * Crops the image from point $x$y with dimension $wx$h.
972
+     *
973
+     * @param int $x Horizontal position
974
+     * @param int $y Vertical position
975
+     * @param int $w Width
976
+     * @param int $h Height
977
+     * @return bool for success or failure
978
+     */
979
+    public function crop($x, $y, $w, $h) {
980
+        if (!$this->valid()) {
981
+            $this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
982
+            return false;
983
+        }
984
+        $process = imagecreatetruecolor($w, $h);
985
+        if ($process == false) {
986
+            $this->logger->error(__METHOD__ . '(): Error creating true color image', array('app' => 'core'));
987
+            imagedestroy($process);
988
+            return false;
989
+        }
990 990
 
991
-		// preserve transparency
992
-		if ($this->imageType == IMAGETYPE_GIF or $this->imageType == IMAGETYPE_PNG) {
993
-			imagecolortransparent($process, imagecolorallocatealpha($process, 0, 0, 0, 127));
994
-			imagealphablending($process, false);
995
-			imagesavealpha($process, true);
996
-		}
991
+        // preserve transparency
992
+        if ($this->imageType == IMAGETYPE_GIF or $this->imageType == IMAGETYPE_PNG) {
993
+            imagecolortransparent($process, imagecolorallocatealpha($process, 0, 0, 0, 127));
994
+            imagealphablending($process, false);
995
+            imagesavealpha($process, true);
996
+        }
997 997
 
998
-		imagecopyresampled($process, $this->resource, 0, 0, $x, $y, $w, $h, $w, $h);
999
-		if ($process == false) {
1000
-			$this->logger->error(__METHOD__ . '(): Error re-sampling process image ' . $w . 'x' . $h, array('app' => 'core'));
1001
-			imagedestroy($process);
1002
-			return false;
1003
-		}
1004
-		imagedestroy($this->resource);
1005
-		$this->resource = $process;
1006
-		return true;
1007
-	}
998
+        imagecopyresampled($process, $this->resource, 0, 0, $x, $y, $w, $h, $w, $h);
999
+        if ($process == false) {
1000
+            $this->logger->error(__METHOD__ . '(): Error re-sampling process image ' . $w . 'x' . $h, array('app' => 'core'));
1001
+            imagedestroy($process);
1002
+            return false;
1003
+        }
1004
+        imagedestroy($this->resource);
1005
+        $this->resource = $process;
1006
+        return true;
1007
+    }
1008 1008
 
1009
-	/**
1010
-	 * Resizes the image to fit within a boundary while preserving ratio.
1011
-	 *
1012
-	 * Warning: Images smaller than $maxWidth x $maxHeight will end up being scaled up
1013
-	 *
1014
-	 * @param integer $maxWidth
1015
-	 * @param integer $maxHeight
1016
-	 * @return bool
1017
-	 */
1018
-	public function fitIn($maxWidth, $maxHeight) {
1019
-		if (!$this->valid()) {
1020
-			$this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
1021
-			return false;
1022
-		}
1023
-		$widthOrig = imagesx($this->resource);
1024
-		$heightOrig = imagesy($this->resource);
1025
-		$ratio = $widthOrig / $heightOrig;
1009
+    /**
1010
+     * Resizes the image to fit within a boundary while preserving ratio.
1011
+     *
1012
+     * Warning: Images smaller than $maxWidth x $maxHeight will end up being scaled up
1013
+     *
1014
+     * @param integer $maxWidth
1015
+     * @param integer $maxHeight
1016
+     * @return bool
1017
+     */
1018
+    public function fitIn($maxWidth, $maxHeight) {
1019
+        if (!$this->valid()) {
1020
+            $this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
1021
+            return false;
1022
+        }
1023
+        $widthOrig = imagesx($this->resource);
1024
+        $heightOrig = imagesy($this->resource);
1025
+        $ratio = $widthOrig / $heightOrig;
1026 1026
 
1027
-		$newWidth = min($maxWidth, $ratio * $maxHeight);
1028
-		$newHeight = min($maxHeight, $maxWidth / $ratio);
1027
+        $newWidth = min($maxWidth, $ratio * $maxHeight);
1028
+        $newHeight = min($maxHeight, $maxWidth / $ratio);
1029 1029
 
1030
-		$this->preciseResize(round($newWidth), round($newHeight));
1031
-		return true;
1032
-	}
1030
+        $this->preciseResize(round($newWidth), round($newHeight));
1031
+        return true;
1032
+    }
1033 1033
 
1034
-	/**
1035
-	 * Shrinks larger images to fit within specified boundaries while preserving ratio.
1036
-	 *
1037
-	 * @param integer $maxWidth
1038
-	 * @param integer $maxHeight
1039
-	 * @return bool
1040
-	 */
1041
-	public function scaleDownToFit($maxWidth, $maxHeight) {
1042
-		if (!$this->valid()) {
1043
-			$this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
1044
-			return false;
1045
-		}
1046
-		$widthOrig = imagesx($this->resource);
1047
-		$heightOrig = imagesy($this->resource);
1034
+    /**
1035
+     * Shrinks larger images to fit within specified boundaries while preserving ratio.
1036
+     *
1037
+     * @param integer $maxWidth
1038
+     * @param integer $maxHeight
1039
+     * @return bool
1040
+     */
1041
+    public function scaleDownToFit($maxWidth, $maxHeight) {
1042
+        if (!$this->valid()) {
1043
+            $this->logger->error(__METHOD__ . '(): No image loaded', array('app' => 'core'));
1044
+            return false;
1045
+        }
1046
+        $widthOrig = imagesx($this->resource);
1047
+        $heightOrig = imagesy($this->resource);
1048 1048
 
1049
-		if ($widthOrig > $maxWidth || $heightOrig > $maxHeight) {
1050
-			return $this->fitIn($maxWidth, $maxHeight);
1051
-		}
1049
+        if ($widthOrig > $maxWidth || $heightOrig > $maxHeight) {
1050
+            return $this->fitIn($maxWidth, $maxHeight);
1051
+        }
1052 1052
 
1053
-		return false;
1054
-	}
1053
+        return false;
1054
+    }
1055 1055
 
1056
-	/**
1057
-	 * Destroys the current image and resets the object
1058
-	 */
1059
-	public function destroy() {
1060
-		if ($this->valid()) {
1061
-			imagedestroy($this->resource);
1062
-		}
1063
-		$this->resource = null;
1064
-	}
1056
+    /**
1057
+     * Destroys the current image and resets the object
1058
+     */
1059
+    public function destroy() {
1060
+        if ($this->valid()) {
1061
+            imagedestroy($this->resource);
1062
+        }
1063
+        $this->resource = null;
1064
+    }
1065 1065
 
1066
-	public function __destruct() {
1067
-		$this->destroy();
1068
-	}
1066
+    public function __destruct() {
1067
+        $this->destroy();
1068
+    }
1069 1069
 }
1070 1070
 
1071 1071
 if (!function_exists('imagebmp')) {
1072
-	/**
1073
-	 * Output a BMP image to either the browser or a file
1074
-	 *
1075
-	 * @link http://www.ugia.cn/wp-data/imagebmp.php
1076
-	 * @author legend <[email protected]>
1077
-	 * @link http://www.programmierer-forum.de/imagebmp-gute-funktion-gefunden-t143716.htm
1078
-	 * @author mgutt <[email protected]>
1079
-	 * @version 1.00
1080
-	 * @param resource $im
1081
-	 * @param string $fileName [optional] <p>The path to save the file to.</p>
1082
-	 * @param int $bit [optional] <p>Bit depth, (default is 24).</p>
1083
-	 * @param int $compression [optional]
1084
-	 * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure.
1085
-	 */
1086
-	function imagebmp($im, $fileName = '', $bit = 24, $compression = 0) {
1087
-		if (!in_array($bit, array(1, 4, 8, 16, 24, 32))) {
1088
-			$bit = 24;
1089
-		} else if ($bit == 32) {
1090
-			$bit = 24;
1091
-		}
1092
-		$bits = pow(2, $bit);
1093
-		imagetruecolortopalette($im, true, $bits);
1094
-		$width = imagesx($im);
1095
-		$height = imagesy($im);
1096
-		$colorsNum = imagecolorstotal($im);
1097
-		$rgbQuad = '';
1098
-		if ($bit <= 8) {
1099
-			for ($i = 0; $i < $colorsNum; $i++) {
1100
-				$colors = imagecolorsforindex($im, $i);
1101
-				$rgbQuad .= chr($colors['blue']) . chr($colors['green']) . chr($colors['red']) . "\0";
1102
-			}
1103
-			$bmpData = '';
1104
-			if ($compression == 0 || $bit < 8) {
1105
-				$compression = 0;
1106
-				$extra = '';
1107
-				$padding = 4 - ceil($width / (8 / $bit)) % 4;
1108
-				if ($padding % 4 != 0) {
1109
-					$extra = str_repeat("\0", $padding);
1110
-				}
1111
-				for ($j = $height - 1; $j >= 0; $j--) {
1112
-					$i = 0;
1113
-					while ($i < $width) {
1114
-						$bin = 0;
1115
-						$limit = $width - $i < 8 / $bit ? (8 / $bit - $width + $i) * $bit : 0;
1116
-						for ($k = 8 - $bit; $k >= $limit; $k -= $bit) {
1117
-							$index = imagecolorat($im, $i, $j);
1118
-							$bin |= $index << $k;
1119
-							$i++;
1120
-						}
1121
-						$bmpData .= chr($bin);
1122
-					}
1123
-					$bmpData .= $extra;
1124
-				}
1125
-			} // RLE8
1126
-			else if ($compression == 1 && $bit == 8) {
1127
-				for ($j = $height - 1; $j >= 0; $j--) {
1128
-					$lastIndex = "\0";
1129
-					$sameNum = 0;
1130
-					for ($i = 0; $i <= $width; $i++) {
1131
-						$index = imagecolorat($im, $i, $j);
1132
-						if ($index !== $lastIndex || $sameNum > 255) {
1133
-							if ($sameNum != 0) {
1134
-								$bmpData .= chr($sameNum) . chr($lastIndex);
1135
-							}
1136
-							$lastIndex = $index;
1137
-							$sameNum = 1;
1138
-						} else {
1139
-							$sameNum++;
1140
-						}
1141
-					}
1142
-					$bmpData .= "\0\0";
1143
-				}
1144
-				$bmpData .= "\0\1";
1145
-			}
1146
-			$sizeQuad = strlen($rgbQuad);
1147
-			$sizeData = strlen($bmpData);
1148
-		} else {
1149
-			$extra = '';
1150
-			$padding = 4 - ($width * ($bit / 8)) % 4;
1151
-			if ($padding % 4 != 0) {
1152
-				$extra = str_repeat("\0", $padding);
1153
-			}
1154
-			$bmpData = '';
1155
-			for ($j = $height - 1; $j >= 0; $j--) {
1156
-				for ($i = 0; $i < $width; $i++) {
1157
-					$index = imagecolorat($im, $i, $j);
1158
-					$colors = imagecolorsforindex($im, $index);
1159
-					if ($bit == 16) {
1160
-						$bin = 0 << $bit;
1161
-						$bin |= ($colors['red'] >> 3) << 10;
1162
-						$bin |= ($colors['green'] >> 3) << 5;
1163
-						$bin |= $colors['blue'] >> 3;
1164
-						$bmpData .= pack("v", $bin);
1165
-					} else {
1166
-						$bmpData .= pack("c*", $colors['blue'], $colors['green'], $colors['red']);
1167
-					}
1168
-				}
1169
-				$bmpData .= $extra;
1170
-			}
1171
-			$sizeQuad = 0;
1172
-			$sizeData = strlen($bmpData);
1173
-			$colorsNum = 0;
1174
-		}
1175
-		$fileHeader = 'BM' . pack('V3', 54 + $sizeQuad + $sizeData, 0, 54 + $sizeQuad);
1176
-		$infoHeader = pack('V3v2V*', 0x28, $width, $height, 1, $bit, $compression, $sizeData, 0, 0, $colorsNum, 0);
1177
-		if ($fileName != '') {
1178
-			$fp = fopen($fileName, 'wb');
1179
-			fwrite($fp, $fileHeader . $infoHeader . $rgbQuad . $bmpData);
1180
-			fclose($fp);
1181
-			return true;
1182
-		}
1183
-		echo $fileHeader . $infoHeader . $rgbQuad . $bmpData;
1184
-		return true;
1185
-	}
1072
+    /**
1073
+     * Output a BMP image to either the browser or a file
1074
+     *
1075
+     * @link http://www.ugia.cn/wp-data/imagebmp.php
1076
+     * @author legend <[email protected]>
1077
+     * @link http://www.programmierer-forum.de/imagebmp-gute-funktion-gefunden-t143716.htm
1078
+     * @author mgutt <[email protected]>
1079
+     * @version 1.00
1080
+     * @param resource $im
1081
+     * @param string $fileName [optional] <p>The path to save the file to.</p>
1082
+     * @param int $bit [optional] <p>Bit depth, (default is 24).</p>
1083
+     * @param int $compression [optional]
1084
+     * @return bool <b>TRUE</b> on success or <b>FALSE</b> on failure.
1085
+     */
1086
+    function imagebmp($im, $fileName = '', $bit = 24, $compression = 0) {
1087
+        if (!in_array($bit, array(1, 4, 8, 16, 24, 32))) {
1088
+            $bit = 24;
1089
+        } else if ($bit == 32) {
1090
+            $bit = 24;
1091
+        }
1092
+        $bits = pow(2, $bit);
1093
+        imagetruecolortopalette($im, true, $bits);
1094
+        $width = imagesx($im);
1095
+        $height = imagesy($im);
1096
+        $colorsNum = imagecolorstotal($im);
1097
+        $rgbQuad = '';
1098
+        if ($bit <= 8) {
1099
+            for ($i = 0; $i < $colorsNum; $i++) {
1100
+                $colors = imagecolorsforindex($im, $i);
1101
+                $rgbQuad .= chr($colors['blue']) . chr($colors['green']) . chr($colors['red']) . "\0";
1102
+            }
1103
+            $bmpData = '';
1104
+            if ($compression == 0 || $bit < 8) {
1105
+                $compression = 0;
1106
+                $extra = '';
1107
+                $padding = 4 - ceil($width / (8 / $bit)) % 4;
1108
+                if ($padding % 4 != 0) {
1109
+                    $extra = str_repeat("\0", $padding);
1110
+                }
1111
+                for ($j = $height - 1; $j >= 0; $j--) {
1112
+                    $i = 0;
1113
+                    while ($i < $width) {
1114
+                        $bin = 0;
1115
+                        $limit = $width - $i < 8 / $bit ? (8 / $bit - $width + $i) * $bit : 0;
1116
+                        for ($k = 8 - $bit; $k >= $limit; $k -= $bit) {
1117
+                            $index = imagecolorat($im, $i, $j);
1118
+                            $bin |= $index << $k;
1119
+                            $i++;
1120
+                        }
1121
+                        $bmpData .= chr($bin);
1122
+                    }
1123
+                    $bmpData .= $extra;
1124
+                }
1125
+            } // RLE8
1126
+            else if ($compression == 1 && $bit == 8) {
1127
+                for ($j = $height - 1; $j >= 0; $j--) {
1128
+                    $lastIndex = "\0";
1129
+                    $sameNum = 0;
1130
+                    for ($i = 0; $i <= $width; $i++) {
1131
+                        $index = imagecolorat($im, $i, $j);
1132
+                        if ($index !== $lastIndex || $sameNum > 255) {
1133
+                            if ($sameNum != 0) {
1134
+                                $bmpData .= chr($sameNum) . chr($lastIndex);
1135
+                            }
1136
+                            $lastIndex = $index;
1137
+                            $sameNum = 1;
1138
+                        } else {
1139
+                            $sameNum++;
1140
+                        }
1141
+                    }
1142
+                    $bmpData .= "\0\0";
1143
+                }
1144
+                $bmpData .= "\0\1";
1145
+            }
1146
+            $sizeQuad = strlen($rgbQuad);
1147
+            $sizeData = strlen($bmpData);
1148
+        } else {
1149
+            $extra = '';
1150
+            $padding = 4 - ($width * ($bit / 8)) % 4;
1151
+            if ($padding % 4 != 0) {
1152
+                $extra = str_repeat("\0", $padding);
1153
+            }
1154
+            $bmpData = '';
1155
+            for ($j = $height - 1; $j >= 0; $j--) {
1156
+                for ($i = 0; $i < $width; $i++) {
1157
+                    $index = imagecolorat($im, $i, $j);
1158
+                    $colors = imagecolorsforindex($im, $index);
1159
+                    if ($bit == 16) {
1160
+                        $bin = 0 << $bit;
1161
+                        $bin |= ($colors['red'] >> 3) << 10;
1162
+                        $bin |= ($colors['green'] >> 3) << 5;
1163
+                        $bin |= $colors['blue'] >> 3;
1164
+                        $bmpData .= pack("v", $bin);
1165
+                    } else {
1166
+                        $bmpData .= pack("c*", $colors['blue'], $colors['green'], $colors['red']);
1167
+                    }
1168
+                }
1169
+                $bmpData .= $extra;
1170
+            }
1171
+            $sizeQuad = 0;
1172
+            $sizeData = strlen($bmpData);
1173
+            $colorsNum = 0;
1174
+        }
1175
+        $fileHeader = 'BM' . pack('V3', 54 + $sizeQuad + $sizeData, 0, 54 + $sizeQuad);
1176
+        $infoHeader = pack('V3v2V*', 0x28, $width, $height, 1, $bit, $compression, $sizeData, 0, 0, $colorsNum, 0);
1177
+        if ($fileName != '') {
1178
+            $fp = fopen($fileName, 'wb');
1179
+            fwrite($fp, $fileHeader . $infoHeader . $rgbQuad . $bmpData);
1180
+            fclose($fp);
1181
+            return true;
1182
+        }
1183
+        echo $fileHeader . $infoHeader . $rgbQuad . $bmpData;
1184
+        return true;
1185
+    }
1186 1186
 }
1187 1187
 
1188 1188
 if (!function_exists('exif_imagetype')) {
1189
-	/**
1190
-	 * Workaround if exif_imagetype does not exist
1191
-	 *
1192
-	 * @link http://www.php.net/manual/en/function.exif-imagetype.php#80383
1193
-	 * @param string $fileName
1194
-	 * @return string|boolean
1195
-	 */
1196
-	function exif_imagetype($fileName) {
1197
-		if (($info = getimagesize($fileName)) !== false) {
1198
-			return $info[2];
1199
-		}
1200
-		return false;
1201
-	}
1189
+    /**
1190
+     * Workaround if exif_imagetype does not exist
1191
+     *
1192
+     * @link http://www.php.net/manual/en/function.exif-imagetype.php#80383
1193
+     * @param string $fileName
1194
+     * @return string|boolean
1195
+     */
1196
+    function exif_imagetype($fileName) {
1197
+        if (($info = getimagesize($fileName)) !== false) {
1198
+            return $info[2];
1199
+        }
1200
+        return false;
1201
+    }
1202 1202
 }
Please login to merge, or discard this patch.
lib/private/legacy/template/functions.php 2 patches
Indentation   +115 added lines, -115 removed lines patch added patch discarded remove patch
@@ -35,7 +35,7 @@  discard block
 block discarded – undo
35 35
  * @param string $string the string which will be escaped and printed
36 36
  */
37 37
 function p($string) {
38
-	print(\OCP\Util::sanitizeHTML($string));
38
+    print(\OCP\Util::sanitizeHTML($string));
39 39
 }
40 40
 
41 41
 
@@ -45,14 +45,14 @@  discard block
 block discarded – undo
45 45
  * @param string $opts, additional optional options
46 46
 */
47 47
 function emit_css_tag($href, $opts = '') {
48
-	$s='<link rel="stylesheet"';
49
-	if (!empty($href)) {
50
-		$s.=' href="' . $href .'"';
51
-	}
52
-	if (!empty($opts)) {
53
-		$s.=' '.$opts;
54
-	}
55
-	print_unescaped($s.">\n");
48
+    $s='<link rel="stylesheet"';
49
+    if (!empty($href)) {
50
+        $s.=' href="' . $href .'"';
51
+    }
52
+    if (!empty($opts)) {
53
+        $s.=' '.$opts;
54
+    }
55
+    print_unescaped($s.">\n");
56 56
 }
57 57
 
58 58
 /**
@@ -60,12 +60,12 @@  discard block
 block discarded – undo
60 60
  * @param array $obj all the script information from template
61 61
 */
62 62
 function emit_css_loading_tags($obj) {
63
-	foreach($obj['cssfiles'] as $css) {
64
-		emit_css_tag($css);
65
-	}
66
-	foreach($obj['printcssfiles'] as $css) {
67
-		emit_css_tag($css, 'media="print"');
68
-	}
63
+    foreach($obj['cssfiles'] as $css) {
64
+        emit_css_tag($css);
65
+    }
66
+    foreach($obj['printcssfiles'] as $css) {
67
+        emit_css_tag($css, 'media="print"');
68
+    }
69 69
 }
70 70
 
71 71
 /**
@@ -74,20 +74,20 @@  discard block
 block discarded – undo
74 74
  * @param string $script_content the inline script content, ignored when empty
75 75
 */
76 76
 function emit_script_tag($src, $script_content='') {
77
-	$defer_str=' defer';
78
-	$s='<script nonce="' . \OC::$server->getContentSecurityPolicyNonceManager()->getNonce() . '"';
79
-	if (!empty($src)) {
80
-		 // emit script tag for deferred loading from $src
81
-		$s.=$defer_str.' src="' . $src .'">';
82
-	} else if (!empty($script_content)) {
83
-		// emit script tag for inline script from $script_content without defer (see MDN)
84
-		$s.=">\n".$script_content."\n";
85
-	} else {
86
-		// no $src nor $src_content, really useless empty tag
87
-		$s.='>';
88
-	}
89
-	$s.='</script>';
90
-	print_unescaped($s."\n");
77
+    $defer_str=' defer';
78
+    $s='<script nonce="' . \OC::$server->getContentSecurityPolicyNonceManager()->getNonce() . '"';
79
+    if (!empty($src)) {
80
+            // emit script tag for deferred loading from $src
81
+        $s.=$defer_str.' src="' . $src .'">';
82
+    } else if (!empty($script_content)) {
83
+        // emit script tag for inline script from $script_content without defer (see MDN)
84
+        $s.=">\n".$script_content."\n";
85
+    } else {
86
+        // no $src nor $src_content, really useless empty tag
87
+        $s.='>';
88
+    }
89
+    $s.='</script>';
90
+    print_unescaped($s."\n");
91 91
 }
92 92
 
93 93
 /**
@@ -95,12 +95,12 @@  discard block
 block discarded – undo
95 95
  * @param array $obj all the script information from template
96 96
 */
97 97
 function emit_script_loading_tags($obj) {
98
-	foreach($obj['jsfiles'] as $jsfile) {
99
-		emit_script_tag($jsfile, '');
100
-	}
101
-	if (!empty($obj['inline_ocjs'])) {
102
-		emit_script_tag('', $obj['inline_ocjs']);
103
-	}
98
+    foreach($obj['jsfiles'] as $jsfile) {
99
+        emit_script_tag($jsfile, '');
100
+    }
101
+    if (!empty($obj['inline_ocjs'])) {
102
+        emit_script_tag('', $obj['inline_ocjs']);
103
+    }
104 104
 }
105 105
 
106 106
 /**
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
  * @param string|array $string the string which will be printed as it is
110 110
  */
111 111
 function print_unescaped($string) {
112
-	print($string);
112
+    print($string);
113 113
 }
114 114
 
115 115
 /**
@@ -119,13 +119,13 @@  discard block
 block discarded – undo
119 119
  * if an array is given it will add all scripts
120 120
  */
121 121
 function script($app, $file = null) {
122
-	if(is_array($file)) {
123
-		foreach($file as $f) {
124
-			OC_Util::addScript($app, $f);
125
-		}
126
-	} else {
127
-		OC_Util::addScript($app, $file);
128
-	}
122
+    if(is_array($file)) {
123
+        foreach($file as $f) {
124
+            OC_Util::addScript($app, $f);
125
+        }
126
+    } else {
127
+        OC_Util::addScript($app, $file);
128
+    }
129 129
 }
130 130
 
131 131
 /**
@@ -135,13 +135,13 @@  discard block
 block discarded – undo
135 135
  * if an array is given it will add all scripts
136 136
  */
137 137
 function vendor_script($app, $file = null) {
138
-	if(is_array($file)) {
139
-		foreach($file as $f) {
140
-			OC_Util::addVendorScript($app, $f);
141
-		}
142
-	} else {
143
-		OC_Util::addVendorScript($app, $file);
144
-	}
138
+    if(is_array($file)) {
139
+        foreach($file as $f) {
140
+            OC_Util::addVendorScript($app, $f);
141
+        }
142
+    } else {
143
+        OC_Util::addVendorScript($app, $file);
144
+    }
145 145
 }
146 146
 
147 147
 /**
@@ -151,13 +151,13 @@  discard block
 block discarded – undo
151 151
  * if an array is given it will add all styles
152 152
  */
153 153
 function style($app, $file = null) {
154
-	if(is_array($file)) {
155
-		foreach($file as $f) {
156
-			OC_Util::addStyle($app, $f);
157
-		}
158
-	} else {
159
-		OC_Util::addStyle($app, $file);
160
-	}
154
+    if(is_array($file)) {
155
+        foreach($file as $f) {
156
+            OC_Util::addStyle($app, $f);
157
+        }
158
+    } else {
159
+        OC_Util::addStyle($app, $file);
160
+    }
161 161
 }
162 162
 
163 163
 /**
@@ -167,13 +167,13 @@  discard block
 block discarded – undo
167 167
  * if an array is given it will add all styles
168 168
  */
169 169
 function vendor_style($app, $file = null) {
170
-	if(is_array($file)) {
171
-		foreach($file as $f) {
172
-			OC_Util::addVendorStyle($app, $f);
173
-		}
174
-	} else {
175
-		OC_Util::addVendorStyle($app, $file);
176
-	}
170
+    if(is_array($file)) {
171
+        foreach($file as $f) {
172
+            OC_Util::addVendorStyle($app, $f);
173
+        }
174
+    } else {
175
+        OC_Util::addVendorStyle($app, $file);
176
+    }
177 177
 }
178 178
 
179 179
 /**
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
  * if an array is given it will add all styles
183 183
  */
184 184
 function translation($app) {
185
-	OC_Util::addTranslations($app);
185
+    OC_Util::addTranslations($app);
186 186
 }
187 187
 
188 188
 /**
@@ -192,15 +192,15 @@  discard block
 block discarded – undo
192 192
  * if an array is given it will add all components
193 193
  */
194 194
 function component($app, $file) {
195
-	if(is_array($file)) {
196
-		foreach($file as $f) {
197
-			$url = link_to($app, 'component/' . $f . '.html');
198
-			OC_Util::addHeader('link', array('rel' => 'import', 'href' => $url));
199
-		}
200
-	} else {
201
-		$url = link_to($app, 'component/' . $file . '.html');
202
-		OC_Util::addHeader('link', array('rel' => 'import', 'href' => $url));
203
-	}
195
+    if(is_array($file)) {
196
+        foreach($file as $f) {
197
+            $url = link_to($app, 'component/' . $f . '.html');
198
+            OC_Util::addHeader('link', array('rel' => 'import', 'href' => $url));
199
+        }
200
+    } else {
201
+        $url = link_to($app, 'component/' . $file . '.html');
202
+        OC_Util::addHeader('link', array('rel' => 'import', 'href' => $url));
203
+    }
204 204
 }
205 205
 
206 206
 /**
@@ -213,7 +213,7 @@  discard block
 block discarded – undo
213 213
  * For further information have a look at \OCP\IURLGenerator::linkTo
214 214
  */
215 215
 function link_to( $app, $file, $args = array() ) {
216
-	return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
216
+    return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
217 217
 }
218 218
 
219 219
 /**
@@ -221,7 +221,7 @@  discard block
 block discarded – undo
221 221
  * @return string url to the online documentation
222 222
  */
223 223
 function link_to_docs($key) {
224
-	return \OC::$server->getURLGenerator()->linkToDocs($key);
224
+    return \OC::$server->getURLGenerator()->linkToDocs($key);
225 225
 }
226 226
 
227 227
 /**
@@ -233,7 +233,7 @@  discard block
 block discarded – undo
233 233
  * For further information have a look at \OCP\IURLGenerator::imagePath
234 234
  */
235 235
 function image_path( $app, $image ) {
236
-	return \OC::$server->getURLGenerator()->imagePath( $app, $image );
236
+    return \OC::$server->getURLGenerator()->imagePath( $app, $image );
237 237
 }
238 238
 
239 239
 /**
@@ -242,7 +242,7 @@  discard block
 block discarded – undo
242 242
  * @return string link to the image
243 243
  */
244 244
 function mimetype_icon( $mimetype ) {
245
-	return \OC::$server->getMimeTypeDetector()->mimeTypeIcon( $mimetype );
245
+    return \OC::$server->getMimeTypeDetector()->mimeTypeIcon( $mimetype );
246 246
 }
247 247
 
248 248
 /**
@@ -252,7 +252,7 @@  discard block
 block discarded – undo
252 252
  * @return string link to the preview
253 253
  */
254 254
 function preview_icon( $path ) {
255
-	return \OC::$server->getURLGenerator()->linkToRoute('core.Preview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path]);
255
+    return \OC::$server->getURLGenerator()->linkToRoute('core.Preview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path]);
256 256
 }
257 257
 
258 258
 /**
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
  * @return string
262 262
  */
263 263
 function publicPreview_icon ( $path, $token ) {
264
-	return \OC::$server->getURLGenerator()->linkToRoute('files_sharing.PublicPreview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path, 't' => $token]);
264
+    return \OC::$server->getURLGenerator()->linkToRoute('files_sharing.PublicPreview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path, 't' => $token]);
265 265
 }
266 266
 
267 267
 /**
@@ -272,7 +272,7 @@  discard block
 block discarded – undo
272 272
  * For further information have a look at OC_Helper::humanFileSize
273 273
  */
274 274
 function human_file_size( $bytes ) {
275
-	return OC_Helper::humanFileSize( $bytes );
275
+    return OC_Helper::humanFileSize( $bytes );
276 276
 }
277 277
 
278 278
 /**
@@ -281,9 +281,9 @@  discard block
 block discarded – undo
281 281
  * @return int timestamp without time value
282 282
  */
283 283
 function strip_time($timestamp){
284
-	$date = new \DateTime("@{$timestamp}");
285
-	$date->setTime(0, 0, 0);
286
-	return intval($date->format('U'));
284
+    $date = new \DateTime("@{$timestamp}");
285
+    $date->setTime(0, 0, 0);
286
+    return intval($date->format('U'));
287 287
 }
288 288
 
289 289
 /**
@@ -295,39 +295,39 @@  discard block
 block discarded – undo
295 295
  * @return string timestamp
296 296
  */
297 297
 function relative_modified_date($timestamp, $fromTime = null, $dateOnly = false) {
298
-	/** @var \OC\DateTimeFormatter $formatter */
299
-	$formatter = \OC::$server->query('DateTimeFormatter');
298
+    /** @var \OC\DateTimeFormatter $formatter */
299
+    $formatter = \OC::$server->query('DateTimeFormatter');
300 300
 
301
-	if ($dateOnly){
302
-		return $formatter->formatDateSpan($timestamp, $fromTime);
303
-	}
304
-	return $formatter->formatTimeSpan($timestamp, $fromTime);
301
+    if ($dateOnly){
302
+        return $formatter->formatDateSpan($timestamp, $fromTime);
303
+    }
304
+    return $formatter->formatTimeSpan($timestamp, $fromTime);
305 305
 }
306 306
 
307 307
 function html_select_options($options, $selected, $params=array()) {
308
-	if (!is_array($selected)) {
309
-		$selected=array($selected);
310
-	}
311
-	if (isset($params['combine']) && $params['combine']) {
312
-		$options = array_combine($options, $options);
313
-	}
314
-	$value_name = $label_name = false;
315
-	if (isset($params['value'])) {
316
-		$value_name = $params['value'];
317
-	}
318
-	if (isset($params['label'])) {
319
-		$label_name = $params['label'];
320
-	}
321
-	$html = '';
322
-	foreach($options as $value => $label) {
323
-		if ($value_name && is_array($label)) {
324
-			$value = $label[$value_name];
325
-		}
326
-		if ($label_name && is_array($label)) {
327
-			$label = $label[$label_name];
328
-		}
329
-		$select = in_array($value, $selected) ? ' selected="selected"' : '';
330
-		$html .= '<option value="' . \OCP\Util::sanitizeHTML($value) . '"' . $select . '>' . \OCP\Util::sanitizeHTML($label) . '</option>'."\n";
331
-	}
332
-	return $html;
308
+    if (!is_array($selected)) {
309
+        $selected=array($selected);
310
+    }
311
+    if (isset($params['combine']) && $params['combine']) {
312
+        $options = array_combine($options, $options);
313
+    }
314
+    $value_name = $label_name = false;
315
+    if (isset($params['value'])) {
316
+        $value_name = $params['value'];
317
+    }
318
+    if (isset($params['label'])) {
319
+        $label_name = $params['label'];
320
+    }
321
+    $html = '';
322
+    foreach($options as $value => $label) {
323
+        if ($value_name && is_array($label)) {
324
+            $value = $label[$value_name];
325
+        }
326
+        if ($label_name && is_array($label)) {
327
+            $label = $label[$label_name];
328
+        }
329
+        $select = in_array($value, $selected) ? ' selected="selected"' : '';
330
+        $html .= '<option value="' . \OCP\Util::sanitizeHTML($value) . '"' . $select . '>' . \OCP\Util::sanitizeHTML($label) . '</option>'."\n";
331
+    }
332
+    return $html;
333 333
 }
Please login to merge, or discard this patch.
Spacing   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -45,12 +45,12 @@  discard block
 block discarded – undo
45 45
  * @param string $opts, additional optional options
46 46
 */
47 47
 function emit_css_tag($href, $opts = '') {
48
-	$s='<link rel="stylesheet"';
48
+	$s = '<link rel="stylesheet"';
49 49
 	if (!empty($href)) {
50
-		$s.=' href="' . $href .'"';
50
+		$s .= ' href="'.$href.'"';
51 51
 	}
52 52
 	if (!empty($opts)) {
53
-		$s.=' '.$opts;
53
+		$s .= ' '.$opts;
54 54
 	}
55 55
 	print_unescaped($s.">\n");
56 56
 }
@@ -60,10 +60,10 @@  discard block
 block discarded – undo
60 60
  * @param array $obj all the script information from template
61 61
 */
62 62
 function emit_css_loading_tags($obj) {
63
-	foreach($obj['cssfiles'] as $css) {
63
+	foreach ($obj['cssfiles'] as $css) {
64 64
 		emit_css_tag($css);
65 65
 	}
66
-	foreach($obj['printcssfiles'] as $css) {
66
+	foreach ($obj['printcssfiles'] as $css) {
67 67
 		emit_css_tag($css, 'media="print"');
68 68
 	}
69 69
 }
@@ -73,20 +73,20 @@  discard block
 block discarded – undo
73 73
  * @param string $src the source URL, ignored when empty
74 74
  * @param string $script_content the inline script content, ignored when empty
75 75
 */
76
-function emit_script_tag($src, $script_content='') {
77
-	$defer_str=' defer';
78
-	$s='<script nonce="' . \OC::$server->getContentSecurityPolicyNonceManager()->getNonce() . '"';
76
+function emit_script_tag($src, $script_content = '') {
77
+	$defer_str = ' defer';
78
+	$s = '<script nonce="'.\OC::$server->getContentSecurityPolicyNonceManager()->getNonce().'"';
79 79
 	if (!empty($src)) {
80 80
 		 // emit script tag for deferred loading from $src
81
-		$s.=$defer_str.' src="' . $src .'">';
81
+		$s .= $defer_str.' src="'.$src.'">';
82 82
 	} else if (!empty($script_content)) {
83 83
 		// emit script tag for inline script from $script_content without defer (see MDN)
84
-		$s.=">\n".$script_content."\n";
84
+		$s .= ">\n".$script_content."\n";
85 85
 	} else {
86 86
 		// no $src nor $src_content, really useless empty tag
87
-		$s.='>';
87
+		$s .= '>';
88 88
 	}
89
-	$s.='</script>';
89
+	$s .= '</script>';
90 90
 	print_unescaped($s."\n");
91 91
 }
92 92
 
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
  * @param array $obj all the script information from template
96 96
 */
97 97
 function emit_script_loading_tags($obj) {
98
-	foreach($obj['jsfiles'] as $jsfile) {
98
+	foreach ($obj['jsfiles'] as $jsfile) {
99 99
 		emit_script_tag($jsfile, '');
100 100
 	}
101 101
 	if (!empty($obj['inline_ocjs'])) {
@@ -119,8 +119,8 @@  discard block
 block discarded – undo
119 119
  * if an array is given it will add all scripts
120 120
  */
121 121
 function script($app, $file = null) {
122
-	if(is_array($file)) {
123
-		foreach($file as $f) {
122
+	if (is_array($file)) {
123
+		foreach ($file as $f) {
124 124
 			OC_Util::addScript($app, $f);
125 125
 		}
126 126
 	} else {
@@ -135,8 +135,8 @@  discard block
 block discarded – undo
135 135
  * if an array is given it will add all scripts
136 136
  */
137 137
 function vendor_script($app, $file = null) {
138
-	if(is_array($file)) {
139
-		foreach($file as $f) {
138
+	if (is_array($file)) {
139
+		foreach ($file as $f) {
140 140
 			OC_Util::addVendorScript($app, $f);
141 141
 		}
142 142
 	} else {
@@ -151,8 +151,8 @@  discard block
 block discarded – undo
151 151
  * if an array is given it will add all styles
152 152
  */
153 153
 function style($app, $file = null) {
154
-	if(is_array($file)) {
155
-		foreach($file as $f) {
154
+	if (is_array($file)) {
155
+		foreach ($file as $f) {
156 156
 			OC_Util::addStyle($app, $f);
157 157
 		}
158 158
 	} else {
@@ -167,8 +167,8 @@  discard block
 block discarded – undo
167 167
  * if an array is given it will add all styles
168 168
  */
169 169
 function vendor_style($app, $file = null) {
170
-	if(is_array($file)) {
171
-		foreach($file as $f) {
170
+	if (is_array($file)) {
171
+		foreach ($file as $f) {
172 172
 			OC_Util::addVendorStyle($app, $f);
173 173
 		}
174 174
 	} else {
@@ -192,13 +192,13 @@  discard block
 block discarded – undo
192 192
  * if an array is given it will add all components
193 193
  */
194 194
 function component($app, $file) {
195
-	if(is_array($file)) {
196
-		foreach($file as $f) {
197
-			$url = link_to($app, 'component/' . $f . '.html');
195
+	if (is_array($file)) {
196
+		foreach ($file as $f) {
197
+			$url = link_to($app, 'component/'.$f.'.html');
198 198
 			OC_Util::addHeader('link', array('rel' => 'import', 'href' => $url));
199 199
 		}
200 200
 	} else {
201
-		$url = link_to($app, 'component/' . $file . '.html');
201
+		$url = link_to($app, 'component/'.$file.'.html');
202 202
 		OC_Util::addHeader('link', array('rel' => 'import', 'href' => $url));
203 203
 	}
204 204
 }
@@ -212,7 +212,7 @@  discard block
 block discarded – undo
212 212
  *
213 213
  * For further information have a look at \OCP\IURLGenerator::linkTo
214 214
  */
215
-function link_to( $app, $file, $args = array() ) {
215
+function link_to($app, $file, $args = array()) {
216 216
 	return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
217 217
 }
218 218
 
@@ -232,8 +232,8 @@  discard block
 block discarded – undo
232 232
  *
233 233
  * For further information have a look at \OCP\IURLGenerator::imagePath
234 234
  */
235
-function image_path( $app, $image ) {
236
-	return \OC::$server->getURLGenerator()->imagePath( $app, $image );
235
+function image_path($app, $image) {
236
+	return \OC::$server->getURLGenerator()->imagePath($app, $image);
237 237
 }
238 238
 
239 239
 /**
@@ -241,8 +241,8 @@  discard block
 block discarded – undo
241 241
  * @param string $mimetype mimetype
242 242
  * @return string link to the image
243 243
  */
244
-function mimetype_icon( $mimetype ) {
245
-	return \OC::$server->getMimeTypeDetector()->mimeTypeIcon( $mimetype );
244
+function mimetype_icon($mimetype) {
245
+	return \OC::$server->getMimeTypeDetector()->mimeTypeIcon($mimetype);
246 246
 }
247 247
 
248 248
 /**
@@ -251,7 +251,7 @@  discard block
 block discarded – undo
251 251
  * @param string $path path of file
252 252
  * @return string link to the preview
253 253
  */
254
-function preview_icon( $path ) {
254
+function preview_icon($path) {
255 255
 	return \OC::$server->getURLGenerator()->linkToRoute('core.Preview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path]);
256 256
 }
257 257
 
@@ -260,7 +260,7 @@  discard block
 block discarded – undo
260 260
  * @param string $token
261 261
  * @return string
262 262
  */
263
-function publicPreview_icon ( $path, $token ) {
263
+function publicPreview_icon($path, $token) {
264 264
 	return \OC::$server->getURLGenerator()->linkToRoute('files_sharing.PublicPreview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path, 't' => $token]);
265 265
 }
266 266
 
@@ -271,8 +271,8 @@  discard block
 block discarded – undo
271 271
  *
272 272
  * For further information have a look at OC_Helper::humanFileSize
273 273
  */
274
-function human_file_size( $bytes ) {
275
-	return OC_Helper::humanFileSize( $bytes );
274
+function human_file_size($bytes) {
275
+	return OC_Helper::humanFileSize($bytes);
276 276
 }
277 277
 
278 278
 /**
@@ -280,7 +280,7 @@  discard block
 block discarded – undo
280 280
  * @param int $timestamp UNIX timestamp to strip
281 281
  * @return int timestamp without time value
282 282
  */
283
-function strip_time($timestamp){
283
+function strip_time($timestamp) {
284 284
 	$date = new \DateTime("@{$timestamp}");
285 285
 	$date->setTime(0, 0, 0);
286 286
 	return intval($date->format('U'));
@@ -298,15 +298,15 @@  discard block
 block discarded – undo
298 298
 	/** @var \OC\DateTimeFormatter $formatter */
299 299
 	$formatter = \OC::$server->query('DateTimeFormatter');
300 300
 
301
-	if ($dateOnly){
301
+	if ($dateOnly) {
302 302
 		return $formatter->formatDateSpan($timestamp, $fromTime);
303 303
 	}
304 304
 	return $formatter->formatTimeSpan($timestamp, $fromTime);
305 305
 }
306 306
 
307
-function html_select_options($options, $selected, $params=array()) {
307
+function html_select_options($options, $selected, $params = array()) {
308 308
 	if (!is_array($selected)) {
309
-		$selected=array($selected);
309
+		$selected = array($selected);
310 310
 	}
311 311
 	if (isset($params['combine']) && $params['combine']) {
312 312
 		$options = array_combine($options, $options);
@@ -319,7 +319,7 @@  discard block
 block discarded – undo
319 319
 		$label_name = $params['label'];
320 320
 	}
321 321
 	$html = '';
322
-	foreach($options as $value => $label) {
322
+	foreach ($options as $value => $label) {
323 323
 		if ($value_name && is_array($label)) {
324 324
 			$value = $label[$value_name];
325 325
 		}
@@ -327,7 +327,7 @@  discard block
 block discarded – undo
327 327
 			$label = $label[$label_name];
328 328
 		}
329 329
 		$select = in_array($value, $selected) ? ' selected="selected"' : '';
330
-		$html .= '<option value="' . \OCP\Util::sanitizeHTML($value) . '"' . $select . '>' . \OCP\Util::sanitizeHTML($label) . '</option>'."\n";
330
+		$html .= '<option value="'.\OCP\Util::sanitizeHTML($value).'"'.$select.'>'.\OCP\Util::sanitizeHTML($label).'</option>'."\n";
331 331
 	}
332 332
 	return $html;
333 333
 }
Please login to merge, or discard this patch.
lib/private/Tags.php 1 patch
Indentation   +757 added lines, -757 removed lines patch added patch discarded remove patch
@@ -48,761 +48,761 @@
 block discarded – undo
48 48
 
49 49
 class Tags implements \OCP\ITags {
50 50
 
51
-	/**
52
-	 * Tags
53
-	 *
54
-	 * @var array
55
-	 */
56
-	private $tags = array();
57
-
58
-	/**
59
-	 * Used for storing objectid/categoryname pairs while rescanning.
60
-	 *
61
-	 * @var array
62
-	 */
63
-	private static $relations = array();
64
-
65
-	/**
66
-	 * Type
67
-	 *
68
-	 * @var string
69
-	 */
70
-	private $type;
71
-
72
-	/**
73
-	 * User
74
-	 *
75
-	 * @var string
76
-	 */
77
-	private $user;
78
-
79
-	/**
80
-	 * Are we including tags for shared items?
81
-	 *
82
-	 * @var bool
83
-	 */
84
-	private $includeShared = false;
85
-
86
-	/**
87
-	 * The current user, plus any owners of the items shared with the current
88
-	 * user, if $this->includeShared === true.
89
-	 *
90
-	 * @var array
91
-	 */
92
-	private $owners = array();
93
-
94
-	/**
95
-	 * The Mapper we're using to communicate our Tag objects to the database.
96
-	 *
97
-	 * @var TagMapper
98
-	 */
99
-	private $mapper;
100
-
101
-	/**
102
-	 * The sharing backend for objects of $this->type. Required if
103
-	 * $this->includeShared === true to determine ownership of items.
104
-	 *
105
-	 * @var \OCP\Share_Backend
106
-	 */
107
-	private $backend;
108
-
109
-	const TAG_TABLE = '*PREFIX*vcategory';
110
-	const RELATION_TABLE = '*PREFIX*vcategory_to_object';
111
-
112
-	const TAG_FAVORITE = '_$!<Favorite>!$_';
113
-
114
-	/**
115
-	* Constructor.
116
-	*
117
-	* @param TagMapper $mapper Instance of the TagMapper abstraction layer.
118
-	* @param string $user The user whose data the object will operate on.
119
-	* @param string $type The type of items for which tags will be loaded.
120
-	* @param array $defaultTags Tags that should be created at construction.
121
-	* @param boolean $includeShared Whether to include tags for items shared with this user by others.
122
-	*/
123
-	public function __construct(TagMapper $mapper, $user, $type, $defaultTags = array(), $includeShared = false) {
124
-		$this->mapper = $mapper;
125
-		$this->user = $user;
126
-		$this->type = $type;
127
-		$this->includeShared = $includeShared;
128
-		$this->owners = array($this->user);
129
-		if ($this->includeShared) {
130
-			$this->owners = array_merge($this->owners, \OC\Share\Share::getSharedItemsOwners($this->user, $this->type, true));
131
-			$this->backend = \OC\Share\Share::getBackend($this->type);
132
-		}
133
-		$this->tags = $this->mapper->loadTags($this->owners, $this->type);
134
-
135
-		if(count($defaultTags) > 0 && count($this->tags) === 0) {
136
-			$this->addMultiple($defaultTags, true);
137
-		}
138
-	}
139
-
140
-	/**
141
-	* Check if any tags are saved for this type and user.
142
-	*
143
-	* @return boolean
144
-	*/
145
-	public function isEmpty() {
146
-		return count($this->tags) === 0;
147
-	}
148
-
149
-	/**
150
-	* Returns an array mapping a given tag's properties to its values:
151
-	* ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
152
-	*
153
-	* @param string $id The ID of the tag that is going to be mapped
154
-	* @return array|false
155
-	*/
156
-	public function getTag($id) {
157
-		$key = $this->getTagById($id);
158
-		if ($key !== false) {
159
-			return $this->tagMap($this->tags[$key]);
160
-		}
161
-		return false;
162
-	}
163
-
164
-	/**
165
-	* Get the tags for a specific user.
166
-	*
167
-	* This returns an array with maps containing each tag's properties:
168
-	* [
169
-	* 	['id' => 0, 'name' = 'First tag', 'owner' = 'User', 'type' => 'tagtype'],
170
-	* 	['id' => 1, 'name' = 'Shared tag', 'owner' = 'Other user', 'type' => 'tagtype'],
171
-	* ]
172
-	*
173
-	* @return array
174
-	*/
175
-	public function getTags() {
176
-		if(!count($this->tags)) {
177
-			return array();
178
-		}
179
-
180
-		usort($this->tags, function($a, $b) {
181
-			return strnatcasecmp($a->getName(), $b->getName());
182
-		});
183
-		$tagMap = array();
184
-
185
-		foreach($this->tags as $tag) {
186
-			if($tag->getName() !== self::TAG_FAVORITE) {
187
-				$tagMap[] = $this->tagMap($tag);
188
-			}
189
-		}
190
-		return $tagMap;
191
-
192
-	}
193
-
194
-	/**
195
-	* Return only the tags owned by the given user, omitting any tags shared
196
-	* by other users.
197
-	*
198
-	* @param string $user The user whose tags are to be checked.
199
-	* @return array An array of Tag objects.
200
-	*/
201
-	public function getTagsForUser($user) {
202
-		return array_filter($this->tags,
203
-			function($tag) use($user) {
204
-				return $tag->getOwner() === $user;
205
-			}
206
-		);
207
-	}
208
-
209
-	/**
210
-	 * Get the list of tags for the given ids.
211
-	 *
212
-	 * @param array $objIds array of object ids
213
-	 * @return array|boolean of tags id as key to array of tag names
214
-	 * or false if an error occurred
215
-	 */
216
-	public function getTagsForObjects(array $objIds) {
217
-		$entries = array();
218
-
219
-		try {
220
-			$conn = \OC::$server->getDatabaseConnection();
221
-			$chunks = array_chunk($objIds, 900, false);
222
-			foreach ($chunks as $chunk) {
223
-				$result = $conn->executeQuery(
224
-					'SELECT `category`, `categoryid`, `objid` ' .
225
-					'FROM `' . self::RELATION_TABLE . '` r, `' . self::TAG_TABLE . '` ' .
226
-					'WHERE `categoryid` = `id` AND `uid` = ? AND r.`type` = ? AND `objid` IN (?)',
227
-					array($this->user, $this->type, $chunk),
228
-					array(null, null, IQueryBuilder::PARAM_INT_ARRAY)
229
-				);
230
-				while ($row = $result->fetch()) {
231
-					$objId = (int)$row['objid'];
232
-					if (!isset($entries[$objId])) {
233
-						$entries[$objId] = array();
234
-					}
235
-					$entries[$objId][] = $row['category'];
236
-				}
237
-				if (\OCP\DB::isError($result)) {
238
-					\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
239
-					return false;
240
-				}
241
-			}
242
-		} catch(\Exception $e) {
243
-			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
244
-				\OCP\Util::ERROR);
245
-			return false;
246
-		}
247
-
248
-		return $entries;
249
-	}
250
-
251
-	/**
252
-	* Get the a list if items tagged with $tag.
253
-	*
254
-	* Throws an exception if the tag could not be found.
255
-	*
256
-	* @param string $tag Tag id or name.
257
-	* @return array|false An array of object ids or false on error.
258
-	* @throws \Exception
259
-	*/
260
-	public function getIdsForTag($tag) {
261
-		$result = null;
262
-		$tagId = false;
263
-		if(is_numeric($tag)) {
264
-			$tagId = $tag;
265
-		} elseif(is_string($tag)) {
266
-			$tag = trim($tag);
267
-			if($tag === '') {
268
-				\OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', \OCP\Util::DEBUG);
269
-				return false;
270
-			}
271
-			$tagId = $this->getTagId($tag);
272
-		}
273
-
274
-		if($tagId === false) {
275
-			$l10n = \OC::$server->getL10N('core');
276
-			throw new \Exception(
277
-				$l10n->t('Could not find category "%s"', [$tag])
278
-			);
279
-		}
280
-
281
-		$ids = array();
282
-		$sql = 'SELECT `objid` FROM `' . self::RELATION_TABLE
283
-			. '` WHERE `categoryid` = ?';
284
-
285
-		try {
286
-			$stmt = \OCP\DB::prepare($sql);
287
-			$result = $stmt->execute(array($tagId));
288
-			if (\OCP\DB::isError($result)) {
289
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
290
-				return false;
291
-			}
292
-		} catch(\Exception $e) {
293
-			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
294
-				\OCP\Util::ERROR);
295
-			return false;
296
-		}
297
-
298
-		if(!is_null($result)) {
299
-			while( $row = $result->fetchRow()) {
300
-				$id = (int)$row['objid'];
301
-
302
-				if ($this->includeShared) {
303
-					// We have to check if we are really allowed to access the
304
-					// items that are tagged with $tag. To that end, we ask the
305
-					// corresponding sharing backend if the item identified by $id
306
-					// is owned by any of $this->owners.
307
-					foreach ($this->owners as $owner) {
308
-						if ($this->backend->isValidSource($id, $owner)) {
309
-							$ids[] = $id;
310
-							break;
311
-						}
312
-					}
313
-				} else {
314
-					$ids[] = $id;
315
-				}
316
-			}
317
-		}
318
-
319
-		return $ids;
320
-	}
321
-
322
-	/**
323
-	* Checks whether a tag is saved for the given user,
324
-	* disregarding the ones shared with him or her.
325
-	*
326
-	* @param string $name The tag name to check for.
327
-	* @param string $user The user whose tags are to be checked.
328
-	* @return bool
329
-	*/
330
-	public function userHasTag($name, $user) {
331
-		$key = $this->array_searchi($name, $this->getTagsForUser($user));
332
-		return ($key !== false) ? $this->tags[$key]->getId() : false;
333
-	}
334
-
335
-	/**
336
-	* Checks whether a tag is saved for or shared with the current user.
337
-	*
338
-	* @param string $name The tag name to check for.
339
-	* @return bool
340
-	*/
341
-	public function hasTag($name) {
342
-		return $this->getTagId($name) !== false;
343
-	}
344
-
345
-	/**
346
-	* Add a new tag.
347
-	*
348
-	* @param string $name A string with a name of the tag
349
-	* @return false|int the id of the added tag or false on error.
350
-	*/
351
-	public function add($name) {
352
-		$name = trim($name);
353
-
354
-		if($name === '') {
355
-			\OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', \OCP\Util::DEBUG);
356
-			return false;
357
-		}
358
-		if($this->userHasTag($name, $this->user)) {
359
-			\OCP\Util::writeLog('core', __METHOD__.', name: ' . $name. ' exists already', \OCP\Util::DEBUG);
360
-			return false;
361
-		}
362
-		try {
363
-			$tag = new Tag($this->user, $this->type, $name);
364
-			$tag = $this->mapper->insert($tag);
365
-			$this->tags[] = $tag;
366
-		} catch(\Exception $e) {
367
-			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
368
-				\OCP\Util::ERROR);
369
-			return false;
370
-		}
371
-		\OCP\Util::writeLog('core', __METHOD__.', id: ' . $tag->getId(), \OCP\Util::DEBUG);
372
-		return $tag->getId();
373
-	}
374
-
375
-	/**
376
-	* Rename tag.
377
-	*
378
-	* @param string|integer $from The name or ID of the existing tag
379
-	* @param string $to The new name of the tag.
380
-	* @return bool
381
-	*/
382
-	public function rename($from, $to) {
383
-		$from = trim($from);
384
-		$to = trim($to);
385
-
386
-		if($to === '' || $from === '') {
387
-			\OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', \OCP\Util::DEBUG);
388
-			return false;
389
-		}
390
-
391
-		if (is_numeric($from)) {
392
-			$key = $this->getTagById($from);
393
-		} else {
394
-			$key = $this->getTagByName($from);
395
-		}
396
-		if($key === false) {
397
-			\OCP\Util::writeLog('core', __METHOD__.', tag: ' . $from. ' does not exist', \OCP\Util::DEBUG);
398
-			return false;
399
-		}
400
-		$tag = $this->tags[$key];
401
-
402
-		if($this->userHasTag($to, $tag->getOwner())) {
403
-			\OCP\Util::writeLog('core', __METHOD__.', A tag named ' . $to. ' already exists for user ' . $tag->getOwner() . '.', \OCP\Util::DEBUG);
404
-			return false;
405
-		}
406
-
407
-		try {
408
-			$tag->setName($to);
409
-			$this->tags[$key] = $this->mapper->update($tag);
410
-		} catch(\Exception $e) {
411
-			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
412
-				\OCP\Util::ERROR);
413
-			return false;
414
-		}
415
-		return true;
416
-	}
417
-
418
-	/**
419
-	* Add a list of new tags.
420
-	*
421
-	* @param string[] $names A string with a name or an array of strings containing
422
-	* the name(s) of the tag(s) to add.
423
-	* @param bool $sync When true, save the tags
424
-	* @param int|null $id int Optional object id to add to this|these tag(s)
425
-	* @return bool Returns false on error.
426
-	*/
427
-	public function addMultiple($names, $sync=false, $id = null) {
428
-		if(!is_array($names)) {
429
-			$names = array($names);
430
-		}
431
-		$names = array_map('trim', $names);
432
-		array_filter($names);
433
-
434
-		$newones = array();
435
-		foreach($names as $name) {
436
-			if(!$this->hasTag($name) && $name !== '') {
437
-				$newones[] = new Tag($this->user, $this->type, $name);
438
-			}
439
-			if(!is_null($id) ) {
440
-				// Insert $objectid, $categoryid  pairs if not exist.
441
-				self::$relations[] = array('objid' => $id, 'tag' => $name);
442
-			}
443
-		}
444
-		$this->tags = array_merge($this->tags, $newones);
445
-		if($sync === true) {
446
-			$this->save();
447
-		}
448
-
449
-		return true;
450
-	}
451
-
452
-	/**
453
-	 * Save the list of tags and their object relations
454
-	 */
455
-	protected function save() {
456
-		if(is_array($this->tags)) {
457
-			foreach($this->tags as $tag) {
458
-				try {
459
-					if (!$this->mapper->tagExists($tag)) {
460
-						$this->mapper->insert($tag);
461
-					}
462
-				} catch(\Exception $e) {
463
-					\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
464
-						\OCP\Util::ERROR);
465
-				}
466
-			}
467
-
468
-			// reload tags to get the proper ids.
469
-			$this->tags = $this->mapper->loadTags($this->owners, $this->type);
470
-			\OCP\Util::writeLog('core', __METHOD__.', tags: ' . print_r($this->tags, true),
471
-				\OCP\Util::DEBUG);
472
-			// Loop through temporarily cached objectid/tagname pairs
473
-			// and save relations.
474
-			$tags = $this->tags;
475
-			// For some reason this is needed or array_search(i) will return 0..?
476
-			ksort($tags);
477
-			foreach(self::$relations as $relation) {
478
-				$tagId = $this->getTagId($relation['tag']);
479
-				\OCP\Util::writeLog('core', __METHOD__ . 'catid, ' . $relation['tag'] . ' ' . $tagId, \OCP\Util::DEBUG);
480
-				if($tagId) {
481
-					try {
482
-						\OCP\DB::insertIfNotExist(self::RELATION_TABLE,
483
-							array(
484
-								'objid' => $relation['objid'],
485
-								'categoryid' => $tagId,
486
-								'type' => $this->type,
487
-								));
488
-					} catch(\Exception $e) {
489
-						\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
490
-							\OCP\Util::ERROR);
491
-					}
492
-				}
493
-			}
494
-			self::$relations = array(); // reset
495
-		} else {
496
-			\OCP\Util::writeLog('core', __METHOD__.', $this->tags is not an array! '
497
-				. print_r($this->tags, true), \OCP\Util::ERROR);
498
-		}
499
-	}
500
-
501
-	/**
502
-	* Delete tags and tag/object relations for a user.
503
-	*
504
-	* For hooking up on post_deleteUser
505
-	*
506
-	* @param array $arguments
507
-	*/
508
-	public static function post_deleteUser($arguments) {
509
-		// Find all objectid/tagId pairs.
510
-		$result = null;
511
-		try {
512
-			$stmt = \OCP\DB::prepare('SELECT `id` FROM `' . self::TAG_TABLE . '` '
513
-				. 'WHERE `uid` = ?');
514
-			$result = $stmt->execute(array($arguments['uid']));
515
-			if (\OCP\DB::isError($result)) {
516
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
517
-			}
518
-		} catch(\Exception $e) {
519
-			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
520
-				\OCP\Util::ERROR);
521
-		}
522
-
523
-		if(!is_null($result)) {
524
-			try {
525
-				$stmt = \OCP\DB::prepare('DELETE FROM `' . self::RELATION_TABLE . '` '
526
-					. 'WHERE `categoryid` = ?');
527
-				while( $row = $result->fetchRow()) {
528
-					try {
529
-						$stmt->execute(array($row['id']));
530
-					} catch(\Exception $e) {
531
-						\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
532
-							\OCP\Util::ERROR);
533
-					}
534
-				}
535
-			} catch(\Exception $e) {
536
-				\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
537
-					\OCP\Util::ERROR);
538
-			}
539
-		}
540
-		try {
541
-			$stmt = \OCP\DB::prepare('DELETE FROM `' . self::TAG_TABLE . '` '
542
-				. 'WHERE `uid` = ?');
543
-			$result = $stmt->execute(array($arguments['uid']));
544
-			if (\OCP\DB::isError($result)) {
545
-				\OCP\Util::writeLog('core', __METHOD__. ', DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
546
-			}
547
-		} catch(\Exception $e) {
548
-			\OCP\Util::writeLog('core', __METHOD__ . ', exception: '
549
-				. $e->getMessage(), \OCP\Util::ERROR);
550
-		}
551
-	}
552
-
553
-	/**
554
-	* Delete tag/object relations from the db
555
-	*
556
-	* @param array $ids The ids of the objects
557
-	* @return boolean Returns false on error.
558
-	*/
559
-	public function purgeObjects(array $ids) {
560
-		if(count($ids) === 0) {
561
-			// job done ;)
562
-			return true;
563
-		}
564
-		$updates = $ids;
565
-		try {
566
-			$query = 'DELETE FROM `' . self::RELATION_TABLE . '` ';
567
-			$query .= 'WHERE `objid` IN (' . str_repeat('?,', count($ids)-1) . '?) ';
568
-			$query .= 'AND `type`= ?';
569
-			$updates[] = $this->type;
570
-			$stmt = \OCP\DB::prepare($query);
571
-			$result = $stmt->execute($updates);
572
-			if (\OCP\DB::isError($result)) {
573
-				\OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
574
-				return false;
575
-			}
576
-		} catch(\Exception $e) {
577
-			\OCP\Util::writeLog('core', __METHOD__.', exception: ' . $e->getMessage(),
578
-				\OCP\Util::ERROR);
579
-			return false;
580
-		}
581
-		return true;
582
-	}
583
-
584
-	/**
585
-	* Get favorites for an object type
586
-	*
587
-	* @return array|false An array of object ids.
588
-	*/
589
-	public function getFavorites() {
590
-		try {
591
-			return $this->getIdsForTag(self::TAG_FAVORITE);
592
-		} catch(\Exception $e) {
593
-			\OCP\Util::writeLog('core', __METHOD__.', exception: ' . $e->getMessage(),
594
-				\OCP\Util::DEBUG);
595
-			return array();
596
-		}
597
-	}
598
-
599
-	/**
600
-	* Add an object to favorites
601
-	*
602
-	* @param int $objid The id of the object
603
-	* @return boolean
604
-	*/
605
-	public function addToFavorites($objid) {
606
-		if(!$this->userHasTag(self::TAG_FAVORITE, $this->user)) {
607
-			$this->add(self::TAG_FAVORITE);
608
-		}
609
-		return $this->tagAs($objid, self::TAG_FAVORITE);
610
-	}
611
-
612
-	/**
613
-	* Remove an object from favorites
614
-	*
615
-	* @param int $objid The id of the object
616
-	* @return boolean
617
-	*/
618
-	public function removeFromFavorites($objid) {
619
-		return $this->unTag($objid, self::TAG_FAVORITE);
620
-	}
621
-
622
-	/**
623
-	* Creates a tag/object relation.
624
-	*
625
-	* @param int $objid The id of the object
626
-	* @param string $tag The id or name of the tag
627
-	* @return boolean Returns false on error.
628
-	*/
629
-	public function tagAs($objid, $tag) {
630
-		if(is_string($tag) && !is_numeric($tag)) {
631
-			$tag = trim($tag);
632
-			if($tag === '') {
633
-				\OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', \OCP\Util::DEBUG);
634
-				return false;
635
-			}
636
-			if(!$this->hasTag($tag)) {
637
-				$this->add($tag);
638
-			}
639
-			$tagId =  $this->getTagId($tag);
640
-		} else {
641
-			$tagId = $tag;
642
-		}
643
-		try {
644
-			\OCP\DB::insertIfNotExist(self::RELATION_TABLE,
645
-				array(
646
-					'objid' => $objid,
647
-					'categoryid' => $tagId,
648
-					'type' => $this->type,
649
-				));
650
-		} catch(\Exception $e) {
651
-			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
652
-				\OCP\Util::ERROR);
653
-			return false;
654
-		}
655
-		return true;
656
-	}
657
-
658
-	/**
659
-	* Delete single tag/object relation from the db
660
-	*
661
-	* @param int $objid The id of the object
662
-	* @param string $tag The id or name of the tag
663
-	* @return boolean
664
-	*/
665
-	public function unTag($objid, $tag) {
666
-		if(is_string($tag) && !is_numeric($tag)) {
667
-			$tag = trim($tag);
668
-			if($tag === '') {
669
-				\OCP\Util::writeLog('core', __METHOD__.', Tag name is empty', \OCP\Util::DEBUG);
670
-				return false;
671
-			}
672
-			$tagId =  $this->getTagId($tag);
673
-		} else {
674
-			$tagId = $tag;
675
-		}
676
-
677
-		try {
678
-			$sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
679
-					. 'WHERE `objid` = ? AND `categoryid` = ? AND `type` = ?';
680
-			$stmt = \OCP\DB::prepare($sql);
681
-			$stmt->execute(array($objid, $tagId, $this->type));
682
-		} catch(\Exception $e) {
683
-			\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
684
-				\OCP\Util::ERROR);
685
-			return false;
686
-		}
687
-		return true;
688
-	}
689
-
690
-	/**
691
-	* Delete tags from the database.
692
-	*
693
-	* @param string[]|integer[] $names An array of tags (names or IDs) to delete
694
-	* @return bool Returns false on error
695
-	*/
696
-	public function delete($names) {
697
-		if(!is_array($names)) {
698
-			$names = array($names);
699
-		}
700
-
701
-		$names = array_map('trim', $names);
702
-		array_filter($names);
703
-
704
-		\OCP\Util::writeLog('core', __METHOD__ . ', before: '
705
-			. print_r($this->tags, true), \OCP\Util::DEBUG);
706
-		foreach($names as $name) {
707
-			$id = null;
708
-
709
-			if (is_numeric($name)) {
710
-				$key = $this->getTagById($name);
711
-			} else {
712
-				$key = $this->getTagByName($name);
713
-			}
714
-			if ($key !== false) {
715
-				$tag = $this->tags[$key];
716
-				$id = $tag->getId();
717
-				unset($this->tags[$key]);
718
-				$this->mapper->delete($tag);
719
-			} else {
720
-				\OCP\Util::writeLog('core', __METHOD__ . 'Cannot delete tag ' . $name
721
-					. ': not found.', \OCP\Util::ERROR);
722
-			}
723
-			if(!is_null($id) && $id !== false) {
724
-				try {
725
-					$sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
726
-							. 'WHERE `categoryid` = ?';
727
-					$stmt = \OCP\DB::prepare($sql);
728
-					$result = $stmt->execute(array($id));
729
-					if (\OCP\DB::isError($result)) {
730
-						\OCP\Util::writeLog('core',
731
-							__METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(),
732
-							\OCP\Util::ERROR);
733
-						return false;
734
-					}
735
-				} catch(\Exception $e) {
736
-					\OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
737
-						\OCP\Util::ERROR);
738
-					return false;
739
-				}
740
-			}
741
-		}
742
-		return true;
743
-	}
744
-
745
-	// case-insensitive array_search
746
-	protected function array_searchi($needle, $haystack, $mem='getName') {
747
-		if(!is_array($haystack)) {
748
-			return false;
749
-		}
750
-		return array_search(strtolower($needle), array_map(
751
-			function($tag) use($mem) {
752
-				return strtolower(call_user_func(array($tag, $mem)));
753
-			}, $haystack)
754
-		);
755
-	}
756
-
757
-	/**
758
-	* Get a tag's ID.
759
-	*
760
-	* @param string $name The tag name to look for.
761
-	* @return string|bool The tag's id or false if no matching tag is found.
762
-	*/
763
-	private function getTagId($name) {
764
-		$key = $this->array_searchi($name, $this->tags);
765
-		if ($key !== false) {
766
-			return $this->tags[$key]->getId();
767
-		}
768
-		return false;
769
-	}
770
-
771
-	/**
772
-	* Get a tag by its name.
773
-	*
774
-	* @param string $name The tag name.
775
-	* @return integer|bool The tag object's offset within the $this->tags
776
-	*                      array or false if it doesn't exist.
777
-	*/
778
-	private function getTagByName($name) {
779
-		return $this->array_searchi($name, $this->tags, 'getName');
780
-	}
781
-
782
-	/**
783
-	* Get a tag by its ID.
784
-	*
785
-	* @param string $id The tag ID to look for.
786
-	* @return integer|bool The tag object's offset within the $this->tags
787
-	*                      array or false if it doesn't exist.
788
-	*/
789
-	private function getTagById($id) {
790
-		return $this->array_searchi($id, $this->tags, 'getId');
791
-	}
792
-
793
-	/**
794
-	* Returns an array mapping a given tag's properties to its values:
795
-	* ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
796
-	*
797
-	* @param Tag $tag The tag that is going to be mapped
798
-	* @return array
799
-	*/
800
-	private function tagMap(Tag $tag) {
801
-		return array(
802
-			'id'    => $tag->getId(),
803
-			'name'  => $tag->getName(),
804
-			'owner' => $tag->getOwner(),
805
-			'type'  => $tag->getType()
806
-		);
807
-	}
51
+    /**
52
+     * Tags
53
+     *
54
+     * @var array
55
+     */
56
+    private $tags = array();
57
+
58
+    /**
59
+     * Used for storing objectid/categoryname pairs while rescanning.
60
+     *
61
+     * @var array
62
+     */
63
+    private static $relations = array();
64
+
65
+    /**
66
+     * Type
67
+     *
68
+     * @var string
69
+     */
70
+    private $type;
71
+
72
+    /**
73
+     * User
74
+     *
75
+     * @var string
76
+     */
77
+    private $user;
78
+
79
+    /**
80
+     * Are we including tags for shared items?
81
+     *
82
+     * @var bool
83
+     */
84
+    private $includeShared = false;
85
+
86
+    /**
87
+     * The current user, plus any owners of the items shared with the current
88
+     * user, if $this->includeShared === true.
89
+     *
90
+     * @var array
91
+     */
92
+    private $owners = array();
93
+
94
+    /**
95
+     * The Mapper we're using to communicate our Tag objects to the database.
96
+     *
97
+     * @var TagMapper
98
+     */
99
+    private $mapper;
100
+
101
+    /**
102
+     * The sharing backend for objects of $this->type. Required if
103
+     * $this->includeShared === true to determine ownership of items.
104
+     *
105
+     * @var \OCP\Share_Backend
106
+     */
107
+    private $backend;
108
+
109
+    const TAG_TABLE = '*PREFIX*vcategory';
110
+    const RELATION_TABLE = '*PREFIX*vcategory_to_object';
111
+
112
+    const TAG_FAVORITE = '_$!<Favorite>!$_';
113
+
114
+    /**
115
+     * Constructor.
116
+     *
117
+     * @param TagMapper $mapper Instance of the TagMapper abstraction layer.
118
+     * @param string $user The user whose data the object will operate on.
119
+     * @param string $type The type of items for which tags will be loaded.
120
+     * @param array $defaultTags Tags that should be created at construction.
121
+     * @param boolean $includeShared Whether to include tags for items shared with this user by others.
122
+     */
123
+    public function __construct(TagMapper $mapper, $user, $type, $defaultTags = array(), $includeShared = false) {
124
+        $this->mapper = $mapper;
125
+        $this->user = $user;
126
+        $this->type = $type;
127
+        $this->includeShared = $includeShared;
128
+        $this->owners = array($this->user);
129
+        if ($this->includeShared) {
130
+            $this->owners = array_merge($this->owners, \OC\Share\Share::getSharedItemsOwners($this->user, $this->type, true));
131
+            $this->backend = \OC\Share\Share::getBackend($this->type);
132
+        }
133
+        $this->tags = $this->mapper->loadTags($this->owners, $this->type);
134
+
135
+        if(count($defaultTags) > 0 && count($this->tags) === 0) {
136
+            $this->addMultiple($defaultTags, true);
137
+        }
138
+    }
139
+
140
+    /**
141
+     * Check if any tags are saved for this type and user.
142
+     *
143
+     * @return boolean
144
+     */
145
+    public function isEmpty() {
146
+        return count($this->tags) === 0;
147
+    }
148
+
149
+    /**
150
+     * Returns an array mapping a given tag's properties to its values:
151
+     * ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
152
+     *
153
+     * @param string $id The ID of the tag that is going to be mapped
154
+     * @return array|false
155
+     */
156
+    public function getTag($id) {
157
+        $key = $this->getTagById($id);
158
+        if ($key !== false) {
159
+            return $this->tagMap($this->tags[$key]);
160
+        }
161
+        return false;
162
+    }
163
+
164
+    /**
165
+     * Get the tags for a specific user.
166
+     *
167
+     * This returns an array with maps containing each tag's properties:
168
+     * [
169
+     * 	['id' => 0, 'name' = 'First tag', 'owner' = 'User', 'type' => 'tagtype'],
170
+     * 	['id' => 1, 'name' = 'Shared tag', 'owner' = 'Other user', 'type' => 'tagtype'],
171
+     * ]
172
+     *
173
+     * @return array
174
+     */
175
+    public function getTags() {
176
+        if(!count($this->tags)) {
177
+            return array();
178
+        }
179
+
180
+        usort($this->tags, function($a, $b) {
181
+            return strnatcasecmp($a->getName(), $b->getName());
182
+        });
183
+        $tagMap = array();
184
+
185
+        foreach($this->tags as $tag) {
186
+            if($tag->getName() !== self::TAG_FAVORITE) {
187
+                $tagMap[] = $this->tagMap($tag);
188
+            }
189
+        }
190
+        return $tagMap;
191
+
192
+    }
193
+
194
+    /**
195
+     * Return only the tags owned by the given user, omitting any tags shared
196
+     * by other users.
197
+     *
198
+     * @param string $user The user whose tags are to be checked.
199
+     * @return array An array of Tag objects.
200
+     */
201
+    public function getTagsForUser($user) {
202
+        return array_filter($this->tags,
203
+            function($tag) use($user) {
204
+                return $tag->getOwner() === $user;
205
+            }
206
+        );
207
+    }
208
+
209
+    /**
210
+     * Get the list of tags for the given ids.
211
+     *
212
+     * @param array $objIds array of object ids
213
+     * @return array|boolean of tags id as key to array of tag names
214
+     * or false if an error occurred
215
+     */
216
+    public function getTagsForObjects(array $objIds) {
217
+        $entries = array();
218
+
219
+        try {
220
+            $conn = \OC::$server->getDatabaseConnection();
221
+            $chunks = array_chunk($objIds, 900, false);
222
+            foreach ($chunks as $chunk) {
223
+                $result = $conn->executeQuery(
224
+                    'SELECT `category`, `categoryid`, `objid` ' .
225
+                    'FROM `' . self::RELATION_TABLE . '` r, `' . self::TAG_TABLE . '` ' .
226
+                    'WHERE `categoryid` = `id` AND `uid` = ? AND r.`type` = ? AND `objid` IN (?)',
227
+                    array($this->user, $this->type, $chunk),
228
+                    array(null, null, IQueryBuilder::PARAM_INT_ARRAY)
229
+                );
230
+                while ($row = $result->fetch()) {
231
+                    $objId = (int)$row['objid'];
232
+                    if (!isset($entries[$objId])) {
233
+                        $entries[$objId] = array();
234
+                    }
235
+                    $entries[$objId][] = $row['category'];
236
+                }
237
+                if (\OCP\DB::isError($result)) {
238
+                    \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
239
+                    return false;
240
+                }
241
+            }
242
+        } catch(\Exception $e) {
243
+            \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
244
+                \OCP\Util::ERROR);
245
+            return false;
246
+        }
247
+
248
+        return $entries;
249
+    }
250
+
251
+    /**
252
+     * Get the a list if items tagged with $tag.
253
+     *
254
+     * Throws an exception if the tag could not be found.
255
+     *
256
+     * @param string $tag Tag id or name.
257
+     * @return array|false An array of object ids or false on error.
258
+     * @throws \Exception
259
+     */
260
+    public function getIdsForTag($tag) {
261
+        $result = null;
262
+        $tagId = false;
263
+        if(is_numeric($tag)) {
264
+            $tagId = $tag;
265
+        } elseif(is_string($tag)) {
266
+            $tag = trim($tag);
267
+            if($tag === '') {
268
+                \OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', \OCP\Util::DEBUG);
269
+                return false;
270
+            }
271
+            $tagId = $this->getTagId($tag);
272
+        }
273
+
274
+        if($tagId === false) {
275
+            $l10n = \OC::$server->getL10N('core');
276
+            throw new \Exception(
277
+                $l10n->t('Could not find category "%s"', [$tag])
278
+            );
279
+        }
280
+
281
+        $ids = array();
282
+        $sql = 'SELECT `objid` FROM `' . self::RELATION_TABLE
283
+            . '` WHERE `categoryid` = ?';
284
+
285
+        try {
286
+            $stmt = \OCP\DB::prepare($sql);
287
+            $result = $stmt->execute(array($tagId));
288
+            if (\OCP\DB::isError($result)) {
289
+                \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
290
+                return false;
291
+            }
292
+        } catch(\Exception $e) {
293
+            \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
294
+                \OCP\Util::ERROR);
295
+            return false;
296
+        }
297
+
298
+        if(!is_null($result)) {
299
+            while( $row = $result->fetchRow()) {
300
+                $id = (int)$row['objid'];
301
+
302
+                if ($this->includeShared) {
303
+                    // We have to check if we are really allowed to access the
304
+                    // items that are tagged with $tag. To that end, we ask the
305
+                    // corresponding sharing backend if the item identified by $id
306
+                    // is owned by any of $this->owners.
307
+                    foreach ($this->owners as $owner) {
308
+                        if ($this->backend->isValidSource($id, $owner)) {
309
+                            $ids[] = $id;
310
+                            break;
311
+                        }
312
+                    }
313
+                } else {
314
+                    $ids[] = $id;
315
+                }
316
+            }
317
+        }
318
+
319
+        return $ids;
320
+    }
321
+
322
+    /**
323
+     * Checks whether a tag is saved for the given user,
324
+     * disregarding the ones shared with him or her.
325
+     *
326
+     * @param string $name The tag name to check for.
327
+     * @param string $user The user whose tags are to be checked.
328
+     * @return bool
329
+     */
330
+    public function userHasTag($name, $user) {
331
+        $key = $this->array_searchi($name, $this->getTagsForUser($user));
332
+        return ($key !== false) ? $this->tags[$key]->getId() : false;
333
+    }
334
+
335
+    /**
336
+     * Checks whether a tag is saved for or shared with the current user.
337
+     *
338
+     * @param string $name The tag name to check for.
339
+     * @return bool
340
+     */
341
+    public function hasTag($name) {
342
+        return $this->getTagId($name) !== false;
343
+    }
344
+
345
+    /**
346
+     * Add a new tag.
347
+     *
348
+     * @param string $name A string with a name of the tag
349
+     * @return false|int the id of the added tag or false on error.
350
+     */
351
+    public function add($name) {
352
+        $name = trim($name);
353
+
354
+        if($name === '') {
355
+            \OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', \OCP\Util::DEBUG);
356
+            return false;
357
+        }
358
+        if($this->userHasTag($name, $this->user)) {
359
+            \OCP\Util::writeLog('core', __METHOD__.', name: ' . $name. ' exists already', \OCP\Util::DEBUG);
360
+            return false;
361
+        }
362
+        try {
363
+            $tag = new Tag($this->user, $this->type, $name);
364
+            $tag = $this->mapper->insert($tag);
365
+            $this->tags[] = $tag;
366
+        } catch(\Exception $e) {
367
+            \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
368
+                \OCP\Util::ERROR);
369
+            return false;
370
+        }
371
+        \OCP\Util::writeLog('core', __METHOD__.', id: ' . $tag->getId(), \OCP\Util::DEBUG);
372
+        return $tag->getId();
373
+    }
374
+
375
+    /**
376
+     * Rename tag.
377
+     *
378
+     * @param string|integer $from The name or ID of the existing tag
379
+     * @param string $to The new name of the tag.
380
+     * @return bool
381
+     */
382
+    public function rename($from, $to) {
383
+        $from = trim($from);
384
+        $to = trim($to);
385
+
386
+        if($to === '' || $from === '') {
387
+            \OCP\Util::writeLog('core', __METHOD__.', Cannot use empty tag names', \OCP\Util::DEBUG);
388
+            return false;
389
+        }
390
+
391
+        if (is_numeric($from)) {
392
+            $key = $this->getTagById($from);
393
+        } else {
394
+            $key = $this->getTagByName($from);
395
+        }
396
+        if($key === false) {
397
+            \OCP\Util::writeLog('core', __METHOD__.', tag: ' . $from. ' does not exist', \OCP\Util::DEBUG);
398
+            return false;
399
+        }
400
+        $tag = $this->tags[$key];
401
+
402
+        if($this->userHasTag($to, $tag->getOwner())) {
403
+            \OCP\Util::writeLog('core', __METHOD__.', A tag named ' . $to. ' already exists for user ' . $tag->getOwner() . '.', \OCP\Util::DEBUG);
404
+            return false;
405
+        }
406
+
407
+        try {
408
+            $tag->setName($to);
409
+            $this->tags[$key] = $this->mapper->update($tag);
410
+        } catch(\Exception $e) {
411
+            \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
412
+                \OCP\Util::ERROR);
413
+            return false;
414
+        }
415
+        return true;
416
+    }
417
+
418
+    /**
419
+     * Add a list of new tags.
420
+     *
421
+     * @param string[] $names A string with a name or an array of strings containing
422
+     * the name(s) of the tag(s) to add.
423
+     * @param bool $sync When true, save the tags
424
+     * @param int|null $id int Optional object id to add to this|these tag(s)
425
+     * @return bool Returns false on error.
426
+     */
427
+    public function addMultiple($names, $sync=false, $id = null) {
428
+        if(!is_array($names)) {
429
+            $names = array($names);
430
+        }
431
+        $names = array_map('trim', $names);
432
+        array_filter($names);
433
+
434
+        $newones = array();
435
+        foreach($names as $name) {
436
+            if(!$this->hasTag($name) && $name !== '') {
437
+                $newones[] = new Tag($this->user, $this->type, $name);
438
+            }
439
+            if(!is_null($id) ) {
440
+                // Insert $objectid, $categoryid  pairs if not exist.
441
+                self::$relations[] = array('objid' => $id, 'tag' => $name);
442
+            }
443
+        }
444
+        $this->tags = array_merge($this->tags, $newones);
445
+        if($sync === true) {
446
+            $this->save();
447
+        }
448
+
449
+        return true;
450
+    }
451
+
452
+    /**
453
+     * Save the list of tags and their object relations
454
+     */
455
+    protected function save() {
456
+        if(is_array($this->tags)) {
457
+            foreach($this->tags as $tag) {
458
+                try {
459
+                    if (!$this->mapper->tagExists($tag)) {
460
+                        $this->mapper->insert($tag);
461
+                    }
462
+                } catch(\Exception $e) {
463
+                    \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
464
+                        \OCP\Util::ERROR);
465
+                }
466
+            }
467
+
468
+            // reload tags to get the proper ids.
469
+            $this->tags = $this->mapper->loadTags($this->owners, $this->type);
470
+            \OCP\Util::writeLog('core', __METHOD__.', tags: ' . print_r($this->tags, true),
471
+                \OCP\Util::DEBUG);
472
+            // Loop through temporarily cached objectid/tagname pairs
473
+            // and save relations.
474
+            $tags = $this->tags;
475
+            // For some reason this is needed or array_search(i) will return 0..?
476
+            ksort($tags);
477
+            foreach(self::$relations as $relation) {
478
+                $tagId = $this->getTagId($relation['tag']);
479
+                \OCP\Util::writeLog('core', __METHOD__ . 'catid, ' . $relation['tag'] . ' ' . $tagId, \OCP\Util::DEBUG);
480
+                if($tagId) {
481
+                    try {
482
+                        \OCP\DB::insertIfNotExist(self::RELATION_TABLE,
483
+                            array(
484
+                                'objid' => $relation['objid'],
485
+                                'categoryid' => $tagId,
486
+                                'type' => $this->type,
487
+                                ));
488
+                    } catch(\Exception $e) {
489
+                        \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
490
+                            \OCP\Util::ERROR);
491
+                    }
492
+                }
493
+            }
494
+            self::$relations = array(); // reset
495
+        } else {
496
+            \OCP\Util::writeLog('core', __METHOD__.', $this->tags is not an array! '
497
+                . print_r($this->tags, true), \OCP\Util::ERROR);
498
+        }
499
+    }
500
+
501
+    /**
502
+     * Delete tags and tag/object relations for a user.
503
+     *
504
+     * For hooking up on post_deleteUser
505
+     *
506
+     * @param array $arguments
507
+     */
508
+    public static function post_deleteUser($arguments) {
509
+        // Find all objectid/tagId pairs.
510
+        $result = null;
511
+        try {
512
+            $stmt = \OCP\DB::prepare('SELECT `id` FROM `' . self::TAG_TABLE . '` '
513
+                . 'WHERE `uid` = ?');
514
+            $result = $stmt->execute(array($arguments['uid']));
515
+            if (\OCP\DB::isError($result)) {
516
+                \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
517
+            }
518
+        } catch(\Exception $e) {
519
+            \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
520
+                \OCP\Util::ERROR);
521
+        }
522
+
523
+        if(!is_null($result)) {
524
+            try {
525
+                $stmt = \OCP\DB::prepare('DELETE FROM `' . self::RELATION_TABLE . '` '
526
+                    . 'WHERE `categoryid` = ?');
527
+                while( $row = $result->fetchRow()) {
528
+                    try {
529
+                        $stmt->execute(array($row['id']));
530
+                    } catch(\Exception $e) {
531
+                        \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
532
+                            \OCP\Util::ERROR);
533
+                    }
534
+                }
535
+            } catch(\Exception $e) {
536
+                \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
537
+                    \OCP\Util::ERROR);
538
+            }
539
+        }
540
+        try {
541
+            $stmt = \OCP\DB::prepare('DELETE FROM `' . self::TAG_TABLE . '` '
542
+                . 'WHERE `uid` = ?');
543
+            $result = $stmt->execute(array($arguments['uid']));
544
+            if (\OCP\DB::isError($result)) {
545
+                \OCP\Util::writeLog('core', __METHOD__. ', DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
546
+            }
547
+        } catch(\Exception $e) {
548
+            \OCP\Util::writeLog('core', __METHOD__ . ', exception: '
549
+                . $e->getMessage(), \OCP\Util::ERROR);
550
+        }
551
+    }
552
+
553
+    /**
554
+     * Delete tag/object relations from the db
555
+     *
556
+     * @param array $ids The ids of the objects
557
+     * @return boolean Returns false on error.
558
+     */
559
+    public function purgeObjects(array $ids) {
560
+        if(count($ids) === 0) {
561
+            // job done ;)
562
+            return true;
563
+        }
564
+        $updates = $ids;
565
+        try {
566
+            $query = 'DELETE FROM `' . self::RELATION_TABLE . '` ';
567
+            $query .= 'WHERE `objid` IN (' . str_repeat('?,', count($ids)-1) . '?) ';
568
+            $query .= 'AND `type`= ?';
569
+            $updates[] = $this->type;
570
+            $stmt = \OCP\DB::prepare($query);
571
+            $result = $stmt->execute($updates);
572
+            if (\OCP\DB::isError($result)) {
573
+                \OCP\Util::writeLog('core', __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
574
+                return false;
575
+            }
576
+        } catch(\Exception $e) {
577
+            \OCP\Util::writeLog('core', __METHOD__.', exception: ' . $e->getMessage(),
578
+                \OCP\Util::ERROR);
579
+            return false;
580
+        }
581
+        return true;
582
+    }
583
+
584
+    /**
585
+     * Get favorites for an object type
586
+     *
587
+     * @return array|false An array of object ids.
588
+     */
589
+    public function getFavorites() {
590
+        try {
591
+            return $this->getIdsForTag(self::TAG_FAVORITE);
592
+        } catch(\Exception $e) {
593
+            \OCP\Util::writeLog('core', __METHOD__.', exception: ' . $e->getMessage(),
594
+                \OCP\Util::DEBUG);
595
+            return array();
596
+        }
597
+    }
598
+
599
+    /**
600
+     * Add an object to favorites
601
+     *
602
+     * @param int $objid The id of the object
603
+     * @return boolean
604
+     */
605
+    public function addToFavorites($objid) {
606
+        if(!$this->userHasTag(self::TAG_FAVORITE, $this->user)) {
607
+            $this->add(self::TAG_FAVORITE);
608
+        }
609
+        return $this->tagAs($objid, self::TAG_FAVORITE);
610
+    }
611
+
612
+    /**
613
+     * Remove an object from favorites
614
+     *
615
+     * @param int $objid The id of the object
616
+     * @return boolean
617
+     */
618
+    public function removeFromFavorites($objid) {
619
+        return $this->unTag($objid, self::TAG_FAVORITE);
620
+    }
621
+
622
+    /**
623
+     * Creates a tag/object relation.
624
+     *
625
+     * @param int $objid The id of the object
626
+     * @param string $tag The id or name of the tag
627
+     * @return boolean Returns false on error.
628
+     */
629
+    public function tagAs($objid, $tag) {
630
+        if(is_string($tag) && !is_numeric($tag)) {
631
+            $tag = trim($tag);
632
+            if($tag === '') {
633
+                \OCP\Util::writeLog('core', __METHOD__.', Cannot add an empty tag', \OCP\Util::DEBUG);
634
+                return false;
635
+            }
636
+            if(!$this->hasTag($tag)) {
637
+                $this->add($tag);
638
+            }
639
+            $tagId =  $this->getTagId($tag);
640
+        } else {
641
+            $tagId = $tag;
642
+        }
643
+        try {
644
+            \OCP\DB::insertIfNotExist(self::RELATION_TABLE,
645
+                array(
646
+                    'objid' => $objid,
647
+                    'categoryid' => $tagId,
648
+                    'type' => $this->type,
649
+                ));
650
+        } catch(\Exception $e) {
651
+            \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
652
+                \OCP\Util::ERROR);
653
+            return false;
654
+        }
655
+        return true;
656
+    }
657
+
658
+    /**
659
+     * Delete single tag/object relation from the db
660
+     *
661
+     * @param int $objid The id of the object
662
+     * @param string $tag The id or name of the tag
663
+     * @return boolean
664
+     */
665
+    public function unTag($objid, $tag) {
666
+        if(is_string($tag) && !is_numeric($tag)) {
667
+            $tag = trim($tag);
668
+            if($tag === '') {
669
+                \OCP\Util::writeLog('core', __METHOD__.', Tag name is empty', \OCP\Util::DEBUG);
670
+                return false;
671
+            }
672
+            $tagId =  $this->getTagId($tag);
673
+        } else {
674
+            $tagId = $tag;
675
+        }
676
+
677
+        try {
678
+            $sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
679
+                    . 'WHERE `objid` = ? AND `categoryid` = ? AND `type` = ?';
680
+            $stmt = \OCP\DB::prepare($sql);
681
+            $stmt->execute(array($objid, $tagId, $this->type));
682
+        } catch(\Exception $e) {
683
+            \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
684
+                \OCP\Util::ERROR);
685
+            return false;
686
+        }
687
+        return true;
688
+    }
689
+
690
+    /**
691
+     * Delete tags from the database.
692
+     *
693
+     * @param string[]|integer[] $names An array of tags (names or IDs) to delete
694
+     * @return bool Returns false on error
695
+     */
696
+    public function delete($names) {
697
+        if(!is_array($names)) {
698
+            $names = array($names);
699
+        }
700
+
701
+        $names = array_map('trim', $names);
702
+        array_filter($names);
703
+
704
+        \OCP\Util::writeLog('core', __METHOD__ . ', before: '
705
+            . print_r($this->tags, true), \OCP\Util::DEBUG);
706
+        foreach($names as $name) {
707
+            $id = null;
708
+
709
+            if (is_numeric($name)) {
710
+                $key = $this->getTagById($name);
711
+            } else {
712
+                $key = $this->getTagByName($name);
713
+            }
714
+            if ($key !== false) {
715
+                $tag = $this->tags[$key];
716
+                $id = $tag->getId();
717
+                unset($this->tags[$key]);
718
+                $this->mapper->delete($tag);
719
+            } else {
720
+                \OCP\Util::writeLog('core', __METHOD__ . 'Cannot delete tag ' . $name
721
+                    . ': not found.', \OCP\Util::ERROR);
722
+            }
723
+            if(!is_null($id) && $id !== false) {
724
+                try {
725
+                    $sql = 'DELETE FROM `' . self::RELATION_TABLE . '` '
726
+                            . 'WHERE `categoryid` = ?';
727
+                    $stmt = \OCP\DB::prepare($sql);
728
+                    $result = $stmt->execute(array($id));
729
+                    if (\OCP\DB::isError($result)) {
730
+                        \OCP\Util::writeLog('core',
731
+                            __METHOD__. 'DB error: ' . \OCP\DB::getErrorMessage(),
732
+                            \OCP\Util::ERROR);
733
+                        return false;
734
+                    }
735
+                } catch(\Exception $e) {
736
+                    \OCP\Util::writeLog('core', __METHOD__.', exception: '.$e->getMessage(),
737
+                        \OCP\Util::ERROR);
738
+                    return false;
739
+                }
740
+            }
741
+        }
742
+        return true;
743
+    }
744
+
745
+    // case-insensitive array_search
746
+    protected function array_searchi($needle, $haystack, $mem='getName') {
747
+        if(!is_array($haystack)) {
748
+            return false;
749
+        }
750
+        return array_search(strtolower($needle), array_map(
751
+            function($tag) use($mem) {
752
+                return strtolower(call_user_func(array($tag, $mem)));
753
+            }, $haystack)
754
+        );
755
+    }
756
+
757
+    /**
758
+     * Get a tag's ID.
759
+     *
760
+     * @param string $name The tag name to look for.
761
+     * @return string|bool The tag's id or false if no matching tag is found.
762
+     */
763
+    private function getTagId($name) {
764
+        $key = $this->array_searchi($name, $this->tags);
765
+        if ($key !== false) {
766
+            return $this->tags[$key]->getId();
767
+        }
768
+        return false;
769
+    }
770
+
771
+    /**
772
+     * Get a tag by its name.
773
+     *
774
+     * @param string $name The tag name.
775
+     * @return integer|bool The tag object's offset within the $this->tags
776
+     *                      array or false if it doesn't exist.
777
+     */
778
+    private function getTagByName($name) {
779
+        return $this->array_searchi($name, $this->tags, 'getName');
780
+    }
781
+
782
+    /**
783
+     * Get a tag by its ID.
784
+     *
785
+     * @param string $id The tag ID to look for.
786
+     * @return integer|bool The tag object's offset within the $this->tags
787
+     *                      array or false if it doesn't exist.
788
+     */
789
+    private function getTagById($id) {
790
+        return $this->array_searchi($id, $this->tags, 'getId');
791
+    }
792
+
793
+    /**
794
+     * Returns an array mapping a given tag's properties to its values:
795
+     * ['id' => 0, 'name' = 'Tag', 'owner' = 'User', 'type' => 'tagtype']
796
+     *
797
+     * @param Tag $tag The tag that is going to be mapped
798
+     * @return array
799
+     */
800
+    private function tagMap(Tag $tag) {
801
+        return array(
802
+            'id'    => $tag->getId(),
803
+            'name'  => $tag->getName(),
804
+            'owner' => $tag->getOwner(),
805
+            'type'  => $tag->getType()
806
+        );
807
+    }
808 808
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/Http.php 1 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 int 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 int 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.