Completed
Push — master ( 43b569...fd5663 )
by
unknown
41:16 queued 28:28
created

Util::isEmptyString()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author Arthur Schiwon <[email protected]>
4
 * @author Bart Visscher <[email protected]>
5
 * @author Björn Schießle <[email protected]>
6
 * @author Frank Karlitschek <[email protected]>
7
 * @author Georg Ehrke <[email protected]>
8
 * @author Individual IT Services <[email protected]>
9
 * @author Jens-Christian Fischer <[email protected]>
10
 * @author Joas Schilling <[email protected]>
11
 * @author Lukas Reschke <[email protected]>
12
 * @author Michael Gapczynski <[email protected]>
13
 * @author Morris Jobke <[email protected]>
14
 * @author Nicolas Grekas <[email protected]>
15
 * @author Pellaeon Lin <[email protected]>
16
 * @author Randolph Carter <[email protected]>
17
 * @author Robin Appelman <[email protected]>
18
 * @author Robin McCorkell <[email protected]>
19
 * @author Roeland Jago Douma <[email protected]>
20
 * @author Stefan Herbrechtsmeier <[email protected]>
21
 * @author Thomas Müller <[email protected]>
22
 * @author Thomas Tanghus <[email protected]>
23
 * @author Victor Dubiniuk <[email protected]>
24
 * @author Vincent Petry <[email protected]>
25
 *
26
 * @copyright Copyright (c) 2018, ownCloud GmbH
27
 * @license AGPL-3.0
28
 *
29
 * This code is free software: you can redistribute it and/or modify
30
 * it under the terms of the GNU Affero General Public License, version 3,
31
 * as published by the Free Software Foundation.
32
 *
33
 * This program is distributed in the hope that it will be useful,
34
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
35
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
36
 * GNU Affero General Public License for more details.
37
 *
38
 * You should have received a copy of the GNU Affero General Public License, version 3,
39
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
40
 *
41
 */
42
43
/**
44
 * Public interface of ownCloud for apps to use.
45
 * Utility Class.
46
 *
47
 */
48
49
// use OCP namespace for all classes that are considered public.
50
// This means that they should be used by apps instead of the internal ownCloud classes
51
namespace OCP;
52
use DateTimeZone;
53
54
/**
55
 * This class provides different helper functions to make the life of a developer easier
56
 * @since 4.0.0
57
 */
58
class Util {
59
	// consts for Logging
60
	const DEBUG=0;
61
	const INFO=1;
62
	const WARN=2;
63
	const ERROR=3;
64
	const FATAL=4;
65
66
	/** \OCP\Share\IManager */
67
	private static $shareManager;
68
69
	/**
70
	 * get the current installed version of ownCloud
71
	 * @return array
72
	 * @since 4.0.0
73
	 */
74
	public static function getVersion() {
75
		return(\OC_Util::getVersion());
76
	}
77
	
78
	/**
79
	 * Set current update channel
80
	 * @param string $channel
81
	 * @since 8.1.0
82
	 */
83
	public static function setChannel($channel) {
84
		//Flush timestamp to reload version.php
85
		\OC::$server->getSession()->set('OC_Version_Timestamp', 0);
86
		\OC::$server->getAppConfig()->setValue('core', 'OC_Channel', $channel);
87
	}
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
	 */
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) {
0 ignored issues
show
Unused Code introduced by
The parameter $level is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
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
		$userSession = \OC::$server->getUserSession();
185
		// session is null while installing OC
186
		if ($userSession !== null) {
187
			$user = $userSession->getUser();
188
			if ($user !== null) {
189
				$user = $user->getUID();
190
			}
191
		} else {
192
			$user = null;
193
		}
194
195
		return self::$shareManager->sharingDisabledForUser($user);
196
	}
197
198
	/**
199
	 * get l10n object
200
	 * @param string $application
201
	 * @param string|null $language
202
	 * @return \OCP\IL10N
203
	 * @since 6.0.0 - parameter $language was added in 8.0.0
204
	 */
205
	public static function getL10N($application, $language = null) {
206
		return \OC::$server->getL10N($application, $language);
207
	}
208
209
	/**
210
	 * add a css file
211
	 * @param string $application
212
	 * @param string $file
213
	 * @since 4.0.0
214
	 */
215
	public static function addStyle($application, $file = null) {
216
		\OC_Util::addStyle($application, $file);
217
	}
218
219
	/**
220
	 * add a javascript file
221
	 * @param string $application
222
	 * @param string $file
223
	 * @since 4.0.0
224
	 */
225
	public static function addScript($application, $file = null) {
226
		\OC_Util::addScript($application, $file);
227
	}
228
229
	/**
230
	 * Add a translation JS file
231
	 * @param string $application application id
232
	 * @param string $languageCode language code, defaults to the current locale
233
	 * @since 8.0.0
234
	 */
235
	public static function addTranslations($application, $languageCode = null) {
236
		\OC_Util::addTranslations($application, $languageCode);
237
	}
238
239
	/**
240
	 * Add a custom element to the header
241
	 * If $text is null then the element will be written as empty element.
242
	 * So use "" to get a closing tag.
243
	 * @param string $tag tag name of the element
244
	 * @param array $attributes array of attributes for the element
245
	 * @param string $text the text content for the element
246
	 * @since 4.0.0
247
	 */
248
	public static function addHeader($tag, $attributes, $text=null) {
249
		\OC_Util::addHeader($tag, $attributes, $text);
250
	}
251
252
	/**
253
	 * formats a timestamp in the "right" way
254
	 * @param int $timestamp $timestamp
255
	 * @param bool $dateOnly option to omit time from the result
256
	 * @param DateTimeZone|string $timeZone where the given timestamp shall be converted to
257
	 * @return string timestamp
258
	 *
259
	 * @deprecated 8.0.0 Use \OC::$server->query('DateTimeFormatter') instead
260
	 * @since 4.0.0
261
	 */
262
	public static function formatDate($timestamp, $dateOnly=false, $timeZone = null) {
263
		return(\OC_Util::formatDate($timestamp, $dateOnly, $timeZone));
264
	}
265
266
	/**
267
	 * check if some encrypted files are stored
268
	 * @return bool
269
	 *
270
	 * @deprecated 8.1.0 No longer required
271
	 * @since 6.0.0
272
	 */
273
	public static function encryptedFiles() {
274
		return false;
275
	}
276
277
	/**
278
	 * Creates an absolute url to the given app and file.
279
	 * @param string $app app
280
	 * @param string $file file
281
	 * @param array $args array with param=>value, will be appended to the returned url
282
	 * 	The value of $args will be urlencoded
283
	 * @return string the url
284
	 * @since 4.0.0 - parameter $args was added in 4.5.0
285
	 */
286
	public static function linkToAbsolute($app, $file, $args = []) {
287
		$urlGenerator = \OC::$server->getURLGenerator();
288
		return $urlGenerator->getAbsoluteURL(
289
			$urlGenerator->linkTo($app, $file, $args)
290
		);
291
	}
292
293
	/**
294
	 * Creates an absolute url for remote use.
295
	 * @param string $service id
296
	 * @return string the url
297
	 * @since 4.0.0
298
	 */
299
	public static function linkToRemote($service) {
300
		$urlGenerator = \OC::$server->getURLGenerator();
301
		$remoteBase = $urlGenerator->linkTo('', 'remote.php') . '/' . $service;
302
		return $urlGenerator->getAbsoluteURL(
303
			$remoteBase . (($service[\strlen($service) - 1] != '/') ? '/' : '')
304
		);
305
	}
306
307
	/**
308
	 * Creates an absolute url for public use
309
	 * @param string $service id
310
	 * @return string the url
311
	 * @since 4.5.0
312
	 */
313
	public static function linkToPublic($service) {
314
		return \OC_Helper::linkToPublic($service);
315
	}
316
317
	/**
318
	 * Creates an url using a defined route
319
	 * @param string $route
320
	 * @param array $parameters
321
	 * @internal param array $args with param=>value, will be appended to the returned url
322
	 * @return string the url
323
	 * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->linkToRoute($route, $parameters)
324
	 * @since 5.0.0
325
	 */
326
	public static function linkToRoute($route, $parameters = []) {
327
		return \OC::$server->getURLGenerator()->linkToRoute($route, $parameters);
328
	}
329
330
	/**
331
	 * Creates an url to the given app and file
332
	 * @param string $app app
333
	 * @param string $file file
334
	 * @param array $args array with param=>value, will be appended to the returned url
335
	 * 	The value of $args will be urlencoded
336
	 * @return string the url
337
	 * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->linkTo($app, $file, $args)
338
	 * @since 4.0.0 - parameter $args was added in 4.5.0
339
	 */
340
	public static function linkTo($app, $file, $args = []) {
341
		return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
342
	}
343
344
	/**
345
	 * Returns the server host, even if the website uses one or more reverse proxy
346
	 * @return string the server host
347
	 * @deprecated 8.1.0 Use \OCP\IRequest::getServerHost
348
	 * @since 4.0.0
349
	 */
350
	public static function getServerHost() {
351
		return \OC::$server->getRequest()->getServerHost();
352
	}
353
354
	/**
355
	 * Returns the server host name without an eventual port number
356
	 * @return string the server hostname
357
	 * @since 5.0.0
358
	 */
359
	public static function getServerHostName() {
360
		$host_name = self::getServerHost();
361
		// strip away port number (if existing)
362
		$colon_pos = \strpos($host_name, ':');
363
		if ($colon_pos != false) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $colon_pos of type integer to the boolean false. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
364
			$host_name = \substr($host_name, 0, $colon_pos);
365
		}
366
		return $host_name;
367
	}
368
369
	/**
370
	 * Returns the default email address
371
	 * @param string $user_part the user part of the address
372
	 * @return string the default email address
373
	 *
374
	 * Assembles a default email address (using the server hostname
375
	 * and the given user part, and returns it
376
	 * Example: when given lostpassword-noreply as $user_part param,
377
	 *     and is currently accessed via http(s)://example.com/,
378
	 *     it would return '[email protected]'
379
	 *
380
	 * If the configuration value 'mail_from_address' is set in
381
	 * config.php, this value will override the $user_part that
382
	 * is passed to this function
383
	 * @since 5.0.0
384
	 */
385
	public static function getDefaultEmailAddress($user_part) {
386
		$config = \OC::$server->getConfig();
387
		$user_part = $config->getSystemValue('mail_from_address', $user_part);
388
		$host_name = self::getServerHostName();
389
		$host_name = $config->getSystemValue('mail_domain', $host_name);
390
		$defaultEmailAddress = $user_part.'@'.$host_name;
391
392
		$mailer = \OC::$server->getMailer();
393
		if ($mailer->validateMailAddress($defaultEmailAddress)) {
394
			return $defaultEmailAddress;
395
		}
396
397
		// in case we cannot build a valid email address from the hostname let's fallback to 'localhost.localdomain'
398
		return $user_part.'@localhost.localdomain';
399
	}
400
401
	/**
402
	 * Returns the server protocol. It respects reverse proxy servers and load balancers
403
	 * @return string the server protocol
404
	 * @deprecated 8.1.0 Use \OCP\IRequest::getServerProtocol
405
	 * @since 4.5.0
406
	 */
407
	public static function getServerProtocol() {
408
		return \OC::$server->getRequest()->getServerProtocol();
409
	}
410
411
	/**
412
	 * Returns the request uri, even if the website uses one or more reverse proxies
413
	 * @return string the request uri
414
	 * @deprecated 8.1.0 Use \OCP\IRequest::getRequestUri
415
	 * @since 5.0.0
416
	 */
417
	public static function getRequestUri() {
418
		return \OC::$server->getRequest()->getRequestUri();
419
	}
420
421
	/**
422
	 * Returns the script name, even if the website uses one or more reverse proxies
423
	 * @return string the script name
424
	 * @deprecated 8.1.0 Use \OCP\IRequest::getScriptName
425
	 * @since 5.0.0
426
	 */
427
	public static function getScriptName() {
428
		return \OC::$server->getRequest()->getScriptName();
429
	}
430
431
	/**
432
	 * Creates path to an image
433
	 * @param string $app app
434
	 * @param string $image image name
435
	 * @return string the url
436
	 * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->imagePath($app, $image)
437
	 * @since 4.0.0
438
	 */
439
	public static function imagePath($app, $image) {
440
		return \OC::$server->getURLGenerator()->imagePath($app, $image);
441
	}
442
443
	/**
444
	 * Make a human file size (2048 to 2 kB)
445
	 * @param int $bytes file size in bytes
446
	 * @return string a human readable file size
447
	 * @since 4.0.0
448
	 */
449
	public static function humanFileSize($bytes) {
450
		return(\OC_Helper::humanFileSize($bytes));
451
	}
452
453
	/**
454
	 * Make a computer file size (2 kB to 2048)
455
	 * @param string $str file size in a fancy format
456
	 * @return int a file size in bytes
457
	 *
458
	 * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
459
	 * @since 4.0.0
460
	 */
461
	public static function computerFileSize($str) {
462
		return(\OC_Helper::computerFileSize($str));
463
	}
464
465
	/**
466
	 * connects a function to a hook
467
	 *
468
	 * @param string $signalClass class name of emitter
469
	 * @param string $signalName name of signal
470
	 * @param string|object $slotClass class name of slot
471
	 * @param string $slotName name of slot
472
	 * @return bool
473
	 *
474
	 * This function makes it very easy to connect to use hooks.
475
	 *
476
	 * TODO: write example
477
	 * @since 4.0.0
478
	 */
479
	public static function connectHook($signalClass, $signalName, $slotClass, $slotName) {
480
		return(\OC_Hook::connect($signalClass, $signalName, $slotClass, $slotName));
481
	}
482
483
	/**
484
	 * Emits a signal. To get data from the slot use references!
485
	 * @param string $signalclass class name of emitter
486
	 * @param string $signalname name of signal
487
	 * @param array $params default: array() array with additional data
488
	 * @return bool true if slots exists or false if not
489
	 *
490
	 * TODO: write example
491
	 * @since 4.0.0
492
	 */
493
	public static function emitHook($signalclass, $signalname, $params = []) {
494
		return(\OC_Hook::emit($signalclass, $signalname, $params));
495
	}
496
497
	/**
498
	 * Cached encrypted CSRF token. Some static unit-tests of ownCloud compare
499
	 * multiple OC_Template elements which invoke `callRegister`. If the value
500
	 * would not be cached these unit-tests would fail.
501
	 * @var string
502
	 */
503
	private static $token = '';
504
505
	/**
506
	 * Register an get/post call. This is important to prevent CSRF attacks
507
	 * @since 4.5.0
508
	 */
509
	public static function callRegister() {
510
		if (self::$token === '') {
511
			self::$token = \OC::$server->getCsrfTokenManager()->getToken()->getEncryptedValue();
512
		}
513
		return self::$token;
514
	}
515
516
	/**
517
	 * Check an ajax get/post call if the request token is valid. exit if not.
518
	 * @since 4.5.0
519
	 * @deprecated 9.0.0 Use annotations based on the app framework.
520
	 */
521
	public static function callCheck() {
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') {
0 ignored issues
show
Unused Code introduced by
The parameter $encoding is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
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) {
0 ignored issues
show
Unused Code introduced by
The parameter $encoding is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
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 int $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
	 */
653
	public static function isValidFileName($file) {
654
		return \OC_Util::isValidFileName($file);
655
	}
656
657
	/**
658
	 * Determine if the string is, strictly-speaking, empty or not
659
	 *
660
	 * @param $value
661
	 * @return bool
662
	 * @since 10.0.1
663
	 */
664
	public static function isEmptyString($value) {
665
		$value = \trim(\strval($value));
666
		return ($value === '' || $value === '0');
667
	}
668
669
	/**
670
	 * Generates a cryptographic secure pseudo-random string
671
	 * @param int $length of the random string
672
	 * @return string
673
	 * @deprecated 8.0.0 Use \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate($length); instead
674
	 * @since 7.0.0
675
	 */
676
	public static function generateRandomBytes($length = 30) {
677
		return \OC::$server->getSecureRandom()->generate($length, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
678
	}
679
680
	/**
681
	 * Compare two strings to provide a natural sort
682
	 * @param string $a first string to compare
683
	 * @param string $b second string to compare
684
	 * @return -1 if $b comes before $a, 1 if $a comes before $b
0 ignored issues
show
Documentation introduced by
The doc-type -1 could not be parsed: Unknown type name "-1" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
685
	 * or 0 if the strings are identical
686
	 * @since 7.0.0
687
	 */
688
	public static function naturalSortCompare($a, $b) {
689
		return \OC\NaturalSort::getInstance()->compare($a, $b);
690
	}
691
692
	/**
693
	 * check if a password is required for each public link
694
	 * This is deprecated due to not reflecting all the possibilities now. Falling back to
695
	 * enforce password for read-only links. Note that read & write or write-only options won't
696
	 * be considered here
697
	 * @return boolean
698
	 * @since 7.0.0
699
	 * @deprecated
700
	 */
701
	public static function isPublicLinkPasswordRequired() {
702
		return \OC_Util::isPublicLinkPasswordRequired();
0 ignored issues
show
Deprecated Code introduced by
The method OC_Util::isPublicLinkPasswordRequired() has been deprecated.

This method has been deprecated.

Loading history...
703
	}
704
705
	/**
706
	 * check if share API enforces a default expire date
707
	 * @return boolean
708
	 * @since 8.0.0
709
	 */
710
	public static function isDefaultExpireDateEnforced() {
711
		return \OC_Util::isDefaultExpireDateEnforced();
712
	}
713
714
	protected static $needUpgradeCache = null;
715
716
	/**
717
	 * Checks whether the current version needs upgrade.
718
	 *
719
	 * @return bool true if upgrade is needed, false otherwise
720
	 * @since 7.0.0
721
	 */
722
	public static function needUpgrade() {
723
		if (!isset(self::$needUpgradeCache)) {
724
			self::$needUpgradeCache=\OC_Util::needUpgrade(\OC::$server->getConfig());
725
		}
726
		return self::$needUpgradeCache;
727
	}
728
729
	/**
730
	 * Collects all status infos.
731
	 *
732
	 * @param bool $includeVersion
733
	 * @return array
734
	 * @since 10.0
735
	 */
736
	public static function getStatusInfo($includeVersion = false, $serverHide = false) {
737
		$systemConfig = \OC::$server->getSystemConfig();
738
739
		$installed = (bool) $systemConfig->getValue('installed', false);
740
		$maintenance = (bool) $systemConfig->getValue('maintenance', false);
741
742
		// see core/lib/private/legacy/defaults.php and core/themes/example/defaults.php
743
		// for description and defaults
744
		$defaults = new \OCP\Defaults();
745
		$values = [
746
			'installed'=> $installed ? true : false,
747
			'maintenance' => $maintenance ? true : false,
748
			'needsDbUpgrade' => self::needUpgrade() ? true : false,
749
			'version' => '',
750
			'versionstring' => '',
751
			'edition' => '',
752
			'productname' => ''];
753
754
		// expose version and servername details
755
		if ($includeVersion || (bool) $systemConfig->getValue('version.hide', false) === false) {
756
			$values['version'] = \implode('.', self::getVersion());
757
			$values['versionstring'] = \OC_Util::getVersionString();
758
			$values['edition'] = \OC_Util::getEditionString();
759
			$values['productname'] = $defaults->getName();
760
			// expose the servername only if allowed via version, but never when called via status.php
761
			if ($serverHide === false) {
762
				$values['hostname'] = \gethostname();
763
			}
764
		}
765
766
		return $values;
767
	}
768
769
	/**
770
	 * Returns the protocol, domain and port as string in a normalized
771
	 * format for easier comparison.
772
	 * Example: "HTTPS://HOST.tld:8080" is returned as "https://host.tld:8080"
773
	 *
774
	 * If no port was specified, it will add the default port
775
	 * of the specified protocol (80 for http or 443 for https)
776
	 *
777
	 * @param string $url full url
778
	 * @return string protocol, domain and port as string
779
	 * @since 10.0.5
780
	 */
781
	public static function getFullDomain($url) {
782
		$parts = \parse_url($url);
783
		if ($parts === false) {
784
			throw new \InvalidArgumentException('Invalid url "' . $url . '"');
785
		}
786
		if (!isset($parts['scheme']) || !isset($parts['host'])) {
787
			throw new \InvalidArgumentException('Invalid url "' . $url . '"');
788
		}
789
		$protocol = \strtolower($parts['scheme']);
790
		$host = \strtolower($parts['host']);
791
		$port = null;
792
		if ($protocol === 'http') {
793
			$port = 80;
794
		} elseif ($protocol === 'https') {
795
			$port = 443;
796
		} else {
797
			throw new \InvalidArgumentException('Only http based URLs supported');
798
		}
799
800
		if (isset($parts['port']) && $port !== '') {
0 ignored issues
show
Unused Code Bug introduced by
The strict comparison !== seems to always evaluate to true as the types of $port (integer) and '' (string) can never be identical. Maybe you want to use a loose comparison != instead?
Loading history...
801
			$port = $parts['port'];
802
		}
803
804
		return $protocol . '://' . \strtolower($host) . ':' . $port;
805
	}
806
807
	/**
808
	 * Check whether the given URLs have the same protocol, domain and port.
809
	 * This is useful to check a browser's cross-domain situation.
810
	 * If this method returns false, a browser would consider both URLs to be
811
	 * a cross-domain situation and would require a CORS setup.
812
	 *
813
	 * @param string $url1
814
	 * @param string $url2
815
	 *
816
	 * @return bool true if both URLs have the same protocol, domain and port
817
	 *
818
	 * @since 10.0.5
819
	 */
820
	public static function isSameDomain($url1, $url2) {
821
		return self::getFullDomain($url1) === self::getFullDomain($url2);
822
	}
823
}
824