]> git.mxchange.org Git - friendica.git/blob - boot.php
Bugfix: The notify value for Diaspora wasn't assigned
[friendica.git] / boot.php
1 <?php
2 /** @file boot.php
3  *
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('include/autoloader.php');
21
22 require_once('include/config.php');
23 require_once('include/network.php');
24 require_once('include/plugin.php');
25 require_once('include/text.php');
26 require_once('include/datetime.php');
27 require_once('include/pgettext.php');
28 require_once('include/nav.php');
29 require_once('include/cache.php');
30 require_once('library/Mobile_Detect/Mobile_Detect.php');
31 require_once('include/features.php');
32 require_once('include/identity.php');
33 require_once('include/pidfile.php');
34 require_once('update.php');
35 require_once('include/dbstructure.php');
36
37 define ( 'FRIENDICA_PLATFORM',     'Friendica');
38 define ( 'FRIENDICA_CODENAME',     'Asparagus');
39 define ( 'FRIENDICA_VERSION',      '3.5-dev' );
40 define ( 'DFRN_PROTOCOL_VERSION',  '2.23'    );
41 define ( 'DB_UPDATE_VERSION',      1198      );
42
43 /**
44  * @brief Constant with a HTML line break.
45  *
46  * Contains a HTML line break (br) element and a real carriage return with line
47  * feed for the source.
48  * This can be used in HTML and JavaScript where needed a line break.
49  */
50 define ( 'EOL',                    "<br />\r\n"     );
51 define ( 'ATOM_TIME',              'Y-m-d\TH:i:s\Z' );
52
53
54 /**
55  * @brief Image storage quality.
56  * 
57  * Lower numbers save space at cost of image detail.
58  * For ease of upgrade, please do not change here. Change jpeg quality with
59  * $a->config['system']['jpeg_quality'] = n;
60  * in .htconfig.php, where n is netween 1 and 100, and with very poor results
61  * below about 50
62  *
63  */
64
65 define ( 'JPEG_QUALITY',            100  );
66 /**
67  * $a->config['system']['png_quality'] from 0 (uncompressed) to 9
68  */
69 define ( 'PNG_QUALITY',             8  );
70
71 /**
72  *
73  * An alternate way of limiting picture upload sizes. Specify the maximum pixel
74  * length that pictures are allowed to be (for non-square pictures, it will apply
75  * to the longest side). Pictures longer than this length will be resized to be
76  * this length (on the longest side, the other side will be scaled appropriately).
77  * Modify this value using
78  *
79  *    $a->config['system']['max_image_length'] = n;
80  *
81  * in .htconfig.php
82  *
83  * If you don't want to set a maximum length, set to -1. The default value is
84  * defined by 'MAX_IMAGE_LENGTH' below.
85  *
86  */
87 define ( 'MAX_IMAGE_LENGTH',        -1  );
88
89
90 /**
91  * Not yet used
92  */
93
94 define ( 'DEFAULT_DB_ENGINE',  'MyISAM'  );
95
96 /**
97  * @name SSL Policy
98  * 
99  * SSL redirection policies
100  * @{
101  */
102 define ( 'SSL_POLICY_NONE',         0 );
103 define ( 'SSL_POLICY_FULL',         1 );
104 define ( 'SSL_POLICY_SELFSIGN',     2 );
105 /* @}*/
106
107 /**
108  * @name Logger
109  * 
110  * log levels
111  * @{
112  */
113 define ( 'LOGGER_NORMAL',          0 );
114 define ( 'LOGGER_TRACE',           1 );
115 define ( 'LOGGER_DEBUG',           2 );
116 define ( 'LOGGER_DATA',            3 );
117 define ( 'LOGGER_ALL',             4 );
118 /* @}*/
119
120 /**
121  * @name Cache
122  * 
123  * Cache levels
124  * @{
125  */
126 define ( 'CACHE_MONTH',            0 );
127 define ( 'CACHE_WEEK',             1 );
128 define ( 'CACHE_DAY',              2 );
129 define ( 'CACHE_HOUR',             3 );
130 /* @}*/
131
132 /**
133  * @name Register
134  * 
135  * Registration policies
136  * @{
137  */
138 define ( 'REGISTER_CLOSED',        0 );
139 define ( 'REGISTER_APPROVE',       1 );
140 define ( 'REGISTER_OPEN',          2 );
141 /** @}*/
142
143 /**
144  * @name Contact_is
145  * 
146  * Relationship types
147  * @{
148  */
149 define ( 'CONTACT_IS_FOLLOWER', 1);
150 define ( 'CONTACT_IS_SHARING',  2);
151 define ( 'CONTACT_IS_FRIEND',   3);
152 /** @}*/
153
154 /**
155  * @name Update
156  * 
157  * DB update return values
158  * @{
159  */
160 define ( 'UPDATE_SUCCESS', 0);
161 define ( 'UPDATE_FAILED',  1);
162 /** @}*/
163
164
165 /**
166  * @name page/profile types
167  *
168  * PAGE_NORMAL is a typical personal profile account
169  * PAGE_SOAPBOX automatically approves all friend requests as CONTACT_IS_SHARING, (readonly)
170  * PAGE_COMMUNITY automatically approves all friend requests as CONTACT_IS_SHARING, but with
171  *      write access to wall and comments (no email and not included in page owner's ACL lists)
172  * PAGE_FREELOVE automatically approves all friend requests as full friends (CONTACT_IS_FRIEND).
173  *
174  * @{
175  */
176 define ( 'PAGE_NORMAL',            0 );
177 define ( 'PAGE_SOAPBOX',           1 );
178 define ( 'PAGE_COMMUNITY',         2 );
179 define ( 'PAGE_FREELOVE',          3 );
180 define ( 'PAGE_BLOG',              4 );
181 define ( 'PAGE_PRVGROUP',          5 );
182 /** @}*/
183
184 /**
185  * @name CP
186  * 
187  * Type of the community page
188  * @{
189  */
190 define ( 'CP_NO_COMMUNITY_PAGE',   -1 );
191 define ( 'CP_USERS_ON_SERVER',     0 );
192 define ( 'CP_GLOBAL_COMMUNITY',    1 );
193 /** @}*/
194
195 /**
196  * @name Network
197  * 
198  * Network and protocol family types
199  * @{
200  */
201 define ( 'NETWORK_DFRN',             'dfrn');    // Friendica, Mistpark, other DFRN implementations
202 define ( 'NETWORK_ZOT',              'zot!');    // Zot!
203 define ( 'NETWORK_OSTATUS',          'stat');    // status.net, identi.ca, GNU-social, other OStatus implementations
204 define ( 'NETWORK_FEED',             'feed');    // RSS/Atom feeds with no known "post/notify" protocol
205 define ( 'NETWORK_DIASPORA',         'dspr');    // Diaspora
206 define ( 'NETWORK_MAIL',             'mail');    // IMAP/POP
207 define ( 'NETWORK_MAIL2',            'mai2');    // extended IMAP/POP
208 define ( 'NETWORK_FACEBOOK',         'face');    // Facebook API
209 define ( 'NETWORK_LINKEDIN',         'lnkd');    // LinkedIn
210 define ( 'NETWORK_XMPP',             'xmpp');    // XMPP
211 define ( 'NETWORK_MYSPACE',          'mysp');    // MySpace
212 define ( 'NETWORK_GPLUS',            'goog');    // Google+
213 define ( 'NETWORK_PUMPIO',           'pump');    // pump.io
214 define ( 'NETWORK_TWITTER',          'twit');    // Twitter
215 define ( 'NETWORK_DIASPORA2',        'dspc');    // Diaspora connector
216 define ( 'NETWORK_STATUSNET',        'stac');    // Statusnet connector
217 define ( 'NETWORK_APPNET',           'apdn');    // app.net
218 define ( 'NETWORK_NEWS',             'nntp');    // Network News Transfer Protocol
219 define ( 'NETWORK_ICALENDAR',        'ical');    // iCalendar
220 define ( 'NETWORK_PHANTOM',          'unkn');    // Place holder
221 /** @}*/
222
223 /**
224  * These numbers are used in stored permissions
225  * and existing allocations MUST NEVER BE CHANGED
226  * OR RE-ASSIGNED! You may only add to them.
227  */
228
229 $netgroup_ids = array(
230         NETWORK_DFRN     => (-1),
231         NETWORK_ZOT      => (-2),
232         NETWORK_OSTATUS  => (-3),
233         NETWORK_FEED     => (-4),
234         NETWORK_DIASPORA => (-5),
235         NETWORK_MAIL     => (-6),
236         NETWORK_MAIL2    => (-7),
237         NETWORK_FACEBOOK => (-8),
238         NETWORK_LINKEDIN => (-9),
239         NETWORK_XMPP     => (-10),
240         NETWORK_MYSPACE  => (-11),
241         NETWORK_GPLUS    => (-12),
242         NETWORK_PUMPIO   => (-13),
243         NETWORK_TWITTER  => (-14),
244         NETWORK_DIASPORA2 => (-15),
245         NETWORK_STATUSNET => (-16),
246         NETWORK_APPNET    => (-17),
247         NETWORK_NEWS      => (-18),
248         NETWORK_ICALENDAR => (-19),
249
250         NETWORK_PHANTOM  => (-127),
251 );
252
253
254 /**
255  * Maximum number of "people who like (or don't like) this"  that we will list by name
256  */
257
258 define ( 'MAX_LIKERS',    75);
259
260 /**
261  * Communication timeout
262  */
263
264 define ( 'ZCURL_TIMEOUT' , (-1));
265
266
267 /**
268  * @name Notify
269  * 
270  * Email notification options
271  * @{
272  */
273 define ( 'NOTIFY_INTRO',    0x0001 );
274 define ( 'NOTIFY_CONFIRM',  0x0002 );
275 define ( 'NOTIFY_WALL',     0x0004 );
276 define ( 'NOTIFY_COMMENT',  0x0008 );
277 define ( 'NOTIFY_MAIL',     0x0010 );
278 define ( 'NOTIFY_SUGGEST',  0x0020 );
279 define ( 'NOTIFY_PROFILE',  0x0040 );
280 define ( 'NOTIFY_TAGSELF',  0x0080 );
281 define ( 'NOTIFY_TAGSHARE', 0x0100 );
282 define ( 'NOTIFY_POKE',     0x0200 );
283 define ( 'NOTIFY_SHARE',    0x0400 );
284
285 define ( 'NOTIFY_SYSTEM',   0x8000 );
286 /* @}*/
287
288
289 /**
290  * @name Term
291  * 
292  * Tag/term types
293  * @{
294  */
295 define ( 'TERM_UNKNOWN',   0 );
296 define ( 'TERM_HASHTAG',   1 );
297 define ( 'TERM_MENTION',   2 );
298 define ( 'TERM_CATEGORY',  3 );
299 define ( 'TERM_PCATEGORY', 4 );
300 define ( 'TERM_FILE',      5 );
301 define ( 'TERM_SAVEDSEARCH', 6 );
302 define ( 'TERM_CONVERSATION', 7 );
303
304 define ( 'TERM_OBJ_POST',  1 );
305 define ( 'TERM_OBJ_PHOTO', 2 );
306
307
308
309 /**
310  * @name Namespaces
311  * 
312  * Various namespaces we may need to parse
313  * @{
314  */
315 define ( 'NAMESPACE_ZOT',             'http://purl.org/zot' );
316 define ( 'NAMESPACE_DFRN' ,           'http://purl.org/macgirvin/dfrn/1.0' );
317 define ( 'NAMESPACE_THREAD' ,         'http://purl.org/syndication/thread/1.0' );
318 define ( 'NAMESPACE_TOMB' ,           'http://purl.org/atompub/tombstones/1.0' );
319 define ( 'NAMESPACE_ACTIVITY',        'http://activitystrea.ms/spec/1.0/' );
320 define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/' );
321 define ( 'NAMESPACE_MEDIA',           'http://purl.org/syndication/atommedia' );
322 define ( 'NAMESPACE_SALMON_ME',       'http://salmon-protocol.org/ns/magic-env' );
323 define ( 'NAMESPACE_OSTATUSSUB',      'http://ostatus.org/schema/1.0/subscribe' );
324 define ( 'NAMESPACE_GEORSS',          'http://www.georss.org/georss' );
325 define ( 'NAMESPACE_POCO',            'http://portablecontacts.net/spec/1.0' );
326 define ( 'NAMESPACE_FEED',            'http://schemas.google.com/g/2010#updates-from' );
327 define ( 'NAMESPACE_OSTATUS',         'http://ostatus.org/schema/1.0' );
328 define ( 'NAMESPACE_STATUSNET',       'http://status.net/schema/api/1/' );
329 define ( 'NAMESPACE_ATOM1',           'http://www.w3.org/2005/Atom' );
330 /* @}*/
331
332 /**
333  * @name Activity
334  * 
335  * Activity stream defines
336  * @{
337  */
338 define ( 'ACTIVITY_LIKE',        NAMESPACE_ACTIVITY_SCHEMA . 'like' );
339 define ( 'ACTIVITY_DISLIKE',     NAMESPACE_DFRN            . '/dislike' );
340 define ( 'ACTIVITY_ATTEND',      NAMESPACE_ZOT             . '/activity/attendyes' );
341 define ( 'ACTIVITY_ATTENDNO',    NAMESPACE_ZOT             . '/activity/attendno' );
342 define ( 'ACTIVITY_ATTENDMAYBE', NAMESPACE_ZOT             . '/activity/attendmaybe' );
343
344 define ( 'ACTIVITY_OBJ_HEART',   NAMESPACE_DFRN            . '/heart' );
345
346 define ( 'ACTIVITY_FRIEND',      NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
347 define ( 'ACTIVITY_REQ_FRIEND',  NAMESPACE_ACTIVITY_SCHEMA . 'request-friend' );
348 define ( 'ACTIVITY_UNFRIEND',    NAMESPACE_ACTIVITY_SCHEMA . 'remove-friend' );
349 define ( 'ACTIVITY_FOLLOW',      NAMESPACE_ACTIVITY_SCHEMA . 'follow' );
350 define ( 'ACTIVITY_UNFOLLOW',    NAMESPACE_ACTIVITY_SCHEMA . 'stop-following' );
351 define ( 'ACTIVITY_JOIN',        NAMESPACE_ACTIVITY_SCHEMA . 'join' );
352
353 define ( 'ACTIVITY_POST',        NAMESPACE_ACTIVITY_SCHEMA . 'post' );
354 define ( 'ACTIVITY_UPDATE',      NAMESPACE_ACTIVITY_SCHEMA . 'update' );
355 define ( 'ACTIVITY_TAG',         NAMESPACE_ACTIVITY_SCHEMA . 'tag' );
356 define ( 'ACTIVITY_FAVORITE',    NAMESPACE_ACTIVITY_SCHEMA . 'favorite' );
357 define ( 'ACTIVITY_SHARE',       NAMESPACE_ACTIVITY_SCHEMA . 'share' );
358
359 define ( 'ACTIVITY_POKE',        NAMESPACE_ZOT . '/activity/poke' );
360 define ( 'ACTIVITY_MOOD',        NAMESPACE_ZOT . '/activity/mood' );
361
362 define ( 'ACTIVITY_OBJ_BOOKMARK', NAMESPACE_ACTIVITY_SCHEMA . 'bookmark' );
363 define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
364 define ( 'ACTIVITY_OBJ_NOTE',    NAMESPACE_ACTIVITY_SCHEMA . 'note' );
365 define ( 'ACTIVITY_OBJ_PERSON',  NAMESPACE_ACTIVITY_SCHEMA . 'person' );
366 define ( 'ACTIVITY_OBJ_IMAGE',   NAMESPACE_ACTIVITY_SCHEMA . 'image' );
367 define ( 'ACTIVITY_OBJ_PHOTO',   NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
368 define ( 'ACTIVITY_OBJ_VIDEO',   NAMESPACE_ACTIVITY_SCHEMA . 'video' );
369 define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
370 define ( 'ACTIVITY_OBJ_ALBUM',   NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
371 define ( 'ACTIVITY_OBJ_EVENT',   NAMESPACE_ACTIVITY_SCHEMA . 'event' );
372 define ( 'ACTIVITY_OBJ_GROUP',   NAMESPACE_ACTIVITY_SCHEMA . 'group' );
373 define ( 'ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN            . '/tagterm' );
374 define ( 'ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN            . '/profile' );
375 define ( 'ACTIVITY_OBJ_QUESTION', 'http://activityschema.org/object/question' );
376 /* @}*/
377
378 /**
379  * @name Gravity
380  * 
381  * Item weight for query ordering
382  * @{
383  */
384 define ( 'GRAVITY_PARENT',       0);
385 define ( 'GRAVITY_LIKE',         3);
386 define ( 'GRAVITY_COMMENT',      6);
387 /* @}*/
388
389
390 // Normally this constant is defined - but not if "pcntl" isn't installed
391 if (!defined("SIGTERM"))
392         define("SIGTERM", 15);
393
394 /**
395  *
396  * Reverse the effect of magic_quotes_gpc if it is enabled.
397  * Please disable magic_quotes_gpc so we don't have to do this.
398  * See http://php.net/manual/en/security.magicquotes.disabling.php
399  *
400  */
401
402 function startup() {
403
404         error_reporting(E_ERROR | E_WARNING | E_PARSE);
405
406         set_time_limit(0);
407
408         // This has to be quite large to deal with embedded private photos
409         ini_set('pcre.backtrack_limit', 500000);
410
411
412         if (get_magic_quotes_gpc()) {
413                 $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
414                 while (list($key, $val) = each($process)) {
415                         foreach ($val as $k => $v) {
416                                 unset($process[$key][$k]);
417                                 if (is_array($v)) {
418                                         $process[$key][stripslashes($k)] = $v;
419                                         $process[] = &$process[$key][stripslashes($k)];
420                                 } else {
421                                         $process[$key][stripslashes($k)] = stripslashes($v);
422                                 }
423                         }
424                 }
425                 unset($process);
426         }
427
428 }
429
430 /**
431  *
432  * class: App
433  * 
434  * @brief Our main application structure for the life of this page.
435  * 
436  * Primarily deals with the URL that got us here
437  * and tries to make some sense of it, and
438  * stores our page contents and config storage
439  * and anything else that might need to be passed around
440  * before we spit the page out.
441  *
442  */
443 class App {
444
445         public  $module_loaded = false;
446         public  $query_string;
447         public  $config;
448         public  $page;
449         public  $profile;
450         public  $profile_uid;
451         public  $user;
452         public  $cid;
453         public  $contact;
454         public  $contacts;
455         public  $page_contact;
456         public  $content;
457         public  $data = array();
458         public  $error = false;
459         public  $cmd;
460         public  $argv;
461         public  $argc;
462         public  $module;
463         public  $pager;
464         public  $strings;
465         public  $path;
466         public  $hooks;
467         public  $timezone;
468         public  $interactive = true;
469         public  $plugins;
470         public  $apps = array();
471         public  $identities;
472         public  $is_mobile = false;
473         public  $is_tablet = false;
474         public  $is_friendica_app;
475         public  $performance = array();
476         public  $callstack = array();
477         public  $theme_info = array();
478
479         public $nav_sel;
480
481         public $category;
482
483
484         // Allow themes to control internal parameters
485         // by changing App values in theme.php
486
487         public  $sourcename = '';
488         public  $videowidth = 425;
489         public  $videoheight = 350;
490         public  $force_max_items = 0;
491         public  $theme_thread_allow = true;
492         public  $theme_events_in_profile = true;
493
494         /**
495          * @brief An array for all theme-controllable parameters
496          *
497          * Mostly unimplemented yet. Only options 'template_engine' and
498          * beyond are used.
499          */
500         public  $theme = array(
501                 'sourcename' => '',
502                 'videowidth' => 425,
503                 'videoheight' => 350,
504                 'force_max_items' => 0,
505                 'thread_allow' => true,
506                 'stylesheet' => '',
507                 'template_engine' => 'smarty3',
508         );
509
510         /**
511          * @brief An array of registered template engines ('name'=>'class name')
512          */
513         public $template_engines = array();
514         /**
515          * @brief An array of instanced template engines ('name'=>'instance')
516          */
517         public $template_engine_instance = array();
518
519         private $ldelim = array(
520                 'internal' => '',
521                 'smarty3' => '{{'
522         );
523         private $rdelim = array(
524                 'internal' => '',
525                 'smarty3' => '}}'
526         );
527
528         private $scheme;
529         private $hostname;
530         private $baseurl;
531         private $db;
532
533         private $curl_code;
534         private $curl_content_type;
535         private $curl_headers;
536
537         private $cached_profile_image;
538         private $cached_profile_picdate;
539
540         private static $a;
541
542         /**
543          * @brief App constructor.
544          */
545         function __construct() {
546
547                 global $default_timezone;
548
549                 $hostname = "";
550
551                 if (file_exists(".htpreconfig.php"))
552                         @include(".htpreconfig.php");
553
554                 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
555
556                 date_default_timezone_set($this->timezone);
557
558                 $this->performance["start"] = microtime(true);
559                 $this->performance["database"] = 0;
560                 $this->performance["network"] = 0;
561                 $this->performance["file"] = 0;
562                 $this->performance["rendering"] = 0;
563                 $this->performance["parser"] = 0;
564                 $this->performance["marktime"] = 0;
565                 $this->performance["markstart"] = microtime(true);
566
567                 $this->callstack["database"] = array();
568                 $this->callstack["network"] = array();
569                 $this->callstack["file"] = array();
570                 $this->callstack["rendering"] = array();
571                 $this->callstack["parser"] = array();
572
573                 $this->config = array();
574                 $this->page = array();
575                 $this->pager= array();
576
577                 $this->query_string = '';
578
579                 startup();
580
581                 set_include_path(
582                                 'include' . PATH_SEPARATOR
583                                 . 'library' . PATH_SEPARATOR
584                                 . 'library/phpsec' . PATH_SEPARATOR
585                                 . 'library/langdet' . PATH_SEPARATOR
586                                 . '.' );
587
588
589                 $this->scheme = 'http';
590                 if((x($_SERVER,'HTTPS') && $_SERVER['HTTPS']) ||
591                    (x($_SERVER['HTTP_FORWARDED']) && preg_match("/proto=https/", $_SERVER['HTTP_FORWARDED'])) ||
592                    (x($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
593                    (x($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
594                    (x($_SERVER['FRONT_END_HTTPS']) && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
595                    (x($_SERVER,'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
596                    ) {
597                         $this->scheme = 'https';
598                    }
599
600                 if(x($_SERVER,'SERVER_NAME')) {
601                         $this->hostname = $_SERVER['SERVER_NAME'];
602
603                         if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
604                                 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
605                         /*
606                          * Figure out if we are running at the top of a domain
607                          * or in a sub-directory and adjust accordingly
608                          */
609
610                         $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
611                         if(isset($path) && strlen($path) && ($path != $this->path))
612                                 $this->path = $path;
613                 }
614
615                 if ($hostname != "")
616                         $this->hostname = $hostname;
617
618                 if (is_array($_SERVER["argv"]) && $_SERVER["argc"]>1 && substr(end($_SERVER["argv"]), 0, 4)=="http" ) {
619                         $this->set_baseurl(array_pop($_SERVER["argv"]) );
620                         $_SERVER["argc"] --;
621                 }
622
623                 #set_include_path("include/$this->hostname" . PATH_SEPARATOR . get_include_path());
624
625                 if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,9) === "pagename=") {
626                         $this->query_string = substr($_SERVER['QUERY_STRING'],9);
627                         // removing trailing / - maybe a nginx problem
628                         if (substr($this->query_string, 0, 1) == "/")
629                                 $this->query_string = substr($this->query_string, 1);
630                 } elseif((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
631                         $this->query_string = substr($_SERVER['QUERY_STRING'],2);
632                         // removing trailing / - maybe a nginx problem
633                         if (substr($this->query_string, 0, 1) == "/")
634                                 $this->query_string = substr($this->query_string, 1);
635                 }
636
637                 if (x($_GET,'pagename'))
638                         $this->cmd = trim($_GET['pagename'],'/\\');
639                 elseif (x($_GET,'q'))
640                         $this->cmd = trim($_GET['q'],'/\\');
641
642
643                 // fix query_string
644                 $this->query_string = str_replace($this->cmd."&",$this->cmd."?", $this->query_string);
645
646
647                 // unix style "homedir"
648
649                 if(substr($this->cmd,0,1) === '~')
650                         $this->cmd = 'profile/' . substr($this->cmd,1);
651
652                 // Diaspora style profile url
653
654                 if(substr($this->cmd,0,2) === 'u/')
655                         $this->cmd = 'profile/' . substr($this->cmd,2);
656
657
658                 /*
659                  *
660                  * Break the URL path into C style argc/argv style arguments for our
661                  * modules. Given "http://example.com/module/arg1/arg2", $this->argc
662                  * will be 3 (integer) and $this->argv will contain:
663                  *   [0] => 'module'
664                  *   [1] => 'arg1'
665                  *   [2] => 'arg2'
666                  *
667                  *
668                  * There will always be one argument. If provided a naked domain
669                  * URL, $this->argv[0] is set to "home".
670                  *
671                  */
672
673                 $this->argv = explode('/',$this->cmd);
674                 $this->argc = count($this->argv);
675                 if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
676                         $this->module = str_replace(".", "_", $this->argv[0]);
677                         $this->module = str_replace("-", "_", $this->module);
678                 }
679                 else {
680                         $this->argc = 1;
681                         $this->argv = array('home');
682                         $this->module = 'home';
683                 }
684
685                 /*
686                  * See if there is any page number information, and initialise
687                  * pagination
688                  */
689
690                 $this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
691                 $this->pager['itemspage'] = 50;
692                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
693                 if($this->pager['start'] < 0)
694                         $this->pager['start'] = 0;
695                 $this->pager['total'] = 0;
696
697                 /*
698                  * Detect mobile devices
699                  */
700
701                 $mobile_detect = new Mobile_Detect();
702                 $this->is_mobile = $mobile_detect->isMobile();
703                 $this->is_tablet = $mobile_detect->isTablet();
704
705                 // Friendica-Client
706                 $this->is_friendica_app = ($_SERVER['HTTP_USER_AGENT'] == "Apache-HttpClient/UNAVAILABLE (java 1.4)");
707
708                 /*
709                  * register template engines
710                  */
711                 $dc = get_declared_classes();
712                 foreach ($dc as $k) {
713                         if (in_array("ITemplateEngine", class_implements($k))){
714                                 $this->register_template_engine($k);
715                         }
716                 }
717
718                 self::$a = $this;
719
720         }
721
722         function get_basepath() {
723
724                 $basepath = get_config("system", "basepath");
725
726                 if ($basepath == "")
727                         $basepath = dirname(__FILE__);
728
729                 if ($basepath == "")
730                         $basepath = $_SERVER["DOCUMENT_ROOT"];
731
732                 if ($basepath == "")
733                         $basepath = $_SERVER["PWD"];
734
735                 return($basepath);
736         }
737
738         function get_scheme() {
739                 return($this->scheme);
740         }
741
742         function get_baseurl($ssl = false) {
743
744                 // Is the function called statically?
745                 if (!is_object($this))
746                         return(self::$a->get_baseurl($ssl));
747
748                 $scheme = $this->scheme;
749
750                 if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
751                         if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
752                                 $scheme = 'https';
753
754                         //      Basically, we have $ssl = true on any links which can only be seen by a logged in user
755                         //      (and also the login link). Anything seen by an outsider will have it turned off.
756
757                         if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
758                                 if($ssl)
759                                         $scheme = 'https';
760                                 else
761                                         $scheme = 'http';
762                         }
763                 }
764
765                 if (get_config('config','hostname') != "")
766                         $this->hostname = get_config('config','hostname');
767
768                 $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
769                 return $this->baseurl;
770         }
771
772         function set_baseurl($url) {
773                 $parsed = @parse_url($url);
774
775                 $this->baseurl = $url;
776
777                 if($parsed) {
778                         $this->scheme = $parsed['scheme'];
779
780                         $hostname = $parsed['host'];
781                         if(x($parsed,'port'))
782                                 $hostname .= ':' . $parsed['port'];
783                         if(x($parsed,'path'))
784                                 $this->path = trim($parsed['path'],'\\/');
785
786                         if (file_exists(".htpreconfig.php"))
787                                 @include(".htpreconfig.php");
788
789                         if (get_config('config','hostname') != "")
790                                 $this->hostname = get_config('config','hostname');
791
792                         if (!isset($this->hostname) OR ($this->hostname == ""))
793                                 $this->hostname = $hostname;
794                 }
795
796         }
797
798         function get_hostname() {
799                 if (get_config('config','hostname') != "")
800                         $this->hostname = get_config('config','hostname');
801
802                 return $this->hostname;
803         }
804
805         function set_hostname($h) {
806                 $this->hostname = $h;
807         }
808
809         function set_path($p) {
810                 $this->path = trim(trim($p),'/');
811         }
812
813         function get_path() {
814                 return $this->path;
815         }
816
817         function set_pager_total($n) {
818                 $this->pager['total'] = intval($n);
819         }
820
821         function set_pager_itemspage($n) {
822                 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
823                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
824         }
825
826         function set_pager_page($n) {
827                 $this->pager['page'] = $n;
828                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
829         }
830
831         function init_pagehead() {
832                 $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
833
834                 // If the update is "deactivated" set it to the highest integer number (~24 days)
835                 if ($interval < 0)
836                         $interval = 2147483647;
837
838                 if($interval < 10000)
839                         $interval = 40000;
840
841                 // compose the page title from the sitename and the
842                 // current module called
843                 if (!$this->module=='')
844                 {
845                     $this->page['title'] = $this->config['sitename'].' ('.$this->module.')';
846                 } else {
847                     $this->page['title'] = $this->config['sitename'];
848                 }
849
850                 /* put the head template at the beginning of page['htmlhead']
851                  * since the code added by the modules frequently depends on it
852                  * being first
853                  */
854                 if(!isset($this->page['htmlhead']))
855                         $this->page['htmlhead'] = '';
856
857                 // If we're using Smarty, then doing replace_macros() will replace
858                 // any unrecognized variables with a blank string. Since we delay
859                 // replacing $stylesheet until later, we need to replace it now
860                 // with another variable name
861                 if($this->theme['template_engine'] === 'smarty3')
862                         $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
863                 else
864                         $stylesheet = '$stylesheet';
865
866                 $shortcut_icon = get_config("system", "shortcut_icon");
867                 if ($shortcut_icon == "")
868                         $shortcut_icon = "images/friendica-32.png";
869
870                 $touch_icon = get_config("system", "touch_icon");
871                 if ($touch_icon == "")
872                         $touch_icon = "images/friendica-128.png";
873
874                 // get data wich is needed for infinite scroll on the network page
875                 $invinite_scroll = infinite_scroll_data($this->module);
876
877                 $tpl = get_markup_template('head.tpl');
878                 $this->page['htmlhead'] = replace_macros($tpl,array(
879                         '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
880                         '$local_user' => local_user(),
881                         '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
882                         '$delitem' => t('Delete this item?'),
883                         '$comment' => t('Comment'),
884                         '$showmore' => t('show more'),
885                         '$showfewer' => t('show fewer'),
886                         '$update_interval' => $interval,
887                         '$shortcut_icon' => $shortcut_icon,
888                         '$touch_icon' => $touch_icon,
889                         '$stylesheet' => $stylesheet,
890                         '$infinite_scroll' => $invinite_scroll,
891                 )) . $this->page['htmlhead'];
892         }
893
894         function init_page_end() {
895                 if(!isset($this->page['end']))
896                         $this->page['end'] = '';
897                 $tpl = get_markup_template('end.tpl');
898                 $this->page['end'] = replace_macros($tpl,array(
899                         '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
900                 )) . $this->page['end'];
901         }
902
903         function set_curl_code($code) {
904                 $this->curl_code = $code;
905         }
906
907         function get_curl_code() {
908                 return $this->curl_code;
909         }
910
911         function set_curl_content_type($content_type) {
912                 $this->curl_content_type = $content_type;
913         }
914
915         function get_curl_content_type() {
916                 return $this->curl_content_type;
917         }
918
919         function set_curl_headers($headers) {
920                 $this->curl_headers = $headers;
921         }
922
923         function get_curl_headers() {
924                 return $this->curl_headers;
925         }
926
927         function get_cached_avatar_image($avatar_image){
928                 return $avatar_image;
929
930                 // The following code is deactivated. It doesn't seem to make any sense and it slows down the system.
931                 /*
932                 if($this->cached_profile_image[$avatar_image])
933                         return $this->cached_profile_image[$avatar_image];
934
935                 $path_parts = explode("/",$avatar_image);
936                 $common_filename = $path_parts[count($path_parts)-1];
937
938                 if($this->cached_profile_picdate[$common_filename]){
939                         $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
940                 } else {
941                         $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like '%%/%s'",
942                                 $common_filename);
943                         if(! dbm::is_result($r)){
944                                 $this->cached_profile_image[$avatar_image] = $avatar_image;
945                         } else {
946                                 $this->cached_profile_picdate[$common_filename] = "?rev=".urlencode($r[0]['picdate']);
947                                 $this->cached_profile_image[$avatar_image] = $avatar_image.$this->cached_profile_picdate[$common_filename];
948                         }
949                 }
950                 return $this->cached_profile_image[$avatar_image];
951                 */
952         }
953
954
955         /**
956          * @brief Removes the baseurl from an url. This avoids some mixed content problems.
957          *
958          * @param string $url
959          *
960          * @return string The cleaned url
961          */
962         function remove_baseurl($url){
963
964                 // Is the function called statically?
965                 if (!is_object($this))
966                         return(self::$a->remove_baseurl($url));
967
968                 $url = normalise_link($url);
969                 $base = normalise_link($this->get_baseurl());
970                 $url = str_replace($base."/", "", $url);
971                 return $url;
972         }
973
974         /**
975          * @brief Register template engine class
976          * 
977          * If $name is "", is used class static property $class::$name
978          * 
979          * @param string $class
980          * @param string $name
981          */
982         function register_template_engine($class, $name = '') {
983                 if ($name===""){
984                         $v = get_class_vars( $class );
985                         if(x($v,"name")) $name = $v['name'];
986                 }
987                 if ($name===""){
988                         echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
989                         killme();
990                 }
991                 $this->template_engines[$name] = $class;
992         }
993
994         /**
995          * @brief Return template engine instance.
996          * 
997          * If $name is not defined, return engine defined by theme,
998          * or default
999          *
1000          * @param strin $name Template engine name
1001          * @return object Template Engine instance
1002          */
1003         function template_engine($name = ''){
1004                 if ($name!=="") {
1005                         $template_engine = $name;
1006                 } else {
1007                         $template_engine = 'smarty3';
1008                         if (x($this->theme, 'template_engine')) {
1009                                 $template_engine = $this->theme['template_engine'];
1010                         }
1011                 }
1012
1013                 if (isset($this->template_engines[$template_engine])){
1014                         if(isset($this->template_engine_instance[$template_engine])){
1015                                 return $this->template_engine_instance[$template_engine];
1016                         } else {
1017                                 $class = $this->template_engines[$template_engine];
1018                                 $obj = new $class;
1019                                 $this->template_engine_instance[$template_engine] = $obj;
1020                                 return $obj;
1021                         }
1022                 }
1023
1024                 echo "template engine <tt>$template_engine</tt> is not registered!\n"; killme();
1025         }
1026
1027         /**
1028          * @brief Returns the active template engine.
1029          *
1030          * @return string
1031          */
1032         function get_template_engine() {
1033                 return $this->theme['template_engine'];
1034         }
1035
1036         function set_template_engine($engine = 'smarty3') {
1037                 $this->theme['template_engine'] = $engine;
1038                 /*
1039                 $this->theme['template_engine'] = 'smarty3';
1040
1041                 switch($engine) {
1042                         case 'smarty3':
1043                                 if(is_writable('view/smarty3/'))
1044                                         $this->theme['template_engine'] = 'smarty3';
1045                                 break;
1046                         default:
1047                                 break;
1048                 }
1049                 */
1050         }
1051
1052         function get_template_ldelim($engine = 'smarty3') {
1053                 return $this->ldelim[$engine];
1054         }
1055
1056         function get_template_rdelim($engine = 'smarty3') {
1057                 return $this->rdelim[$engine];
1058         }
1059
1060         function save_timestamp($stamp, $value) {
1061                 $duration = (float)(microtime(true)-$stamp);
1062
1063                 if (!isset($this->performance[$value])) {
1064                         // Prevent ugly E_NOTICE
1065                         $this->performance[$value] = 0;
1066                 }
1067
1068                 $this->performance[$value] += (float)$duration;
1069                 $this->performance["marktime"] += (float)$duration;
1070
1071                 $callstack = $this->callstack();
1072
1073                 if (!isset($this->callstack[$value][$callstack])) {
1074                         // Prevent ugly E_NOTICE
1075                         $this->callstack[$value][$callstack] = 0;
1076                 }
1077
1078                 $this->callstack[$value][$callstack] += (float)$duration;
1079
1080         }
1081
1082         /**
1083          * @brief Returns a string with a callstack. Can be used for logging.
1084          *
1085          * @return string
1086          */
1087         function callstack() {
1088                 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 6);
1089
1090                 // We remove the first two items from the list since they contain data that we don't need.
1091                 array_shift($trace);
1092                 array_shift($trace);
1093
1094                 $callstack = array();
1095                 foreach ($trace AS $func)
1096                         $callstack[] = $func["function"];
1097
1098                 return implode(", ", $callstack);
1099         }
1100
1101         function mark_timestamp($mark) {
1102                 //$this->performance["markstart"] -= microtime(true) - $this->performance["marktime"];
1103                 $this->performance["markstart"] = microtime(true) - $this->performance["markstart"] - $this->performance["marktime"];
1104         }
1105
1106         function get_useragent() {
1107                 return(FRIENDICA_PLATFORM." '".FRIENDICA_CODENAME."' ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION."; ".$this->get_baseurl());
1108         }
1109
1110         function is_friendica_app() {
1111                 return($this->is_friendica_app);
1112         }
1113
1114         /**
1115          * @brief Checks if the maximum load is reached
1116          *
1117          * @return bool Is the load reached?
1118          */
1119         function maxload_reached() {
1120
1121                 $maxsysload = intval(get_config('system', 'maxloadavg'));
1122                 if ($maxsysload < 1)
1123                         $maxsysload = 50;
1124
1125                 $load = current_load();
1126                 if ($load) {
1127                         if (intval($load) > $maxsysload) {
1128                                 logger('system: load '.$load.' too high.');
1129                                 return true;
1130                         }
1131                 }
1132                 return false;
1133         }
1134
1135         /**
1136          * @brief Checks if the process is already running
1137          *
1138          * @param string $taskname The name of the task that will be used for the name of the lockfile
1139          * @param string $task The path and name of the php script
1140          * @param int $timeout The timeout after which a task should be killed
1141          *
1142          * @return bool Is the process running?
1143          */
1144         function is_already_running($taskname, $task = "", $timeout = 540) {
1145
1146                 $lockpath = get_lockpath();
1147                 if ($lockpath != '') {
1148                         $pidfile = new pidfile($lockpath, $taskname);
1149                         if ($pidfile->is_already_running()) {
1150                                 logger("Already running");
1151                                 if ($pidfile->running_time() > $timeout) {
1152                                         $pidfile->kill();
1153                                         logger("killed stale process");
1154                                         // Calling a new instance
1155                                         if ($task != "")
1156                                                 proc_run('php', $task);
1157                                 }
1158                                 return true;
1159                         }
1160                 }
1161                 return false;
1162         }
1163 }
1164
1165 /**
1166  * @brief Retrieve the App structure
1167  * 
1168  * Useful in functions which require it but don't get it passed to them
1169  */
1170 function get_app() {
1171         global $a;
1172         return $a;
1173 }
1174
1175
1176 /**
1177  * @brief Multi-purpose function to check variable state.
1178  *
1179  * Usage: x($var) or $x($array, 'key')
1180  *
1181  * returns false if variable/key is not set
1182  * if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
1183  * e.g. x('') or x(0) returns 0;
1184  *
1185  * @param string|array $s variable to check
1186  * @param string $k key inside the array to check
1187  *
1188  * @return bool|int
1189  */
1190 function x($s,$k = NULL) {
1191         if($k != NULL) {
1192                 if((is_array($s)) && (array_key_exists($k,$s))) {
1193                         if($s[$k])
1194                                 return (int) 1;
1195                         return (int) 0;
1196         }
1197                 return false;
1198         }
1199         else {
1200                 if(isset($s)) {
1201                         if($s) {
1202                                 return (int) 1;
1203                         }
1204                         return (int) 0;
1205                 }
1206                 return false;
1207         }
1208 }
1209
1210
1211 /**
1212  * @brief Called from db initialisation if db is dead.
1213  */
1214 function system_unavailable() {
1215         include('system_unavailable.php');
1216         system_down();
1217         killme();
1218 }
1219
1220
1221 function clean_urls() {
1222         global $a;
1223         //      if($a->config['system']['clean_urls'])
1224         return true;
1225         //      return false;
1226 }
1227
1228 function z_path() {
1229         global $a;
1230         $base = $a->get_baseurl();
1231         if(! clean_urls())
1232                 $base .= '/?q=';
1233         return $base;
1234 }
1235
1236 /**
1237  * @brief Returns the baseurl.
1238  *
1239  * @see App::get_baseurl()
1240  *
1241  * @return string
1242  */
1243 function z_root() {
1244         global $a;
1245         return $a->get_baseurl();
1246 }
1247
1248 /**
1249  * @brief Return absolut URL for given $path.
1250  *
1251  * @param string $path
1252  *
1253  * @return string
1254  */
1255 function absurl($path) {
1256         if(strpos($path,'/') === 0)
1257                 return z_path() . $path;
1258         return $path;
1259 }
1260
1261 /**
1262  * @brief Function to check if request was an AJAX (xmlhttprequest) request.
1263  *
1264  * @return boolean
1265  */
1266 function is_ajax() {
1267         return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
1268 }
1269
1270 function check_db() {
1271
1272         $build = get_config('system','build');
1273         if(! x($build)) {
1274                 set_config('system','build',DB_UPDATE_VERSION);
1275                 $build = DB_UPDATE_VERSION;
1276         }
1277         if($build != DB_UPDATE_VERSION)
1278                 proc_run('php', 'include/dbupdate.php');
1279
1280 }
1281
1282
1283 /**
1284  * Sets the base url for use in cmdline programs which don't have
1285  * $_SERVER variables
1286  */
1287 function check_url(&$a) {
1288
1289         $url = get_config('system','url');
1290
1291         // if the url isn't set or the stored url is radically different
1292         // than the currently visited url, store the current value accordingly.
1293         // "Radically different" ignores common variations such as http vs https
1294         // and www.example.com vs example.com.
1295         // We will only change the url to an ip address if there is no existing setting
1296
1297         if(! x($url))
1298                 $url = set_config('system','url',$a->get_baseurl());
1299         if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
1300                 $url = set_config('system','url',$a->get_baseurl());
1301
1302         return;
1303 }
1304
1305
1306 /**
1307  * @brief Automatic database updates
1308  */
1309 function update_db(&$a) {
1310         $build = get_config('system','build');
1311         if(! x($build))
1312                 $build = set_config('system','build',DB_UPDATE_VERSION);
1313
1314         if($build != DB_UPDATE_VERSION) {
1315                 $stored = intval($build);
1316                 $current = intval(DB_UPDATE_VERSION);
1317                 if($stored < $current) {
1318                         load_config('database');
1319
1320                         // We're reporting a different version than what is currently installed.
1321                         // Run any existing update scripts to bring the database up to current.
1322
1323                         // make sure that boot.php and update.php are the same release, we might be
1324                         // updating right this very second and the correct version of the update.php
1325                         // file may not be here yet. This can happen on a very busy site.
1326
1327                         if(DB_UPDATE_VERSION == UPDATE_VERSION) {
1328                                 // Compare the current structure with the defined structure
1329
1330                                 $t = get_config('database','dbupdate_'.DB_UPDATE_VERSION);
1331                                 if($t !== false)
1332                                         return;
1333
1334                                 set_config('database','dbupdate_'.DB_UPDATE_VERSION, time());
1335
1336                                 // run old update routine (wich could modify the schema and
1337                                 // conflits with new routine)
1338                                 for ($x = $stored; $x < NEW_UPDATE_ROUTINE_VERSION; $x++) {
1339                                         $r = run_update_function($x);
1340                                         if (!$r) break;
1341                                 }
1342                                 if ($stored < NEW_UPDATE_ROUTINE_VERSION) $stored = NEW_UPDATE_ROUTINE_VERSION;
1343
1344
1345                                 // run new update routine
1346                                 // it update the structure in one call
1347                                 $retval = update_structure(false, true);
1348                                 if($retval) {
1349                                         update_fail(
1350                                                 DB_UPDATE_VERSION,
1351                                                 $retval
1352                                         );
1353                                         return;
1354                                 } else {
1355                                         set_config('database','dbupdate_'.DB_UPDATE_VERSION, 'success');
1356                                 }
1357
1358                                 // run any left update_nnnn functions in update.php
1359                                 for($x = $stored; $x < $current; $x ++) {
1360                                         $r = run_update_function($x);
1361                                         if (!$r) break;
1362                                 }
1363                         }
1364                 }
1365         }
1366
1367         return;
1368 }
1369
1370 function run_update_function($x) {
1371         if(function_exists('update_' . $x)) {
1372
1373                 // There could be a lot of processes running or about to run.
1374                 // We want exactly one process to run the update command.
1375                 // So store the fact that we're taking responsibility
1376                 // after first checking to see if somebody else already has.
1377
1378                 // If the update fails or times-out completely you may need to
1379                 // delete the config entry to try again.
1380
1381                 $t = get_config('database','update_' . $x);
1382                 if($t !== false)
1383                         return false;
1384                 set_config('database','update_' . $x, time());
1385
1386                 // call the specific update
1387
1388                 $func = 'update_' . $x;
1389                 $retval = $func();
1390
1391                 if($retval) {
1392                         //send the administrator an e-mail
1393                         update_fail(
1394                                 $x,
1395                                 sprintf(t('Update %s failed. See error logs.'), $x)
1396                         );
1397                         return false;
1398                 } else {
1399                         set_config('database','update_' . $x, 'success');
1400                         set_config('system','build', $x + 1);
1401                         return true;
1402                 }
1403         } else {
1404                 set_config('database','update_' . $x, 'success');
1405                 set_config('system','build', $x + 1);
1406                 return true;
1407         }
1408         return true;
1409 }
1410
1411 /**
1412  * @brief Synchronise plugins:
1413  *
1414  * $a->config['system']['addon'] contains a comma-separated list of names
1415  * of plugins/addons which are used on this system.
1416  * Go through the database list of already installed addons, and if we have
1417  * an entry, but it isn't in the config list, call the uninstall procedure
1418  * and mark it uninstalled in the database (for now we'll remove it).
1419  * Then go through the config list and if we have a plugin that isn't installed,
1420  * call the install procedure and add it to the database.
1421  * 
1422  * @param App $a
1423  *
1424          */
1425 function check_plugins(&$a) {
1426
1427         $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
1428         if(dbm::is_result($r))
1429                 $installed = $r;
1430         else
1431                 $installed = array();
1432
1433         $plugins = get_config('system','addon');
1434         $plugins_arr = array();
1435
1436         if($plugins)
1437                 $plugins_arr = explode(',',str_replace(' ', '',$plugins));
1438
1439         $a->plugins = $plugins_arr;
1440
1441         $installed_arr = array();
1442
1443         if(count($installed)) {
1444                 foreach($installed as $i) {
1445                         if(! in_array($i['name'],$plugins_arr)) {
1446                                 uninstall_plugin($i['name']);
1447                         }
1448                         else {
1449                                 $installed_arr[] = $i['name'];
1450                         }
1451                 }
1452         }
1453
1454         if(count($plugins_arr)) {
1455                 foreach($plugins_arr as $p) {
1456                         if(! in_array($p,$installed_arr)) {
1457                                 install_plugin($p);
1458                         }
1459                 }
1460         }
1461
1462
1463         load_hooks();
1464
1465         return;
1466 }
1467
1468 function get_guid($size=16, $prefix = "") {
1469
1470         if ($prefix == "") {
1471                 $a = get_app();
1472                 $prefix = hash("crc32", $a->get_hostname());
1473         }
1474
1475         while (strlen($prefix) < ($size - 13))
1476                 $prefix .= mt_rand();
1477
1478         if ($size >= 24) {
1479                 $prefix = substr($prefix, 0, $size - 22);
1480                 return(str_replace(".", "", uniqid($prefix, true)));
1481         } else {
1482                 $prefix = substr($prefix, 0, max($size - 13, 0));
1483                 return(uniqid($prefix));
1484         }
1485 }
1486
1487 /** 
1488  * @brief Wrapper for adding a login box.
1489  * 
1490  * @param bool $register
1491  *      If $register == true provide a registration link.
1492  *      This will most always depend on the value of $a->config['register_policy'].
1493  * @param bool $hiddens
1494  * 
1495  * @return string
1496  *      Returns the complete html for inserting into the page
1497  * 
1498  * @hooks 'login_hook'
1499  *      string $o
1500  */
1501 function login($register = false, $hiddens=false) {
1502         $a = get_app();
1503         $o = "";
1504         $reg = false;
1505         if ($register) {
1506                 $reg = array(
1507                         'title' => t('Create a New Account'),
1508                         'desc' => t('Register')
1509                 );
1510         }
1511
1512         $noid = get_config('system','no_openid');
1513
1514         $dest_url = $a->query_string;
1515
1516         if(local_user()) {
1517                 $tpl = get_markup_template("logout.tpl");
1518         }
1519         else {
1520                 $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
1521                         '$baseurl'              => $a->get_baseurl(true)
1522                 ));
1523
1524                 $tpl = get_markup_template("login.tpl");
1525                 $_SESSION['return_url'] = $a->query_string;
1526                 $a->module = 'login';
1527         }
1528
1529         $o .= replace_macros($tpl, array(
1530
1531                 '$dest_url'     => $dest_url,
1532                 '$logout'       => t('Logout'),
1533                 '$login'        => t('Login'),
1534
1535                 '$lname'        => array('username', t('Nickname or Email: ') , '', ''),
1536                 '$lpassword'    => array('password', t('Password: '), '', ''),
1537                 '$lremember'    => array('remember', t('Remember me'), 0,  ''),
1538
1539                 '$openid'       => !$noid,
1540                 '$lopenid'      => array('openid_url', t('Or login using OpenID: '),'',''),
1541
1542                 '$hiddens'      => $hiddens,
1543
1544                 '$register'     => $reg,
1545
1546                 '$lostpass'     => t('Forgot your password?'),
1547                 '$lostlink'     => t('Password Reset'),
1548
1549                 '$tostitle'     => t('Website Terms of Service'),
1550                 '$toslink'      => t('terms of service'),
1551
1552                 '$privacytitle' => t('Website Privacy Policy'),
1553                 '$privacylink'  => t('privacy policy'),
1554
1555         ));
1556
1557         call_hooks('login_hook',$o);
1558
1559         return $o;
1560 }
1561
1562 /**
1563  * @brief Used to end the current process, after saving session state.
1564  */
1565 function killme() {
1566         session_write_close();
1567         exit;
1568 }
1569
1570 /**
1571  * @brief Redirect to another URL and terminate this process.
1572  */
1573 function goaway($s) {
1574         if (!strstr(normalise_link($s), "http://"))
1575                 $s = App::get_baseurl()."/".$s;
1576
1577         header("Location: $s");
1578         killme();
1579 }
1580
1581
1582 /**
1583  * @brief Returns the user id of locally logged in user or false.
1584  * 
1585  * @return int|bool user id or false
1586  */
1587 function local_user() {
1588         if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
1589                 return intval($_SESSION['uid']);
1590         return false;
1591 }
1592
1593 /**
1594  * @brief Returns contact id of authenticated site visitor or false
1595  * 
1596  * @return int|bool visitor_id or false
1597  */
1598 function remote_user() {
1599         if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
1600                 return intval($_SESSION['visitor_id']);
1601         return false;
1602 }
1603
1604 /**
1605  * @brief Show an error message to user.
1606  *
1607  * This function save text in session, to be shown to the user at next page load
1608  *
1609  * @param string $s - Text of notice
1610  */
1611 function notice($s) {
1612         $a = get_app();
1613         if(! x($_SESSION,'sysmsg'))     $_SESSION['sysmsg'] = array();
1614         if($a->interactive)
1615                 $_SESSION['sysmsg'][] = $s;
1616 }
1617
1618 /**
1619  * @brief Show an info message to user.
1620  *
1621  * This function save text in session, to be shown to the user at next page load
1622  *
1623  * @param string $s - Text of notice
1624  */
1625 function info($s) {
1626         $a = get_app();
1627
1628         if (local_user() AND get_pconfig(local_user(),'system','ignore_info'))
1629                 return;
1630
1631         if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
1632         if($a->interactive)
1633                 $_SESSION['sysmsg_info'][] = $s;
1634 }
1635
1636
1637 /**
1638  * @brief Wrapper around config to limit the text length of an incoming message
1639  *
1640  * @return int
1641  */
1642 function get_max_import_size() {
1643         global $a;
1644         return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
1645 }
1646
1647 /**
1648  * @brief Wrap calls to proc_close(proc_open()) and call hook
1649  *      so plugins can take part in process :)
1650  *
1651  * @param string $cmd program to run
1652  * 
1653  * next args are passed as $cmd command line
1654  * e.g.: proc_run("ls","-la","/tmp");
1655  *
1656  * @note $cmd and string args are surrounded with ""
1657  * 
1658  * @hooks 'proc_run'
1659  *      array $arr
1660  */
1661 function proc_run($cmd){
1662
1663         $a = get_app();
1664
1665         $args = func_get_args();
1666
1667         $newargs = array();
1668         if(! count($args))
1669                 return;
1670
1671         // expand any arrays
1672
1673         foreach($args as $arg) {
1674                 if(is_array($arg)) {
1675                         foreach($arg as $n) {
1676                                 $newargs[] = $n;
1677                         }
1678                 }
1679                 else
1680                         $newargs[] = $arg;
1681         }
1682
1683         $args = $newargs;
1684
1685         $arr = array('args' => $args, 'run_cmd' => true);
1686
1687         call_hooks("proc_run", $arr);
1688         if(! $arr['run_cmd'])
1689                 return;
1690
1691         if(count($args) && $args[0] === 'php') {
1692
1693                 if (get_config("system", "worker")) {
1694                         $argv = $args;
1695                         array_shift($argv);
1696
1697                         $parameters = json_encode($argv);
1698                         $found = q("SELECT `id` FROM `workerqueue` WHERE `parameter` = '%s'",
1699                                         dbesc($parameters));
1700
1701                         if (!$found)
1702                                 q("INSERT INTO `workerqueue` (`parameter`, `created`, `priority`)
1703                                                         VALUES ('%s', '%s', %d)",
1704                                         dbesc($parameters),
1705                                         dbesc(datetime_convert()),
1706                                         intval(0));
1707
1708                         // Should we quit and wait for the poller to be called as a cronjob?
1709                         if (get_config("system", "worker_dont_fork"))
1710                                 return;
1711
1712                         // Checking number of workers
1713                         $workers = q("SELECT COUNT(*) AS `workers` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
1714
1715                         // Get number of allowed number of worker threads
1716                         $queues = intval(get_config("system", "worker_queues"));
1717
1718                         if ($queues == 0)
1719                                 $queues = 4;
1720
1721                         // If there are already enough workers running, don't fork another one
1722                         if ($workers[0]["workers"] >= $queues)
1723                                 return;
1724
1725                         // Now call the poller to execute the jobs that we just added to the queue
1726                         $args = array("php", "include/poller.php", "no_cron");
1727                 }
1728
1729                 $args[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
1730         }
1731
1732         // add baseurl to args. cli scripts can't construct it
1733         $args[] = $a->get_baseurl();
1734
1735         for($x = 0; $x < count($args); $x ++)
1736                 $args[$x] = escapeshellarg($args[$x]);
1737
1738         $cmdline = implode($args," ");
1739
1740         if(get_config('system','proc_windows'))
1741                 proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
1742         else
1743                 proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
1744 }
1745
1746 function current_theme(){
1747         $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
1748
1749         $a = get_app();
1750
1751         $page_theme = null;
1752
1753         // Find the theme that belongs to the user whose stuff we are looking at
1754
1755         if($a->profile_uid && ($a->profile_uid != local_user())) {
1756                 $r = q("select theme from user where uid = %d limit 1",
1757                         intval($a->profile_uid)
1758                 );
1759                 if(dbm::is_result($r))
1760                         $page_theme = $r[0]['theme'];
1761         }
1762
1763         // Allow folks to over-rule user themes and always use their own on their own site.
1764         // This works only if the user is on the same server
1765
1766         if($page_theme && local_user() && (local_user() != $a->profile_uid)) {
1767                 if(get_pconfig(local_user(),'system','always_my_theme'))
1768                         $page_theme = null;
1769         }
1770
1771 //              $mobile_detect = new Mobile_Detect();
1772 //              $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1773         $is_mobile = $a->is_mobile || $a->is_tablet;
1774
1775         $standard_system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1776         $standard_theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $standard_system_theme);
1777
1778         if($is_mobile) {
1779                 if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
1780                         $system_theme = $standard_system_theme;
1781                         $theme_name = $standard_theme_name;
1782                 }
1783                 else {
1784                         $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : $standard_system_theme);
1785                         $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
1786
1787                         if($theme_name === '---') {
1788                                 // user has selected to have the mobile theme be the same as the normal one
1789                                 $system_theme = $standard_system_theme;
1790                                 $theme_name = $standard_theme_name;
1791
1792                                 if($page_theme)
1793                                         $theme_name = $page_theme;
1794                         }
1795                 }
1796         }
1797         else {
1798                 $system_theme = $standard_system_theme;
1799                 $theme_name = $standard_theme_name;
1800
1801                 if($page_theme)
1802                         $theme_name = $page_theme;
1803         }
1804
1805         if($theme_name &&
1806                         (file_exists('view/theme/' . $theme_name . '/style.css') ||
1807                                         file_exists('view/theme/' . $theme_name . '/style.php')))
1808                 return($theme_name);
1809
1810         foreach($app_base_themes as $t) {
1811                 if(file_exists('view/theme/' . $t . '/style.css')||
1812                                 file_exists('view/theme/' . $t . '/style.php'))
1813                         return($t);
1814         }
1815
1816         $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
1817         if(count($fallback))
1818                 return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
1819
1820 }
1821
1822 /**
1823  * @brief Return full URL to theme which is currently in effect.
1824  * 
1825  * Provide a sane default if nothing is chosen or the specified theme does not exist.
1826  * 
1827  * @return string
1828  */
1829 function current_theme_url() {
1830         global $a;
1831
1832         $t = current_theme();
1833
1834         $opts = (($a->profile_uid) ? '?f=&puid=' . $a->profile_uid : '');
1835         if (file_exists('view/theme/' . $t . '/style.php'))
1836                 return('view/theme/'.$t.'/style.pcss'.$opts);
1837
1838         return('view/theme/'.$t.'/style.css');
1839 }
1840
1841 function feed_birthday($uid,$tz) {
1842
1843         /**
1844          *
1845          * Determine the next birthday, but only if the birthday is published
1846          * in the default profile. We _could_ also look for a private profile that the
1847          * recipient can see, but somebody could get mad at us if they start getting
1848          * public birthday greetings when they haven't made this info public.
1849          *
1850          * Assuming we are able to publish this info, we are then going to convert
1851          * the start time from the owner's timezone to UTC.
1852          *
1853          * This will potentially solve the problem found with some social networks
1854          * where birthdays are converted to the viewer's timezone and salutations from
1855          * elsewhere in the world show up on the wrong day. We will convert it to the
1856          * viewer's timezone also, but first we are going to convert it from the birthday
1857          * person's timezone to GMT - so the viewer may find the birthday starting at
1858          * 6:00PM the day before, but that will correspond to midnight to the birthday person.
1859          *
1860          */
1861
1862
1863         $birthday = '';
1864
1865         if(! strlen($tz))
1866                 $tz = 'UTC';
1867
1868         $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
1869                         intval($uid)
1870         );
1871
1872         if(dbm::is_result($p)) {
1873                 $tmp_dob = substr($p[0]['dob'],5);
1874                 if(intval($tmp_dob)) {
1875                         $y = datetime_convert($tz,$tz,'now','Y');
1876                         $bd = $y . '-' . $tmp_dob . ' 00:00';
1877                         $t_dob = strtotime($bd);
1878                         $now = strtotime(datetime_convert($tz,$tz,'now'));
1879                         if($t_dob < $now)
1880                                 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
1881                         $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
1882                 }
1883         }
1884
1885         return $birthday;
1886 }
1887
1888 /**
1889  * @brief Check if current user has admin role.
1890  *
1891  * @return bool true if user is an admin
1892  */
1893 function is_site_admin() {
1894         $a = get_app();
1895
1896         $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
1897
1898         //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
1899         if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && in_array($a->user['email'], $adminlist))
1900                 return true;
1901         return false;
1902 }
1903
1904 /**
1905  * @brief Returns querystring as string from a mapped array.
1906  *
1907  * @param array $params mapped array with query parameters
1908  * @param string $name of parameter, default null
1909  *
1910  * @return string
1911  */
1912 function build_querystring($params, $name=null) {
1913         $ret = "";
1914         foreach($params as $key=>$val) {
1915                 if(is_array($val)) {
1916                         if($name==null) {
1917                                 $ret .= build_querystring($val, $key);
1918                         } else {
1919                                 $ret .= build_querystring($val, $name."[$key]");
1920                         }
1921                 } else {
1922                         $val = urlencode($val);
1923                         if($name!=null) {
1924                                 $ret.=$name."[$key]"."=$val&";
1925                         } else {
1926                                 $ret.= "$key=$val&";
1927                         }
1928                 }
1929         }
1930         return $ret;
1931 }
1932
1933 function explode_querystring($query) {
1934         $arg_st = strpos($query, '?');
1935         if($arg_st !== false) {
1936                 $base = substr($query, 0, $arg_st);
1937                 $arg_st += 1;
1938         } else {
1939                 $base = '';
1940                 $arg_st = 0;
1941         }
1942
1943         $args = explode('&', substr($query, $arg_st));
1944         foreach($args as $k=>$arg) {
1945                 if($arg === '')
1946                         unset($args[$k]);
1947         }
1948         $args = array_values($args);
1949
1950         if(!$base) {
1951                 $base = $args[0];
1952                 unset($args[0]);
1953                 $args = array_values($args);
1954         }
1955
1956         return array(
1957                 'base' => $base,
1958                 'args' => $args,
1959         );
1960 }
1961
1962 /**
1963 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
1964 *
1965 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
1966 */
1967 function curPageURL() {
1968         $pageURL = 'http';
1969         if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
1970         $pageURL .= "://";
1971         if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
1972                 $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
1973         } else {
1974                 $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
1975         }
1976         return $pageURL;
1977 }
1978
1979 function random_digits($digits) {
1980         $rn = '';
1981         for($i = 0; $i < $digits; $i++) {
1982                 $rn .= rand(0,9);
1983         }
1984         return $rn;
1985 }
1986
1987 function get_server() {
1988         $server = get_config("system", "directory");
1989
1990         if ($server == "")
1991                 $server = "http://dir.friendi.ca";
1992
1993         return($server);
1994 }
1995
1996 function get_cachefile($file, $writemode = true) {
1997         $cache = get_itemcachepath();
1998
1999         if ((! $cache) || (! is_dir($cache)))
2000                 return("");
2001
2002         $subfolder = $cache."/".substr($file, 0, 2);
2003
2004         $cachepath = $subfolder."/".$file;
2005
2006         if ($writemode) {
2007                 if (!is_dir($subfolder)) {
2008                         mkdir($subfolder);
2009                         chmod($subfolder, 0777);
2010                 }
2011         }
2012
2013         return($cachepath);
2014 }
2015
2016 function clear_cache($basepath = "", $path = "") {
2017         if ($path == "") {
2018                 $basepath = get_itemcachepath();
2019                 $path = $basepath;
2020         }
2021
2022         if (($path == "") OR (!is_dir($path)))
2023                 return;
2024
2025         if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
2026                 return;
2027
2028         $cachetime = (int)get_config('system','itemcache_duration');
2029         if ($cachetime == 0)
2030                 $cachetime = 86400;
2031
2032         if (is_writable($path)){
2033                 if ($dh = opendir($path)) {
2034                         while (($file = readdir($dh)) !== false) {
2035                                 $fullpath = $path."/".$file;
2036                                 if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
2037                                         clear_cache($basepath, $fullpath);
2038                                 if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
2039                                         unlink($fullpath);
2040                         }
2041                         closedir($dh);
2042                 }
2043         }
2044 }
2045
2046 function get_itemcachepath() {
2047         // Checking, if the cache is deactivated
2048         $cachetime = (int)get_config('system','itemcache_duration');
2049         if ($cachetime < 0)
2050                 return "";
2051
2052         $itemcache = get_config('system','itemcache');
2053         if (($itemcache != "") AND is_dir($itemcache) AND is_writable($itemcache))
2054                 return($itemcache);
2055
2056         $temppath = get_temppath();
2057
2058         if ($temppath != "") {
2059                 $itemcache = $temppath."/itemcache";
2060                 if(!file_exists($itemcache) && !is_dir($itemcache)) {
2061                         mkdir($itemcache);
2062                 }
2063
2064                 if (is_dir($itemcache) AND is_writable($itemcache)) {
2065                         set_config("system", "itemcache", $itemcache);
2066                         return($itemcache);
2067                 }
2068         }
2069         return "";
2070 }
2071
2072 function get_lockpath() {
2073         $lockpath = get_config('system','lockpath');
2074         if (($lockpath != "") AND is_dir($lockpath) AND is_writable($lockpath))
2075                 return($lockpath);
2076
2077         $temppath = get_temppath();
2078
2079         if ($temppath != "") {
2080                 $lockpath = $temppath."/lock";
2081
2082                 if (!is_dir($lockpath))
2083                         mkdir($lockpath);
2084                 elseif (!is_writable($lockpath))
2085                         $lockpath = $temppath;
2086
2087                 if (is_dir($lockpath) AND is_writable($lockpath)) {
2088                         set_config("system", "lockpath", $lockpath);
2089                         return($lockpath);
2090                 }
2091         }
2092         return "";
2093 }
2094
2095 function get_temppath() {
2096         $a = get_app();
2097
2098         $temppath = get_config("system","temppath");
2099         if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath))
2100                 return($temppath);
2101
2102         $temppath = sys_get_temp_dir();
2103         if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath)) {
2104                 $temppath .= "/".$a->get_hostname();
2105                 if (!is_dir($temppath))
2106                         mkdir($temppath);
2107
2108                 if (is_dir($temppath) AND is_writable($temppath)) {
2109                         set_config("system", "temppath", $temppath);
2110                         return($temppath);
2111                 }
2112         }
2113
2114         return("");
2115 }
2116
2117 function set_template_engine(&$a, $engine = 'internal') {
2118 /// @note This function is no longer necessary, but keep it as a wrapper to the class method
2119 /// to avoid breaking themes again unnecessarily
2120
2121         $a->set_template_engine($engine);
2122 }
2123
2124 if(!function_exists('exif_imagetype')) {
2125         function exif_imagetype($file) {
2126                 $size = getimagesize($file);
2127                 return($size[2]);
2128         }
2129 }
2130
2131 function validate_include(&$file) {
2132         $orig_file = $file;
2133
2134         $file = realpath($file);
2135
2136         if (strpos($file, getcwd()) !== 0)
2137                 return false;
2138
2139         $file = str_replace(getcwd()."/", "", $file, $count);
2140         if ($count != 1)
2141                 return false;
2142
2143         if ($orig_file !== $file)
2144                 return false;
2145
2146         $valid = false;
2147         if (strpos($file, "include/") === 0)
2148                 $valid = true;
2149
2150         if (strpos($file, "addon/") === 0)
2151                 $valid = true;
2152
2153         if (!$valid)
2154                 return false;
2155
2156         return true;
2157 }
2158
2159 function current_load() {
2160         if (!function_exists('sys_getloadavg'))
2161                 return false;
2162
2163         $load_arr = sys_getloadavg();
2164
2165         if (!is_array($load_arr))
2166                 return false;
2167
2168         return max($load_arr);
2169 }
2170
2171 /**
2172  * @brief get c-style args
2173  * 
2174  * @return int
2175  */
2176 function argc() {
2177         return get_app()->argc;
2178 }
2179
2180 /**
2181  * @brief Returns the value of a argv key
2182  * 
2183  * @param int $x argv key
2184  * @return string Value of the argv key
2185  */
2186 function argv($x) {
2187         if(array_key_exists($x,get_app()->argv))
2188                 return get_app()->argv[$x];
2189
2190         return '';
2191 }
2192
2193 /**
2194  * @brief Get the data which is needed for infinite scroll
2195  * 
2196  * For invinite scroll we need the page number of the actual page
2197  * and the the URI where the content of the next page comes from.
2198  * This data is needed for the js part in main.js.
2199  * Note: infinite scroll does only work for the network page (module)
2200  * 
2201  * @param string $module The name of the module (e.g. "network")
2202  * @return array Of infinite scroll data
2203  *      'pageno' => $pageno The number of the actual page
2204  *      'reload_uri' => $reload_uri The URI of the content we have to load
2205  */
2206 function infinite_scroll_data($module) {
2207
2208         if (get_pconfig(local_user(),'system','infinite_scroll')
2209                 AND ($module == "network") AND ($_GET["mode"] != "minimal")) {
2210
2211                 // get the page number
2212                 if (is_string($_GET["page"]))
2213                         $pageno = $_GET["page"];
2214                 else
2215                         $pageno = 1;
2216
2217                 $reload_uri = "";
2218
2219                 // try to get the uri from which we load the content
2220                 foreach ($_GET AS $param => $value)
2221                         if (($param != "page") AND ($param != "q"))
2222                                 $reload_uri .= "&".$param."=".urlencode($value);
2223
2224                 if (($a->page_offset != "") AND !strstr($reload_uri, "&offset="))
2225                         $reload_uri .= "&offset=".urlencode($a->page_offset);
2226
2227                 $arr = array("pageno" => $pageno, "reload_uri" => $reload_uri);
2228
2229                 return $arr;
2230         }
2231 }