Completed
Push — master ( a2678d...3adda3 )
by Morris
21:22 queued 05:07
created
lib/public/Util.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -51,7 +51,6 @@
 block discarded – undo
51 51
 // use OCP namespace for all classes that are considered public.
52 52
 // This means that they should be used by apps instead of the internal ownCloud classes
53 53
 namespace OCP;
54
-use DateTimeZone;
55 54
 
56 55
 /**
57 56
  * This class provides different helper functions to make the life of a developer easier
Please login to merge, or discard this patch.
Indentation   +625 added lines, -625 removed lines patch added patch discarded remove patch
@@ -58,631 +58,631 @@
 block discarded – undo
58 58
  * @since 4.0.0
59 59
  */
60 60
 class Util {
61
-	// consts for Logging
62
-	const DEBUG=0;
63
-	const INFO=1;
64
-	const WARN=2;
65
-	const ERROR=3;
66
-	const FATAL=4;
67
-
68
-	/** \OCP\Share\IManager */
69
-	private static $shareManager;
70
-
71
-	/**
72
-	 * get the current installed version of ownCloud
73
-	 * @return array
74
-	 * @since 4.0.0
75
-	 */
76
-	public static function getVersion() {
77
-		return \OC_Util::getVersion();
78
-	}
61
+    // consts for Logging
62
+    const DEBUG=0;
63
+    const INFO=1;
64
+    const WARN=2;
65
+    const ERROR=3;
66
+    const FATAL=4;
67
+
68
+    /** \OCP\Share\IManager */
69
+    private static $shareManager;
70
+
71
+    /**
72
+     * get the current installed version of ownCloud
73
+     * @return array
74
+     * @since 4.0.0
75
+     */
76
+    public static function getVersion() {
77
+        return \OC_Util::getVersion();
78
+    }
79 79
 	
80
-	/**
81
-	 * Set current update channel
82
-	 * @param string $channel
83
-	 * @since 8.1.0
84
-	 */
85
-	public static function setChannel($channel) {
86
-		\OC::$server->getConfig()->setSystemValue('updater.release.channel', $channel);
87
-	}
80
+    /**
81
+     * Set current update channel
82
+     * @param string $channel
83
+     * @since 8.1.0
84
+     */
85
+    public static function setChannel($channel) {
86
+        \OC::$server->getConfig()->setSystemValue('updater.release.channel', $channel);
87
+    }
88 88
 	
89
-	/**
90
-	 * Get current update channel
91
-	 * @return string
92
-	 * @since 8.1.0
93
-	 */
94
-	public static function getChannel() {
95
-		return \OC_Util::getChannel();
96
-	}
97
-
98
-	/**
99
-	 * send an email
100
-	 * @param string $toaddress
101
-	 * @param string $toname
102
-	 * @param string $subject
103
-	 * @param string $mailtext
104
-	 * @param string $fromaddress
105
-	 * @param string $fromname
106
-	 * @param int $html
107
-	 * @param string $altbody
108
-	 * @param string $ccaddress
109
-	 * @param string $ccname
110
-	 * @param string $bcc
111
-	 * @deprecated 8.1.0 Use \OCP\Mail\IMailer instead
112
-	 * @since 4.0.0
113
-	 */
114
-	public static function sendMail($toaddress, $toname, $subject, $mailtext, $fromaddress, $fromname,
115
-		$html = 0, $altbody = '', $ccaddress = '', $ccname = '', $bcc = '') {
116
-		$mailer = \OC::$server->getMailer();
117
-		$message = $mailer->createMessage();
118
-		$message->setTo([$toaddress => $toname]);
119
-		$message->setSubject($subject);
120
-		$message->setPlainBody($mailtext);
121
-		$message->setFrom([$fromaddress => $fromname]);
122
-		if($html === 1) {
123
-			$message->setHtmlBody($altbody);
124
-		}
125
-
126
-		if($altbody === '') {
127
-			$message->setHtmlBody($mailtext);
128
-			$message->setPlainBody('');
129
-		} else {
130
-			$message->setHtmlBody($mailtext);
131
-			$message->setPlainBody($altbody);
132
-		}
133
-
134
-		if(!empty($ccaddress)) {
135
-			if(!empty($ccname)) {
136
-				$message->setCc([$ccaddress => $ccname]);
137
-			} else {
138
-				$message->setCc([$ccaddress]);
139
-			}
140
-		}
141
-		if(!empty($bcc)) {
142
-			$message->setBcc([$bcc]);
143
-		}
144
-
145
-		$mailer->send($message);
146
-	}
147
-
148
-	/**
149
-	 * write a message in the log
150
-	 * @param string $app
151
-	 * @param string $message
152
-	 * @param int $level
153
-	 * @since 4.0.0
154
-	 * @deprecated 13.0.0 use log of \OCP\ILogger
155
-	 */
156
-	public static function writeLog( $app, $message, $level ) {
157
-		$context = ['app' => $app];
158
-		\OC::$server->getLogger()->log($level, $message, $context);
159
-	}
160
-
161
-	/**
162
-	 * write exception into the log
163
-	 * @param string $app app name
164
-	 * @param \Exception $ex exception to log
165
-	 * @param int $level log level, defaults to \OCP\Util::FATAL
166
-	 * @since ....0.0 - parameter $level was added in 7.0.0
167
-	 * @deprecated 8.2.0 use logException of \OCP\ILogger
168
-	 */
169
-	public static function logException( $app, \Exception $ex, $level = \OCP\Util::FATAL ) {
170
-		\OC::$server->getLogger()->logException($ex, ['app' => $app]);
171
-	}
172
-
173
-	/**
174
-	 * check if sharing is disabled for the current user
175
-	 *
176
-	 * @return boolean
177
-	 * @since 7.0.0
178
-	 * @deprecated 9.1.0 Use \OC::$server->getShareManager()->sharingDisabledForUser
179
-	 */
180
-	public static function isSharingDisabledForUser() {
181
-		if (self::$shareManager === null) {
182
-			self::$shareManager = \OC::$server->getShareManager();
183
-		}
184
-
185
-		$user = \OC::$server->getUserSession()->getUser();
186
-		if ($user !== null) {
187
-			$user = $user->getUID();
188
-		}
189
-
190
-		return self::$shareManager->sharingDisabledForUser($user);
191
-	}
192
-
193
-	/**
194
-	 * get l10n object
195
-	 * @param string $application
196
-	 * @param string|null $language
197
-	 * @return \OCP\IL10N
198
-	 * @since 6.0.0 - parameter $language was added in 8.0.0
199
-	 */
200
-	public static function getL10N($application, $language = null) {
201
-		return \OC::$server->getL10N($application, $language);
202
-	}
203
-
204
-	/**
205
-	 * add a css file
206
-	 * @param string $application
207
-	 * @param string $file
208
-	 * @since 4.0.0
209
-	 */
210
-	public static function addStyle( $application, $file = null ) {
211
-		\OC_Util::addStyle( $application, $file );
212
-	}
213
-
214
-	/**
215
-	 * add a javascript file
216
-	 * @param string $application
217
-	 * @param string $file
218
-	 * @since 4.0.0
219
-	 */
220
-	public static function addScript( $application, $file = null ) {
221
-		\OC_Util::addScript( $application, $file );
222
-	}
223
-
224
-	/**
225
-	 * Add a translation JS file
226
-	 * @param string $application application id
227
-	 * @param string $languageCode language code, defaults to the current locale
228
-	 * @since 8.0.0
229
-	 */
230
-	public static function addTranslations($application, $languageCode = null) {
231
-		\OC_Util::addTranslations($application, $languageCode);
232
-	}
233
-
234
-	/**
235
-	 * Add a custom element to the header
236
-	 * If $text is null then the element will be written as empty element.
237
-	 * So use "" to get a closing tag.
238
-	 * @param string $tag tag name of the element
239
-	 * @param array $attributes array of attributes for the element
240
-	 * @param string $text the text content for the element
241
-	 * @since 4.0.0
242
-	 */
243
-	public static function addHeader($tag, $attributes, $text=null) {
244
-		\OC_Util::addHeader($tag, $attributes, $text);
245
-	}
246
-
247
-	/**
248
-	 * check if some encrypted files are stored
249
-	 * @return bool
250
-	 *
251
-	 * @deprecated 8.1.0 No longer required
252
-	 * @since 6.0.0
253
-	 */
254
-	public static function encryptedFiles() {
255
-		return false;
256
-	}
257
-
258
-	/**
259
-	 * Creates an absolute url to the given app and file.
260
-	 * @param string $app app
261
-	 * @param string $file file
262
-	 * @param array $args array with param=>value, will be appended to the returned url
263
-	 * 	The value of $args will be urlencoded
264
-	 * @return string the url
265
-	 * @since 4.0.0 - parameter $args was added in 4.5.0
266
-	 */
267
-	public static function linkToAbsolute( $app, $file, $args = array() ) {
268
-		$urlGenerator = \OC::$server->getURLGenerator();
269
-		return $urlGenerator->getAbsoluteURL(
270
-			$urlGenerator->linkTo($app, $file, $args)
271
-		);
272
-	}
273
-
274
-	/**
275
-	 * Creates an absolute url for remote use.
276
-	 * @param string $service id
277
-	 * @return string the url
278
-	 * @since 4.0.0
279
-	 */
280
-	public static function linkToRemote( $service ) {
281
-		$urlGenerator = \OC::$server->getURLGenerator();
282
-		$remoteBase = $urlGenerator->linkTo('', 'remote.php') . '/' . $service;
283
-		return $urlGenerator->getAbsoluteURL(
284
-			$remoteBase . (($service[strlen($service) - 1] != '/') ? '/' : '')
285
-		);
286
-	}
287
-
288
-	/**
289
-	 * Creates an absolute url for public use
290
-	 * @param string $service id
291
-	 * @return string the url
292
-	 * @since 4.5.0
293
-	 */
294
-	public static function linkToPublic($service) {
295
-		return \OC_Helper::linkToPublic($service);
296
-	}
297
-
298
-	/**
299
-	 * Creates an url using a defined route
300
-	 * @param string $route
301
-	 * @param array $parameters
302
-	 * @internal param array $args with param=>value, will be appended to the returned url
303
-	 * @return string the url
304
-	 * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->linkToRoute($route, $parameters)
305
-	 * @since 5.0.0
306
-	 */
307
-	public static function linkToRoute( $route, $parameters = array() ) {
308
-		return \OC::$server->getURLGenerator()->linkToRoute($route, $parameters);
309
-	}
310
-
311
-	/**
312
-	 * Creates an url to the given app and file
313
-	 * @param string $app app
314
-	 * @param string $file file
315
-	 * @param array $args array with param=>value, will be appended to the returned url
316
-	 * 	The value of $args will be urlencoded
317
-	 * @return string the url
318
-	 * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->linkTo($app, $file, $args)
319
-	 * @since 4.0.0 - parameter $args was added in 4.5.0
320
-	 */
321
-	public static function linkTo( $app, $file, $args = array() ) {
322
-		return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
323
-	}
324
-
325
-	/**
326
-	 * Returns the server host, even if the website uses one or more reverse proxy
327
-	 * @return string the server host
328
-	 * @deprecated 8.1.0 Use \OCP\IRequest::getServerHost
329
-	 * @since 4.0.0
330
-	 */
331
-	public static function getServerHost() {
332
-		return \OC::$server->getRequest()->getServerHost();
333
-	}
334
-
335
-	/**
336
-	 * Returns the server host name without an eventual port number
337
-	 * @return string the server hostname
338
-	 * @since 5.0.0
339
-	 */
340
-	public static function getServerHostName() {
341
-		$host_name = \OC::$server->getRequest()->getServerHost();
342
-		// strip away port number (if existing)
343
-		$colon_pos = strpos($host_name, ':');
344
-		if ($colon_pos != FALSE) {
345
-			$host_name = substr($host_name, 0, $colon_pos);
346
-		}
347
-		return $host_name;
348
-	}
349
-
350
-	/**
351
-	 * Returns the default email address
352
-	 * @param string $user_part the user part of the address
353
-	 * @return string the default email address
354
-	 *
355
-	 * Assembles a default email address (using the server hostname
356
-	 * and the given user part, and returns it
357
-	 * Example: when given lostpassword-noreply as $user_part param,
358
-	 *     and is currently accessed via http(s)://example.com/,
359
-	 *     it would return '[email protected]'
360
-	 *
361
-	 * If the configuration value 'mail_from_address' is set in
362
-	 * config.php, this value will override the $user_part that
363
-	 * is passed to this function
364
-	 * @since 5.0.0
365
-	 */
366
-	public static function getDefaultEmailAddress($user_part) {
367
-		$config = \OC::$server->getConfig();
368
-		$user_part = $config->getSystemValue('mail_from_address', $user_part);
369
-		$host_name = self::getServerHostName();
370
-		$host_name = $config->getSystemValue('mail_domain', $host_name);
371
-		$defaultEmailAddress = $user_part.'@'.$host_name;
372
-
373
-		$mailer = \OC::$server->getMailer();
374
-		if ($mailer->validateMailAddress($defaultEmailAddress)) {
375
-			return $defaultEmailAddress;
376
-		}
377
-
378
-		// in case we cannot build a valid email address from the hostname let's fallback to 'localhost.localdomain'
379
-		return $user_part.'@localhost.localdomain';
380
-	}
381
-
382
-	/**
383
-	 * Returns the server protocol. It respects reverse proxy servers and load balancers
384
-	 * @return string the server protocol
385
-	 * @deprecated 8.1.0 Use \OCP\IRequest::getServerProtocol
386
-	 * @since 4.5.0
387
-	 */
388
-	public static function getServerProtocol() {
389
-		return \OC::$server->getRequest()->getServerProtocol();
390
-	}
391
-
392
-	/**
393
-	 * Returns the request uri, even if the website uses one or more reverse proxies
394
-	 * @return string the request uri
395
-	 * @deprecated 8.1.0 Use \OCP\IRequest::getRequestUri
396
-	 * @since 5.0.0
397
-	 */
398
-	public static function getRequestUri() {
399
-		return \OC::$server->getRequest()->getRequestUri();
400
-	}
401
-
402
-	/**
403
-	 * Returns the script name, even if the website uses one or more reverse proxies
404
-	 * @return string the script name
405
-	 * @deprecated 8.1.0 Use \OCP\IRequest::getScriptName
406
-	 * @since 5.0.0
407
-	 */
408
-	public static function getScriptName() {
409
-		return \OC::$server->getRequest()->getScriptName();
410
-	}
411
-
412
-	/**
413
-	 * Creates path to an image
414
-	 * @param string $app app
415
-	 * @param string $image image name
416
-	 * @return string the url
417
-	 * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->imagePath($app, $image)
418
-	 * @since 4.0.0
419
-	 */
420
-	public static function imagePath( $app, $image ) {
421
-		return \OC::$server->getURLGenerator()->imagePath($app, $image);
422
-	}
423
-
424
-	/**
425
-	 * Make a human file size (2048 to 2 kB)
426
-	 * @param int $bytes file size in bytes
427
-	 * @return string a human readable file size
428
-	 * @since 4.0.0
429
-	 */
430
-	public static function humanFileSize($bytes) {
431
-		return \OC_Helper::humanFileSize($bytes);
432
-	}
433
-
434
-	/**
435
-	 * Make a computer file size (2 kB to 2048)
436
-	 * @param string $str file size in a fancy format
437
-	 * @return float a file size in bytes
438
-	 *
439
-	 * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
440
-	 * @since 4.0.0
441
-	 */
442
-	public static function computerFileSize($str) {
443
-		return \OC_Helper::computerFileSize($str);
444
-	}
445
-
446
-	/**
447
-	 * connects a function to a hook
448
-	 *
449
-	 * @param string $signalClass class name of emitter
450
-	 * @param string $signalName name of signal
451
-	 * @param string|object $slotClass class name of slot
452
-	 * @param string $slotName name of slot
453
-	 * @return bool
454
-	 *
455
-	 * This function makes it very easy to connect to use hooks.
456
-	 *
457
-	 * TODO: write example
458
-	 * @since 4.0.0
459
-	 */
460
-	static public function connectHook($signalClass, $signalName, $slotClass, $slotName) {
461
-		return \OC_Hook::connect($signalClass, $signalName, $slotClass, $slotName);
462
-	}
463
-
464
-	/**
465
-	 * Emits a signal. To get data from the slot use references!
466
-	 * @param string $signalclass class name of emitter
467
-	 * @param string $signalname name of signal
468
-	 * @param array $params default: array() array with additional data
469
-	 * @return bool true if slots exists or false if not
470
-	 *
471
-	 * TODO: write example
472
-	 * @since 4.0.0
473
-	 */
474
-	static public function emitHook($signalclass, $signalname, $params = array()) {
475
-		return \OC_Hook::emit($signalclass, $signalname, $params);
476
-	}
477
-
478
-	/**
479
-	 * Cached encrypted CSRF token. Some static unit-tests of ownCloud compare
480
-	 * multiple OC_Template elements which invoke `callRegister`. If the value
481
-	 * would not be cached these unit-tests would fail.
482
-	 * @var string
483
-	 */
484
-	private static $token = '';
485
-
486
-	/**
487
-	 * Register an get/post call. This is important to prevent CSRF attacks
488
-	 * @since 4.5.0
489
-	 */
490
-	public static function callRegister() {
491
-		if(self::$token === '') {
492
-			self::$token = \OC::$server->getCsrfTokenManager()->getToken()->getEncryptedValue();
493
-		}
494
-		return self::$token;
495
-	}
496
-
497
-	/**
498
-	 * Check an ajax get/post call if the request token is valid. exit if not.
499
-	 * @since 4.5.0
500
-	 * @deprecated 9.0.0 Use annotations based on the app framework.
501
-	 */
502
-	public static function callCheck() {
503
-		if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
504
-			header('Location: '.\OC::$WEBROOT);
505
-			exit();
506
-		}
507
-
508
-		if (!\OC::$server->getRequest()->passesCSRFCheck()) {
509
-			exit();
510
-		}
511
-	}
512
-
513
-	/**
514
-	 * Used to sanitize HTML
515
-	 *
516
-	 * This function is used to sanitize HTML and should be applied on any
517
-	 * string or array of strings before displaying it on a web page.
518
-	 *
519
-	 * @param string|array $value
520
-	 * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
521
-	 * @since 4.5.0
522
-	 */
523
-	public static function sanitizeHTML($value) {
524
-		return \OC_Util::sanitizeHTML($value);
525
-	}
526
-
527
-	/**
528
-	 * Public function to encode url parameters
529
-	 *
530
-	 * This function is used to encode path to file before output.
531
-	 * Encoding is done according to RFC 3986 with one exception:
532
-	 * Character '/' is preserved as is.
533
-	 *
534
-	 * @param string $component part of URI to encode
535
-	 * @return string
536
-	 * @since 6.0.0
537
-	 */
538
-	public static function encodePath($component) {
539
-		return \OC_Util::encodePath($component);
540
-	}
541
-
542
-	/**
543
-	 * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
544
-	 *
545
-	 * @param array $input The array to work on
546
-	 * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
547
-	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
548
-	 * @return array
549
-	 * @since 4.5.0
550
-	 */
551
-	public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
552
-		return \OC_Helper::mb_array_change_key_case($input, $case, $encoding);
553
-	}
554
-
555
-	/**
556
-	 * replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.
557
-	 *
558
-	 * @param string $string The input string. Opposite to the PHP build-in function does not accept an array.
559
-	 * @param string $replacement The replacement string.
560
-	 * @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.
561
-	 * @param int $length Length of the part to be replaced
562
-	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
563
-	 * @return string
564
-	 * @since 4.5.0
565
-	 * @deprecated 8.2.0 Use substr_replace() instead.
566
-	 */
567
-	public static function mb_substr_replace($string, $replacement, $start, $length = null, $encoding = 'UTF-8') {
568
-		return substr_replace($string, $replacement, $start, $length);
569
-	}
570
-
571
-	/**
572
-	 * Replace all occurrences of the search string with the replacement string
573
-	 *
574
-	 * @param string $search The value being searched for, otherwise known as the needle. String.
575
-	 * @param string $replace The replacement string.
576
-	 * @param string $subject The string or array being searched and replaced on, otherwise known as the haystack.
577
-	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
578
-	 * @param int $count If passed, this will be set to the number of replacements performed.
579
-	 * @return string
580
-	 * @since 4.5.0
581
-	 * @deprecated 8.2.0 Use str_replace() instead.
582
-	 */
583
-	public static function mb_str_replace($search, $replace, $subject, $encoding = 'UTF-8', &$count = null) {
584
-		return str_replace($search, $replace, $subject, $count);
585
-	}
586
-
587
-	/**
588
-	 * performs a search in a nested array
589
-	 *
590
-	 * @param array $haystack the array to be searched
591
-	 * @param string $needle the search string
592
-	 * @param mixed $index optional, only search this key name
593
-	 * @return mixed the key of the matching field, otherwise false
594
-	 * @since 4.5.0
595
-	 */
596
-	public static function recursiveArraySearch($haystack, $needle, $index = null) {
597
-		return \OC_Helper::recursiveArraySearch($haystack, $needle, $index);
598
-	}
599
-
600
-	/**
601
-	 * calculates the maximum upload size respecting system settings, free space and user quota
602
-	 *
603
-	 * @param string $dir the current folder where the user currently operates
604
-	 * @param int $free the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
605
-	 * @return int number of bytes representing
606
-	 * @since 5.0.0
607
-	 */
608
-	public static function maxUploadFilesize($dir, $free = null) {
609
-		return \OC_Helper::maxUploadFilesize($dir, $free);
610
-	}
611
-
612
-	/**
613
-	 * Calculate free space left within user quota
614
-	 * @param string $dir the current folder where the user currently operates
615
-	 * @return int number of bytes representing
616
-	 * @since 7.0.0
617
-	 */
618
-	public static function freeSpace($dir) {
619
-		return \OC_Helper::freeSpace($dir);
620
-	}
621
-
622
-	/**
623
-	 * Calculate PHP upload limit
624
-	 *
625
-	 * @return int number of bytes representing
626
-	 * @since 7.0.0
627
-	 */
628
-	public static function uploadLimit() {
629
-		return \OC_Helper::uploadLimit();
630
-	}
631
-
632
-	/**
633
-	 * Returns whether the given file name is valid
634
-	 * @param string $file file name to check
635
-	 * @return bool true if the file name is valid, false otherwise
636
-	 * @deprecated 8.1.0 use \OC\Files\View::verifyPath()
637
-	 * @since 7.0.0
638
-	 * @suppress PhanDeprecatedFunction
639
-	 */
640
-	public static function isValidFileName($file) {
641
-		return \OC_Util::isValidFileName($file);
642
-	}
643
-
644
-	/**
645
-	 * Compare two strings to provide a natural sort
646
-	 * @param string $a first string to compare
647
-	 * @param string $b second string to compare
648
-	 * @return int -1 if $b comes before $a, 1 if $a comes before $b
649
-	 * or 0 if the strings are identical
650
-	 * @since 7.0.0
651
-	 */
652
-	public static function naturalSortCompare($a, $b) {
653
-		return \OC\NaturalSort::getInstance()->compare($a, $b);
654
-	}
655
-
656
-	/**
657
-	 * check if a password is required for each public link
658
-	 * @return boolean
659
-	 * @since 7.0.0
660
-	 */
661
-	public static function isPublicLinkPasswordRequired() {
662
-		return \OC_Util::isPublicLinkPasswordRequired();
663
-	}
664
-
665
-	/**
666
-	 * check if share API enforces a default expire date
667
-	 * @return boolean
668
-	 * @since 8.0.0
669
-	 */
670
-	public static function isDefaultExpireDateEnforced() {
671
-		return \OC_Util::isDefaultExpireDateEnforced();
672
-	}
673
-
674
-	protected static $needUpgradeCache = null;
675
-
676
-	/**
677
-	 * Checks whether the current version needs upgrade.
678
-	 *
679
-	 * @return bool true if upgrade is needed, false otherwise
680
-	 * @since 7.0.0
681
-	 */
682
-	public static function needUpgrade() {
683
-		if (!isset(self::$needUpgradeCache)) {
684
-			self::$needUpgradeCache=\OC_Util::needUpgrade(\OC::$server->getSystemConfig());
685
-		}		
686
-		return self::$needUpgradeCache;
687
-	}
89
+    /**
90
+     * Get current update channel
91
+     * @return string
92
+     * @since 8.1.0
93
+     */
94
+    public static function getChannel() {
95
+        return \OC_Util::getChannel();
96
+    }
97
+
98
+    /**
99
+     * send an email
100
+     * @param string $toaddress
101
+     * @param string $toname
102
+     * @param string $subject
103
+     * @param string $mailtext
104
+     * @param string $fromaddress
105
+     * @param string $fromname
106
+     * @param int $html
107
+     * @param string $altbody
108
+     * @param string $ccaddress
109
+     * @param string $ccname
110
+     * @param string $bcc
111
+     * @deprecated 8.1.0 Use \OCP\Mail\IMailer instead
112
+     * @since 4.0.0
113
+     */
114
+    public static function sendMail($toaddress, $toname, $subject, $mailtext, $fromaddress, $fromname,
115
+        $html = 0, $altbody = '', $ccaddress = '', $ccname = '', $bcc = '') {
116
+        $mailer = \OC::$server->getMailer();
117
+        $message = $mailer->createMessage();
118
+        $message->setTo([$toaddress => $toname]);
119
+        $message->setSubject($subject);
120
+        $message->setPlainBody($mailtext);
121
+        $message->setFrom([$fromaddress => $fromname]);
122
+        if($html === 1) {
123
+            $message->setHtmlBody($altbody);
124
+        }
125
+
126
+        if($altbody === '') {
127
+            $message->setHtmlBody($mailtext);
128
+            $message->setPlainBody('');
129
+        } else {
130
+            $message->setHtmlBody($mailtext);
131
+            $message->setPlainBody($altbody);
132
+        }
133
+
134
+        if(!empty($ccaddress)) {
135
+            if(!empty($ccname)) {
136
+                $message->setCc([$ccaddress => $ccname]);
137
+            } else {
138
+                $message->setCc([$ccaddress]);
139
+            }
140
+        }
141
+        if(!empty($bcc)) {
142
+            $message->setBcc([$bcc]);
143
+        }
144
+
145
+        $mailer->send($message);
146
+    }
147
+
148
+    /**
149
+     * write a message in the log
150
+     * @param string $app
151
+     * @param string $message
152
+     * @param int $level
153
+     * @since 4.0.0
154
+     * @deprecated 13.0.0 use log of \OCP\ILogger
155
+     */
156
+    public static function writeLog( $app, $message, $level ) {
157
+        $context = ['app' => $app];
158
+        \OC::$server->getLogger()->log($level, $message, $context);
159
+    }
160
+
161
+    /**
162
+     * write exception into the log
163
+     * @param string $app app name
164
+     * @param \Exception $ex exception to log
165
+     * @param int $level log level, defaults to \OCP\Util::FATAL
166
+     * @since ....0.0 - parameter $level was added in 7.0.0
167
+     * @deprecated 8.2.0 use logException of \OCP\ILogger
168
+     */
169
+    public static function logException( $app, \Exception $ex, $level = \OCP\Util::FATAL ) {
170
+        \OC::$server->getLogger()->logException($ex, ['app' => $app]);
171
+    }
172
+
173
+    /**
174
+     * check if sharing is disabled for the current user
175
+     *
176
+     * @return boolean
177
+     * @since 7.0.0
178
+     * @deprecated 9.1.0 Use \OC::$server->getShareManager()->sharingDisabledForUser
179
+     */
180
+    public static function isSharingDisabledForUser() {
181
+        if (self::$shareManager === null) {
182
+            self::$shareManager = \OC::$server->getShareManager();
183
+        }
184
+
185
+        $user = \OC::$server->getUserSession()->getUser();
186
+        if ($user !== null) {
187
+            $user = $user->getUID();
188
+        }
189
+
190
+        return self::$shareManager->sharingDisabledForUser($user);
191
+    }
192
+
193
+    /**
194
+     * get l10n object
195
+     * @param string $application
196
+     * @param string|null $language
197
+     * @return \OCP\IL10N
198
+     * @since 6.0.0 - parameter $language was added in 8.0.0
199
+     */
200
+    public static function getL10N($application, $language = null) {
201
+        return \OC::$server->getL10N($application, $language);
202
+    }
203
+
204
+    /**
205
+     * add a css file
206
+     * @param string $application
207
+     * @param string $file
208
+     * @since 4.0.0
209
+     */
210
+    public static function addStyle( $application, $file = null ) {
211
+        \OC_Util::addStyle( $application, $file );
212
+    }
213
+
214
+    /**
215
+     * add a javascript file
216
+     * @param string $application
217
+     * @param string $file
218
+     * @since 4.0.0
219
+     */
220
+    public static function addScript( $application, $file = null ) {
221
+        \OC_Util::addScript( $application, $file );
222
+    }
223
+
224
+    /**
225
+     * Add a translation JS file
226
+     * @param string $application application id
227
+     * @param string $languageCode language code, defaults to the current locale
228
+     * @since 8.0.0
229
+     */
230
+    public static function addTranslations($application, $languageCode = null) {
231
+        \OC_Util::addTranslations($application, $languageCode);
232
+    }
233
+
234
+    /**
235
+     * Add a custom element to the header
236
+     * If $text is null then the element will be written as empty element.
237
+     * So use "" to get a closing tag.
238
+     * @param string $tag tag name of the element
239
+     * @param array $attributes array of attributes for the element
240
+     * @param string $text the text content for the element
241
+     * @since 4.0.0
242
+     */
243
+    public static function addHeader($tag, $attributes, $text=null) {
244
+        \OC_Util::addHeader($tag, $attributes, $text);
245
+    }
246
+
247
+    /**
248
+     * check if some encrypted files are stored
249
+     * @return bool
250
+     *
251
+     * @deprecated 8.1.0 No longer required
252
+     * @since 6.0.0
253
+     */
254
+    public static function encryptedFiles() {
255
+        return false;
256
+    }
257
+
258
+    /**
259
+     * Creates an absolute url to the given app and file.
260
+     * @param string $app app
261
+     * @param string $file file
262
+     * @param array $args array with param=>value, will be appended to the returned url
263
+     * 	The value of $args will be urlencoded
264
+     * @return string the url
265
+     * @since 4.0.0 - parameter $args was added in 4.5.0
266
+     */
267
+    public static function linkToAbsolute( $app, $file, $args = array() ) {
268
+        $urlGenerator = \OC::$server->getURLGenerator();
269
+        return $urlGenerator->getAbsoluteURL(
270
+            $urlGenerator->linkTo($app, $file, $args)
271
+        );
272
+    }
273
+
274
+    /**
275
+     * Creates an absolute url for remote use.
276
+     * @param string $service id
277
+     * @return string the url
278
+     * @since 4.0.0
279
+     */
280
+    public static function linkToRemote( $service ) {
281
+        $urlGenerator = \OC::$server->getURLGenerator();
282
+        $remoteBase = $urlGenerator->linkTo('', 'remote.php') . '/' . $service;
283
+        return $urlGenerator->getAbsoluteURL(
284
+            $remoteBase . (($service[strlen($service) - 1] != '/') ? '/' : '')
285
+        );
286
+    }
287
+
288
+    /**
289
+     * Creates an absolute url for public use
290
+     * @param string $service id
291
+     * @return string the url
292
+     * @since 4.5.0
293
+     */
294
+    public static function linkToPublic($service) {
295
+        return \OC_Helper::linkToPublic($service);
296
+    }
297
+
298
+    /**
299
+     * Creates an url using a defined route
300
+     * @param string $route
301
+     * @param array $parameters
302
+     * @internal param array $args with param=>value, will be appended to the returned url
303
+     * @return string the url
304
+     * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->linkToRoute($route, $parameters)
305
+     * @since 5.0.0
306
+     */
307
+    public static function linkToRoute( $route, $parameters = array() ) {
308
+        return \OC::$server->getURLGenerator()->linkToRoute($route, $parameters);
309
+    }
310
+
311
+    /**
312
+     * Creates an url to the given app and file
313
+     * @param string $app app
314
+     * @param string $file file
315
+     * @param array $args array with param=>value, will be appended to the returned url
316
+     * 	The value of $args will be urlencoded
317
+     * @return string the url
318
+     * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->linkTo($app, $file, $args)
319
+     * @since 4.0.0 - parameter $args was added in 4.5.0
320
+     */
321
+    public static function linkTo( $app, $file, $args = array() ) {
322
+        return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
323
+    }
324
+
325
+    /**
326
+     * Returns the server host, even if the website uses one or more reverse proxy
327
+     * @return string the server host
328
+     * @deprecated 8.1.0 Use \OCP\IRequest::getServerHost
329
+     * @since 4.0.0
330
+     */
331
+    public static function getServerHost() {
332
+        return \OC::$server->getRequest()->getServerHost();
333
+    }
334
+
335
+    /**
336
+     * Returns the server host name without an eventual port number
337
+     * @return string the server hostname
338
+     * @since 5.0.0
339
+     */
340
+    public static function getServerHostName() {
341
+        $host_name = \OC::$server->getRequest()->getServerHost();
342
+        // strip away port number (if existing)
343
+        $colon_pos = strpos($host_name, ':');
344
+        if ($colon_pos != FALSE) {
345
+            $host_name = substr($host_name, 0, $colon_pos);
346
+        }
347
+        return $host_name;
348
+    }
349
+
350
+    /**
351
+     * Returns the default email address
352
+     * @param string $user_part the user part of the address
353
+     * @return string the default email address
354
+     *
355
+     * Assembles a default email address (using the server hostname
356
+     * and the given user part, and returns it
357
+     * Example: when given lostpassword-noreply as $user_part param,
358
+     *     and is currently accessed via http(s)://example.com/,
359
+     *     it would return '[email protected]'
360
+     *
361
+     * If the configuration value 'mail_from_address' is set in
362
+     * config.php, this value will override the $user_part that
363
+     * is passed to this function
364
+     * @since 5.0.0
365
+     */
366
+    public static function getDefaultEmailAddress($user_part) {
367
+        $config = \OC::$server->getConfig();
368
+        $user_part = $config->getSystemValue('mail_from_address', $user_part);
369
+        $host_name = self::getServerHostName();
370
+        $host_name = $config->getSystemValue('mail_domain', $host_name);
371
+        $defaultEmailAddress = $user_part.'@'.$host_name;
372
+
373
+        $mailer = \OC::$server->getMailer();
374
+        if ($mailer->validateMailAddress($defaultEmailAddress)) {
375
+            return $defaultEmailAddress;
376
+        }
377
+
378
+        // in case we cannot build a valid email address from the hostname let's fallback to 'localhost.localdomain'
379
+        return $user_part.'@localhost.localdomain';
380
+    }
381
+
382
+    /**
383
+     * Returns the server protocol. It respects reverse proxy servers and load balancers
384
+     * @return string the server protocol
385
+     * @deprecated 8.1.0 Use \OCP\IRequest::getServerProtocol
386
+     * @since 4.5.0
387
+     */
388
+    public static function getServerProtocol() {
389
+        return \OC::$server->getRequest()->getServerProtocol();
390
+    }
391
+
392
+    /**
393
+     * Returns the request uri, even if the website uses one or more reverse proxies
394
+     * @return string the request uri
395
+     * @deprecated 8.1.0 Use \OCP\IRequest::getRequestUri
396
+     * @since 5.0.0
397
+     */
398
+    public static function getRequestUri() {
399
+        return \OC::$server->getRequest()->getRequestUri();
400
+    }
401
+
402
+    /**
403
+     * Returns the script name, even if the website uses one or more reverse proxies
404
+     * @return string the script name
405
+     * @deprecated 8.1.0 Use \OCP\IRequest::getScriptName
406
+     * @since 5.0.0
407
+     */
408
+    public static function getScriptName() {
409
+        return \OC::$server->getRequest()->getScriptName();
410
+    }
411
+
412
+    /**
413
+     * Creates path to an image
414
+     * @param string $app app
415
+     * @param string $image image name
416
+     * @return string the url
417
+     * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->imagePath($app, $image)
418
+     * @since 4.0.0
419
+     */
420
+    public static function imagePath( $app, $image ) {
421
+        return \OC::$server->getURLGenerator()->imagePath($app, $image);
422
+    }
423
+
424
+    /**
425
+     * Make a human file size (2048 to 2 kB)
426
+     * @param int $bytes file size in bytes
427
+     * @return string a human readable file size
428
+     * @since 4.0.0
429
+     */
430
+    public static function humanFileSize($bytes) {
431
+        return \OC_Helper::humanFileSize($bytes);
432
+    }
433
+
434
+    /**
435
+     * Make a computer file size (2 kB to 2048)
436
+     * @param string $str file size in a fancy format
437
+     * @return float a file size in bytes
438
+     *
439
+     * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
440
+     * @since 4.0.0
441
+     */
442
+    public static function computerFileSize($str) {
443
+        return \OC_Helper::computerFileSize($str);
444
+    }
445
+
446
+    /**
447
+     * connects a function to a hook
448
+     *
449
+     * @param string $signalClass class name of emitter
450
+     * @param string $signalName name of signal
451
+     * @param string|object $slotClass class name of slot
452
+     * @param string $slotName name of slot
453
+     * @return bool
454
+     *
455
+     * This function makes it very easy to connect to use hooks.
456
+     *
457
+     * TODO: write example
458
+     * @since 4.0.0
459
+     */
460
+    static public function connectHook($signalClass, $signalName, $slotClass, $slotName) {
461
+        return \OC_Hook::connect($signalClass, $signalName, $slotClass, $slotName);
462
+    }
463
+
464
+    /**
465
+     * Emits a signal. To get data from the slot use references!
466
+     * @param string $signalclass class name of emitter
467
+     * @param string $signalname name of signal
468
+     * @param array $params default: array() array with additional data
469
+     * @return bool true if slots exists or false if not
470
+     *
471
+     * TODO: write example
472
+     * @since 4.0.0
473
+     */
474
+    static public function emitHook($signalclass, $signalname, $params = array()) {
475
+        return \OC_Hook::emit($signalclass, $signalname, $params);
476
+    }
477
+
478
+    /**
479
+     * Cached encrypted CSRF token. Some static unit-tests of ownCloud compare
480
+     * multiple OC_Template elements which invoke `callRegister`. If the value
481
+     * would not be cached these unit-tests would fail.
482
+     * @var string
483
+     */
484
+    private static $token = '';
485
+
486
+    /**
487
+     * Register an get/post call. This is important to prevent CSRF attacks
488
+     * @since 4.5.0
489
+     */
490
+    public static function callRegister() {
491
+        if(self::$token === '') {
492
+            self::$token = \OC::$server->getCsrfTokenManager()->getToken()->getEncryptedValue();
493
+        }
494
+        return self::$token;
495
+    }
496
+
497
+    /**
498
+     * Check an ajax get/post call if the request token is valid. exit if not.
499
+     * @since 4.5.0
500
+     * @deprecated 9.0.0 Use annotations based on the app framework.
501
+     */
502
+    public static function callCheck() {
503
+        if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
504
+            header('Location: '.\OC::$WEBROOT);
505
+            exit();
506
+        }
507
+
508
+        if (!\OC::$server->getRequest()->passesCSRFCheck()) {
509
+            exit();
510
+        }
511
+    }
512
+
513
+    /**
514
+     * Used to sanitize HTML
515
+     *
516
+     * This function is used to sanitize HTML and should be applied on any
517
+     * string or array of strings before displaying it on a web page.
518
+     *
519
+     * @param string|array $value
520
+     * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
521
+     * @since 4.5.0
522
+     */
523
+    public static function sanitizeHTML($value) {
524
+        return \OC_Util::sanitizeHTML($value);
525
+    }
526
+
527
+    /**
528
+     * Public function to encode url parameters
529
+     *
530
+     * This function is used to encode path to file before output.
531
+     * Encoding is done according to RFC 3986 with one exception:
532
+     * Character '/' is preserved as is.
533
+     *
534
+     * @param string $component part of URI to encode
535
+     * @return string
536
+     * @since 6.0.0
537
+     */
538
+    public static function encodePath($component) {
539
+        return \OC_Util::encodePath($component);
540
+    }
541
+
542
+    /**
543
+     * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
544
+     *
545
+     * @param array $input The array to work on
546
+     * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
547
+     * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
548
+     * @return array
549
+     * @since 4.5.0
550
+     */
551
+    public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
552
+        return \OC_Helper::mb_array_change_key_case($input, $case, $encoding);
553
+    }
554
+
555
+    /**
556
+     * replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.
557
+     *
558
+     * @param string $string The input string. Opposite to the PHP build-in function does not accept an array.
559
+     * @param string $replacement The replacement string.
560
+     * @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.
561
+     * @param int $length Length of the part to be replaced
562
+     * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
563
+     * @return string
564
+     * @since 4.5.0
565
+     * @deprecated 8.2.0 Use substr_replace() instead.
566
+     */
567
+    public static function mb_substr_replace($string, $replacement, $start, $length = null, $encoding = 'UTF-8') {
568
+        return substr_replace($string, $replacement, $start, $length);
569
+    }
570
+
571
+    /**
572
+     * Replace all occurrences of the search string with the replacement string
573
+     *
574
+     * @param string $search The value being searched for, otherwise known as the needle. String.
575
+     * @param string $replace The replacement string.
576
+     * @param string $subject The string or array being searched and replaced on, otherwise known as the haystack.
577
+     * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
578
+     * @param int $count If passed, this will be set to the number of replacements performed.
579
+     * @return string
580
+     * @since 4.5.0
581
+     * @deprecated 8.2.0 Use str_replace() instead.
582
+     */
583
+    public static function mb_str_replace($search, $replace, $subject, $encoding = 'UTF-8', &$count = null) {
584
+        return str_replace($search, $replace, $subject, $count);
585
+    }
586
+
587
+    /**
588
+     * performs a search in a nested array
589
+     *
590
+     * @param array $haystack the array to be searched
591
+     * @param string $needle the search string
592
+     * @param mixed $index optional, only search this key name
593
+     * @return mixed the key of the matching field, otherwise false
594
+     * @since 4.5.0
595
+     */
596
+    public static function recursiveArraySearch($haystack, $needle, $index = null) {
597
+        return \OC_Helper::recursiveArraySearch($haystack, $needle, $index);
598
+    }
599
+
600
+    /**
601
+     * calculates the maximum upload size respecting system settings, free space and user quota
602
+     *
603
+     * @param string $dir the current folder where the user currently operates
604
+     * @param int $free the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
605
+     * @return int number of bytes representing
606
+     * @since 5.0.0
607
+     */
608
+    public static function maxUploadFilesize($dir, $free = null) {
609
+        return \OC_Helper::maxUploadFilesize($dir, $free);
610
+    }
611
+
612
+    /**
613
+     * Calculate free space left within user quota
614
+     * @param string $dir the current folder where the user currently operates
615
+     * @return int number of bytes representing
616
+     * @since 7.0.0
617
+     */
618
+    public static function freeSpace($dir) {
619
+        return \OC_Helper::freeSpace($dir);
620
+    }
621
+
622
+    /**
623
+     * Calculate PHP upload limit
624
+     *
625
+     * @return int number of bytes representing
626
+     * @since 7.0.0
627
+     */
628
+    public static function uploadLimit() {
629
+        return \OC_Helper::uploadLimit();
630
+    }
631
+
632
+    /**
633
+     * Returns whether the given file name is valid
634
+     * @param string $file file name to check
635
+     * @return bool true if the file name is valid, false otherwise
636
+     * @deprecated 8.1.0 use \OC\Files\View::verifyPath()
637
+     * @since 7.0.0
638
+     * @suppress PhanDeprecatedFunction
639
+     */
640
+    public static function isValidFileName($file) {
641
+        return \OC_Util::isValidFileName($file);
642
+    }
643
+
644
+    /**
645
+     * Compare two strings to provide a natural sort
646
+     * @param string $a first string to compare
647
+     * @param string $b second string to compare
648
+     * @return int -1 if $b comes before $a, 1 if $a comes before $b
649
+     * or 0 if the strings are identical
650
+     * @since 7.0.0
651
+     */
652
+    public static function naturalSortCompare($a, $b) {
653
+        return \OC\NaturalSort::getInstance()->compare($a, $b);
654
+    }
655
+
656
+    /**
657
+     * check if a password is required for each public link
658
+     * @return boolean
659
+     * @since 7.0.0
660
+     */
661
+    public static function isPublicLinkPasswordRequired() {
662
+        return \OC_Util::isPublicLinkPasswordRequired();
663
+    }
664
+
665
+    /**
666
+     * check if share API enforces a default expire date
667
+     * @return boolean
668
+     * @since 8.0.0
669
+     */
670
+    public static function isDefaultExpireDateEnforced() {
671
+        return \OC_Util::isDefaultExpireDateEnforced();
672
+    }
673
+
674
+    protected static $needUpgradeCache = null;
675
+
676
+    /**
677
+     * Checks whether the current version needs upgrade.
678
+     *
679
+     * @return bool true if upgrade is needed, false otherwise
680
+     * @since 7.0.0
681
+     */
682
+    public static function needUpgrade() {
683
+        if (!isset(self::$needUpgradeCache)) {
684
+            self::$needUpgradeCache=\OC_Util::needUpgrade(\OC::$server->getSystemConfig());
685
+        }		
686
+        return self::$needUpgradeCache;
687
+    }
688 688
 }
Please login to merge, or discard this patch.
Spacing   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -59,11 +59,11 @@  discard block
 block discarded – undo
59 59
  */
60 60
 class Util {
61 61
 	// consts for Logging
62
-	const DEBUG=0;
63
-	const INFO=1;
64
-	const WARN=2;
65
-	const ERROR=3;
66
-	const FATAL=4;
62
+	const DEBUG = 0;
63
+	const INFO = 1;
64
+	const WARN = 2;
65
+	const ERROR = 3;
66
+	const FATAL = 4;
67 67
 
68 68
 	/** \OCP\Share\IManager */
69 69
 	private static $shareManager;
@@ -119,11 +119,11 @@  discard block
 block discarded – undo
119 119
 		$message->setSubject($subject);
120 120
 		$message->setPlainBody($mailtext);
121 121
 		$message->setFrom([$fromaddress => $fromname]);
122
-		if($html === 1) {
122
+		if ($html === 1) {
123 123
 			$message->setHtmlBody($altbody);
124 124
 		}
125 125
 
126
-		if($altbody === '') {
126
+		if ($altbody === '') {
127 127
 			$message->setHtmlBody($mailtext);
128 128
 			$message->setPlainBody('');
129 129
 		} else {
@@ -131,14 +131,14 @@  discard block
 block discarded – undo
131 131
 			$message->setPlainBody($altbody);
132 132
 		}
133 133
 
134
-		if(!empty($ccaddress)) {
135
-			if(!empty($ccname)) {
134
+		if (!empty($ccaddress)) {
135
+			if (!empty($ccname)) {
136 136
 				$message->setCc([$ccaddress => $ccname]);
137 137
 			} else {
138 138
 				$message->setCc([$ccaddress]);
139 139
 			}
140 140
 		}
141
-		if(!empty($bcc)) {
141
+		if (!empty($bcc)) {
142 142
 			$message->setBcc([$bcc]);
143 143
 		}
144 144
 
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
 	 * @since 4.0.0
154 154
 	 * @deprecated 13.0.0 use log of \OCP\ILogger
155 155
 	 */
156
-	public static function writeLog( $app, $message, $level ) {
156
+	public static function writeLog($app, $message, $level) {
157 157
 		$context = ['app' => $app];
158 158
 		\OC::$server->getLogger()->log($level, $message, $context);
159 159
 	}
@@ -166,7 +166,7 @@  discard block
 block discarded – undo
166 166
 	 * @since ....0.0 - parameter $level was added in 7.0.0
167 167
 	 * @deprecated 8.2.0 use logException of \OCP\ILogger
168 168
 	 */
169
-	public static function logException( $app, \Exception $ex, $level = \OCP\Util::FATAL ) {
169
+	public static function logException($app, \Exception $ex, $level = \OCP\Util::FATAL) {
170 170
 		\OC::$server->getLogger()->logException($ex, ['app' => $app]);
171 171
 	}
172 172
 
@@ -207,8 +207,8 @@  discard block
 block discarded – undo
207 207
 	 * @param string $file
208 208
 	 * @since 4.0.0
209 209
 	 */
210
-	public static function addStyle( $application, $file = null ) {
211
-		\OC_Util::addStyle( $application, $file );
210
+	public static function addStyle($application, $file = null) {
211
+		\OC_Util::addStyle($application, $file);
212 212
 	}
213 213
 
214 214
 	/**
@@ -217,8 +217,8 @@  discard block
 block discarded – undo
217 217
 	 * @param string $file
218 218
 	 * @since 4.0.0
219 219
 	 */
220
-	public static function addScript( $application, $file = null ) {
221
-		\OC_Util::addScript( $application, $file );
220
+	public static function addScript($application, $file = null) {
221
+		\OC_Util::addScript($application, $file);
222 222
 	}
223 223
 
224 224
 	/**
@@ -240,7 +240,7 @@  discard block
 block discarded – undo
240 240
 	 * @param string $text the text content for the element
241 241
 	 * @since 4.0.0
242 242
 	 */
243
-	public static function addHeader($tag, $attributes, $text=null) {
243
+	public static function addHeader($tag, $attributes, $text = null) {
244 244
 		\OC_Util::addHeader($tag, $attributes, $text);
245 245
 	}
246 246
 
@@ -264,7 +264,7 @@  discard block
 block discarded – undo
264 264
 	 * @return string the url
265 265
 	 * @since 4.0.0 - parameter $args was added in 4.5.0
266 266
 	 */
267
-	public static function linkToAbsolute( $app, $file, $args = array() ) {
267
+	public static function linkToAbsolute($app, $file, $args = array()) {
268 268
 		$urlGenerator = \OC::$server->getURLGenerator();
269 269
 		return $urlGenerator->getAbsoluteURL(
270 270
 			$urlGenerator->linkTo($app, $file, $args)
@@ -277,11 +277,11 @@  discard block
 block discarded – undo
277 277
 	 * @return string the url
278 278
 	 * @since 4.0.0
279 279
 	 */
280
-	public static function linkToRemote( $service ) {
280
+	public static function linkToRemote($service) {
281 281
 		$urlGenerator = \OC::$server->getURLGenerator();
282
-		$remoteBase = $urlGenerator->linkTo('', 'remote.php') . '/' . $service;
282
+		$remoteBase = $urlGenerator->linkTo('', 'remote.php').'/'.$service;
283 283
 		return $urlGenerator->getAbsoluteURL(
284
-			$remoteBase . (($service[strlen($service) - 1] != '/') ? '/' : '')
284
+			$remoteBase.(($service[strlen($service) - 1] != '/') ? '/' : '')
285 285
 		);
286 286
 	}
287 287
 
@@ -304,7 +304,7 @@  discard block
 block discarded – undo
304 304
 	 * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->linkToRoute($route, $parameters)
305 305
 	 * @since 5.0.0
306 306
 	 */
307
-	public static function linkToRoute( $route, $parameters = array() ) {
307
+	public static function linkToRoute($route, $parameters = array()) {
308 308
 		return \OC::$server->getURLGenerator()->linkToRoute($route, $parameters);
309 309
 	}
310 310
 
@@ -318,7 +318,7 @@  discard block
 block discarded – undo
318 318
 	 * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->linkTo($app, $file, $args)
319 319
 	 * @since 4.0.0 - parameter $args was added in 4.5.0
320 320
 	 */
321
-	public static function linkTo( $app, $file, $args = array() ) {
321
+	public static function linkTo($app, $file, $args = array()) {
322 322
 		return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
323 323
 	}
324 324
 
@@ -417,7 +417,7 @@  discard block
 block discarded – undo
417 417
 	 * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->imagePath($app, $image)
418 418
 	 * @since 4.0.0
419 419
 	 */
420
-	public static function imagePath( $app, $image ) {
420
+	public static function imagePath($app, $image) {
421 421
 		return \OC::$server->getURLGenerator()->imagePath($app, $image);
422 422
 	}
423 423
 
@@ -488,7 +488,7 @@  discard block
 block discarded – undo
488 488
 	 * @since 4.5.0
489 489
 	 */
490 490
 	public static function callRegister() {
491
-		if(self::$token === '') {
491
+		if (self::$token === '') {
492 492
 			self::$token = \OC::$server->getCsrfTokenManager()->getToken()->getEncryptedValue();
493 493
 		}
494 494
 		return self::$token;
@@ -500,7 +500,7 @@  discard block
 block discarded – undo
500 500
 	 * @deprecated 9.0.0 Use annotations based on the app framework.
501 501
 	 */
502 502
 	public static function callCheck() {
503
-		if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
503
+		if (!\OC::$server->getRequest()->passesStrictCookieCheck()) {
504 504
 			header('Location: '.\OC::$WEBROOT);
505 505
 			exit();
506 506
 		}
@@ -681,7 +681,7 @@  discard block
 block discarded – undo
681 681
 	 */
682 682
 	public static function needUpgrade() {
683 683
 		if (!isset(self::$needUpgradeCache)) {
684
-			self::$needUpgradeCache=\OC_Util::needUpgrade(\OC::$server->getSystemConfig());
684
+			self::$needUpgradeCache = \OC_Util::needUpgrade(\OC::$server->getSystemConfig());
685 685
 		}		
686 686
 		return self::$needUpgradeCache;
687 687
 	}
Please login to merge, or discard this patch.
apps/files_external/lib/config.php 2 patches
Indentation   +367 added lines, -367 removed lines patch added patch discarded remove patch
@@ -46,371 +46,371 @@
 block discarded – undo
46 46
  * Class to configure mount.json globally and for users
47 47
  */
48 48
 class OC_Mount_Config {
49
-	// TODO: make this class non-static and give it a proper namespace
50
-
51
-	const MOUNT_TYPE_GLOBAL = 'global';
52
-	const MOUNT_TYPE_GROUP = 'group';
53
-	const MOUNT_TYPE_USER = 'user';
54
-	const MOUNT_TYPE_PERSONAL = 'personal';
55
-
56
-	// whether to skip backend test (for unit tests, as this static class is not mockable)
57
-	public static $skipTest = false;
58
-
59
-	/** @var Application */
60
-	public static $app;
61
-
62
-	/**
63
-	 * @param string $class
64
-	 * @param array $definition
65
-	 * @return bool
66
-	 * @deprecated 8.2.0 use \OCA\Files_External\Service\BackendService::registerBackend()
67
-	 */
68
-	public static function registerBackend($class, $definition) {
69
-		$backendService = self::$app->getContainer()->query('OCA\Files_External\Service\BackendService');
70
-		$auth = self::$app->getContainer()->query('OCA\Files_External\Lib\Auth\Builtin');
71
-
72
-		$backendService->registerBackend(new LegacyBackend($class, $definition, $auth));
73
-
74
-		return true;
75
-	}
76
-
77
-	/**
78
-	 * Returns the mount points for the given user.
79
-	 * The mount point is relative to the data directory.
80
-	 *
81
-	 * @param string $uid user
82
-	 * @return array of mount point string as key, mountpoint config as value
83
-	 *
84
-	 * @deprecated 8.2.0 use UserGlobalStoragesService::getStorages() and UserStoragesService::getStorages()
85
-	 */
86
-	public static function getAbsoluteMountPoints($uid) {
87
-		$mountPoints = array();
88
-
89
-		$userGlobalStoragesService = self::$app->getContainer()->query('OCA\Files_External\Service\UserGlobalStoragesService');
90
-		$userStoragesService = self::$app->getContainer()->query('OCA\Files_External\Service\UserStoragesService');
91
-		$user = self::$app->getContainer()->query('OCP\IUserManager')->get($uid);
92
-
93
-		$userGlobalStoragesService->setUser($user);
94
-		$userStoragesService->setUser($user);
95
-
96
-		foreach ($userGlobalStoragesService->getStorages() as $storage) {
97
-			/** @var \OCA\Files_External\Lib\StorageConfig $storage */
98
-			$mountPoint = '/'.$uid.'/files'.$storage->getMountPoint();
99
-			$mountEntry = self::prepareMountPointEntry($storage, false);
100
-			foreach ($mountEntry['options'] as &$option) {
101
-				$option = self::setUserVars($uid, $option);
102
-			}
103
-			$mountPoints[$mountPoint] = $mountEntry;
104
-		}
105
-
106
-		foreach ($userStoragesService->getStorages() as $storage) {
107
-			$mountPoint = '/'.$uid.'/files'.$storage->getMountPoint();
108
-			$mountEntry = self::prepareMountPointEntry($storage, true);
109
-			foreach ($mountEntry['options'] as &$option) {
110
-				$option = self::setUserVars($uid, $option);
111
-			}
112
-			$mountPoints[$mountPoint] = $mountEntry;
113
-		}
114
-
115
-		$userGlobalStoragesService->resetUser();
116
-		$userStoragesService->resetUser();
117
-
118
-		return $mountPoints;
119
-	}
120
-
121
-	/**
122
-	 * Get the system mount points
123
-	 *
124
-	 * @return array
125
-	 *
126
-	 * @deprecated 8.2.0 use GlobalStoragesService::getStorages()
127
-	 */
128
-	public static function getSystemMountPoints() {
129
-		$mountPoints = [];
130
-		$service = self::$app->getContainer()->query('OCA\Files_External\Service\GlobalStoragesService');
131
-
132
-		foreach ($service->getStorages() as $storage) {
133
-			$mountPoints[] = self::prepareMountPointEntry($storage, false);
134
-		}
135
-
136
-		return $mountPoints;
137
-	}
138
-
139
-	/**
140
-	 * Get the personal mount points of the current user
141
-	 *
142
-	 * @return array
143
-	 *
144
-	 * @deprecated 8.2.0 use UserStoragesService::getStorages()
145
-	 */
146
-	public static function getPersonalMountPoints() {
147
-		$mountPoints = [];
148
-		$service = self::$app->getContainer()->query('OCA\Files_External\Service\UserStoragesService');
149
-
150
-		foreach ($service->getStorages() as $storage) {
151
-			$mountPoints[] = self::prepareMountPointEntry($storage, true);
152
-		}
153
-
154
-		return $mountPoints;
155
-	}
156
-
157
-	/**
158
-	 * Convert a StorageConfig to the legacy mountPoints array format
159
-	 * There's a lot of extra information in here, to satisfy all of the legacy functions
160
-	 *
161
-	 * @param StorageConfig $storage
162
-	 * @param bool $isPersonal
163
-	 * @return array
164
-	 */
165
-	private static function prepareMountPointEntry(StorageConfig $storage, $isPersonal) {
166
-		$mountEntry = [];
167
-
168
-		$mountEntry['mountpoint'] = substr($storage->getMountPoint(), 1); // remove leading slash
169
-		$mountEntry['class'] = $storage->getBackend()->getIdentifier();
170
-		$mountEntry['backend'] = $storage->getBackend()->getText();
171
-		$mountEntry['authMechanism'] = $storage->getAuthMechanism()->getIdentifier();
172
-		$mountEntry['personal'] = $isPersonal;
173
-		$mountEntry['options'] = self::decryptPasswords($storage->getBackendOptions());
174
-		$mountEntry['mountOptions'] = $storage->getMountOptions();
175
-		$mountEntry['priority'] = $storage->getPriority();
176
-		$mountEntry['applicable'] = [
177
-			'groups' => $storage->getApplicableGroups(),
178
-			'users' => $storage->getApplicableUsers(),
179
-		];
180
-		// if mountpoint is applicable to all users the old API expects ['all']
181
-		if (empty($mountEntry['applicable']['groups']) && empty($mountEntry['applicable']['users'])) {
182
-			$mountEntry['applicable']['users'] = ['all'];
183
-		}
184
-
185
-		$mountEntry['id'] = $storage->getId();
186
-
187
-		return $mountEntry;
188
-	}
189
-
190
-	/**
191
-	 * fill in the correct values for $user
192
-	 *
193
-	 * @param string $user user value
194
-	 * @param string|array $input
195
-	 * @return string
196
-	 */
197
-	public static function setUserVars($user, $input) {
198
-		if (is_array($input)) {
199
-			foreach ($input as &$value) {
200
-				if (is_string($value)) {
201
-					$value = str_replace('$user', $user, $value);
202
-				}
203
-			}
204
-		} else {
205
-			if (is_string($input)) {
206
-				$input = str_replace('$user', $user, $input);
207
-			}
208
-		}
209
-		return $input;
210
-	}
211
-
212
-	/**
213
-	 * Test connecting using the given backend configuration
214
-	 *
215
-	 * @param string $class backend class name
216
-	 * @param array $options backend configuration options
217
-	 * @param boolean $isPersonal
218
-	 * @return int see self::STATUS_*
219
-	 * @throws Exception
220
-	 */
221
-	public static function getBackendStatus($class, $options, $isPersonal, $testOnly = true) {
222
-		if (self::$skipTest) {
223
-			return StorageNotAvailableException::STATUS_SUCCESS;
224
-		}
225
-		foreach ($options as &$option) {
226
-			$option = self::setUserVars(OCP\User::getUser(), $option);
227
-		}
228
-		if (class_exists($class)) {
229
-			try {
230
-				/** @var \OC\Files\Storage\Common $storage */
231
-				$storage = new $class($options);
232
-
233
-				try {
234
-					$result = $storage->test($isPersonal, $testOnly);
235
-					$storage->setAvailability($result);
236
-					if ($result) {
237
-						return StorageNotAvailableException::STATUS_SUCCESS;
238
-					}
239
-				} catch (\Exception $e) {
240
-					$storage->setAvailability(false);
241
-					throw $e;
242
-				}
243
-			} catch (Exception $exception) {
244
-				\OCP\Util::logException('files_external', $exception);
245
-				throw $exception;
246
-			}
247
-		}
248
-		return StorageNotAvailableException::STATUS_ERROR;
249
-	}
250
-
251
-	/**
252
-	 * Read the mount points in the config file into an array
253
-	 *
254
-	 * @param string|null $user If not null, personal for $user, otherwise system
255
-	 * @return array
256
-	 */
257
-	public static function readData($user = null) {
258
-		if (isset($user)) {
259
-			$jsonFile = \OC::$server->getUserManager()->get($user)->getHome() . '/mount.json';
260
-		} else {
261
-			$config = \OC::$server->getConfig();
262
-			$datadir = $config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data/');
263
-			$jsonFile = $config->getSystemValue('mount_file', $datadir . '/mount.json');
264
-		}
265
-		if (is_file($jsonFile)) {
266
-			$mountPoints = json_decode(file_get_contents($jsonFile), true);
267
-			if (is_array($mountPoints)) {
268
-				return $mountPoints;
269
-			}
270
-		}
271
-		return array();
272
-	}
273
-
274
-	/**
275
-	 * Get backend dependency message
276
-	 * TODO: move into AppFramework along with templates
277
-	 *
278
-	 * @param Backend[] $backends
279
-	 * @return string
280
-	 */
281
-	public static function dependencyMessage($backends) {
282
-		$l = \OC::$server->getL10N('files_external');
283
-		$message = '';
284
-		$dependencyGroups = [];
285
-
286
-		foreach ($backends as $backend) {
287
-			foreach ($backend->checkDependencies() as $dependency) {
288
-				if ($message = $dependency->getMessage()) {
289
-					$message .= '<p>' . $message . '</p>';
290
-				} else {
291
-					$dependencyGroups[$dependency->getDependency()][] = $backend;
292
-				}
293
-			}
294
-		}
295
-
296
-		foreach ($dependencyGroups as $module => $dependants) {
297
-			$backends = implode(', ', array_map(function($backend) {
298
-				return '"' . $backend->getText() . '"';
299
-			}, $dependants));
300
-			$message .= '<p>' . OC_Mount_Config::getSingleDependencyMessage($l, $module, $backends) . '</p>';
301
-		}
302
-
303
-		return $message;
304
-	}
305
-
306
-	/**
307
-	 * Returns a dependency missing message
308
-	 *
309
-	 * @param \OCP\IL10N $l
310
-	 * @param string $module
311
-	 * @param string $backend
312
-	 * @return string
313
-	 */
314
-	private static function getSingleDependencyMessage(\OCP\IL10N $l, $module, $backend) {
315
-		switch (strtolower($module)) {
316
-			case 'curl':
317
-				return (string)$l->t('The cURL support in PHP is not enabled or installed. Mounting of %s is not possible. Please ask your system administrator to install it.', [$backend]);
318
-			case 'ftp':
319
-				return (string)$l->t('The FTP support in PHP is not enabled or installed. Mounting of %s is not possible. Please ask your system administrator to install it.', [$backend]);
320
-			default:
321
-				return (string)$l->t('"%s" is not installed. Mounting of %s is not possible. Please ask your system administrator to install it.', [$module, $backend]);
322
-		}
323
-	}
324
-
325
-	/**
326
-	 * Encrypt passwords in the given config options
327
-	 *
328
-	 * @param array $options mount options
329
-	 * @return array updated options
330
-	 */
331
-	public static function encryptPasswords($options) {
332
-		if (isset($options['password'])) {
333
-			$options['password_encrypted'] = self::encryptPassword($options['password']);
334
-			// do not unset the password, we want to keep the keys order
335
-			// on load... because that's how the UI currently works
336
-			$options['password'] = '';
337
-		}
338
-		return $options;
339
-	}
340
-
341
-	/**
342
-	 * Decrypt passwords in the given config options
343
-	 *
344
-	 * @param array $options mount options
345
-	 * @return array updated options
346
-	 */
347
-	public static function decryptPasswords($options) {
348
-		// note: legacy options might still have the unencrypted password in the "password" field
349
-		if (isset($options['password_encrypted'])) {
350
-			$options['password'] = self::decryptPassword($options['password_encrypted']);
351
-			unset($options['password_encrypted']);
352
-		}
353
-		return $options;
354
-	}
355
-
356
-	/**
357
-	 * Encrypt a single password
358
-	 *
359
-	 * @param string $password plain text password
360
-	 * @return string encrypted password
361
-	 */
362
-	private static function encryptPassword($password) {
363
-		$cipher = self::getCipher();
364
-		$iv = \OC::$server->getSecureRandom()->generate(16);
365
-		$cipher->setIV($iv);
366
-		return base64_encode($iv . $cipher->encrypt($password));
367
-	}
368
-
369
-	/**
370
-	 * Decrypts a single password
371
-	 *
372
-	 * @param string $encryptedPassword encrypted password
373
-	 * @return string plain text password
374
-	 */
375
-	private static function decryptPassword($encryptedPassword) {
376
-		$cipher = self::getCipher();
377
-		$binaryPassword = base64_decode($encryptedPassword);
378
-		$iv = substr($binaryPassword, 0, 16);
379
-		$cipher->setIV($iv);
380
-		$binaryPassword = substr($binaryPassword, 16);
381
-		return $cipher->decrypt($binaryPassword);
382
-	}
383
-
384
-	/**
385
-	 * Returns the encryption cipher
386
-	 *
387
-	 * @return AES
388
-	 */
389
-	private static function getCipher() {
390
-		$cipher = new AES(AES::MODE_CBC);
391
-		$cipher->setKey(\OC::$server->getConfig()->getSystemValue('passwordsalt', null));
392
-		return $cipher;
393
-	}
394
-
395
-	/**
396
-	 * Computes a hash based on the given configuration.
397
-	 * This is mostly used to find out whether configurations
398
-	 * are the same.
399
-	 *
400
-	 * @param array $config
401
-	 * @return string
402
-	 */
403
-	public static function makeConfigHash($config) {
404
-		$data = json_encode(
405
-			array(
406
-				'c' => $config['backend'],
407
-				'a' => $config['authMechanism'],
408
-				'm' => $config['mountpoint'],
409
-				'o' => $config['options'],
410
-				'p' => isset($config['priority']) ? $config['priority'] : -1,
411
-				'mo' => isset($config['mountOptions']) ? $config['mountOptions'] : [],
412
-			)
413
-		);
414
-		return hash('md5', $data);
415
-	}
49
+    // TODO: make this class non-static and give it a proper namespace
50
+
51
+    const MOUNT_TYPE_GLOBAL = 'global';
52
+    const MOUNT_TYPE_GROUP = 'group';
53
+    const MOUNT_TYPE_USER = 'user';
54
+    const MOUNT_TYPE_PERSONAL = 'personal';
55
+
56
+    // whether to skip backend test (for unit tests, as this static class is not mockable)
57
+    public static $skipTest = false;
58
+
59
+    /** @var Application */
60
+    public static $app;
61
+
62
+    /**
63
+     * @param string $class
64
+     * @param array $definition
65
+     * @return bool
66
+     * @deprecated 8.2.0 use \OCA\Files_External\Service\BackendService::registerBackend()
67
+     */
68
+    public static function registerBackend($class, $definition) {
69
+        $backendService = self::$app->getContainer()->query('OCA\Files_External\Service\BackendService');
70
+        $auth = self::$app->getContainer()->query('OCA\Files_External\Lib\Auth\Builtin');
71
+
72
+        $backendService->registerBackend(new LegacyBackend($class, $definition, $auth));
73
+
74
+        return true;
75
+    }
76
+
77
+    /**
78
+     * Returns the mount points for the given user.
79
+     * The mount point is relative to the data directory.
80
+     *
81
+     * @param string $uid user
82
+     * @return array of mount point string as key, mountpoint config as value
83
+     *
84
+     * @deprecated 8.2.0 use UserGlobalStoragesService::getStorages() and UserStoragesService::getStorages()
85
+     */
86
+    public static function getAbsoluteMountPoints($uid) {
87
+        $mountPoints = array();
88
+
89
+        $userGlobalStoragesService = self::$app->getContainer()->query('OCA\Files_External\Service\UserGlobalStoragesService');
90
+        $userStoragesService = self::$app->getContainer()->query('OCA\Files_External\Service\UserStoragesService');
91
+        $user = self::$app->getContainer()->query('OCP\IUserManager')->get($uid);
92
+
93
+        $userGlobalStoragesService->setUser($user);
94
+        $userStoragesService->setUser($user);
95
+
96
+        foreach ($userGlobalStoragesService->getStorages() as $storage) {
97
+            /** @var \OCA\Files_External\Lib\StorageConfig $storage */
98
+            $mountPoint = '/'.$uid.'/files'.$storage->getMountPoint();
99
+            $mountEntry = self::prepareMountPointEntry($storage, false);
100
+            foreach ($mountEntry['options'] as &$option) {
101
+                $option = self::setUserVars($uid, $option);
102
+            }
103
+            $mountPoints[$mountPoint] = $mountEntry;
104
+        }
105
+
106
+        foreach ($userStoragesService->getStorages() as $storage) {
107
+            $mountPoint = '/'.$uid.'/files'.$storage->getMountPoint();
108
+            $mountEntry = self::prepareMountPointEntry($storage, true);
109
+            foreach ($mountEntry['options'] as &$option) {
110
+                $option = self::setUserVars($uid, $option);
111
+            }
112
+            $mountPoints[$mountPoint] = $mountEntry;
113
+        }
114
+
115
+        $userGlobalStoragesService->resetUser();
116
+        $userStoragesService->resetUser();
117
+
118
+        return $mountPoints;
119
+    }
120
+
121
+    /**
122
+     * Get the system mount points
123
+     *
124
+     * @return array
125
+     *
126
+     * @deprecated 8.2.0 use GlobalStoragesService::getStorages()
127
+     */
128
+    public static function getSystemMountPoints() {
129
+        $mountPoints = [];
130
+        $service = self::$app->getContainer()->query('OCA\Files_External\Service\GlobalStoragesService');
131
+
132
+        foreach ($service->getStorages() as $storage) {
133
+            $mountPoints[] = self::prepareMountPointEntry($storage, false);
134
+        }
135
+
136
+        return $mountPoints;
137
+    }
138
+
139
+    /**
140
+     * Get the personal mount points of the current user
141
+     *
142
+     * @return array
143
+     *
144
+     * @deprecated 8.2.0 use UserStoragesService::getStorages()
145
+     */
146
+    public static function getPersonalMountPoints() {
147
+        $mountPoints = [];
148
+        $service = self::$app->getContainer()->query('OCA\Files_External\Service\UserStoragesService');
149
+
150
+        foreach ($service->getStorages() as $storage) {
151
+            $mountPoints[] = self::prepareMountPointEntry($storage, true);
152
+        }
153
+
154
+        return $mountPoints;
155
+    }
156
+
157
+    /**
158
+     * Convert a StorageConfig to the legacy mountPoints array format
159
+     * There's a lot of extra information in here, to satisfy all of the legacy functions
160
+     *
161
+     * @param StorageConfig $storage
162
+     * @param bool $isPersonal
163
+     * @return array
164
+     */
165
+    private static function prepareMountPointEntry(StorageConfig $storage, $isPersonal) {
166
+        $mountEntry = [];
167
+
168
+        $mountEntry['mountpoint'] = substr($storage->getMountPoint(), 1); // remove leading slash
169
+        $mountEntry['class'] = $storage->getBackend()->getIdentifier();
170
+        $mountEntry['backend'] = $storage->getBackend()->getText();
171
+        $mountEntry['authMechanism'] = $storage->getAuthMechanism()->getIdentifier();
172
+        $mountEntry['personal'] = $isPersonal;
173
+        $mountEntry['options'] = self::decryptPasswords($storage->getBackendOptions());
174
+        $mountEntry['mountOptions'] = $storage->getMountOptions();
175
+        $mountEntry['priority'] = $storage->getPriority();
176
+        $mountEntry['applicable'] = [
177
+            'groups' => $storage->getApplicableGroups(),
178
+            'users' => $storage->getApplicableUsers(),
179
+        ];
180
+        // if mountpoint is applicable to all users the old API expects ['all']
181
+        if (empty($mountEntry['applicable']['groups']) && empty($mountEntry['applicable']['users'])) {
182
+            $mountEntry['applicable']['users'] = ['all'];
183
+        }
184
+
185
+        $mountEntry['id'] = $storage->getId();
186
+
187
+        return $mountEntry;
188
+    }
189
+
190
+    /**
191
+     * fill in the correct values for $user
192
+     *
193
+     * @param string $user user value
194
+     * @param string|array $input
195
+     * @return string
196
+     */
197
+    public static function setUserVars($user, $input) {
198
+        if (is_array($input)) {
199
+            foreach ($input as &$value) {
200
+                if (is_string($value)) {
201
+                    $value = str_replace('$user', $user, $value);
202
+                }
203
+            }
204
+        } else {
205
+            if (is_string($input)) {
206
+                $input = str_replace('$user', $user, $input);
207
+            }
208
+        }
209
+        return $input;
210
+    }
211
+
212
+    /**
213
+     * Test connecting using the given backend configuration
214
+     *
215
+     * @param string $class backend class name
216
+     * @param array $options backend configuration options
217
+     * @param boolean $isPersonal
218
+     * @return int see self::STATUS_*
219
+     * @throws Exception
220
+     */
221
+    public static function getBackendStatus($class, $options, $isPersonal, $testOnly = true) {
222
+        if (self::$skipTest) {
223
+            return StorageNotAvailableException::STATUS_SUCCESS;
224
+        }
225
+        foreach ($options as &$option) {
226
+            $option = self::setUserVars(OCP\User::getUser(), $option);
227
+        }
228
+        if (class_exists($class)) {
229
+            try {
230
+                /** @var \OC\Files\Storage\Common $storage */
231
+                $storage = new $class($options);
232
+
233
+                try {
234
+                    $result = $storage->test($isPersonal, $testOnly);
235
+                    $storage->setAvailability($result);
236
+                    if ($result) {
237
+                        return StorageNotAvailableException::STATUS_SUCCESS;
238
+                    }
239
+                } catch (\Exception $e) {
240
+                    $storage->setAvailability(false);
241
+                    throw $e;
242
+                }
243
+            } catch (Exception $exception) {
244
+                \OCP\Util::logException('files_external', $exception);
245
+                throw $exception;
246
+            }
247
+        }
248
+        return StorageNotAvailableException::STATUS_ERROR;
249
+    }
250
+
251
+    /**
252
+     * Read the mount points in the config file into an array
253
+     *
254
+     * @param string|null $user If not null, personal for $user, otherwise system
255
+     * @return array
256
+     */
257
+    public static function readData($user = null) {
258
+        if (isset($user)) {
259
+            $jsonFile = \OC::$server->getUserManager()->get($user)->getHome() . '/mount.json';
260
+        } else {
261
+            $config = \OC::$server->getConfig();
262
+            $datadir = $config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data/');
263
+            $jsonFile = $config->getSystemValue('mount_file', $datadir . '/mount.json');
264
+        }
265
+        if (is_file($jsonFile)) {
266
+            $mountPoints = json_decode(file_get_contents($jsonFile), true);
267
+            if (is_array($mountPoints)) {
268
+                return $mountPoints;
269
+            }
270
+        }
271
+        return array();
272
+    }
273
+
274
+    /**
275
+     * Get backend dependency message
276
+     * TODO: move into AppFramework along with templates
277
+     *
278
+     * @param Backend[] $backends
279
+     * @return string
280
+     */
281
+    public static function dependencyMessage($backends) {
282
+        $l = \OC::$server->getL10N('files_external');
283
+        $message = '';
284
+        $dependencyGroups = [];
285
+
286
+        foreach ($backends as $backend) {
287
+            foreach ($backend->checkDependencies() as $dependency) {
288
+                if ($message = $dependency->getMessage()) {
289
+                    $message .= '<p>' . $message . '</p>';
290
+                } else {
291
+                    $dependencyGroups[$dependency->getDependency()][] = $backend;
292
+                }
293
+            }
294
+        }
295
+
296
+        foreach ($dependencyGroups as $module => $dependants) {
297
+            $backends = implode(', ', array_map(function($backend) {
298
+                return '"' . $backend->getText() . '"';
299
+            }, $dependants));
300
+            $message .= '<p>' . OC_Mount_Config::getSingleDependencyMessage($l, $module, $backends) . '</p>';
301
+        }
302
+
303
+        return $message;
304
+    }
305
+
306
+    /**
307
+     * Returns a dependency missing message
308
+     *
309
+     * @param \OCP\IL10N $l
310
+     * @param string $module
311
+     * @param string $backend
312
+     * @return string
313
+     */
314
+    private static function getSingleDependencyMessage(\OCP\IL10N $l, $module, $backend) {
315
+        switch (strtolower($module)) {
316
+            case 'curl':
317
+                return (string)$l->t('The cURL support in PHP is not enabled or installed. Mounting of %s is not possible. Please ask your system administrator to install it.', [$backend]);
318
+            case 'ftp':
319
+                return (string)$l->t('The FTP support in PHP is not enabled or installed. Mounting of %s is not possible. Please ask your system administrator to install it.', [$backend]);
320
+            default:
321
+                return (string)$l->t('"%s" is not installed. Mounting of %s is not possible. Please ask your system administrator to install it.', [$module, $backend]);
322
+        }
323
+    }
324
+
325
+    /**
326
+     * Encrypt passwords in the given config options
327
+     *
328
+     * @param array $options mount options
329
+     * @return array updated options
330
+     */
331
+    public static function encryptPasswords($options) {
332
+        if (isset($options['password'])) {
333
+            $options['password_encrypted'] = self::encryptPassword($options['password']);
334
+            // do not unset the password, we want to keep the keys order
335
+            // on load... because that's how the UI currently works
336
+            $options['password'] = '';
337
+        }
338
+        return $options;
339
+    }
340
+
341
+    /**
342
+     * Decrypt passwords in the given config options
343
+     *
344
+     * @param array $options mount options
345
+     * @return array updated options
346
+     */
347
+    public static function decryptPasswords($options) {
348
+        // note: legacy options might still have the unencrypted password in the "password" field
349
+        if (isset($options['password_encrypted'])) {
350
+            $options['password'] = self::decryptPassword($options['password_encrypted']);
351
+            unset($options['password_encrypted']);
352
+        }
353
+        return $options;
354
+    }
355
+
356
+    /**
357
+     * Encrypt a single password
358
+     *
359
+     * @param string $password plain text password
360
+     * @return string encrypted password
361
+     */
362
+    private static function encryptPassword($password) {
363
+        $cipher = self::getCipher();
364
+        $iv = \OC::$server->getSecureRandom()->generate(16);
365
+        $cipher->setIV($iv);
366
+        return base64_encode($iv . $cipher->encrypt($password));
367
+    }
368
+
369
+    /**
370
+     * Decrypts a single password
371
+     *
372
+     * @param string $encryptedPassword encrypted password
373
+     * @return string plain text password
374
+     */
375
+    private static function decryptPassword($encryptedPassword) {
376
+        $cipher = self::getCipher();
377
+        $binaryPassword = base64_decode($encryptedPassword);
378
+        $iv = substr($binaryPassword, 0, 16);
379
+        $cipher->setIV($iv);
380
+        $binaryPassword = substr($binaryPassword, 16);
381
+        return $cipher->decrypt($binaryPassword);
382
+    }
383
+
384
+    /**
385
+     * Returns the encryption cipher
386
+     *
387
+     * @return AES
388
+     */
389
+    private static function getCipher() {
390
+        $cipher = new AES(AES::MODE_CBC);
391
+        $cipher->setKey(\OC::$server->getConfig()->getSystemValue('passwordsalt', null));
392
+        return $cipher;
393
+    }
394
+
395
+    /**
396
+     * Computes a hash based on the given configuration.
397
+     * This is mostly used to find out whether configurations
398
+     * are the same.
399
+     *
400
+     * @param array $config
401
+     * @return string
402
+     */
403
+    public static function makeConfigHash($config) {
404
+        $data = json_encode(
405
+            array(
406
+                'c' => $config['backend'],
407
+                'a' => $config['authMechanism'],
408
+                'm' => $config['mountpoint'],
409
+                'o' => $config['options'],
410
+                'p' => isset($config['priority']) ? $config['priority'] : -1,
411
+                'mo' => isset($config['mountOptions']) ? $config['mountOptions'] : [],
412
+            )
413
+        );
414
+        return hash('md5', $data);
415
+    }
416 416
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -256,11 +256,11 @@  discard block
 block discarded – undo
256 256
 	 */
257 257
 	public static function readData($user = null) {
258 258
 		if (isset($user)) {
259
-			$jsonFile = \OC::$server->getUserManager()->get($user)->getHome() . '/mount.json';
259
+			$jsonFile = \OC::$server->getUserManager()->get($user)->getHome().'/mount.json';
260 260
 		} else {
261 261
 			$config = \OC::$server->getConfig();
262
-			$datadir = $config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data/');
263
-			$jsonFile = $config->getSystemValue('mount_file', $datadir . '/mount.json');
262
+			$datadir = $config->getSystemValue('datadirectory', \OC::$SERVERROOT.'/data/');
263
+			$jsonFile = $config->getSystemValue('mount_file', $datadir.'/mount.json');
264 264
 		}
265 265
 		if (is_file($jsonFile)) {
266 266
 			$mountPoints = json_decode(file_get_contents($jsonFile), true);
@@ -286,7 +286,7 @@  discard block
 block discarded – undo
286 286
 		foreach ($backends as $backend) {
287 287
 			foreach ($backend->checkDependencies() as $dependency) {
288 288
 				if ($message = $dependency->getMessage()) {
289
-					$message .= '<p>' . $message . '</p>';
289
+					$message .= '<p>'.$message.'</p>';
290 290
 				} else {
291 291
 					$dependencyGroups[$dependency->getDependency()][] = $backend;
292 292
 				}
@@ -295,9 +295,9 @@  discard block
 block discarded – undo
295 295
 
296 296
 		foreach ($dependencyGroups as $module => $dependants) {
297 297
 			$backends = implode(', ', array_map(function($backend) {
298
-				return '"' . $backend->getText() . '"';
298
+				return '"'.$backend->getText().'"';
299 299
 			}, $dependants));
300
-			$message .= '<p>' . OC_Mount_Config::getSingleDependencyMessage($l, $module, $backends) . '</p>';
300
+			$message .= '<p>'.OC_Mount_Config::getSingleDependencyMessage($l, $module, $backends).'</p>';
301 301
 		}
302 302
 
303 303
 		return $message;
@@ -314,11 +314,11 @@  discard block
 block discarded – undo
314 314
 	private static function getSingleDependencyMessage(\OCP\IL10N $l, $module, $backend) {
315 315
 		switch (strtolower($module)) {
316 316
 			case 'curl':
317
-				return (string)$l->t('The cURL support in PHP is not enabled or installed. Mounting of %s is not possible. Please ask your system administrator to install it.', [$backend]);
317
+				return (string) $l->t('The cURL support in PHP is not enabled or installed. Mounting of %s is not possible. Please ask your system administrator to install it.', [$backend]);
318 318
 			case 'ftp':
319
-				return (string)$l->t('The FTP support in PHP is not enabled or installed. Mounting of %s is not possible. Please ask your system administrator to install it.', [$backend]);
319
+				return (string) $l->t('The FTP support in PHP is not enabled or installed. Mounting of %s is not possible. Please ask your system administrator to install it.', [$backend]);
320 320
 			default:
321
-				return (string)$l->t('"%s" is not installed. Mounting of %s is not possible. Please ask your system administrator to install it.', [$module, $backend]);
321
+				return (string) $l->t('"%s" is not installed. Mounting of %s is not possible. Please ask your system administrator to install it.', [$module, $backend]);
322 322
 		}
323 323
 	}
324 324
 
@@ -363,7 +363,7 @@  discard block
 block discarded – undo
363 363
 		$cipher = self::getCipher();
364 364
 		$iv = \OC::$server->getSecureRandom()->generate(16);
365 365
 		$cipher->setIV($iv);
366
-		return base64_encode($iv . $cipher->encrypt($password));
366
+		return base64_encode($iv.$cipher->encrypt($password));
367 367
 	}
368 368
 
369 369
 	/**
Please login to merge, or discard this patch.