1<?php
2/**
3 * @copyright Copyright (c) 2016, ownCloud, Inc.
4 *
5 * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
6 * @author Bart Visscher <bartv@thisnet.nl>
7 * @author Björn Schießle <bjoern@schiessle.org>
8 * @author Christoph Wurst <christoph@winzerhof-wurst.at>
9 * @author Frank Karlitschek <frank@karlitschek.de>
10 * @author Georg Ehrke <oc.list@georgehrke.com>
11 * @author Individual IT Services <info@individual-it.net>
12 * @author J0WI <J0WI@users.noreply.github.com>
13 * @author Jens-Christian Fischer <jens-christian.fischer@switch.ch>
14 * @author Joas Schilling <coding@schilljs.com>
15 * @author Julius Härtl <jus@bitgrid.net>
16 * @author Lukas Reschke <lukas@statuscode.ch>
17 * @author Michael Gapczynski <GapczynskiM@gmail.com>
18 * @author Morris Jobke <hey@morrisjobke.de>
19 * @author Pellaeon Lin <nfsmwlin@gmail.com>
20 * @author Randolph Carter <RandolphCarter@fantasymail.de>
21 * @author Robin Appelman <robin@icewind.nl>
22 * @author Robin McCorkell <robin@mccorkell.me.uk>
23 * @author Roeland Jago Douma <roeland@famdouma.nl>
24 * @author Thomas Müller <thomas.mueller@tmit.eu>
25 * @author Victor Dubiniuk <dubiniuk@owncloud.com>
26 * @author Vincent Petry <vincent@nextcloud.com>
27 *
28 * @license AGPL-3.0
29 *
30 * This code is free software: you can redistribute it and/or modify
31 * it under the terms of the GNU Affero General Public License, version 3,
32 * as published by the Free Software Foundation.
33 *
34 * This program is distributed in the hope that it will be useful,
35 * but WITHOUT ANY WARRANTY; without even the implied warranty of
36 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
37 * GNU Affero General Public License for more details.
38 *
39 * You should have received a copy of the GNU Affero General Public License, version 3,
40 * along with this program. If not, see <http://www.gnu.org/licenses/>
41 *
42 */
43// use OCP namespace for all classes that are considered public.
44// This means that they should be used by apps instead of the internal ownCloud classes
45
46namespace OCP;
47
48/**
49 * This class provides different helper functions to make the life of a developer easier
50 *
51 * @since 4.0.0
52 */
53class Util {
54	/**
55	 * @deprecated 14.0.0 use \OCP\ILogger::DEBUG
56	 */
57	public const DEBUG = 0;
58	/**
59	 * @deprecated 14.0.0 use \OCP\ILogger::INFO
60	 */
61	public const INFO = 1;
62	/**
63	 * @deprecated 14.0.0 use \OCP\ILogger::WARN
64	 */
65	public const WARN = 2;
66	/**
67	 * @deprecated 14.0.0 use \OCP\ILogger::ERROR
68	 */
69	public const ERROR = 3;
70	/**
71	 * @deprecated 14.0.0 use \OCP\ILogger::FATAL
72	 */
73	public const FATAL = 4;
74
75	/** \OCP\Share\IManager */
76	private static $shareManager;
77
78	/**
79	 * get the current installed version of Nextcloud
80	 * @return array
81	 * @since 4.0.0
82	 */
83	public static function getVersion() {
84		return \OC_Util::getVersion();
85	}
86
87	/**
88	 * @since 17.0.0
89	 */
90	public static function hasExtendedSupport(): bool {
91		try {
92			/** @var \OCP\Support\Subscription\IRegistry */
93			$subscriptionRegistry = \OC::$server->query(\OCP\Support\Subscription\IRegistry::class);
94			return $subscriptionRegistry->delegateHasExtendedSupport();
95		} catch (AppFramework\QueryException $e) {
96		}
97		return \OC::$server->getConfig()->getSystemValueBool('extendedSupport', false);
98	}
99
100	/**
101	 * Set current update channel
102	 * @param string $channel
103	 * @since 8.1.0
104	 */
105	public static function setChannel($channel) {
106		\OC::$server->getConfig()->setSystemValue('updater.release.channel', $channel);
107	}
108
109	/**
110	 * Get current update channel
111	 * @return string
112	 * @since 8.1.0
113	 */
114	public static function getChannel() {
115		return \OC_Util::getChannel();
116	}
117
118	/**
119	 * write a message in the log
120	 * @param string $app
121	 * @param string $message
122	 * @param int $level
123	 * @since 4.0.0
124	 * @deprecated 13.0.0 use log of \OCP\ILogger
125	 */
126	public static function writeLog($app, $message, $level) {
127		$context = ['app' => $app];
128		\OC::$server->getLogger()->log($level, $message, $context);
129	}
130
131	/**
132	 * check if sharing is disabled for the current user
133	 *
134	 * @return boolean
135	 * @since 7.0.0
136	 * @deprecated 9.1.0 Use \OC::$server->getShareManager()->sharingDisabledForUser
137	 */
138	public static function isSharingDisabledForUser() {
139		if (self::$shareManager === null) {
140			self::$shareManager = \OC::$server->getShareManager();
141		}
142
143		$user = \OC::$server->getUserSession()->getUser();
144		if ($user !== null) {
145			$user = $user->getUID();
146		}
147
148		return self::$shareManager->sharingDisabledForUser($user);
149	}
150
151	/**
152	 * get l10n object
153	 * @param string $application
154	 * @param string|null $language
155	 * @return \OCP\IL10N
156	 * @since 6.0.0 - parameter $language was added in 8.0.0
157	 */
158	public static function getL10N($application, $language = null) {
159		return \OC::$server->getL10N($application, $language);
160	}
161
162	/**
163	 * add a css file
164	 * @param string $application
165	 * @param string $file
166	 * @since 4.0.0
167	 */
168	public static function addStyle($application, $file = null) {
169		\OC_Util::addStyle($application, $file);
170	}
171
172	/**
173	 * add a javascript file
174	 * @param string $application
175	 * @param string $file
176	 * @since 4.0.0
177	 */
178	public static function addScript($application, $file = null) {
179		\OC_Util::addScript($application, $file);
180	}
181
182	/**
183	 * Add a translation JS file
184	 * @param string $application application id
185	 * @param string $languageCode language code, defaults to the current locale
186	 * @since 8.0.0
187	 */
188	public static function addTranslations($application, $languageCode = null) {
189		\OC_Util::addTranslations($application, $languageCode);
190	}
191
192	/**
193	 * Add a custom element to the header
194	 * If $text is null then the element will be written as empty element.
195	 * So use "" to get a closing tag.
196	 * @param string $tag tag name of the element
197	 * @param array $attributes array of attributes for the element
198	 * @param string $text the text content for the element
199	 * @since 4.0.0
200	 */
201	public static function addHeader($tag, $attributes, $text = null) {
202		\OC_Util::addHeader($tag, $attributes, $text);
203	}
204
205	/**
206	 * Creates an absolute url to the given app and file.
207	 * @param string $app app
208	 * @param string $file file
209	 * @param array $args array with param=>value, will be appended to the returned url
210	 * 	The value of $args will be urlencoded
211	 * @return string the url
212	 * @since 4.0.0 - parameter $args was added in 4.5.0
213	 */
214	public static function linkToAbsolute($app, $file, $args = []) {
215		$urlGenerator = \OC::$server->getURLGenerator();
216		return $urlGenerator->getAbsoluteURL(
217			$urlGenerator->linkTo($app, $file, $args)
218		);
219	}
220
221	/**
222	 * Creates an absolute url for remote use.
223	 * @param string $service id
224	 * @return string the url
225	 * @since 4.0.0
226	 */
227	public static function linkToRemote($service) {
228		$urlGenerator = \OC::$server->getURLGenerator();
229		$remoteBase = $urlGenerator->linkTo('', 'remote.php') . '/' . $service;
230		return $urlGenerator->getAbsoluteURL(
231			$remoteBase . (($service[strlen($service) - 1] != '/') ? '/' : '')
232		);
233	}
234
235	/**
236	 * Creates an absolute url for public use
237	 * @param string $service id
238	 * @return string the url
239	 * @since 4.5.0
240	 * @deprecated 15.0.0 - use OCP\IURLGenerator
241	 */
242	public static function linkToPublic($service) {
243		$urlGenerator = \OC::$server->getURLGenerator();
244		if ($service === 'files') {
245			return $urlGenerator->getAbsoluteURL('/s');
246		}
247		return $urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'public.php').'?service='.$service);
248	}
249
250	/**
251	 * Returns the server host name without an eventual port number
252	 * @return string the server hostname
253	 * @since 5.0.0
254	 */
255	public static function getServerHostName() {
256		$host_name = \OC::$server->getRequest()->getServerHost();
257		// strip away port number (if existing)
258		$colon_pos = strpos($host_name, ':');
259		if ($colon_pos != false) {
260			$host_name = substr($host_name, 0, $colon_pos);
261		}
262		return $host_name;
263	}
264
265	/**
266	 * Returns the default email address
267	 * @param string $user_part the user part of the address
268	 * @return string the default email address
269	 *
270	 * Assembles a default email address (using the server hostname
271	 * and the given user part, and returns it
272	 * Example: when given lostpassword-noreply as $user_part param,
273	 *     and is currently accessed via http(s)://example.com/,
274	 *     it would return 'lostpassword-noreply@example.com'
275	 *
276	 * If the configuration value 'mail_from_address' is set in
277	 * config.php, this value will override the $user_part that
278	 * is passed to this function
279	 * @since 5.0.0
280	 */
281	public static function getDefaultEmailAddress($user_part) {
282		$config = \OC::$server->getConfig();
283		$user_part = $config->getSystemValue('mail_from_address', $user_part);
284		$host_name = self::getServerHostName();
285		$host_name = $config->getSystemValue('mail_domain', $host_name);
286		$defaultEmailAddress = $user_part.'@'.$host_name;
287
288		$mailer = \OC::$server->getMailer();
289		if ($mailer->validateMailAddress($defaultEmailAddress)) {
290			return $defaultEmailAddress;
291		}
292
293		// in case we cannot build a valid email address from the hostname let's fallback to 'localhost.localdomain'
294		return $user_part.'@localhost.localdomain';
295	}
296
297	/**
298	 * Make a human file size (2048 to 2 kB)
299	 * @param int $bytes file size in bytes
300	 * @return string a human readable file size
301	 * @since 4.0.0
302	 */
303	public static function humanFileSize($bytes) {
304		return \OC_Helper::humanFileSize($bytes);
305	}
306
307	/**
308	 * Make a computer file size (2 kB to 2048)
309	 * @param string $str file size in a fancy format
310	 * @return float a file size in bytes
311	 *
312	 * Inspired by: https://www.php.net/manual/en/function.filesize.php#92418
313	 * @since 4.0.0
314	 */
315	public static function computerFileSize($str) {
316		return \OC_Helper::computerFileSize($str);
317	}
318
319	/**
320	 * connects a function to a hook
321	 *
322	 * @param string $signalClass class name of emitter
323	 * @param string $signalName name of signal
324	 * @param string|object $slotClass class name of slot
325	 * @param string $slotName name of slot
326	 * @return bool
327	 *
328	 * This function makes it very easy to connect to use hooks.
329	 *
330	 * TODO: write example
331	 * @since 4.0.0
332	 * @deprecated 21.0.0 use \OCP\EventDispatcher\IEventDispatcher::addListener
333	 */
334	public static function connectHook($signalClass, $signalName, $slotClass, $slotName) {
335		return \OC_Hook::connect($signalClass, $signalName, $slotClass, $slotName);
336	}
337
338	/**
339	 * Emits a signal. To get data from the slot use references!
340	 * @param string $signalclass class name of emitter
341	 * @param string $signalname name of signal
342	 * @param array $params default: array() array with additional data
343	 * @return bool true if slots exists or false if not
344	 *
345	 * TODO: write example
346	 * @since 4.0.0
347	 * @deprecated 21.0.0 use \OCP\EventDispatcher\IEventDispatcher::dispatchTypedEvent
348	 */
349	public static function emitHook($signalclass, $signalname, $params = []) {
350		return \OC_Hook::emit($signalclass, $signalname, $params);
351	}
352
353	/**
354	 * Cached encrypted CSRF token. Some static unit-tests of ownCloud compare
355	 * multiple OC_Template elements which invoke `callRegister`. If the value
356	 * would not be cached these unit-tests would fail.
357	 * @var string
358	 */
359	private static $token = '';
360
361	/**
362	 * Register an get/post call. This is important to prevent CSRF attacks
363	 * @since 4.5.0
364	 */
365	public static function callRegister() {
366		if (self::$token === '') {
367			self::$token = \OC::$server->getCsrfTokenManager()->getToken()->getEncryptedValue();
368		}
369		return self::$token;
370	}
371
372	/**
373	 * Used to sanitize HTML
374	 *
375	 * This function is used to sanitize HTML and should be applied on any
376	 * string or array of strings before displaying it on a web page.
377	 *
378	 * @param string|array $value
379	 * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
380	 * @since 4.5.0
381	 */
382	public static function sanitizeHTML($value) {
383		return \OC_Util::sanitizeHTML($value);
384	}
385
386	/**
387	 * Public function to encode url parameters
388	 *
389	 * This function is used to encode path to file before output.
390	 * Encoding is done according to RFC 3986 with one exception:
391	 * Character '/' is preserved as is.
392	 *
393	 * @param string $component part of URI to encode
394	 * @return string
395	 * @since 6.0.0
396	 */
397	public static function encodePath($component) {
398		return \OC_Util::encodePath($component);
399	}
400
401	/**
402	 * Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
403	 *
404	 * @param array $input The array to work on
405	 * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
406	 * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
407	 * @return array
408	 * @since 4.5.0
409	 */
410	public static function mb_array_change_key_case($input, $case = MB_CASE_LOWER, $encoding = 'UTF-8') {
411		return \OC_Helper::mb_array_change_key_case($input, $case, $encoding);
412	}
413
414	/**
415	 * performs a search in a nested array
416	 *
417	 * @param array $haystack the array to be searched
418	 * @param string $needle the search string
419	 * @param mixed $index optional, only search this key name
420	 * @return mixed the key of the matching field, otherwise false
421	 * @since 4.5.0
422	 * @deprecated 15.0.0
423	 */
424	public static function recursiveArraySearch($haystack, $needle, $index = null) {
425		return \OC_Helper::recursiveArraySearch($haystack, $needle, $index);
426	}
427
428	/**
429	 * calculates the maximum upload size respecting system settings, free space and user quota
430	 *
431	 * @param string $dir the current folder where the user currently operates
432	 * @param int $free the number of bytes free on the storage holding $dir, if not set this will be received from the storage directly
433	 * @return int number of bytes representing
434	 * @since 5.0.0
435	 */
436	public static function maxUploadFilesize($dir, $free = null) {
437		return \OC_Helper::maxUploadFilesize($dir, $free);
438	}
439
440	/**
441	 * Calculate free space left within user quota
442	 * @param string $dir the current folder where the user currently operates
443	 * @return int number of bytes representing
444	 * @since 7.0.0
445	 */
446	public static function freeSpace($dir) {
447		return \OC_Helper::freeSpace($dir);
448	}
449
450	/**
451	 * Calculate PHP upload limit
452	 *
453	 * @return int number of bytes representing
454	 * @since 7.0.0
455	 */
456	public static function uploadLimit() {
457		return \OC_Helper::uploadLimit();
458	}
459
460	/**
461	 * Returns whether the given file name is valid
462	 * @param string $file file name to check
463	 * @return bool true if the file name is valid, false otherwise
464	 * @deprecated 8.1.0 use \OC\Files\View::verifyPath()
465	 * @since 7.0.0
466	 * @suppress PhanDeprecatedFunction
467	 */
468	public static function isValidFileName($file) {
469		return \OC_Util::isValidFileName($file);
470	}
471
472	/**
473	 * Compare two strings to provide a natural sort
474	 * @param string $a first string to compare
475	 * @param string $b second string to compare
476	 * @return int -1 if $b comes before $a, 1 if $a comes before $b
477	 * or 0 if the strings are identical
478	 * @since 7.0.0
479	 */
480	public static function naturalSortCompare($a, $b) {
481		return \OC\NaturalSort::getInstance()->compare($a, $b);
482	}
483
484	/**
485	 * check if a password is required for each public link
486	 * @return boolean
487	 * @since 7.0.0
488	 */
489	public static function isPublicLinkPasswordRequired() {
490		return \OC_Util::isPublicLinkPasswordRequired();
491	}
492
493	/**
494	 * check if share API enforces a default expire date
495	 * @return boolean
496	 * @since 8.0.0
497	 */
498	public static function isDefaultExpireDateEnforced() {
499		return \OC_Util::isDefaultExpireDateEnforced();
500	}
501
502	protected static $needUpgradeCache = null;
503
504	/**
505	 * Checks whether the current version needs upgrade.
506	 *
507	 * @return bool true if upgrade is needed, false otherwise
508	 * @since 7.0.0
509	 */
510	public static function needUpgrade() {
511		if (!isset(self::$needUpgradeCache)) {
512			self::$needUpgradeCache = \OC_Util::needUpgrade(\OC::$server->getSystemConfig());
513		}
514		return self::$needUpgradeCache;
515	}
516
517	/**
518	 * Sometimes a string has to be shortened to fit within a certain maximum
519	 * data length in bytes. substr() you may break multibyte characters,
520	 * because it operates on single byte level. mb_substr() operates on
521	 * characters, so does not ensure that the shortend string satisfies the
522	 * max length in bytes.
523	 *
524	 * For example, json_encode is messing with multibyte characters a lot,
525	 * replacing them with something along "\u1234".
526	 *
527	 * This function shortens the string with by $accurancy (-5) from
528	 * $dataLength characters, until it fits within $dataLength bytes.
529	 *
530	 * @since 23.0.0
531	 */
532	public static function shortenMultibyteString(string $subject, int $dataLength, int $accuracy = 5): string {
533		$temp = mb_substr($subject, 0, $dataLength);
534		// json encodes encapsulates the string in double quotes, they need to be substracted
535		while ((strlen(json_encode($temp)) - 2) > $dataLength) {
536			$temp = mb_substr($temp, 0, -$accuracy);
537		}
538		return $temp;
539	}
540}
541