]> git.mxchange.org Git - friendica.git/blob - boot.php
Item storage: Permissions aren't stored in the items anymore (#5495)
[friendica.git] / boot.php
1 <?php
2 /**
3  * @file boot.php
4  * This file defines some global constants and includes the central App class.
5  */
6
7 /**
8  * Friendica
9  *
10  * Friendica is a communications platform for integrated social communications
11  * utilising decentralised communications and linkage to several indie social
12  * projects - as well as popular mainstream providers.
13  *
14  * Our mission is to free our friends and families from the clutches of
15  * data-harvesting corporations, and pave the way to a future where social
16  * communications are free and open and flow between alternate providers as
17  * easily as email does today.
18  */
19
20 require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
21
22 use Friendica\App;
23 use Friendica\BaseObject;
24 use Friendica\Core\Addon;
25 use Friendica\Core\Cache;
26 use Friendica\Core\Config;
27 use Friendica\Core\L10n;
28 use Friendica\Core\PConfig;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
33 use Friendica\Database\DBStructure;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Util\DateTimeFormat;
37
38 require_once 'include/text.php';
39
40 define('FRIENDICA_PLATFORM',     'Friendica');
41 define('FRIENDICA_CODENAME',     'The Tazmans Flax-lily');
42 define('FRIENDICA_VERSION',      '2018.08-dev');
43 define('DFRN_PROTOCOL_VERSION',  '2.23');
44 define('DB_UPDATE_VERSION',      1280);
45 define('NEW_UPDATE_ROUTINE_VERSION', 1170);
46
47 /**
48  * @brief Constants for the database update check
49  */
50 const DB_UPDATE_NOT_CHECKED = 0; // Database check wasn't executed before
51 const DB_UPDATE_SUCCESSFUL = 1;  // Database check was successful
52 const DB_UPDATE_FAILED = 2;      // Database check failed
53
54 /**
55  * @brief Constant with a HTML line break.
56  *
57  * Contains a HTML line break (br) element and a real carriage return with line
58  * feed for the source.
59  * This can be used in HTML and JavaScript where needed a line break.
60  */
61 define('EOL',                    "<br />\r\n");
62
63 /**
64  * @brief Image storage quality.
65  *
66  * Lower numbers save space at cost of image detail.
67  * For ease of upgrade, please do not change here. Set [system] jpegquality = n in config/local.ini.php,
68  * where n is between 1 and 100, and with very poor results below about 50
69  */
70 define('JPEG_QUALITY',            100);
71
72 /**
73  * [system] png_quality = n where is between 0 (uncompressed) to 9
74  */
75 define('PNG_QUALITY',             8);
76
77 /**
78  * An alternate way of limiting picture upload sizes. Specify the maximum pixel
79  * length that pictures are allowed to be (for non-square pictures, it will apply
80  * to the longest side). Pictures longer than this length will be resized to be
81  * this length (on the longest side, the other side will be scaled appropriately).
82  * Modify this value using
83  *
84  * [system]
85  * max_image_length = n;
86  *
87  * in config/local.ini.php
88  *
89  * If you don't want to set a maximum length, set to -1. The default value is
90  * defined by 'MAX_IMAGE_LENGTH' below.
91  */
92 define('MAX_IMAGE_LENGTH',        -1);
93
94 /**
95  * Not yet used
96  */
97 define('DEFAULT_DB_ENGINE',  'InnoDB');
98
99 /**
100  * @name SSL Policy
101  *
102  * SSL redirection policies
103  * @{
104  */
105 define('SSL_POLICY_NONE',         0);
106 define('SSL_POLICY_FULL',         1);
107 define('SSL_POLICY_SELFSIGN',     2);
108 /* @}*/
109
110 /**
111  * @name Logger
112  *
113  * log levels
114  * @{
115  */
116 define('LOGGER_WARNING',         0);
117 define('LOGGER_INFO',            1);
118 define('LOGGER_TRACE',           2);
119 define('LOGGER_DEBUG',           3);
120 define('LOGGER_DATA',            4);
121 define('LOGGER_ALL',             5);
122 /* @}*/
123
124 /**
125  * @name Cache
126  * @deprecated since version 3.6
127  * @see Cache
128  *
129  * Cache levels
130  * @{
131  */
132 define('CACHE_MONTH',            Cache::MONTH);
133 define('CACHE_WEEK',             Cache::WEEK);
134 define('CACHE_DAY',              Cache::DAY);
135 define('CACHE_HOUR',             Cache::HOUR);
136 define('CACHE_HALF_HOUR',        Cache::HALF_HOUR);
137 define('CACHE_QUARTER_HOUR',     Cache::QUARTER_HOUR);
138 define('CACHE_FIVE_MINUTES',     Cache::FIVE_MINUTES);
139 define('CACHE_MINUTE',           Cache::MINUTE);
140 /* @}*/
141
142 /**
143  * @name Register
144  *
145  * Registration policies
146  * @{
147  */
148 define('REGISTER_CLOSED',        0);
149 define('REGISTER_APPROVE',       1);
150 define('REGISTER_OPEN',          2);
151 /**
152  * @}
153 */
154
155 /**
156  * @name Update
157  *
158  * DB update return values
159  * @{
160  */
161 define('UPDATE_SUCCESS', 0);
162 define('UPDATE_FAILED',  1);
163 /**
164  * @}
165  */
166
167 /**
168  * @name page/profile types
169  *
170  * PAGE_NORMAL is a typical personal profile account
171  * PAGE_SOAPBOX automatically approves all friend requests as Contact::SHARING, (readonly)
172  * PAGE_COMMUNITY automatically approves all friend requests as Contact::SHARING, but with
173  *      write access to wall and comments (no email and not included in page owner's ACL lists)
174  * PAGE_FREELOVE automatically approves all friend requests as full friends (Contact::FRIEND).
175  *
176  * @{
177  */
178 define('PAGE_NORMAL',            0);
179 define('PAGE_SOAPBOX',           1);
180 define('PAGE_COMMUNITY',         2);
181 define('PAGE_FREELOVE',          3);
182 define('PAGE_BLOG',              4);
183 define('PAGE_PRVGROUP',          5);
184 /**
185  * @}
186  */
187
188 /**
189  * @name account types
190  *
191  * ACCOUNT_TYPE_PERSON - the account belongs to a person
192  *      Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
193  *
194  * ACCOUNT_TYPE_ORGANISATION - the account belongs to an organisation
195  *      Associated page type: PAGE_SOAPBOX
196  *
197  * ACCOUNT_TYPE_NEWS - the account is a news reflector
198  *      Associated page type: PAGE_SOAPBOX
199  *
200  * ACCOUNT_TYPE_COMMUNITY - the account is community forum
201  *      Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
202  *
203  * ACCOUNT_TYPE_RELAY - the account is a relay
204  *      This will only be assigned to contacts, not to user accounts
205  * @{
206  */
207 define('ACCOUNT_TYPE_PERSON',      0);
208 define('ACCOUNT_TYPE_ORGANISATION', 1);
209 define('ACCOUNT_TYPE_NEWS',        2);
210 define('ACCOUNT_TYPE_COMMUNITY',   3);
211 define('ACCOUNT_TYPE_RELAY',       4);
212 /**
213  * @}
214  */
215
216 /**
217  * @name CP
218  *
219  * Type of the community page
220  * @{
221  */
222 define('CP_NO_INTERNAL_COMMUNITY', -2);
223 define('CP_NO_COMMUNITY_PAGE',     -1);
224 define('CP_USERS_ON_SERVER',        0);
225 define('CP_GLOBAL_COMMUNITY',       1);
226 define('CP_USERS_AND_GLOBAL',       2);
227 /**
228  * @}
229  */
230
231 /**
232  * @name Protocols
233  * @deprecated since version 3.6
234  * @see Conversation
235  *
236  * Different protocols that we are storing
237  * @{
238  */
239 define('PROTOCOL_UNKNOWN'        , Conversation::PROTOCOL_UNKNOWN);
240 define('PROTOCOL_DFRN'           , Conversation::PROTOCOL_DFRN);
241 define('PROTOCOL_DIASPORA'       , Conversation::PROTOCOL_DIASPORA);
242 define('PROTOCOL_OSTATUS_SALMON' , Conversation::PROTOCOL_OSTATUS_SALMON);
243 define('PROTOCOL_OSTATUS_FEED'   , Conversation::PROTOCOL_OSTATUS_FEED);    // Deprecated
244 define('PROTOCOL_GS_CONVERSATION', Conversation::PROTOCOL_GS_CONVERSATION); // Deprecated
245 define('PROTOCOL_SPLITTED_CONV'  , Conversation::PROTOCOL_SPLITTED_CONV);
246 /**
247  * @}
248  */
249
250 /**
251  * @name Network constants
252  * @deprecated since version 3.6
253  * @see Protocol
254  *
255  * Network and protocol family types
256  * @{
257  */
258 define('NETWORK_DFRN'     , Protocol::DFRN);      // Friendica, Mistpark, other DFRN implementations
259 define('NETWORK_ZOT'      , Protocol::ZOT);       // Zot! - Currently unsupported
260 define('NETWORK_OSTATUS'  , Protocol::OSTATUS);   // GNU-social, Pleroma, Mastodon, other OStatus implementations
261 define('NETWORK_FEED'     , Protocol::FEED);      // RSS/Atom feeds with no known "post/notify" protocol
262 define('NETWORK_DIASPORA' , Protocol::DIASPORA);  // Diaspora
263 define('NETWORK_MAIL'     , Protocol::MAIL);      // IMAP/POP
264 define('NETWORK_FACEBOOK' , Protocol::FACEBOOK);  // Facebook API
265 define('NETWORK_LINKEDIN' , Protocol::LINKEDIN);  // LinkedIn
266 define('NETWORK_XMPP'     , Protocol::XMPP);      // XMPP - Currently unsupported
267 define('NETWORK_MYSPACE'  , Protocol::MYSPACE);   // MySpace - Currently unsupported
268 define('NETWORK_GPLUS'    , Protocol::GPLUS);     // Google+
269 define('NETWORK_PUMPIO'   , Protocol::PUMPIO);    // pump.io
270 define('NETWORK_TWITTER'  , Protocol::TWITTER);   // Twitter
271 define('NETWORK_DIASPORA2', Protocol::DIASPORA2); // Diaspora connector
272 define('NETWORK_STATUSNET', Protocol::STATUSNET); // Statusnet connector
273 define('NETWORK_APPNET'   , Protocol::APPNET);    // app.net - Dead protocol
274 define('NETWORK_NEWS'     , Protocol::NEWS);      // Network News Transfer Protocol - Currently unsupported
275 define('NETWORK_ICALENDAR', Protocol::ICALENDAR); // iCalendar - Currently unsupported
276 define('NETWORK_PNUT'     , Protocol::PNUT);      // pnut.io - Currently unsupported
277 define('NETWORK_PHANTOM'  , Protocol::PHANTOM);   // Place holder
278 /**
279  * @}
280  */
281
282 /**
283  * These numbers are used in stored permissions
284  * and existing allocations MUST NEVER BE CHANGED
285  * OR RE-ASSIGNED! You may only add to them.
286  */
287 $netgroup_ids = [
288         NETWORK_DFRN     => (-1),
289         NETWORK_ZOT      => (-2),
290         NETWORK_OSTATUS  => (-3),
291         NETWORK_FEED     => (-4),
292         NETWORK_DIASPORA => (-5),
293         NETWORK_MAIL     => (-6),
294         NETWORK_FACEBOOK => (-8),
295         NETWORK_LINKEDIN => (-9),
296         NETWORK_XMPP     => (-10),
297         NETWORK_MYSPACE  => (-11),
298         NETWORK_GPLUS    => (-12),
299         NETWORK_PUMPIO   => (-13),
300         NETWORK_TWITTER  => (-14),
301         NETWORK_DIASPORA2 => (-15),
302         NETWORK_STATUSNET => (-16),
303         NETWORK_APPNET    => (-17),
304         NETWORK_NEWS      => (-18),
305         NETWORK_ICALENDAR => (-19),
306         NETWORK_PNUT      => (-20),
307
308         NETWORK_PHANTOM  => (-127),
309 ];
310
311 /**
312  * Maximum number of "people who like (or don't like) this"  that we will list by name
313  */
314 define('MAX_LIKERS',    75);
315
316 /**
317  * Communication timeout
318  */
319 define('ZCURL_TIMEOUT', (-1));
320
321 /**
322  * @name Notify
323  *
324  * Email notification options
325  * @{
326  */
327 define('NOTIFY_INTRO',    0x0001);
328 define('NOTIFY_CONFIRM',  0x0002);
329 define('NOTIFY_WALL',     0x0004);
330 define('NOTIFY_COMMENT',  0x0008);
331 define('NOTIFY_MAIL',     0x0010);
332 define('NOTIFY_SUGGEST',  0x0020);
333 define('NOTIFY_PROFILE',  0x0040);
334 define('NOTIFY_TAGSELF',  0x0080);
335 define('NOTIFY_TAGSHARE', 0x0100);
336 define('NOTIFY_POKE',     0x0200);
337 define('NOTIFY_SHARE',    0x0400);
338
339 define('SYSTEM_EMAIL',    0x4000);
340
341 define('NOTIFY_SYSTEM',   0x8000);
342 /* @}*/
343
344
345 /**
346  * @name Term
347  *
348  * Tag/term types
349  * @{
350  */
351 define('TERM_UNKNOWN',   0);
352 define('TERM_HASHTAG',   1);
353 define('TERM_MENTION',   2);
354 define('TERM_CATEGORY',  3);
355 define('TERM_PCATEGORY', 4);
356 define('TERM_FILE',      5);
357 define('TERM_SAVEDSEARCH', 6);
358 define('TERM_CONVERSATION', 7);
359
360 define('TERM_OBJ_POST',  1);
361 define('TERM_OBJ_PHOTO', 2);
362
363 /**
364  * @name Namespaces
365  *
366  * Various namespaces we may need to parse
367  * @{
368  */
369 define('NAMESPACE_ZOT',             'http://purl.org/zot');
370 define('NAMESPACE_DFRN',            'http://purl.org/macgirvin/dfrn/1.0');
371 define('NAMESPACE_THREAD',          'http://purl.org/syndication/thread/1.0');
372 define('NAMESPACE_TOMB',            'http://purl.org/atompub/tombstones/1.0');
373 define('NAMESPACE_ACTIVITY',        'http://activitystrea.ms/spec/1.0/');
374 define('NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/');
375 define('NAMESPACE_MEDIA',           'http://purl.org/syndication/atommedia');
376 define('NAMESPACE_SALMON_ME',       'http://salmon-protocol.org/ns/magic-env');
377 define('NAMESPACE_OSTATUSSUB',      'http://ostatus.org/schema/1.0/subscribe');
378 define('NAMESPACE_GEORSS',          'http://www.georss.org/georss');
379 define('NAMESPACE_POCO',            'http://portablecontacts.net/spec/1.0');
380 define('NAMESPACE_FEED',            'http://schemas.google.com/g/2010#updates-from');
381 define('NAMESPACE_OSTATUS',         'http://ostatus.org/schema/1.0');
382 define('NAMESPACE_STATUSNET',       'http://status.net/schema/api/1/');
383 define('NAMESPACE_ATOM1',           'http://www.w3.org/2005/Atom');
384 define('NAMESPACE_MASTODON',        'http://mastodon.social/schema/1.0');
385 /* @}*/
386
387 /**
388  * @name Activity
389  *
390  * Activity stream defines
391  * @{
392  */
393 define('ACTIVITY_LIKE',        NAMESPACE_ACTIVITY_SCHEMA . 'like');
394 define('ACTIVITY_DISLIKE',     NAMESPACE_DFRN            . '/dislike');
395 define('ACTIVITY_ATTEND',      NAMESPACE_ZOT             . '/activity/attendyes');
396 define('ACTIVITY_ATTENDNO',    NAMESPACE_ZOT             . '/activity/attendno');
397 define('ACTIVITY_ATTENDMAYBE', NAMESPACE_ZOT             . '/activity/attendmaybe');
398
399 define('ACTIVITY_OBJ_HEART',   NAMESPACE_DFRN            . '/heart');
400
401 define('ACTIVITY_FRIEND',      NAMESPACE_ACTIVITY_SCHEMA . 'make-friend');
402 define('ACTIVITY_REQ_FRIEND',  NAMESPACE_ACTIVITY_SCHEMA . 'request-friend');
403 define('ACTIVITY_UNFRIEND',    NAMESPACE_ACTIVITY_SCHEMA . 'remove-friend');
404 define('ACTIVITY_FOLLOW',      NAMESPACE_ACTIVITY_SCHEMA . 'follow');
405 define('ACTIVITY_UNFOLLOW',    NAMESPACE_ACTIVITY_SCHEMA . 'stop-following');
406 define('ACTIVITY_JOIN',        NAMESPACE_ACTIVITY_SCHEMA . 'join');
407
408 define('ACTIVITY_POST',        NAMESPACE_ACTIVITY_SCHEMA . 'post');
409 define('ACTIVITY_UPDATE',      NAMESPACE_ACTIVITY_SCHEMA . 'update');
410 define('ACTIVITY_TAG',         NAMESPACE_ACTIVITY_SCHEMA . 'tag');
411 define('ACTIVITY_FAVORITE',    NAMESPACE_ACTIVITY_SCHEMA . 'favorite');
412 define('ACTIVITY_UNFAVORITE',  NAMESPACE_ACTIVITY_SCHEMA . 'unfavorite');
413 define('ACTIVITY_SHARE',       NAMESPACE_ACTIVITY_SCHEMA . 'share');
414 define('ACTIVITY_DELETE',      NAMESPACE_ACTIVITY_SCHEMA . 'delete');
415
416 define('ACTIVITY_POKE',        NAMESPACE_ZOT . '/activity/poke');
417
418 define('ACTIVITY_OBJ_BOOKMARK', NAMESPACE_ACTIVITY_SCHEMA . 'bookmark');
419 define('ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment');
420 define('ACTIVITY_OBJ_NOTE',    NAMESPACE_ACTIVITY_SCHEMA . 'note');
421 define('ACTIVITY_OBJ_PERSON',  NAMESPACE_ACTIVITY_SCHEMA . 'person');
422 define('ACTIVITY_OBJ_IMAGE',   NAMESPACE_ACTIVITY_SCHEMA . 'image');
423 define('ACTIVITY_OBJ_PHOTO',   NAMESPACE_ACTIVITY_SCHEMA . 'photo');
424 define('ACTIVITY_OBJ_VIDEO',   NAMESPACE_ACTIVITY_SCHEMA . 'video');
425 define('ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo');
426 define('ACTIVITY_OBJ_ALBUM',   NAMESPACE_ACTIVITY_SCHEMA . 'photo-album');
427 define('ACTIVITY_OBJ_EVENT',   NAMESPACE_ACTIVITY_SCHEMA . 'event');
428 define('ACTIVITY_OBJ_GROUP',   NAMESPACE_ACTIVITY_SCHEMA . 'group');
429 define('ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN            . '/tagterm');
430 define('ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN            . '/profile');
431 define('ACTIVITY_OBJ_QUESTION', 'http://activityschema.org/object/question');
432 /* @}*/
433
434 /**
435  * @name Gravity
436  *
437  * Item weight for query ordering
438  * @{
439  */
440 define('GRAVITY_PARENT',       0);
441 define('GRAVITY_ACTIVITY',     3);
442 define('GRAVITY_COMMENT',      6);
443 define('GRAVITY_UNKNOWN',      9);
444 /* @}*/
445
446 /**
447  * @name Priority
448  *
449  * Process priority for the worker
450  * @{
451  */
452 define('PRIORITY_UNDEFINED',   0);
453 define('PRIORITY_CRITICAL',   10);
454 define('PRIORITY_HIGH',       20);
455 define('PRIORITY_MEDIUM',     30);
456 define('PRIORITY_LOW',        40);
457 define('PRIORITY_NEGLIGIBLE', 50);
458 /* @}*/
459
460 /**
461  * @name Social Relay settings
462  *
463  * See here: https://github.com/jaywink/social-relay
464  * and here: https://wiki.diasporafoundation.org/Relay_servers_for_public_posts
465  * @{
466  */
467 define('SR_SCOPE_NONE', '');
468 define('SR_SCOPE_ALL',  'all');
469 define('SR_SCOPE_TAGS', 'tags');
470 /* @}*/
471
472 /**
473  * Lowest possible date time value
474  */
475 define('NULL_DATE', '0001-01-01 00:00:00');
476
477 // Normally this constant is defined - but not if "pcntl" isn't installed
478 if (!defined("SIGTERM")) {
479         define("SIGTERM", 15);
480 }
481
482 /**
483  * Depending on the PHP version this constant does exist - or not.
484  * See here: http://php.net/manual/en/curl.constants.php#117928
485  */
486 if (!defined('CURLE_OPERATION_TIMEDOUT')) {
487         define('CURLE_OPERATION_TIMEDOUT', CURLE_OPERATION_TIMEOUTED);
488 }
489
490 /**
491  * @brief Retrieve the App structure
492  *
493  * Useful in functions which require it but don't get it passed to them
494  *
495  * @return App
496  */
497 function get_app()
498 {
499         return BaseObject::getApp();
500 }
501
502 /**
503  * @brief Multi-purpose function to check variable state.
504  *
505  * Usage: x($var) or $x($array, 'key')
506  *
507  * returns false if variable/key is not set
508  * if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
509  * e.g. x('') or x(0) returns 0;
510  *
511  * @param string|array $s variable to check
512  * @param string       $k key inside the array to check
513  *
514  * @return bool|int
515  */
516 function x($s, $k = null)
517 {
518         if ($k != null) {
519                 if ((is_array($s)) && (array_key_exists($k, $s))) {
520                         if ($s[$k]) {
521                                 return (int) 1;
522                         }
523                         return (int) 0;
524                 }
525                 return false;
526         } else {
527                 if (isset($s)) {
528                         if ($s) {
529                                 return (int) 1;
530                         }
531                         return (int) 0;
532                 }
533                 return false;
534         }
535 }
536
537 /**
538  * Return the provided variable value if it exists and is truthy or the provided
539  * default value instead.
540  *
541  * Works with initialized variables and potentially uninitialized array keys
542  *
543  * Usages:
544  * - defaults($var, $default)
545  * - defaults($array, 'key', $default)
546  *
547  * @brief Returns a defaut value if the provided variable or array key is falsy
548  * @see x()
549  * @return mixed
550  */
551 function defaults() {
552         $args = func_get_args();
553
554         if (count($args) < 2) {
555                 throw new BadFunctionCallException('defaults() requires at least 2 parameters');
556         }
557         if (count($args) > 3) {
558                 throw new BadFunctionCallException('defaults() cannot use more than 3 parameters');
559         }
560         if (count($args) === 3 && is_null($args[1])) {
561                 throw new BadFunctionCallException('defaults($arr, $key, $def) $key is null');
562         }
563
564         $default = array_pop($args);
565
566         if (call_user_func_array('x', $args)) {
567                 if (count($args) === 1) {
568                         $return = $args[0];
569                 } else {
570                         $return = $args[0][$args[1]];
571                 }
572         } else {
573                 $return = $default;
574         }
575
576         return $return;
577 }
578
579 /**
580  * @brief Returns the baseurl.
581  *
582  * @see System::baseUrl()
583  *
584  * @return string
585  * @TODO Function is deprecated and only used in some addons
586  */
587 function z_root()
588 {
589         return System::baseUrl();
590 }
591
592 /**
593  * @brief Return absolut URL for given $path.
594  *
595  * @param string $path given path
596  *
597  * @return string
598  */
599 function absurl($path)
600 {
601         if (strpos($path, '/') === 0) {
602                 return z_path() . $path;
603         }
604         return $path;
605 }
606
607 /**
608  * @brief Function to check if request was an AJAX (xmlhttprequest) request.
609  *
610  * @return boolean
611  */
612 function is_ajax()
613 {
614         return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
615 }
616
617 /**
618  * @brief Function to check if request was an AJAX (xmlhttprequest) request.
619  *
620  * @param boolean $via_worker boolean Is the check run via the worker?
621  */
622 function check_db($via_worker)
623 {
624         $build = Config::get('system', 'build');
625
626         if (empty($build)) {
627                 Config::set('system', 'build', DB_UPDATE_VERSION - 1);
628                 $build = DB_UPDATE_VERSION - 1;
629         }
630
631         // We don't support upgrading from very old versions anymore
632         if ($build < NEW_UPDATE_ROUTINE_VERSION) {
633                 die('You try to update from a version prior to database version 1170. The direct upgrade path is not supported. Please update to version 3.5.4 before updating to this version.');
634         }
635
636         if ($build < DB_UPDATE_VERSION) {
637                 // When we cannot execute the database update via the worker, we will do it directly
638                 if (!Worker::add(PRIORITY_CRITICAL, 'DBUpdate') && $via_worker) {
639                         update_db();
640                 }
641         }
642 }
643
644 /**
645  * Sets the base url for use in cmdline programs which don't have
646  * $_SERVER variables
647  *
648  * @param object $a App
649  */
650 function check_url(App $a)
651 {
652         $url = Config::get('system', 'url');
653
654         // if the url isn't set or the stored url is radically different
655         // than the currently visited url, store the current value accordingly.
656         // "Radically different" ignores common variations such as http vs https
657         // and www.example.com vs example.com.
658         // We will only change the url to an ip address if there is no existing setting
659
660         if (empty($url) || (!link_compare($url, System::baseUrl())) && (!preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $a->get_hostname()))) {
661                 Config::set('system', 'url', System::baseUrl());
662         }
663
664         return;
665 }
666
667 /**
668  * @brief Automatic database updates
669  * @param object $a App
670  */
671 function update_db()
672 {
673         $build = Config::get('system', 'build');
674
675         if (empty($build) || ($build > DB_UPDATE_VERSION)) {
676                 $build = DB_UPDATE_VERSION - 1;
677                 Config::set('system', 'build', $build);
678         }
679
680         if ($build != DB_UPDATE_VERSION) {
681                 require_once 'update.php';
682
683                 $stored = intval($build);
684                 $current = intval(DB_UPDATE_VERSION);
685                 if ($stored < $current) {
686                         Config::load('database');
687
688                         // Compare the current structure with the defined structure
689                         $t = Config::get('database', 'dbupdate_' . DB_UPDATE_VERSION);
690                         if (!is_null($t)) {
691                                 return;
692                         }
693
694                         // run the pre_update_nnnn functions in update.php
695                         for ($x = $stored + 1; $x <= $current; $x++) {
696                                 $r = run_update_function($x, 'pre_update');
697                                 if (!$r) {
698                                         break;
699                                 }
700                         }
701
702                         Config::set('database', 'dbupdate_' . DB_UPDATE_VERSION, time());
703
704                         // update the structure in one call
705                         $retval = DBStructure::update(false, true);
706                         if ($retval) {
707                                 DBStructure::updateFail(
708                                         DB_UPDATE_VERSION,
709                                         $retval
710                                 );
711                                 return;
712                         } else {
713                                 Config::set('database', 'dbupdate_' . DB_UPDATE_VERSION, 'success');
714                         }
715
716                         // run the update_nnnn functions in update.php
717                         for ($x = $stored + 1; $x <= $current; $x++) {
718                                 $r = run_update_function($x, 'update');
719                                 if (!$r) {
720                                         break;
721                                 }
722                         }
723                 }
724         }
725
726         return;
727 }
728
729 function run_update_function($x, $prefix)
730 {
731         $funcname = $prefix . '_' . $x;
732
733         if (function_exists($funcname)) {
734                 // There could be a lot of processes running or about to run.
735                 // We want exactly one process to run the update command.
736                 // So store the fact that we're taking responsibility
737                 // after first checking to see if somebody else already has.
738                 // If the update fails or times-out completely you may need to
739                 // delete the config entry to try again.
740
741                 $t = Config::get('database', $funcname);
742                 if (!is_null($t)) {
743                         return false;
744                 }
745                 Config::set('database', $funcname, time());
746
747                 // call the specific update
748                 $retval = $funcname();
749
750                 if ($retval) {
751                         //send the administrator an e-mail
752                         DBStructure::updateFail(
753                                 $x,
754                                 L10n::t('Update %s failed. See error logs.', $x)
755                         );
756                         return false;
757                 } else {
758                         Config::set('database', $funcname, 'success');
759
760                         if ($prefix == 'update') {
761                                 Config::set('system', 'build', $x);
762                         }
763
764                         return true;
765                 }
766         } else {
767                 Config::set('database', $funcname, 'success');
768
769                 if ($prefix == 'update') {
770                         Config::set('system', 'build', $x);
771                 }
772
773                 return true;
774         }
775 }
776
777 /**
778  * @brief Synchronise addons:
779  *
780  * system.addon contains a comma-separated list of names
781  * of addons which are used on this system.
782  * Go through the database list of already installed addons, and if we have
783  * an entry, but it isn't in the config list, call the uninstall procedure
784  * and mark it uninstalled in the database (for now we'll remove it).
785  * Then go through the config list and if we have a addon that isn't installed,
786  * call the install procedure and add it to the database.
787  *
788  * @param object $a App
789  */
790 function check_addons(App $a)
791 {
792         $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
793         if (DBA::isResult($r)) {
794                 $installed = $r;
795         } else {
796                 $installed = [];
797         }
798
799         $addons = Config::get('system', 'addon');
800         $addons_arr = [];
801
802         if ($addons) {
803                 $addons_arr = explode(',', str_replace(' ', '', $addons));
804         }
805
806         $a->addons = $addons_arr;
807
808         $installed_arr = [];
809
810         if (count($installed)) {
811                 foreach ($installed as $i) {
812                         if (!in_array($i['name'], $addons_arr)) {
813                                 Addon::uninstall($i['name']);
814                         } else {
815                                 $installed_arr[] = $i['name'];
816                         }
817                 }
818         }
819
820         if (count($addons_arr)) {
821                 foreach ($addons_arr as $p) {
822                         if (!in_array($p, $installed_arr)) {
823                                 Addon::install($p);
824                         }
825                 }
826         }
827
828         Addon::loadHooks();
829
830         return;
831 }
832
833 /**
834  * @brief Used to end the current process, after saving session state.
835  * @deprecated
836  */
837 function killme()
838 {
839         exit();
840 }
841
842 /**
843  * @brief Redirect to another URL and terminate this process.
844  */
845 function goaway($path)
846 {
847         if (strstr(normalise_link($path), 'http://')) {
848                 $url = $path;
849         } else {
850                 $url = System::baseUrl() . '/' . ltrim($path, '/');
851         }
852
853         header("Location: $url");
854         killme();
855 }
856
857 /**
858  * @brief Returns the user id of locally logged in user or false.
859  *
860  * @return int|bool user id or false
861  */
862 function local_user()
863 {
864         if (!empty($_SESSION['authenticated']) && !empty($_SESSION['uid'])) {
865                 return intval($_SESSION['uid']);
866         }
867         return false;
868 }
869
870 /**
871  * @brief Returns the public contact id of logged in user or false.
872  *
873  * @return int|bool public contact id or false
874  */
875 function public_contact()
876 {
877         static $public_contact_id = false;
878
879         if (!$public_contact_id && x($_SESSION, 'authenticated')) {
880                 if (x($_SESSION, 'my_address')) {
881                         // Local user
882                         $public_contact_id = intval(Contact::getIdForURL($_SESSION['my_address'], 0, true));
883                 } elseif (x($_SESSION, 'visitor_home')) {
884                         // Remote user
885                         $public_contact_id = intval(Contact::getIdForURL($_SESSION['visitor_home'], 0, true));
886                 }
887         } elseif (!x($_SESSION, 'authenticated')) {
888                 $public_contact_id = false;
889         }
890
891         return $public_contact_id;
892 }
893
894 /**
895  * @brief Returns contact id of authenticated site visitor or false
896  *
897  * @return int|bool visitor_id or false
898  */
899 function remote_user()
900 {
901         // You cannot be both local and remote.
902         // Unncommented by rabuzarus because remote authentication to local
903         // profiles wasn't possible anymore (2018-04-12).
904 //      if (local_user()) {
905 //              return false;
906 //      }
907
908         if (empty($_SESSION)) {
909                 return false;
910         }
911
912         if (x($_SESSION, 'authenticated') && x($_SESSION, 'visitor_id')) {
913                 return intval($_SESSION['visitor_id']);
914         }
915         return false;
916 }
917
918 /**
919  * @brief Show an error message to user.
920  *
921  * This function save text in session, to be shown to the user at next page load
922  *
923  * @param string $s - Text of notice
924  */
925 function notice($s)
926 {
927         if (empty($_SESSION)) {
928                 return;
929         }
930
931         $a = get_app();
932         if (!x($_SESSION, 'sysmsg')) {
933                 $_SESSION['sysmsg'] = [];
934         }
935         if ($a->interactive) {
936                 $_SESSION['sysmsg'][] = $s;
937         }
938 }
939
940 /**
941  * @brief Show an info message to user.
942  *
943  * This function save text in session, to be shown to the user at next page load
944  *
945  * @param string $s - Text of notice
946  */
947 function info($s)
948 {
949         $a = get_app();
950
951         if (local_user() && PConfig::get(local_user(), 'system', 'ignore_info')) {
952                 return;
953         }
954
955         if (!x($_SESSION, 'sysmsg_info')) {
956                 $_SESSION['sysmsg_info'] = [];
957         }
958         if ($a->interactive) {
959                 $_SESSION['sysmsg_info'][] = $s;
960         }
961 }
962
963 function feed_birthday($uid, $tz)
964 {
965         /**
966          * Determine the next birthday, but only if the birthday is published
967          * in the default profile. We _could_ also look for a private profile that the
968          * recipient can see, but somebody could get mad at us if they start getting
969          * public birthday greetings when they haven't made this info public.
970          *
971          * Assuming we are able to publish this info, we are then going to convert
972          * the start time from the owner's timezone to UTC.
973          *
974          * This will potentially solve the problem found with some social networks
975          * where birthdays are converted to the viewer's timezone and salutations from
976          * elsewhere in the world show up on the wrong day. We will convert it to the
977          * viewer's timezone also, but first we are going to convert it from the birthday
978          * person's timezone to GMT - so the viewer may find the birthday starting at
979          * 6:00PM the day before, but that will correspond to midnight to the birthday person.
980          */
981         $birthday = '';
982
983         if (!strlen($tz)) {
984                 $tz = 'UTC';
985         }
986
987         $p = q(
988                 "SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
989                 intval($uid)
990         );
991
992         if (DBA::isResult($p)) {
993                 $tmp_dob = substr($p[0]['dob'], 5);
994                 if (intval($tmp_dob)) {
995                         $y = DateTimeFormat::timezoneNow($tz, 'Y');
996                         $bd = $y . '-' . $tmp_dob . ' 00:00';
997                         $t_dob = strtotime($bd);
998                         $now = strtotime(DateTimeFormat::timezoneNow($tz));
999                         if ($t_dob < $now) {
1000                                 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
1001                         }
1002                         $birthday = DateTimeFormat::convert($bd, 'UTC', $tz, DateTimeFormat::ATOM);
1003                 }
1004         }
1005
1006         return $birthday;
1007 }
1008
1009 /**
1010  * @brief Check if current user has admin role.
1011  *
1012  * @return bool true if user is an admin
1013  */
1014 function is_site_admin()
1015 {
1016         $a = get_app();
1017
1018         $admin_email = Config::get('config', 'admin_email');
1019
1020         $adminlist = explode(',', str_replace(' ', '', $admin_email));
1021
1022         return local_user() && $admin_email && in_array(defaults($a->user, 'email', ''), $adminlist);
1023 }
1024
1025 /**
1026  * @brief Returns querystring as string from a mapped array.
1027  *
1028  * @param array  $params mapped array with query parameters
1029  * @param string $name   of parameter, default null
1030  *
1031  * @return string
1032  */
1033 function build_querystring($params, $name = null)
1034 {
1035         $ret = "";
1036         foreach ($params as $key => $val) {
1037                 if (is_array($val)) {
1038                         /// @TODO maybe not compare against null, use is_null()
1039                         if ($name == null) {
1040                                 $ret .= build_querystring($val, $key);
1041                         } else {
1042                                 $ret .= build_querystring($val, $name . "[$key]");
1043                         }
1044                 } else {
1045                         $val = urlencode($val);
1046                         /// @TODO maybe not compare against null, use is_null()
1047                         if ($name != null) {
1048                                 /// @TODO two string concated, can be merged to one
1049                                 $ret .= $name . "[$key]" . "=$val&";
1050                         } else {
1051                                 $ret .= "$key=$val&";
1052                         }
1053                 }
1054         }
1055         return $ret;
1056 }
1057
1058 function explode_querystring($query)
1059 {
1060         $arg_st = strpos($query, '?');
1061         if ($arg_st !== false) {
1062                 $base = substr($query, 0, $arg_st);
1063                 $arg_st += 1;
1064         } else {
1065                 $base = '';
1066                 $arg_st = 0;
1067         }
1068
1069         $args = explode('&', substr($query, $arg_st));
1070         foreach ($args as $k => $arg) {
1071                 /// @TODO really compare type-safe here?
1072                 if ($arg === '') {
1073                         unset($args[$k]);
1074                 }
1075         }
1076         $args = array_values($args);
1077
1078         if (!$base) {
1079                 $base = $args[0];
1080                 unset($args[0]);
1081                 $args = array_values($args);
1082         }
1083
1084         return [
1085                 'base' => $base,
1086                 'args' => $args,
1087         ];
1088 }
1089
1090 /**
1091  * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
1092  *
1093  * Taken from http://webcheatsheet.com/php/get_current_page_url.php
1094  */
1095 function curPageURL()
1096 {
1097         $pageURL = 'http';
1098         if (!empty($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] == "on")) {
1099                 $pageURL .= "s";
1100         }
1101
1102         $pageURL .= "://";
1103
1104         if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
1105                 $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
1106         } else {
1107                 $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
1108         }
1109         return $pageURL;
1110 }
1111
1112 function random_digits($digits)
1113 {
1114         $rn = '';
1115         for ($i = 0; $i < $digits; $i++) {
1116                 /// @TODO Avoid rand/mt_rand, when it comes to cryptography, they are generating predictable (seedable) numbers.
1117                 $rn .= rand(0, 9);
1118         }
1119         return $rn;
1120 }
1121
1122 function get_server()
1123 {
1124         $server = Config::get("system", "directory");
1125
1126         if ($server == "") {
1127                 $server = "https://dir.friendica.social";
1128         }
1129
1130         return $server;
1131 }
1132
1133 function get_temppath()
1134 {
1135         $a = get_app();
1136
1137         $temppath = Config::get("system", "temppath");
1138
1139         if (($temppath != "") && App::directory_usable($temppath)) {
1140                 // We have a temp path and it is usable
1141                 return App::realpath($temppath);
1142         }
1143
1144         // We don't have a working preconfigured temp path, so we take the system path.
1145         $temppath = sys_get_temp_dir();
1146
1147         // Check if it is usable
1148         if (($temppath != "") && App::directory_usable($temppath)) {
1149                 // Always store the real path, not the path through symlinks
1150                 $temppath = App::realpath($temppath);
1151
1152                 // To avoid any interferences with other systems we create our own directory
1153                 $new_temppath = $temppath . "/" . $a->get_hostname();
1154                 if (!is_dir($new_temppath)) {
1155                         /// @TODO There is a mkdir()+chmod() upwards, maybe generalize this (+ configurable) into a function/method?
1156                         mkdir($new_temppath);
1157                 }
1158
1159                 if (App::directory_usable($new_temppath)) {
1160                         // The new path is usable, we are happy
1161                         Config::set("system", "temppath", $new_temppath);
1162                         return $new_temppath;
1163                 } else {
1164                         // We can't create a subdirectory, strange.
1165                         // But the directory seems to work, so we use it but don't store it.
1166                         return $temppath;
1167                 }
1168         }
1169
1170         // Reaching this point means that the operating system is configured badly.
1171         return '';
1172 }
1173
1174 function get_cachefile($file, $writemode = true)
1175 {
1176         $cache = get_itemcachepath();
1177
1178         if ((!$cache) || (!is_dir($cache))) {
1179                 return "";
1180         }
1181
1182         $subfolder = $cache . "/" . substr($file, 0, 2);
1183
1184         $cachepath = $subfolder . "/" . $file;
1185
1186         if ($writemode) {
1187                 if (!is_dir($subfolder)) {
1188                         mkdir($subfolder);
1189                         chmod($subfolder, 0777);
1190                 }
1191         }
1192
1193         return $cachepath;
1194 }
1195
1196 function clear_cache($basepath = "", $path = "")
1197 {
1198         if ($path == "") {
1199                 $basepath = get_itemcachepath();
1200                 $path = $basepath;
1201         }
1202
1203         if (($path == "") || (!is_dir($path))) {
1204                 return;
1205         }
1206
1207         if (substr(realpath($path), 0, strlen($basepath)) != $basepath) {
1208                 return;
1209         }
1210
1211         $cachetime = (int) Config::get('system', 'itemcache_duration');
1212         if ($cachetime == 0) {
1213                 $cachetime = 86400;
1214         }
1215
1216         if (is_writable($path)) {
1217                 if ($dh = opendir($path)) {
1218                         while (($file = readdir($dh)) !== false) {
1219                                 $fullpath = $path . "/" . $file;
1220                                 if ((filetype($fullpath) == "dir") && ($file != ".") && ($file != "..")) {
1221                                         clear_cache($basepath, $fullpath);
1222                                 }
1223                                 if ((filetype($fullpath) == "file") && (filectime($fullpath) < (time() - $cachetime))) {
1224                                         unlink($fullpath);
1225                                 }
1226                         }
1227                         closedir($dh);
1228                 }
1229         }
1230 }
1231
1232 function get_itemcachepath()
1233 {
1234         // Checking, if the cache is deactivated
1235         $cachetime = (int) Config::get('system', 'itemcache_duration');
1236         if ($cachetime < 0) {
1237                 return "";
1238         }
1239
1240         $itemcache = Config::get('system', 'itemcache');
1241         if (($itemcache != "") && App::directory_usable($itemcache)) {
1242                 return App::realpath($itemcache);
1243         }
1244
1245         $temppath = get_temppath();
1246
1247         if ($temppath != "") {
1248                 $itemcache = $temppath . "/itemcache";
1249                 if (!file_exists($itemcache) && !is_dir($itemcache)) {
1250                         mkdir($itemcache);
1251                 }
1252
1253                 if (App::directory_usable($itemcache)) {
1254                         Config::set("system", "itemcache", $itemcache);
1255                         return $itemcache;
1256                 }
1257         }
1258         return "";
1259 }
1260
1261 /**
1262  * @brief Returns the path where spool files are stored
1263  *
1264  * @return string Spool path
1265  */
1266 function get_spoolpath()
1267 {
1268         $spoolpath = Config::get('system', 'spoolpath');
1269         if (($spoolpath != "") && App::directory_usable($spoolpath)) {
1270                 // We have a spool path and it is usable
1271                 return $spoolpath;
1272         }
1273
1274         // We don't have a working preconfigured spool path, so we take the temp path.
1275         $temppath = get_temppath();
1276
1277         if ($temppath != "") {
1278                 // To avoid any interferences with other systems we create our own directory
1279                 $spoolpath = $temppath . "/spool";
1280                 if (!is_dir($spoolpath)) {
1281                         mkdir($spoolpath);
1282                 }
1283
1284                 if (App::directory_usable($spoolpath)) {
1285                         // The new path is usable, we are happy
1286                         Config::set("system", "spoolpath", $spoolpath);
1287                         return $spoolpath;
1288                 } else {
1289                         // We can't create a subdirectory, strange.
1290                         // But the directory seems to work, so we use it but don't store it.
1291                         return $temppath;
1292                 }
1293         }
1294
1295         // Reaching this point means that the operating system is configured badly.
1296         return "";
1297 }
1298
1299 if (!function_exists('exif_imagetype')) {
1300         function exif_imagetype($file)
1301         {
1302                 $size = getimagesize($file);
1303                 return $size[2];
1304         }
1305 }
1306
1307 function validate_include(&$file)
1308 {
1309         $orig_file = $file;
1310
1311         $file = realpath($file);
1312
1313         if (strpos($file, getcwd()) !== 0) {
1314                 return false;
1315         }
1316
1317         $file = str_replace(getcwd() . "/", "", $file, $count);
1318         if ($count != 1) {
1319                 return false;
1320         }
1321
1322         if ($orig_file !== $file) {
1323                 return false;
1324         }
1325
1326         $valid = false;
1327         if (strpos($file, "include/") === 0) {
1328                 $valid = true;
1329         }
1330
1331         if (strpos($file, "addon/") === 0) {
1332                 $valid = true;
1333         }
1334
1335         // Simply return flag
1336         return $valid;
1337 }
1338
1339 function current_load()
1340 {
1341         if (!function_exists('sys_getloadavg')) {
1342                 return false;
1343         }
1344
1345         $load_arr = sys_getloadavg();
1346
1347         if (!is_array($load_arr)) {
1348                 return false;
1349         }
1350
1351         return max($load_arr[0], $load_arr[1]);
1352 }
1353
1354 /**
1355  * @brief get c-style args
1356  *
1357  * @return int
1358  */
1359 function argc()
1360 {
1361         return get_app()->argc;
1362 }
1363
1364 /**
1365  * @brief Returns the value of a argv key
1366  *
1367  * @param int $x argv key
1368  * @return string Value of the argv key
1369  */
1370 function argv($x)
1371 {
1372         if (array_key_exists($x, get_app()->argv)) {
1373                 return get_app()->argv[$x];
1374         }
1375
1376         return '';
1377 }
1378
1379 /**
1380  * @brief Get the data which is needed for infinite scroll
1381  *
1382  * For invinite scroll we need the page number of the actual page
1383  * and the the URI where the content of the next page comes from.
1384  * This data is needed for the js part in main.js.
1385  * Note: infinite scroll does only work for the network page (module)
1386  *
1387  * @param string $module The name of the module (e.g. "network")
1388  * @return array Of infinite scroll data
1389  *      'pageno' => $pageno The number of the actual page
1390  *      'reload_uri' => $reload_uri The URI of the content we have to load
1391  */
1392 function infinite_scroll_data($module)
1393 {
1394         if (PConfig::get(local_user(), 'system', 'infinite_scroll')
1395                 && $module == 'network'
1396                 && defaults($_GET, 'mode', '') != 'minimal'
1397         ) {
1398                 // get the page number
1399                 $pageno = defaults($_GET, 'page', 1);
1400
1401                 $reload_uri = "";
1402
1403                 // try to get the uri from which we load the content
1404                 foreach ($_GET as $param => $value) {
1405                         if (($param != "page") && ($param != "q")) {
1406                                 $reload_uri .= "&" . $param . "=" . urlencode($value);
1407                         }
1408                 }
1409
1410                 $a = get_app();
1411                 if ($a->page_offset != "" && !strstr($reload_uri, "&offset=")) {
1412                         $reload_uri .= "&offset=" . urlencode($a->page_offset);
1413                 }
1414
1415                 $arr = ["pageno" => $pageno, "reload_uri" => $reload_uri];
1416
1417                 return $arr;
1418         }
1419 }