]> git.mxchange.org Git - friendica.git/blob - boot.php
Start a gcontact probing for new gcontacts
[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',      1195      );
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 /**
391  *
392  * Reverse the effect of magic_quotes_gpc if it is enabled.
393  * Please disable magic_quotes_gpc so we don't have to do this.
394  * See http://php.net/manual/en/security.magicquotes.disabling.php
395  *
396  */
397
398 function startup() {
399
400         error_reporting(E_ERROR | E_WARNING | E_PARSE);
401
402         set_time_limit(0);
403
404         // This has to be quite large to deal with embedded private photos
405         ini_set('pcre.backtrack_limit', 500000);
406
407
408         if (get_magic_quotes_gpc()) {
409                 $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
410                 while (list($key, $val) = each($process)) {
411                         foreach ($val as $k => $v) {
412                                 unset($process[$key][$k]);
413                                 if (is_array($v)) {
414                                         $process[$key][stripslashes($k)] = $v;
415                                         $process[] = &$process[$key][stripslashes($k)];
416                                 } else {
417                                         $process[$key][stripslashes($k)] = stripslashes($v);
418                                 }
419                         }
420                 }
421                 unset($process);
422         }
423
424 }
425
426 /**
427  *
428  * class: App
429  * 
430  * @brief Our main application structure for the life of this page.
431  * 
432  * Primarily deals with the URL that got us here
433  * and tries to make some sense of it, and
434  * stores our page contents and config storage
435  * and anything else that might need to be passed around
436  * before we spit the page out.
437  *
438  */
439 class App {
440
441         public  $module_loaded = false;
442         public  $query_string;
443         public  $config;
444         public  $page;
445         public  $profile;
446         public  $profile_uid;
447         public  $user;
448         public  $cid;
449         public  $contact;
450         public  $contacts;
451         public  $page_contact;
452         public  $content;
453         public  $data = array();
454         public  $error = false;
455         public  $cmd;
456         public  $argv;
457         public  $argc;
458         public  $module;
459         public  $pager;
460         public  $strings;
461         public  $path;
462         public  $hooks;
463         public  $timezone;
464         public  $interactive = true;
465         public  $plugins;
466         public  $apps = array();
467         public  $identities;
468         public  $is_mobile = false;
469         public  $is_tablet = false;
470         public  $is_friendica_app;
471         public  $performance = array();
472         public  $callstack = array();
473         public  $theme_info = array();
474
475         public $nav_sel;
476
477         public $category;
478
479
480         // Allow themes to control internal parameters
481         // by changing App values in theme.php
482
483         public  $sourcename = '';
484         public  $videowidth = 425;
485         public  $videoheight = 350;
486         public  $force_max_items = 0;
487         public  $theme_thread_allow = true;
488         public  $theme_events_in_profile = true;
489
490         /**
491          * @brief An array for all theme-controllable parameters
492          *
493          * Mostly unimplemented yet. Only options 'template_engine' and
494          * beyond are used.
495          */
496         public  $theme = array(
497                 'sourcename' => '',
498                 'videowidth' => 425,
499                 'videoheight' => 350,
500                 'force_max_items' => 0,
501                 'thread_allow' => true,
502                 'stylesheet' => '',
503                 'template_engine' => 'smarty3',
504         );
505
506         /**
507          * @brief An array of registered template engines ('name'=>'class name')
508          */
509         public $template_engines = array();
510         /**
511          * @brief An array of instanced template engines ('name'=>'instance')
512          */
513         public $template_engine_instance = array();
514
515         private $ldelim = array(
516                 'internal' => '',
517                 'smarty3' => '{{'
518         );
519         private $rdelim = array(
520                 'internal' => '',
521                 'smarty3' => '}}'
522         );
523
524         private $scheme;
525         private $hostname;
526         private $baseurl;
527         private $db;
528
529         private $curl_code;
530         private $curl_content_type;
531         private $curl_headers;
532
533         private $cached_profile_image;
534         private $cached_profile_picdate;
535
536         private static $a;
537
538         /**
539          * @brief App constructor.
540          */
541         function __construct() {
542
543                 global $default_timezone;
544
545                 $hostname = "";
546
547                 if (file_exists(".htpreconfig.php"))
548                         @include(".htpreconfig.php");
549
550                 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
551
552                 date_default_timezone_set($this->timezone);
553
554                 $this->performance["start"] = microtime(true);
555                 $this->performance["database"] = 0;
556                 $this->performance["network"] = 0;
557                 $this->performance["file"] = 0;
558                 $this->performance["rendering"] = 0;
559                 $this->performance["parser"] = 0;
560                 $this->performance["marktime"] = 0;
561                 $this->performance["markstart"] = microtime(true);
562
563                 $this->callstack["database"] = array();
564                 $this->callstack["network"] = array();
565                 $this->callstack["file"] = array();
566                 $this->callstack["rendering"] = array();
567                 $this->callstack["parser"] = array();
568
569                 $this->config = array();
570                 $this->page = array();
571                 $this->pager= array();
572
573                 $this->query_string = '';
574
575                 startup();
576
577                 set_include_path(
578                                 'include' . PATH_SEPARATOR
579                                 . 'library' . PATH_SEPARATOR
580                                 . 'library/phpsec' . PATH_SEPARATOR
581                                 . 'library/langdet' . PATH_SEPARATOR
582                                 . '.' );
583
584
585                 $this->scheme = 'http';
586                 if(x($_SERVER,'HTTPS') && $_SERVER['HTTPS'])
587                         $this->scheme = 'https';
588                 elseif(x($_SERVER,'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443))
589                         $this->scheme = 'https';
590
591                 if(x($_SERVER,'SERVER_NAME')) {
592                         $this->hostname = $_SERVER['SERVER_NAME'];
593
594                         if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
595                                 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
596                         /*
597                          * Figure out if we are running at the top of a domain
598                          * or in a sub-directory and adjust accordingly
599                          */
600
601                         $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
602                         if(isset($path) && strlen($path) && ($path != $this->path))
603                                 $this->path = $path;
604                 }
605
606                 if ($hostname != "")
607                         $this->hostname = $hostname;
608
609                 if (is_array($_SERVER["argv"]) && $_SERVER["argc"]>1 && substr(end($_SERVER["argv"]), 0, 4)=="http" ) {
610                         $this->set_baseurl(array_pop($_SERVER["argv"]) );
611                         $_SERVER["argc"] --;
612                 }
613
614                 #set_include_path("include/$this->hostname" . PATH_SEPARATOR . get_include_path());
615
616                 if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,9) === "pagename=") {
617                         $this->query_string = substr($_SERVER['QUERY_STRING'],9);
618                         // removing trailing / - maybe a nginx problem
619                         if (substr($this->query_string, 0, 1) == "/")
620                                 $this->query_string = substr($this->query_string, 1);
621                 } elseif((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
622                         $this->query_string = substr($_SERVER['QUERY_STRING'],2);
623                         // removing trailing / - maybe a nginx problem
624                         if (substr($this->query_string, 0, 1) == "/")
625                                 $this->query_string = substr($this->query_string, 1);
626                 }
627
628                 if (x($_GET,'pagename'))
629                         $this->cmd = trim($_GET['pagename'],'/\\');
630                 elseif (x($_GET,'q'))
631                         $this->cmd = trim($_GET['q'],'/\\');
632
633
634                 // fix query_string
635                 $this->query_string = str_replace($this->cmd."&",$this->cmd."?", $this->query_string);
636
637
638                 // unix style "homedir"
639
640                 if(substr($this->cmd,0,1) === '~')
641                         $this->cmd = 'profile/' . substr($this->cmd,1);
642
643                 // Diaspora style profile url
644
645                 if(substr($this->cmd,0,2) === 'u/')
646                         $this->cmd = 'profile/' . substr($this->cmd,2);
647
648
649                 /*
650                  *
651                  * Break the URL path into C style argc/argv style arguments for our
652                  * modules. Given "http://example.com/module/arg1/arg2", $this->argc
653                  * will be 3 (integer) and $this->argv will contain:
654                  *   [0] => 'module'
655                  *   [1] => 'arg1'
656                  *   [2] => 'arg2'
657                  *
658                  *
659                  * There will always be one argument. If provided a naked domain
660                  * URL, $this->argv[0] is set to "home".
661                  *
662                  */
663
664                 $this->argv = explode('/',$this->cmd);
665                 $this->argc = count($this->argv);
666                 if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
667                         $this->module = str_replace(".", "_", $this->argv[0]);
668                         $this->module = str_replace("-", "_", $this->module);
669                 }
670                 else {
671                         $this->argc = 1;
672                         $this->argv = array('home');
673                         $this->module = 'home';
674                 }
675
676                 /*
677                  * See if there is any page number information, and initialise
678                  * pagination
679                  */
680
681                 $this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
682                 $this->pager['itemspage'] = 50;
683                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
684                 if($this->pager['start'] < 0)
685                         $this->pager['start'] = 0;
686                 $this->pager['total'] = 0;
687
688                 /*
689                  * Detect mobile devices
690                  */
691
692                 $mobile_detect = new Mobile_Detect();
693                 $this->is_mobile = $mobile_detect->isMobile();
694                 $this->is_tablet = $mobile_detect->isTablet();
695
696                 // Friendica-Client
697                 $this->is_friendica_app = ($_SERVER['HTTP_USER_AGENT'] == "Apache-HttpClient/UNAVAILABLE (java 1.4)");
698
699                 /*
700                  * register template engines
701                  */
702                 $dc = get_declared_classes();
703                 foreach ($dc as $k) {
704                         if (in_array("ITemplateEngine", class_implements($k))){
705                                 $this->register_template_engine($k);
706                         }
707                 }
708
709                 self::$a = $this;
710
711         }
712
713         function get_basepath() {
714
715                 $basepath = get_config("system", "basepath");
716
717                 if ($basepath == "")
718                         $basepath = dirname(__FILE__);
719
720                 if ($basepath == "")
721                         $basepath = $_SERVER["DOCUMENT_ROOT"];
722
723                 if ($basepath == "")
724                         $basepath = $_SERVER["PWD"];
725
726                 return($basepath);
727         }
728
729         function get_scheme() {
730                 return($this->scheme);
731         }
732
733         function get_baseurl($ssl = false) {
734
735                 // Is the function called statically?
736                 if (!is_object($this))
737                         return(self::$a->get_baseurl($ssl));
738
739                 $scheme = $this->scheme;
740
741                 if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
742                         if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
743                                 $scheme = 'https';
744
745                         //      Basically, we have $ssl = true on any links which can only be seen by a logged in user
746                         //      (and also the login link). Anything seen by an outsider will have it turned off.
747
748                         if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
749                                 if($ssl)
750                                         $scheme = 'https';
751                                 else
752                                         $scheme = 'http';
753                         }
754                 }
755
756                 if (get_config('config','hostname') != "")
757                         $this->hostname = get_config('config','hostname');
758
759                 $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
760                 return $this->baseurl;
761         }
762
763         function set_baseurl($url) {
764                 $parsed = @parse_url($url);
765
766                 $this->baseurl = $url;
767
768                 if($parsed) {
769                         $this->scheme = $parsed['scheme'];
770
771                         $hostname = $parsed['host'];
772                         if(x($parsed,'port'))
773                                 $hostname .= ':' . $parsed['port'];
774                         if(x($parsed,'path'))
775                                 $this->path = trim($parsed['path'],'\\/');
776
777                         if (file_exists(".htpreconfig.php"))
778                                 @include(".htpreconfig.php");
779
780                         if (get_config('config','hostname') != "")
781                                 $this->hostname = get_config('config','hostname');
782
783                         if (!isset($this->hostname) OR ($this->hostname == ""))
784                                 $this->hostname = $hostname;
785                 }
786
787         }
788
789         function get_hostname() {
790                 if (get_config('config','hostname') != "")
791                         $this->hostname = get_config('config','hostname');
792
793                 return $this->hostname;
794         }
795
796         function set_hostname($h) {
797                 $this->hostname = $h;
798         }
799
800         function set_path($p) {
801                 $this->path = trim(trim($p),'/');
802         }
803
804         function get_path() {
805                 return $this->path;
806         }
807
808         function set_pager_total($n) {
809                 $this->pager['total'] = intval($n);
810         }
811
812         function set_pager_itemspage($n) {
813                 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
814                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
815         }
816
817         function set_pager_page($n) {
818                 $this->pager['page'] = $n;
819                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
820         }
821
822         function init_pagehead() {
823                 $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
824
825                 // If the update is "deactivated" set it to the highest integer number (~24 days)
826                 if ($interval < 0)
827                         $interval = 2147483647;
828
829                 if($interval < 10000)
830                         $interval = 40000;
831
832                 // compose the page title from the sitename and the
833                 // current module called
834                 if (!$this->module=='')
835                 {
836                     $this->page['title'] = $this->config['sitename'].' ('.$this->module.')';
837                 } else {
838                     $this->page['title'] = $this->config['sitename'];
839                 }
840
841                 /* put the head template at the beginning of page['htmlhead']
842                  * since the code added by the modules frequently depends on it
843                  * being first
844                  */
845                 if(!isset($this->page['htmlhead']))
846                         $this->page['htmlhead'] = '';
847
848                 // If we're using Smarty, then doing replace_macros() will replace
849                 // any unrecognized variables with a blank string. Since we delay
850                 // replacing $stylesheet until later, we need to replace it now
851                 // with another variable name
852                 if($this->theme['template_engine'] === 'smarty3')
853                         $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
854                 else
855                         $stylesheet = '$stylesheet';
856
857                 $shortcut_icon = get_config("system", "shortcut_icon");
858                 if ($shortcut_icon == "")
859                         $shortcut_icon = "images/friendica-32.png";
860
861                 $touch_icon = get_config("system", "touch_icon");
862                 if ($touch_icon == "")
863                         $touch_icon = "images/friendica-128.png";
864
865                 $tpl = get_markup_template('head.tpl');
866                 $this->page['htmlhead'] = replace_macros($tpl,array(
867                         '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
868                         '$local_user' => local_user(),
869                         '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
870                         '$delitem' => t('Delete this item?'),
871                         '$comment' => t('Comment'),
872                         '$showmore' => t('show more'),
873                         '$showfewer' => t('show fewer'),
874                         '$update_interval' => $interval,
875                         '$shortcut_icon' => $shortcut_icon,
876                         '$touch_icon' => $touch_icon,
877                         '$stylesheet' => $stylesheet
878                 )) . $this->page['htmlhead'];
879         }
880
881         function init_page_end() {
882                 if(!isset($this->page['end']))
883                         $this->page['end'] = '';
884                 $tpl = get_markup_template('end.tpl');
885                 $this->page['end'] = replace_macros($tpl,array(
886                         '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
887                 )) . $this->page['end'];
888         }
889
890         function set_curl_code($code) {
891                 $this->curl_code = $code;
892         }
893
894         function get_curl_code() {
895                 return $this->curl_code;
896         }
897
898         function set_curl_content_type($content_type) {
899                 $this->curl_content_type = $content_type;
900         }
901
902         function get_curl_content_type() {
903                 return $this->curl_content_type;
904         }
905
906         function set_curl_headers($headers) {
907                 $this->curl_headers = $headers;
908         }
909
910         function get_curl_headers() {
911                 return $this->curl_headers;
912         }
913
914         function get_cached_avatar_image($avatar_image){
915                 return $avatar_image;
916
917                 // The following code is deactivated. It doesn't seem to make any sense and it slows down the system.
918                 /*
919                 if($this->cached_profile_image[$avatar_image])
920                         return $this->cached_profile_image[$avatar_image];
921
922                 $path_parts = explode("/",$avatar_image);
923                 $common_filename = $path_parts[count($path_parts)-1];
924
925                 if($this->cached_profile_picdate[$common_filename]){
926                         $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
927                 } else {
928                         $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like '%%/%s'",
929                                 $common_filename);
930                         if(! count($r)){
931                                 $this->cached_profile_image[$avatar_image] = $avatar_image;
932                         } else {
933                                 $this->cached_profile_picdate[$common_filename] = "?rev=".urlencode($r[0]['picdate']);
934                                 $this->cached_profile_image[$avatar_image] = $avatar_image.$this->cached_profile_picdate[$common_filename];
935                         }
936                 }
937                 return $this->cached_profile_image[$avatar_image];
938                 */
939         }
940
941
942         /**
943          * @brief Removes the baseurl from an url. This avoids some mixed content problems.
944          *
945          * @param string $url
946          *
947          * @return string The cleaned url
948          */
949         function remove_baseurl($url){
950
951                 // Is the function called statically?
952                 if (!is_object($this))
953                         return(self::$a->remove_baseurl($url));
954
955                 $url = normalise_link($url);
956                 $base = normalise_link($this->get_baseurl());
957                 $url = str_replace($base."/", "", $url);
958                 return $url;
959         }
960
961         /**
962          * @brief Register template engine class
963          * 
964          * If $name is "", is used class static property $class::$name
965          * 
966          * @param string $class
967          * @param string $name
968          */
969         function register_template_engine($class, $name = '') {
970                 if ($name===""){
971                         $v = get_class_vars( $class );
972                         if(x($v,"name")) $name = $v['name'];
973                 }
974                 if ($name===""){
975                         echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
976                         killme();
977                 }
978                 $this->template_engines[$name] = $class;
979         }
980
981         /**
982          * @brief Return template engine instance.
983          * 
984          * If $name is not defined, return engine defined by theme,
985          * or default
986          *
987          * @param strin $name Template engine name
988          * @return object Template Engine instance
989          */
990         function template_engine($name = ''){
991                 if ($name!=="") {
992                         $template_engine = $name;
993                 } else {
994                         $template_engine = 'smarty3';
995                         if (x($this->theme, 'template_engine')) {
996                                 $template_engine = $this->theme['template_engine'];
997                         }
998                 }
999
1000                 if (isset($this->template_engines[$template_engine])){
1001                         if(isset($this->template_engine_instance[$template_engine])){
1002                                 return $this->template_engine_instance[$template_engine];
1003                         } else {
1004                                 $class = $this->template_engines[$template_engine];
1005                                 $obj = new $class;
1006                                 $this->template_engine_instance[$template_engine] = $obj;
1007                                 return $obj;
1008                         }
1009                 }
1010
1011                 echo "template engine <tt>$template_engine</tt> is not registered!\n"; killme();
1012         }
1013
1014         /**
1015          * @brief Returns the active template engine.
1016          *
1017          * @return string
1018          */
1019         function get_template_engine() {
1020                 return $this->theme['template_engine'];
1021         }
1022
1023         function set_template_engine($engine = 'smarty3') {
1024                 $this->theme['template_engine'] = $engine;
1025                 /*
1026                 $this->theme['template_engine'] = 'smarty3';
1027
1028                 switch($engine) {
1029                         case 'smarty3':
1030                                 if(is_writable('view/smarty3/'))
1031                                         $this->theme['template_engine'] = 'smarty3';
1032                                 break;
1033                         default:
1034                                 break;
1035                 }
1036                 */
1037         }
1038
1039         function get_template_ldelim($engine = 'smarty3') {
1040                 return $this->ldelim[$engine];
1041         }
1042
1043         function get_template_rdelim($engine = 'smarty3') {
1044                 return $this->rdelim[$engine];
1045         }
1046
1047         function save_timestamp($stamp, $value) {
1048                 $duration = (float)(microtime(true)-$stamp);
1049
1050                 if (!isset($this->performance[$value])) {
1051                         // Prevent ugly E_NOTICE
1052                         $this->performance[$value] = 0;
1053                 }
1054
1055                 $this->performance[$value] += (float)$duration;
1056                 $this->performance["marktime"] += (float)$duration;
1057
1058                 $callstack = $this->callstack();
1059
1060                 if (!isset($this->callstack[$value][$callstack])) {
1061                         // Prevent ugly E_NOTICE
1062                         $this->callstack[$value][$callstack] = 0;
1063                 }
1064
1065                 $this->callstack[$value][$callstack] += (float)$duration;
1066
1067         }
1068
1069         /**
1070          * @brief Returns a string with a callstack. Can be used for logging.
1071          *
1072          * @return string
1073          */
1074         function callstack() {
1075                 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 6);
1076
1077                 // We remove the first two items from the list since they contain data that we don't need.
1078                 array_shift($trace);
1079                 array_shift($trace);
1080
1081                 $callstack = array();
1082                 foreach ($trace AS $func)
1083                         $callstack[] = $func["function"];
1084
1085                 return implode(", ", $callstack);
1086         }
1087
1088         function mark_timestamp($mark) {
1089                 //$this->performance["markstart"] -= microtime(true) - $this->performance["marktime"];
1090                 $this->performance["markstart"] = microtime(true) - $this->performance["markstart"] - $this->performance["marktime"];
1091         }
1092
1093         function get_useragent() {
1094                 return(FRIENDICA_PLATFORM." '".FRIENDICA_CODENAME."' ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION."; ".$this->get_baseurl());
1095         }
1096
1097         function is_friendica_app() {
1098                 return($this->is_friendica_app);
1099         }
1100
1101         /**
1102          * @brief Checks if the maximum load is reached
1103          *
1104          * @return bool Is the load reached?
1105          */
1106         function maxload_reached() {
1107
1108                 $maxsysload = intval(get_config('system', 'maxloadavg'));
1109                 if ($maxsysload < 1)
1110                         $maxsysload = 50;
1111
1112                 $load = current_load();
1113                 if ($load) {
1114                         if (intval($load) > $maxsysload) {
1115                                 logger('system: load '.$load.' too high.');
1116                                 return true;
1117                         }
1118                 }
1119                 return false;
1120         }
1121
1122         /**
1123          * @brief Checks if the process is already running
1124          *
1125          * @param string $taskname The name of the task that will be used for the name of the lockfile
1126          * @param string $task The path and name of the php script
1127          * @param int $timeout The timeout after which a task should be killed
1128          *
1129          * @return bool Is the process running?
1130          */
1131         function is_already_running($taskname, $task = "", $timeout = 540) {
1132
1133                 $lockpath = get_lockpath();
1134                 if ($lockpath != '') {
1135                         $pidfile = new pidfile($lockpath, $taskname);
1136                         if ($pidfile->is_already_running()) {
1137                                 logger("Already running");
1138                                 if ($pidfile->running_time() > $timeout) {
1139                                         $pidfile->kill();
1140                                         logger("killed stale process");
1141                                         // Calling a new instance
1142                                         if ($task != "")
1143                                                 proc_run('php', $task);
1144                                 }
1145                                 return true;
1146                         }
1147                 }
1148                 return false;
1149         }
1150 }
1151
1152 /**
1153  * @brief Retrieve the App structure
1154  * 
1155  * Useful in functions which require it but don't get it passed to them
1156  */
1157 function get_app() {
1158         global $a;
1159         return $a;
1160 }
1161
1162
1163 /**
1164  * @brief Multi-purpose function to check variable state.
1165  *
1166  * Usage: x($var) or $x($array, 'key')
1167  *
1168  * returns false if variable/key is not set
1169  * if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
1170  * e.g. x('') or x(0) returns 0;
1171  *
1172  * @param string|array $s variable to check
1173  * @param string $k key inside the array to check
1174  *
1175  * @return bool|int
1176  */
1177 function x($s,$k = NULL) {
1178         if($k != NULL) {
1179                 if((is_array($s)) && (array_key_exists($k,$s))) {
1180                         if($s[$k])
1181                                 return (int) 1;
1182                         return (int) 0;
1183         }
1184                 return false;
1185         }
1186         else {
1187                 if(isset($s)) {
1188                         if($s) {
1189                                 return (int) 1;
1190                         }
1191                         return (int) 0;
1192                 }
1193                 return false;
1194         }
1195 }
1196
1197
1198 /**
1199  * @brief Called from db initialisation if db is dead.
1200  */
1201 function system_unavailable() {
1202         include('system_unavailable.php');
1203         system_down();
1204         killme();
1205 }
1206
1207
1208 function clean_urls() {
1209         global $a;
1210         //      if($a->config['system']['clean_urls'])
1211         return true;
1212         //      return false;
1213 }
1214
1215 function z_path() {
1216         global $a;
1217         $base = $a->get_baseurl();
1218         if(! clean_urls())
1219                 $base .= '/?q=';
1220         return $base;
1221 }
1222
1223 /**
1224  * @brief Returns the baseurl.
1225  *
1226  * @see App::get_baseurl()
1227  *
1228  * @return string
1229  */
1230 function z_root() {
1231         global $a;
1232         return $a->get_baseurl();
1233 }
1234
1235 /**
1236  * @brief Return absolut URL for given $path.
1237  *
1238  * @param string $path
1239  *
1240  * @return string
1241  */
1242 function absurl($path) {
1243         if(strpos($path,'/') === 0)
1244                 return z_path() . $path;
1245         return $path;
1246 }
1247
1248 /**
1249  * @brief Function to check if request was an AJAX (xmlhttprequest) request.
1250  *
1251  * @return boolean
1252  */
1253 function is_ajax() {
1254         return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
1255 }
1256
1257 function check_db() {
1258
1259         $build = get_config('system','build');
1260         if(! x($build)) {
1261                 set_config('system','build',DB_UPDATE_VERSION);
1262                 $build = DB_UPDATE_VERSION;
1263         }
1264         if($build != DB_UPDATE_VERSION)
1265                 proc_run('php', 'include/dbupdate.php');
1266
1267 }
1268
1269
1270 /**
1271  * Sets the base url for use in cmdline programs which don't have
1272  * $_SERVER variables
1273  */
1274 function check_url(&$a) {
1275
1276         $url = get_config('system','url');
1277
1278         // if the url isn't set or the stored url is radically different
1279         // than the currently visited url, store the current value accordingly.
1280         // "Radically different" ignores common variations such as http vs https
1281         // and www.example.com vs example.com.
1282         // We will only change the url to an ip address if there is no existing setting
1283
1284         if(! x($url))
1285                 $url = set_config('system','url',$a->get_baseurl());
1286         if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
1287                 $url = set_config('system','url',$a->get_baseurl());
1288
1289         return;
1290 }
1291
1292
1293 /**
1294  * @brief Automatic database updates
1295  */
1296 function update_db(&$a) {
1297         $build = get_config('system','build');
1298         if(! x($build))
1299                 $build = set_config('system','build',DB_UPDATE_VERSION);
1300
1301         if($build != DB_UPDATE_VERSION) {
1302                 $stored = intval($build);
1303                 $current = intval(DB_UPDATE_VERSION);
1304                 if($stored < $current) {
1305                         load_config('database');
1306
1307                         // We're reporting a different version than what is currently installed.
1308                         // Run any existing update scripts to bring the database up to current.
1309
1310                         // make sure that boot.php and update.php are the same release, we might be
1311                         // updating right this very second and the correct version of the update.php
1312                         // file may not be here yet. This can happen on a very busy site.
1313
1314                         if(DB_UPDATE_VERSION == UPDATE_VERSION) {
1315                                 // Compare the current structure with the defined structure
1316
1317                                 $t = get_config('database','dbupdate_'.DB_UPDATE_VERSION);
1318                                 if($t !== false)
1319                                         return;
1320
1321                                 set_config('database','dbupdate_'.DB_UPDATE_VERSION, time());
1322
1323                                 // run old update routine (wich could modify the schema and
1324                                 // conflits with new routine)
1325                                 for ($x = $stored; $x < NEW_UPDATE_ROUTINE_VERSION; $x++) {
1326                                         $r = run_update_function($x);
1327                                         if (!$r) break;
1328                                 }
1329                                 if ($stored < NEW_UPDATE_ROUTINE_VERSION) $stored = NEW_UPDATE_ROUTINE_VERSION;
1330
1331
1332                                 // run new update routine
1333                                 // it update the structure in one call
1334                                 $retval = update_structure(false, true);
1335                                 if($retval) {
1336                                         update_fail(
1337                                                 DB_UPDATE_VERSION,
1338                                                 $retval
1339                                         );
1340                                         return;
1341                                 } else {
1342                                         set_config('database','dbupdate_'.DB_UPDATE_VERSION, 'success');
1343                                 }
1344
1345                                 // run any left update_nnnn functions in update.php
1346                                 for($x = $stored; $x < $current; $x ++) {
1347                                         $r = run_update_function($x);
1348                                         if (!$r) break;
1349                                 }
1350                         }
1351                 }
1352         }
1353
1354         return;
1355 }
1356
1357 function run_update_function($x) {
1358         if(function_exists('update_' . $x)) {
1359
1360                 // There could be a lot of processes running or about to run.
1361                 // We want exactly one process to run the update command.
1362                 // So store the fact that we're taking responsibility
1363                 // after first checking to see if somebody else already has.
1364
1365                 // If the update fails or times-out completely you may need to
1366                 // delete the config entry to try again.
1367
1368                 $t = get_config('database','update_' . $x);
1369                 if($t !== false)
1370                         return false;
1371                 set_config('database','update_' . $x, time());
1372
1373                 // call the specific update
1374
1375                 $func = 'update_' . $x;
1376                 $retval = $func();
1377
1378                 if($retval) {
1379                         //send the administrator an e-mail
1380                         update_fail(
1381                                 $x,
1382                                 sprintf(t('Update %s failed. See error logs.'), $x)
1383                         );
1384                         return false;
1385                 } else {
1386                         set_config('database','update_' . $x, 'success');
1387                         set_config('system','build', $x + 1);
1388                         return true;
1389                 }
1390         } else {
1391                 set_config('database','update_' . $x, 'success');
1392                 set_config('system','build', $x + 1);
1393                 return true;
1394         }
1395         return true;
1396 }
1397
1398 /**
1399  * @brief Synchronise plugins:
1400  *
1401  * $a->config['system']['addon'] contains a comma-separated list of names
1402  * of plugins/addons which are used on this system.
1403  * Go through the database list of already installed addons, and if we have
1404  * an entry, but it isn't in the config list, call the uninstall procedure
1405  * and mark it uninstalled in the database (for now we'll remove it).
1406  * Then go through the config list and if we have a plugin that isn't installed,
1407  * call the install procedure and add it to the database.
1408  * 
1409  * @param App $a
1410  *
1411          */
1412 function check_plugins(&$a) {
1413
1414         $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
1415         if(count($r))
1416                 $installed = $r;
1417         else
1418                 $installed = array();
1419
1420         $plugins = get_config('system','addon');
1421         $plugins_arr = array();
1422
1423         if($plugins)
1424                 $plugins_arr = explode(',',str_replace(' ', '',$plugins));
1425
1426         $a->plugins = $plugins_arr;
1427
1428         $installed_arr = array();
1429
1430         if(count($installed)) {
1431                 foreach($installed as $i) {
1432                         if(! in_array($i['name'],$plugins_arr)) {
1433                                 uninstall_plugin($i['name']);
1434                         }
1435                         else {
1436                                 $installed_arr[] = $i['name'];
1437                         }
1438                 }
1439         }
1440
1441         if(count($plugins_arr)) {
1442                 foreach($plugins_arr as $p) {
1443                         if(! in_array($p,$installed_arr)) {
1444                                 install_plugin($p);
1445                         }
1446                 }
1447         }
1448
1449
1450         load_hooks();
1451
1452         return;
1453 }
1454
1455 function get_guid($size=16, $prefix = "") {
1456
1457         if ($prefix == "") {
1458                 $a = get_app();
1459                 $prefix = hash("crc32", $a->get_hostname());
1460         }
1461
1462         while (strlen($prefix) < ($size - 13))
1463                 $prefix .= mt_rand();
1464
1465         if ($size >= 24) {
1466                 $prefix = substr($prefix, 0, $size - 22);
1467                 return(str_replace(".", "", uniqid($prefix, true)));
1468         } else {
1469                 $prefix = substr($prefix, 0, max($size - 13, 0));
1470                 return(uniqid($prefix));
1471         }
1472 }
1473
1474 /** 
1475  * @brief Wrapper for adding a login box.
1476  * 
1477  * @param bool $register
1478  *      If $register == true provide a registration link.
1479  *      This will most always depend on the value of $a->config['register_policy'].
1480  * @param bool $hiddens
1481  * 
1482  * @return string
1483  *      Returns the complete html for inserting into the page
1484  * 
1485  * @hooks 'login_hook'
1486  *      string $o
1487  */
1488 function login($register = false, $hiddens=false) {
1489         $a = get_app();
1490         $o = "";
1491         $reg = false;
1492         if ($register) {
1493                 $reg = array(
1494                         'title' => t('Create a New Account'),
1495                         'desc' => t('Register')
1496                 );
1497         }
1498
1499         $noid = get_config('system','no_openid');
1500
1501         $dest_url = $a->query_string;
1502
1503         if(local_user()) {
1504                 $tpl = get_markup_template("logout.tpl");
1505         }
1506         else {
1507                 $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
1508                         '$baseurl'              => $a->get_baseurl(true)
1509                 ));
1510
1511                 $tpl = get_markup_template("login.tpl");
1512                 $_SESSION['return_url'] = $a->query_string;
1513                 $a->module = 'login';
1514         }
1515
1516         $o .= replace_macros($tpl, array(
1517
1518                 '$dest_url'     => $dest_url,
1519                 '$logout'       => t('Logout'),
1520                 '$login'        => t('Login'),
1521
1522                 '$lname'                => array('username', t('Nickname or Email address: ') , '', ''),
1523                 '$lpassword'    => array('password', t('Password: '), '', ''),
1524                 '$lremember'    => array('remember', t('Remember me'), 0,  ''),
1525
1526                 '$openid'               => !$noid,
1527                 '$lopenid'      => array('openid_url', t('Or login using OpenID: '),'',''),
1528
1529                 '$hiddens'      => $hiddens,
1530
1531                 '$register'     => $reg,
1532
1533                 '$lostpass'     => t('Forgot your password?'),
1534                 '$lostlink'     => t('Password Reset'),
1535
1536                 '$tostitle'     => t('Website Terms of Service'),
1537                 '$toslink'      => t('terms of service'),
1538
1539                 '$privacytitle' => t('Website Privacy Policy'),
1540                 '$privacylink'  => t('privacy policy'),
1541
1542         ));
1543
1544         call_hooks('login_hook',$o);
1545
1546         return $o;
1547 }
1548
1549 /**
1550  * @brief Used to end the current process, after saving session state.
1551  */
1552 function killme() {
1553         session_write_close();
1554         exit;
1555 }
1556
1557 /**
1558  * @brief Redirect to another URL and terminate this process.
1559  */
1560 function goaway($s) {
1561         if (!strstr(normalise_link($s), "http://"))
1562                 $s = App::get_baseurl()."/".$s;
1563
1564         header("Location: $s");
1565         killme();
1566 }
1567
1568
1569 /**
1570  * @brief Returns the user id of locally logged in user or false.
1571  * 
1572  * @return int|bool user id or false
1573  */
1574 function local_user() {
1575         if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
1576                 return intval($_SESSION['uid']);
1577         return false;
1578 }
1579
1580 /**
1581  * @brief Returns contact id of authenticated site visitor or false
1582  * 
1583  * @return int|bool visitor_id or false
1584  */
1585 function remote_user() {
1586         if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
1587                 return intval($_SESSION['visitor_id']);
1588         return false;
1589 }
1590
1591 /**
1592  * @brief Show an error message to user.
1593  *
1594  * This function save text in session, to be shown to the user at next page load
1595  *
1596  * @param string $s - Text of notice
1597  */
1598 function notice($s) {
1599         $a = get_app();
1600         if(! x($_SESSION,'sysmsg'))     $_SESSION['sysmsg'] = array();
1601         if($a->interactive)
1602                 $_SESSION['sysmsg'][] = $s;
1603 }
1604
1605 /**
1606  * @brief Show an info message to user.
1607  *
1608  * This function save text in session, to be shown to the user at next page load
1609  *
1610  * @param string $s - Text of notice
1611  */
1612 function info($s) {
1613         $a = get_app();
1614
1615         if (local_user() AND get_pconfig(local_user(),'system','ignore_info'))
1616                 return;
1617
1618         if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
1619         if($a->interactive)
1620                 $_SESSION['sysmsg_info'][] = $s;
1621 }
1622
1623
1624 /**
1625  * @brief Wrapper around config to limit the text length of an incoming message
1626  *
1627  * @return int
1628  */
1629 function get_max_import_size() {
1630         global $a;
1631         return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
1632 }
1633
1634 /**
1635  * @brief Wrap calls to proc_close(proc_open()) and call hook
1636  *      so plugins can take part in process :)
1637  *
1638  * @param string $cmd program to run
1639  * 
1640  * next args are passed as $cmd command line
1641  * e.g.: proc_run("ls","-la","/tmp");
1642  *
1643  * @note $cmd and string args are surrounded with ""
1644  * 
1645  * @hooks 'proc_run'
1646  *      array $arr
1647  */
1648 function proc_run($cmd){
1649
1650         $a = get_app();
1651
1652         $args = func_get_args();
1653
1654         $newargs = array();
1655         if(! count($args))
1656                 return;
1657
1658         // expand any arrays
1659
1660         foreach($args as $arg) {
1661                 if(is_array($arg)) {
1662                         foreach($arg as $n) {
1663                                 $newargs[] = $n;
1664                         }
1665                 }
1666                 else
1667                         $newargs[] = $arg;
1668         }
1669
1670         $args = $newargs;
1671
1672         $arr = array('args' => $args, 'run_cmd' => true);
1673
1674         call_hooks("proc_run", $arr);
1675         if(! $arr['run_cmd'])
1676                 return;
1677
1678         if(count($args) && $args[0] === 'php') {
1679
1680                 if (get_config("system", "worker")) {
1681                         $argv = $args;
1682                         array_shift($argv);
1683
1684                         $parameters = json_encode($argv);
1685                         $found = q("SELECT `id` FROM `workerqueue` WHERE `parameter` = '%s'",
1686                                         dbesc($parameters));
1687
1688                         if (!$found)
1689                                 q("INSERT INTO `workerqueue` (`parameter`, `created`, `priority`)
1690                                                         VALUES ('%s', '%s', %d)",
1691                                         dbesc($parameters),
1692                                         dbesc(datetime_convert()),
1693                                         intval(0));
1694
1695                         // Should we quit and wait for the poller to be called as a cronjob?
1696                         if (get_config("system", "worker_dont_fork"))
1697                                 return;
1698
1699                         // Checking number of workers
1700                         $workers = q("SELECT COUNT(*) AS `workers` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
1701
1702                         // Get number of allowed number of worker threads
1703                         $queues = intval(get_config("system", "worker_queues"));
1704
1705                         if ($queues == 0)
1706                                 $queues = 4;
1707
1708                         // If there are already enough workers running, don't fork another one
1709                         if ($workers[0]["workers"] >= $queues)
1710                                 return;
1711
1712                         // Now call the poller to execute the jobs that we just added to the queue
1713                         $args = array("php", "include/poller.php", "no_cron");
1714                 }
1715
1716                 $args[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
1717         }
1718
1719         // add baseurl to args. cli scripts can't construct it
1720         $args[] = $a->get_baseurl();
1721
1722         for($x = 0; $x < count($args); $x ++)
1723                 $args[$x] = escapeshellarg($args[$x]);
1724
1725         $cmdline = implode($args," ");
1726
1727         if(get_config('system','proc_windows'))
1728                 proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
1729         else
1730                 proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
1731 }
1732
1733 function current_theme(){
1734         $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
1735
1736         $a = get_app();
1737
1738         $page_theme = null;
1739
1740         // Find the theme that belongs to the user whose stuff we are looking at
1741
1742         if($a->profile_uid && ($a->profile_uid != local_user())) {
1743                 $r = q("select theme from user where uid = %d limit 1",
1744                         intval($a->profile_uid)
1745                 );
1746                 if($r)
1747                         $page_theme = $r[0]['theme'];
1748         }
1749
1750         // Allow folks to over-rule user themes and always use their own on their own site.
1751         // This works only if the user is on the same server
1752
1753         if($page_theme && local_user() && (local_user() != $a->profile_uid)) {
1754                 if(get_pconfig(local_user(),'system','always_my_theme'))
1755                         $page_theme = null;
1756         }
1757
1758 //              $mobile_detect = new Mobile_Detect();
1759 //              $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1760         $is_mobile = $a->is_mobile || $a->is_tablet;
1761
1762         $standard_system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1763         $standard_theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $standard_system_theme);
1764
1765         if($is_mobile) {
1766                 if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
1767                         $system_theme = $standard_system_theme;
1768                         $theme_name = $standard_theme_name;
1769                 }
1770                 else {
1771                         $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : $standard_system_theme);
1772                         $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
1773
1774                         if($theme_name === '---') {
1775                                 // user has selected to have the mobile theme be the same as the normal one
1776                                 $system_theme = $standard_system_theme;
1777                                 $theme_name = $standard_theme_name;
1778
1779                                 if($page_theme)
1780                                         $theme_name = $page_theme;
1781                         }
1782                 }
1783         }
1784         else {
1785                 $system_theme = $standard_system_theme;
1786                 $theme_name = $standard_theme_name;
1787
1788                 if($page_theme)
1789                         $theme_name = $page_theme;
1790         }
1791
1792         if($theme_name &&
1793                         (file_exists('view/theme/' . $theme_name . '/style.css') ||
1794                                         file_exists('view/theme/' . $theme_name . '/style.php')))
1795                 return($theme_name);
1796
1797         foreach($app_base_themes as $t) {
1798                 if(file_exists('view/theme/' . $t . '/style.css')||
1799                                 file_exists('view/theme/' . $t . '/style.php'))
1800                         return($t);
1801         }
1802
1803         $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
1804         if(count($fallback))
1805                 return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
1806
1807 }
1808
1809 /**
1810  * @brief Return full URL to theme which is currently in effect.
1811  * 
1812  * Provide a sane default if nothing is chosen or the specified theme does not exist.
1813  * 
1814  * @return string
1815  */
1816 function current_theme_url() {
1817         global $a;
1818
1819         $t = current_theme();
1820
1821         $opts = (($a->profile_uid) ? '?f=&puid=' . $a->profile_uid : '');
1822         if (file_exists('view/theme/' . $t . '/style.php'))
1823                 return('view/theme/'.$t.'/style.pcss'.$opts);
1824
1825         return('view/theme/'.$t.'/style.css');
1826 }
1827
1828 function feed_birthday($uid,$tz) {
1829
1830         /**
1831          *
1832          * Determine the next birthday, but only if the birthday is published
1833          * in the default profile. We _could_ also look for a private profile that the
1834          * recipient can see, but somebody could get mad at us if they start getting
1835          * public birthday greetings when they haven't made this info public.
1836          *
1837          * Assuming we are able to publish this info, we are then going to convert
1838          * the start time from the owner's timezone to UTC.
1839          *
1840          * This will potentially solve the problem found with some social networks
1841          * where birthdays are converted to the viewer's timezone and salutations from
1842          * elsewhere in the world show up on the wrong day. We will convert it to the
1843          * viewer's timezone also, but first we are going to convert it from the birthday
1844          * person's timezone to GMT - so the viewer may find the birthday starting at
1845          * 6:00PM the day before, but that will correspond to midnight to the birthday person.
1846          *
1847          */
1848
1849
1850         $birthday = '';
1851
1852         if(! strlen($tz))
1853                 $tz = 'UTC';
1854
1855         $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
1856                         intval($uid)
1857         );
1858
1859         if($p && count($p)) {
1860                 $tmp_dob = substr($p[0]['dob'],5);
1861                 if(intval($tmp_dob)) {
1862                         $y = datetime_convert($tz,$tz,'now','Y');
1863                         $bd = $y . '-' . $tmp_dob . ' 00:00';
1864                         $t_dob = strtotime($bd);
1865                         $now = strtotime(datetime_convert($tz,$tz,'now'));
1866                         if($t_dob < $now)
1867                                 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
1868                         $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
1869                 }
1870         }
1871
1872         return $birthday;
1873 }
1874
1875 /**
1876  * @brief Check if current user has admin role.
1877  *
1878  * @return bool true if user is an admin
1879  */
1880 function is_site_admin() {
1881         $a = get_app();
1882
1883         $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
1884
1885         //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
1886         if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && in_array($a->user['email'], $adminlist))
1887                 return true;
1888         return false;
1889 }
1890
1891
1892 function load_contact_links($uid) {
1893
1894         $a = get_app();
1895
1896         $ret = array();
1897
1898         if(! $uid || x($a->contacts,'empty'))
1899                 return;
1900
1901         $r = q("SELECT `id`,`network`,`url`,`thumb`, `rel` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `thumb` != ''",
1902                         intval($uid)
1903         );
1904         if(count($r)) {
1905                 foreach($r as $rr){
1906                         $url = normalise_link($rr['url']);
1907                         $ret[$url] = $rr;
1908                 }
1909         } else
1910                 $ret['empty'] = true;
1911
1912         $a->contacts = $ret;
1913         return;
1914 }
1915
1916 /**
1917  * @brief Returns querystring as string from a mapped array.
1918  *
1919  * @param array $params mapped array with query parameters
1920  * @param string $name of parameter, default null
1921  *
1922  * @return string
1923  */
1924 function build_querystring($params, $name=null) {
1925         $ret = "";
1926         foreach($params as $key=>$val) {
1927                 if(is_array($val)) {
1928                         if($name==null) {
1929                                 $ret .= build_querystring($val, $key);
1930                         } else {
1931                                 $ret .= build_querystring($val, $name."[$key]");
1932                         }
1933                 } else {
1934                         $val = urlencode($val);
1935                         if($name!=null) {
1936                                 $ret.=$name."[$key]"."=$val&";
1937                         } else {
1938                                 $ret.= "$key=$val&";
1939                         }
1940                 }
1941         }
1942         return $ret;
1943 }
1944
1945 function explode_querystring($query) {
1946         $arg_st = strpos($query, '?');
1947         if($arg_st !== false) {
1948                 $base = substr($query, 0, $arg_st);
1949                 $arg_st += 1;
1950         } else {
1951                 $base = '';
1952                 $arg_st = 0;
1953         }
1954
1955         $args = explode('&', substr($query, $arg_st));
1956         foreach($args as $k=>$arg) {
1957                 if($arg === '')
1958                         unset($args[$k]);
1959         }
1960         $args = array_values($args);
1961
1962         if(!$base) {
1963                 $base = $args[0];
1964                 unset($args[0]);
1965                 $args = array_values($args);
1966         }
1967
1968         return array(
1969                 'base' => $base,
1970                 'args' => $args,
1971         );
1972 }
1973
1974 /**
1975 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
1976 *
1977 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
1978 */
1979 function curPageURL() {
1980         $pageURL = 'http';
1981         if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
1982         $pageURL .= "://";
1983         if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
1984                 $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
1985         } else {
1986                 $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
1987         }
1988         return $pageURL;
1989 }
1990
1991 function random_digits($digits) {
1992         $rn = '';
1993         for($i = 0; $i < $digits; $i++) {
1994                 $rn .= rand(0,9);
1995         }
1996         return $rn;
1997 }
1998
1999 function get_server() {
2000         $server = get_config("system", "directory");
2001
2002         if ($server == "")
2003                 $server = "http://dir.friendi.ca";
2004
2005         return($server);
2006 }
2007
2008 function get_cachefile($file, $writemode = true) {
2009         $cache = get_itemcachepath();
2010
2011         if ((! $cache) || (! is_dir($cache)))
2012                 return("");
2013
2014         $subfolder = $cache."/".substr($file, 0, 2);
2015
2016         $cachepath = $subfolder."/".$file;
2017
2018         if ($writemode) {
2019                 if (!is_dir($subfolder)) {
2020                         mkdir($subfolder);
2021                         chmod($subfolder, 0777);
2022                 }
2023         }
2024
2025         return($cachepath);
2026 }
2027
2028 function clear_cache($basepath = "", $path = "") {
2029         if ($path == "") {
2030                 $basepath = get_itemcachepath();
2031                 $path = $basepath;
2032         }
2033
2034         if (($path == "") OR (!is_dir($path)))
2035                 return;
2036
2037         if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
2038                 return;
2039
2040         $cachetime = (int)get_config('system','itemcache_duration');
2041         if ($cachetime == 0)
2042                 $cachetime = 86400;
2043
2044         if (is_writable($path)){
2045                 if ($dh = opendir($path)) {
2046                         while (($file = readdir($dh)) !== false) {
2047                                 $fullpath = $path."/".$file;
2048                                 if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
2049                                         clear_cache($basepath, $fullpath);
2050                                 if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
2051                                         unlink($fullpath);
2052                         }
2053                         closedir($dh);
2054                 }
2055         }
2056 }
2057
2058 function get_itemcachepath() {
2059         // Checking, if the cache is deactivated
2060         $cachetime = (int)get_config('system','itemcache_duration');
2061         if ($cachetime < 0)
2062                 return "";
2063
2064         $itemcache = get_config('system','itemcache');
2065         if (($itemcache != "") AND is_dir($itemcache) AND is_writable($itemcache))
2066                 return($itemcache);
2067
2068         $temppath = get_temppath();
2069
2070         if ($temppath != "") {
2071                 $itemcache = $temppath."/itemcache";
2072                 if(!file_exists($itemcache) && !is_dir($itemcache)) {
2073                         mkdir($itemcache);
2074                 }
2075
2076                 if (is_dir($itemcache) AND is_writable($itemcache)) {
2077                         set_config("system", "itemcache", $itemcache);
2078                         return($itemcache);
2079                 }
2080         }
2081         return "";
2082 }
2083
2084 function get_lockpath() {
2085         $lockpath = get_config('system','lockpath');
2086         if (($lockpath != "") AND is_dir($lockpath) AND is_writable($lockpath))
2087                 return($lockpath);
2088
2089         $temppath = get_temppath();
2090
2091         if ($temppath != "") {
2092                 $lockpath = $temppath."/lock";
2093
2094                 if (!is_dir($lockpath))
2095                         mkdir($lockpath);
2096                 elseif (!is_writable($lockpath))
2097                         $lockpath = $temppath;
2098
2099                 if (is_dir($lockpath) AND is_writable($lockpath)) {
2100                         set_config("system", "lockpath", $lockpath);
2101                         return($lockpath);
2102                 }
2103         }
2104         return "";
2105 }
2106
2107 function get_temppath() {
2108         $a = get_app();
2109
2110         $temppath = get_config("system","temppath");
2111         if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath))
2112                 return($temppath);
2113
2114         $temppath = sys_get_temp_dir();
2115         if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath)) {
2116                 $temppath .= "/".$a->get_hostname();
2117                 if (!is_dir($temppath))
2118                         mkdir($temppath);
2119
2120                 if (is_dir($temppath) AND is_writable($temppath)) {
2121                         set_config("system", "temppath", $temppath);
2122                         return($temppath);
2123                 }
2124         }
2125
2126         return("");
2127 }
2128
2129 function set_template_engine(&$a, $engine = 'internal') {
2130 /// @note This function is no longer necessary, but keep it as a wrapper to the class method
2131 /// to avoid breaking themes again unnecessarily
2132
2133         $a->set_template_engine($engine);
2134 }
2135
2136 if(!function_exists('exif_imagetype')) {
2137         function exif_imagetype($file) {
2138                 $size = getimagesize($file);
2139                 return($size[2]);
2140         }
2141 }
2142
2143 function validate_include(&$file) {
2144         $orig_file = $file;
2145
2146         $file = realpath($file);
2147
2148         if (strpos($file, getcwd()) !== 0)
2149                 return false;
2150
2151         $file = str_replace(getcwd()."/", "", $file, $count);
2152         if ($count != 1)
2153                 return false;
2154
2155         if ($orig_file !== $file)
2156                 return false;
2157
2158         $valid = false;
2159         if (strpos($file, "include/") === 0)
2160                 $valid = true;
2161
2162         if (strpos($file, "addon/") === 0)
2163                 $valid = true;
2164
2165         if (!$valid)
2166                 return false;
2167
2168         return true;
2169 }
2170
2171 function current_load() {
2172         if (!function_exists('sys_getloadavg'))
2173                 return false;
2174
2175         $load_arr = sys_getloadavg();
2176
2177         if (!is_array($load_arr))
2178                 return false;
2179
2180         return max($load_arr);
2181 }
2182
2183 /**
2184  * @brief get c-style args
2185  * 
2186  * @return int
2187  */
2188 function argc() {
2189         return get_app()->argc;
2190 }
2191
2192 /**
2193  * @brief Returns the value of a argv key
2194  * 
2195  * @param int $x argv key
2196  * @return string Value of the argv key
2197  */
2198 function argv($x) {
2199         if(array_key_exists($x,get_app()->argv))
2200                 return get_app()->argv[$x];
2201
2202         return '';
2203 }