Completed
Push — master ( 3df2fb...324ce5 )
by Morris
82:05 queued 64:31
created

Util::getServerProtocol()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 *
5
 * @author Arthur Schiwon <[email protected]>
6
 * @author Bart Visscher <[email protected]>
7
 * @author Björn Schießle <[email protected]>
8
 * @author Frank Karlitschek <[email protected]>
9
 * @author Georg Ehrke <[email protected]>
10
 * @author Individual IT Services <[email protected]>
11
 * @author Jens-Christian Fischer <[email protected]>
12
 * @author Joas Schilling <[email protected]>
13
 * @author Julius Härtl <[email protected]>
14
 * @author Lukas Reschke <[email protected]>
15
 * @author Michael Gapczynski <[email protected]>
16
 * @author Morris Jobke <[email protected]>
17
 * @author Nicolas Grekas <[email protected]>
18
 * @author Pellaeon Lin <[email protected]>
19
 * @author Randolph Carter <[email protected]>
20
 * @author Robin Appelman <[email protected]>
21
 * @author Robin McCorkell <[email protected]>
22
 * @author Roeland Jago Douma <[email protected]>
23
 * @author Stefan Herbrechtsmeier <[email protected]>
24
 * @author Thomas Müller <[email protected]>
25
 * @author Thomas Tanghus <[email protected]>
26
 * @author Victor Dubiniuk <[email protected]>
27
 * @author Vincent Petry <[email protected]>
28
 *
29
 * @license AGPL-3.0
30
 *
31
 * This code is free software: you can redistribute it and/or modify
32
 * it under the terms of the GNU Affero General Public License, version 3,
33
 * as published by the Free Software Foundation.
34
 *
35
 * This program is distributed in the hope that it will be useful,
36
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
37
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
38
 * GNU Affero General Public License for more details.
39
 *
40
 * You should have received a copy of the GNU Affero General Public License, version 3,
41
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
42
 *
43
 */
44
45
/**
46
 * Public interface of ownCloud for apps to use.
47
 * Utility Class.
48
 *
49
 */
50
51
// use OCP namespace for all classes that are considered public.
52
// This means that they should be used by apps instead of the internal ownCloud classes
53
namespace OCP;
54
55
/**
56
 * This class provides different helper functions to make the life of a developer easier
57
 * @since 4.0.0
58
 */
59
class Util {
60
	// consts for Logging
61
	const DEBUG=0;
62
	const INFO=1;
63
	const WARN=2;
64
	const ERROR=3;
65
	const FATAL=4;
66
67
	/** \OCP\Share\IManager */
68
	private static $shareManager;
69
70
	/**
71
	 * get the current installed version of ownCloud
72
	 * @return array
73
	 * @since 4.0.0
74
	 */
75
	public static function getVersion() {
76
		return \OC_Util::getVersion();
77
	}
78
	
79
	/**
80
	 * Set current update channel
81
	 * @param string $channel
82
	 * @since 8.1.0
83
	 */
84
	public static function setChannel($channel) {
85
		\OC::$server->getConfig()->setSystemValue('updater.release.channel', $channel);
86
	}
87
	
88
	/**
89
	 * Get current update channel
90
	 * @return string
91
	 * @since 8.1.0
92
	 */
93
	public static function getChannel() {
94
		return \OC_Util::getChannel();
95
	}
96
97
	/**
98
	 * write a message in the log
99
	 * @param string $app
100
	 * @param string $message
101
	 * @param int $level
102
	 * @since 4.0.0
103
	 * @deprecated 13.0.0 use log of \OCP\ILogger
104
	 */
105
	public static function writeLog( $app, $message, $level ) {
106
		$context = ['app' => $app];
107
		\OC::$server->getLogger()->log($level, $message, $context);
108
	}
109
110
	/**
111
	 * write exception into the log
112
	 * @param string $app app name
113
	 * @param \Exception $ex exception to log
114
	 * @param int $level log level, defaults to \OCP\Util::FATAL
115
	 * @since ....0.0 - parameter $level was added in 7.0.0
116
	 * @deprecated 8.2.0 use logException of \OCP\ILogger
117
	 */
118
	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...
119
		\OC::$server->getLogger()->logException($ex, ['app' => $app]);
0 ignored issues
show
Documentation introduced by
$ex is of type object<Exception>, but the function expects a object<Throwable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
120
	}
121
122
	/**
123
	 * check if sharing is disabled for the current user
124
	 *
125
	 * @return boolean
126
	 * @since 7.0.0
127
	 * @deprecated 9.1.0 Use \OC::$server->getShareManager()->sharingDisabledForUser
128
	 */
129
	public static function isSharingDisabledForUser() {
130
		if (self::$shareManager === null) {
131
			self::$shareManager = \OC::$server->getShareManager();
132
		}
133
134
		$user = \OC::$server->getUserSession()->getUser();
135
		if ($user !== null) {
136
			$user = $user->getUID();
137
		}
138
139
		return self::$shareManager->sharingDisabledForUser($user);
140
	}
141
142
	/**
143
	 * get l10n object
144
	 * @param string $application
145
	 * @param string|null $language
146
	 * @return \OCP\IL10N
147
	 * @since 6.0.0 - parameter $language was added in 8.0.0
148
	 */
149
	public static function getL10N($application, $language = null) {
150
		return \OC::$server->getL10N($application, $language);
151
	}
152
153
	/**
154
	 * add a css file
155
	 * @param string $application
156
	 * @param string $file
157
	 * @since 4.0.0
158
	 */
159
	public static function addStyle( $application, $file = null ) {
160
		\OC_Util::addStyle( $application, $file );
161
	}
162
163
	/**
164
	 * add a javascript file
165
	 * @param string $application
166
	 * @param string $file
167
	 * @since 4.0.0
168
	 */
169
	public static function addScript( $application, $file = null ) {
170
		\OC_Util::addScript( $application, $file );
171
	}
172
173
	/**
174
	 * Add a translation JS file
175
	 * @param string $application application id
176
	 * @param string $languageCode language code, defaults to the current locale
177
	 * @since 8.0.0
178
	 */
179
	public static function addTranslations($application, $languageCode = null) {
180
		\OC_Util::addTranslations($application, $languageCode);
181
	}
182
183
	/**
184
	 * Add a custom element to the header
185
	 * If $text is null then the element will be written as empty element.
186
	 * So use "" to get a closing tag.
187
	 * @param string $tag tag name of the element
188
	 * @param array $attributes array of attributes for the element
189
	 * @param string $text the text content for the element
190
	 * @since 4.0.0
191
	 */
192
	public static function addHeader($tag, $attributes, $text=null) {
193
		\OC_Util::addHeader($tag, $attributes, $text);
194
	}
195
196
	/**
197
	 * Creates an absolute url to the given app and file.
198
	 * @param string $app app
199
	 * @param string $file file
200
	 * @param array $args array with param=>value, will be appended to the returned url
201
	 * 	The value of $args will be urlencoded
202
	 * @return string the url
203
	 * @since 4.0.0 - parameter $args was added in 4.5.0
204
	 */
205
	public static function linkToAbsolute( $app, $file, $args = array() ) {
206
		$urlGenerator = \OC::$server->getURLGenerator();
207
		return $urlGenerator->getAbsoluteURL(
208
			$urlGenerator->linkTo($app, $file, $args)
209
		);
210
	}
211
212
	/**
213
	 * Creates an absolute url for remote use.
214
	 * @param string $service id
215
	 * @return string the url
216
	 * @since 4.0.0
217
	 */
218
	public static function linkToRemote( $service ) {
219
		$urlGenerator = \OC::$server->getURLGenerator();
220
		$remoteBase = $urlGenerator->linkTo('', 'remote.php') . '/' . $service;
221
		return $urlGenerator->getAbsoluteURL(
222
			$remoteBase . (($service[strlen($service) - 1] != '/') ? '/' : '')
223
		);
224
	}
225
226
	/**
227
	 * Creates an absolute url for public use
228
	 * @param string $service id
229
	 * @return string the url
230
	 * @since 4.5.0
231
	 */
232
	public static function linkToPublic($service) {
233
		return \OC_Helper::linkToPublic($service);
234
	}
235
236
	/**
237
	 * Creates an url using a defined route
238
	 * @param string $route
239
	 * @param array $parameters
240
	 * @internal param array $args with param=>value, will be appended to the returned url
241
	 * @return string the url
242
	 * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->linkToRoute($route, $parameters)
243
	 * @since 5.0.0
244
	 */
245
	public static function linkToRoute( $route, $parameters = array() ) {
246
		return \OC::$server->getURLGenerator()->linkToRoute($route, $parameters);
247
	}
248
249
	/**
250
	 * Creates an url to the given app and file
251
	 * @param string $app app
252
	 * @param string $file file
253
	 * @param array $args array with param=>value, will be appended to the returned url
254
	 * 	The value of $args will be urlencoded
255
	 * @return string the url
256
	 * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->linkTo($app, $file, $args)
257
	 * @since 4.0.0 - parameter $args was added in 4.5.0
258
	 */
259
	public static function linkTo( $app, $file, $args = array() ) {
260
		return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
261
	}
262
263
	/**
264
	 * Returns the server host name without an eventual port number
265
	 * @return string the server hostname
266
	 * @since 5.0.0
267
	 */
268
	public static function getServerHostName() {
269
		$host_name = \OC::$server->getRequest()->getServerHost();
270
		// strip away port number (if existing)
271
		$colon_pos = strpos($host_name, ':');
272
		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...
273
			$host_name = substr($host_name, 0, $colon_pos);
274
		}
275
		return $host_name;
276
	}
277
278
	/**
279
	 * Returns the default email address
280
	 * @param string $user_part the user part of the address
281
	 * @return string the default email address
282
	 *
283
	 * Assembles a default email address (using the server hostname
284
	 * and the given user part, and returns it
285
	 * Example: when given lostpassword-noreply as $user_part param,
286
	 *     and is currently accessed via http(s)://example.com/,
287
	 *     it would return '[email protected]'
288
	 *
289
	 * If the configuration value 'mail_from_address' is set in
290
	 * config.php, this value will override the $user_part that
291
	 * is passed to this function
292
	 * @since 5.0.0
293
	 */
294
	public static function getDefaultEmailAddress($user_part) {
295
		$config = \OC::$server->getConfig();
296
		$user_part = $config->getSystemValue('mail_from_address', $user_part);
297
		$host_name = self::getServerHostName();
298
		$host_name = $config->getSystemValue('mail_domain', $host_name);
299
		$defaultEmailAddress = $user_part.'@'.$host_name;
300
301
		$mailer = \OC::$server->getMailer();
302
		if ($mailer->validateMailAddress($defaultEmailAddress)) {
303
			return $defaultEmailAddress;
304
		}
305
306
		// in case we cannot build a valid email address from the hostname let's fallback to 'localhost.localdomain'
307
		return $user_part.'@localhost.localdomain';
308
	}
309
310
	/**
311
	 * Creates path to an image
312
	 * @param string $app app
313
	 * @param string $image image name
314
	 * @return string the url
315
	 * @deprecated 8.1.0 Use \OC::$server->getURLGenerator()->imagePath($app, $image)
316
	 * @since 4.0.0
317
	 */
318
	public static function imagePath( $app, $image ) {
319
		return \OC::$server->getURLGenerator()->imagePath($app, $image);
320
	}
321
322
	/**
323
	 * Make a human file size (2048 to 2 kB)
324
	 * @param int $bytes file size in bytes
325
	 * @return string a human readable file size
326
	 * @since 4.0.0
327
	 */
328
	public static function humanFileSize($bytes) {
329
		return \OC_Helper::humanFileSize($bytes);
330
	}
331
332
	/**
333
	 * Make a computer file size (2 kB to 2048)
334
	 * @param string $str file size in a fancy format
335
	 * @return float a file size in bytes
336
	 *
337
	 * Inspired by: http://www.php.net/manual/en/function.filesize.php#92418
338
	 * @since 4.0.0
339
	 */
340
	public static function computerFileSize($str) {
341
		return \OC_Helper::computerFileSize($str);
342
	}
343
344
	/**
345
	 * connects a function to a hook
346
	 *
347
	 * @param string $signalClass class name of emitter
348
	 * @param string $signalName name of signal
349
	 * @param string|object $slotClass class name of slot
350
	 * @param string $slotName name of slot
351
	 * @return bool
352
	 *
353
	 * This function makes it very easy to connect to use hooks.
354
	 *
355
	 * TODO: write example
356
	 * @since 4.0.0
357
	 */
358
	static public function connectHook($signalClass, $signalName, $slotClass, $slotName) {
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
359
		return \OC_Hook::connect($signalClass, $signalName, $slotClass, $slotName);
360
	}
361
362
	/**
363
	 * Emits a signal. To get data from the slot use references!
364
	 * @param string $signalclass class name of emitter
365
	 * @param string $signalname name of signal
366
	 * @param array $params default: array() array with additional data
367
	 * @return bool true if slots exists or false if not
368
	 *
369
	 * TODO: write example
370
	 * @since 4.0.0
371
	 */
372
	static public function emitHook($signalclass, $signalname, $params = array()) {
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
373
		return \OC_Hook::emit($signalclass, $signalname, $params);
374
	}
375
376
	/**
377
	 * Cached encrypted CSRF token. Some static unit-tests of ownCloud compare
378
	 * multiple OC_Template elements which invoke `callRegister`. If the value
379
	 * would not be cached these unit-tests would fail.
380
	 * @var string
381
	 */
382
	private static $token = '';
383
384
	/**
385
	 * Register an get/post call. This is important to prevent CSRF attacks
386
	 * @since 4.5.0
387
	 */
388
	public static function callRegister() {
389
		if(self::$token === '') {
390
			self::$token = \OC::$server->getCsrfTokenManager()->getToken()->getEncryptedValue();
391
		}
392
		return self::$token;
393
	}
394
395
	/**
396
	 * Check an ajax get/post call if the request token is valid. exit if not.
397
	 * @since 4.5.0
398
	 * @deprecated 9.0.0 Use annotations based on the app framework.
399
	 */
400
	public static function callCheck() {
401
		if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
402
			header('Location: '.\OC::$WEBROOT);
403
			exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The method callCheck() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
404
		}
405
406
		if (!\OC::$server->getRequest()->passesCSRFCheck()) {
407
			exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The method callCheck() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
408
		}
409
	}
410
411
	/**
412
	 * Used to sanitize HTML
413
	 *
414
	 * This function is used to sanitize HTML and should be applied on any
415
	 * string or array of strings before displaying it on a web page.
416
	 *
417
	 * @param string|array $value
418
	 * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
419
	 * @since 4.5.0
420
	 */
421
	public static function sanitizeHTML($value) {
422
		return \OC_Util::sanitizeHTML($value);
423
	}
424
425
	/**
426
	 * Public function to encode url parameters
427
	 *
428
	 * This function is used to encode path to file before output.
429
	 * Encoding is done according to RFC 3986 with one exception:
430
	 * Character '/' is preserved as is.
431
	 *
432
	 * @param string $component part of URI to encode
433
	 * @return string
434
	 * @since 6.0.0
435
	 */
436
	public static function encodePath($component) {
437
		return \OC_Util::encodePath($component);
438
	}
439
440
	/**
441
	 * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
442
	 *
443
	 * @param array $input The array to work on
444
	 * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
445
	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
446
	 * @return array
447
	 * @since 4.5.0
448
	 */
449
	public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
450
		return \OC_Helper::mb_array_change_key_case($input, $case, $encoding);
451
	}
452
453
	/**
454
	 * replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.
455
	 *
456
	 * @param string $string The input string. Opposite to the PHP build-in function does not accept an array.
457
	 * @param string $replacement The replacement string.
458
	 * @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.
459
	 * @param int $length Length of the part to be replaced
460
	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
461
	 * @return string
462
	 * @since 4.5.0
463
	 * @deprecated 8.2.0 Use substr_replace() instead.
464
	 */
465
	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...
466
		return substr_replace($string, $replacement, $start, $length);
467
	}
468
469
	/**
470
	 * Replace all occurrences of the search string with the replacement string
471
	 *
472
	 * @param string $search The value being searched for, otherwise known as the needle. String.
473
	 * @param string $replace The replacement string.
474
	 * @param string $subject The string or array being searched and replaced on, otherwise known as the haystack.
475
	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
476
	 * @param int $count If passed, this will be set to the number of replacements performed.
477
	 * @return string
478
	 * @since 4.5.0
479
	 * @deprecated 8.2.0 Use str_replace() instead.
480
	 */
481
	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...
482
		return str_replace($search, $replace, $subject, $count);
483
	}
484
485
	/**
486
	 * performs a search in a nested array
487
	 *
488
	 * @param array $haystack the array to be searched
489
	 * @param string $needle the search string
490
	 * @param mixed $index optional, only search this key name
491
	 * @return mixed the key of the matching field, otherwise false
492
	 * @since 4.5.0
493
	 */
494
	public static function recursiveArraySearch($haystack, $needle, $index = null) {
495
		return \OC_Helper::recursiveArraySearch($haystack, $needle, $index);
496
	}
497
498
	/**
499
	 * calculates the maximum upload size respecting system settings, free space and user quota
500
	 *
501
	 * @param string $dir the current folder where the user currently operates
502
	 * @param int $free the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
503
	 * @return int number of bytes representing
504
	 * @since 5.0.0
505
	 */
506
	public static function maxUploadFilesize($dir, $free = null) {
507
		return \OC_Helper::maxUploadFilesize($dir, $free);
508
	}
509
510
	/**
511
	 * Calculate free space left within user quota
512
	 * @param string $dir the current folder where the user currently operates
513
	 * @return int number of bytes representing
514
	 * @since 7.0.0
515
	 */
516
	public static function freeSpace($dir) {
517
		return \OC_Helper::freeSpace($dir);
518
	}
519
520
	/**
521
	 * Calculate PHP upload limit
522
	 *
523
	 * @return int number of bytes representing
524
	 * @since 7.0.0
525
	 */
526
	public static function uploadLimit() {
527
		return \OC_Helper::uploadLimit();
528
	}
529
530
	/**
531
	 * Returns whether the given file name is valid
532
	 * @param string $file file name to check
533
	 * @return bool true if the file name is valid, false otherwise
534
	 * @deprecated 8.1.0 use \OC\Files\View::verifyPath()
535
	 * @since 7.0.0
536
	 * @suppress PhanDeprecatedFunction
537
	 */
538
	public static function isValidFileName($file) {
539
		return \OC_Util::isValidFileName($file);
540
	}
541
542
	/**
543
	 * Compare two strings to provide a natural sort
544
	 * @param string $a first string to compare
545
	 * @param string $b second string to compare
546
	 * @return int -1 if $b comes before $a, 1 if $a comes before $b
547
	 * or 0 if the strings are identical
548
	 * @since 7.0.0
549
	 */
550
	public static function naturalSortCompare($a, $b) {
551
		return \OC\NaturalSort::getInstance()->compare($a, $b);
552
	}
553
554
	/**
555
	 * check if a password is required for each public link
556
	 * @return boolean
557
	 * @since 7.0.0
558
	 */
559
	public static function isPublicLinkPasswordRequired() {
560
		return \OC_Util::isPublicLinkPasswordRequired();
561
	}
562
563
	/**
564
	 * check if share API enforces a default expire date
565
	 * @return boolean
566
	 * @since 8.0.0
567
	 */
568
	public static function isDefaultExpireDateEnforced() {
569
		return \OC_Util::isDefaultExpireDateEnforced();
570
	}
571
572
	protected static $needUpgradeCache = null;
573
574
	/**
575
	 * Checks whether the current version needs upgrade.
576
	 *
577
	 * @return bool true if upgrade is needed, false otherwise
578
	 * @since 7.0.0
579
	 */
580
	public static function needUpgrade() {
581
		if (!isset(self::$needUpgradeCache)) {
582
			self::$needUpgradeCache=\OC_Util::needUpgrade(\OC::$server->getSystemConfig());
583
		}		
584
		return self::$needUpgradeCache;
585
	}
586
}
587