4 * This file defines some global constants and includes the central App class.
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.
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.
20 require_once('include/autoloader.php');
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');
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', 1201 );
44 * @brief Constant with a HTML line break.
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.
50 define ( 'EOL', "<br />\r\n" );
51 define ( 'ATOM_TIME', 'Y-m-d\TH:i:s\Z' );
55 * @brief Image storage quality.
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
65 define ( 'JPEG_QUALITY', 100 );
67 * $a->config['system']['png_quality'] from 0 (uncompressed) to 9
69 define ( 'PNG_QUALITY', 8 );
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
79 * $a->config['system']['max_image_length'] = n;
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.
87 define ( 'MAX_IMAGE_LENGTH', -1 );
94 define ( 'DEFAULT_DB_ENGINE', 'MyISAM' );
99 * SSL redirection policies
102 define ( 'SSL_POLICY_NONE', 0 );
103 define ( 'SSL_POLICY_FULL', 1 );
104 define ( 'SSL_POLICY_SELFSIGN', 2 );
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 );
126 define ( 'CACHE_MONTH', 0 );
127 define ( 'CACHE_WEEK', 1 );
128 define ( 'CACHE_DAY', 2 );
129 define ( 'CACHE_HOUR', 3 );
135 * Registration policies
138 define ( 'REGISTER_CLOSED', 0 );
139 define ( 'REGISTER_APPROVE', 1 );
140 define ( 'REGISTER_OPEN', 2 );
149 define ( 'CONTACT_IS_FOLLOWER', 1);
150 define ( 'CONTACT_IS_SHARING', 2);
151 define ( 'CONTACT_IS_FRIEND', 3);
157 * DB update return values
160 define ( 'UPDATE_SUCCESS', 0);
161 define ( 'UPDATE_FAILED', 1);
166 * @name page/profile types
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).
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 );
187 * Type of the community page
190 define ( 'CP_NO_COMMUNITY_PAGE', -1 );
191 define ( 'CP_USERS_ON_SERVER', 0 );
192 define ( 'CP_GLOBAL_COMMUNITY', 1 );
198 * Network and protocol family types
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
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.
229 $netgroup_ids = array(
230 NETWORK_DFRN => (-1),
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),
250 NETWORK_PHANTOM => (-127),
255 * Maximum number of "people who like (or don't like) this" that we will list by name
258 define ( 'MAX_LIKERS', 75);
261 * Communication timeout
264 define ( 'ZCURL_TIMEOUT' , (-1));
270 * Email notification options
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 );
285 define ( 'NOTIFY_SYSTEM', 0x8000 );
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 );
304 define ( 'TERM_OBJ_POST', 1 );
305 define ( 'TERM_OBJ_PHOTO', 2 );
312 * Various namespaces we may need to parse
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' );
335 * Activity stream defines
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' );
344 define ( 'ACTIVITY_OBJ_HEART', NAMESPACE_DFRN . '/heart' );
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' );
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' );
359 define ( 'ACTIVITY_POKE', NAMESPACE_ZOT . '/activity/poke' );
360 define ( 'ACTIVITY_MOOD', NAMESPACE_ZOT . '/activity/mood' );
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' );
381 * Item weight for query ordering
384 define ( 'GRAVITY_PARENT', 0);
385 define ( 'GRAVITY_LIKE', 3);
386 define ( 'GRAVITY_COMMENT', 6);
392 * Process priority for the worker
395 define('PRIORITY_UNDEFINED', 0);
396 define('PRIORITY_CRITICAL', 10);
397 define('PRIORITY_HIGH', 20);
398 define('PRIORITY_MEDIUM', 30);
399 define('PRIORITY_LOW', 40);
400 define('PRIORITY_NEGLIGIBLE',50);
404 // Normally this constant is defined - but not if "pcntl" isn't installed
405 if (!defined("SIGTERM"))
406 define("SIGTERM", 15);
410 * Reverse the effect of magic_quotes_gpc if it is enabled.
411 * Please disable magic_quotes_gpc so we don't have to do this.
412 * See http://php.net/manual/en/security.magicquotes.disabling.php
418 error_reporting(E_ERROR | E_WARNING | E_PARSE);
422 // This has to be quite large to deal with embedded private photos
423 ini_set('pcre.backtrack_limit', 500000);
426 if (get_magic_quotes_gpc()) {
427 $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
428 while (list($key, $val) = each($process)) {
429 foreach ($val as $k => $v) {
430 unset($process[$key][$k]);
432 $process[$key][stripslashes($k)] = $v;
433 $process[] = &$process[$key][stripslashes($k)];
435 $process[$key][stripslashes($k)] = stripslashes($v);
448 * @brief Our main application structure for the life of this page.
450 * Primarily deals with the URL that got us here
451 * and tries to make some sense of it, and
452 * stores our page contents and config storage
453 * and anything else that might need to be passed around
454 * before we spit the page out.
459 public $module_loaded = false;
460 public $query_string;
469 public $page_contact;
471 public $data = array();
472 public $error = false;
482 public $interactive = true;
484 public $apps = array();
486 public $is_mobile = false;
487 public $is_tablet = false;
488 public $is_friendica_app;
489 public $performance = array();
490 public $callstack = array();
491 public $theme_info = array();
492 public $backend = true;
499 // Allow themes to control internal parameters
500 // by changing App values in theme.php
502 public $sourcename = '';
503 public $videowidth = 425;
504 public $videoheight = 350;
505 public $force_max_items = 0;
506 public $theme_thread_allow = true;
507 public $theme_events_in_profile = true;
510 * @brief An array for all theme-controllable parameters
512 * Mostly unimplemented yet. Only options 'template_engine' and
515 public $theme = array(
518 'videoheight' => 350,
519 'force_max_items' => 0,
520 'thread_allow' => true,
522 'template_engine' => 'smarty3',
526 * @brief An array of registered template engines ('name'=>'class name')
528 public $template_engines = array();
530 * @brief An array of instanced template engines ('name'=>'instance')
532 public $template_engine_instance = array();
536 private $ldelim = array(
540 private $rdelim = array(
551 private $curl_content_type;
552 private $curl_headers;
554 private $cached_profile_image;
555 private $cached_profile_picdate;
560 * @brief App constructor.
562 function __construct() {
564 global $default_timezone;
568 if (file_exists(".htpreconfig.php"))
569 @include(".htpreconfig.php");
571 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
573 date_default_timezone_set($this->timezone);
575 $this->performance["start"] = microtime(true);
576 $this->performance["database"] = 0;
577 $this->performance["database_write"] = 0;
578 $this->performance["network"] = 0;
579 $this->performance["file"] = 0;
580 $this->performance["rendering"] = 0;
581 $this->performance["parser"] = 0;
582 $this->performance["marktime"] = 0;
583 $this->performance["markstart"] = microtime(true);
585 $this->callstack["database"] = array();
586 $this->callstack["network"] = array();
587 $this->callstack["file"] = array();
588 $this->callstack["rendering"] = array();
589 $this->callstack["parser"] = array();
591 $this->config = array();
592 $this->page = array();
593 $this->pager= array();
595 $this->query_string = '';
597 $this->process_id = uniqid("log", true);
602 'include' . PATH_SEPARATOR
603 . 'library' . PATH_SEPARATOR
604 . 'library/phpsec' . PATH_SEPARATOR
605 . 'library/langdet' . PATH_SEPARATOR
609 $this->scheme = 'http';
610 if((x($_SERVER,'HTTPS') && $_SERVER['HTTPS']) ||
611 (x($_SERVER['HTTP_FORWARDED']) && preg_match("/proto=https/", $_SERVER['HTTP_FORWARDED'])) ||
612 (x($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
613 (x($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
614 (x($_SERVER['FRONT_END_HTTPS']) && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
615 (x($_SERVER,'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
617 $this->scheme = 'https';
620 if(x($_SERVER,'SERVER_NAME')) {
621 $this->hostname = $_SERVER['SERVER_NAME'];
623 if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
624 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
626 * Figure out if we are running at the top of a domain
627 * or in a sub-directory and adjust accordingly
630 $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
631 if(isset($path) && strlen($path) && ($path != $this->path))
636 $this->hostname = $hostname;
638 if (is_array($_SERVER["argv"]) && $_SERVER["argc"]>1 && substr(end($_SERVER["argv"]), 0, 4)=="http" ) {
639 $this->set_baseurl(array_pop($_SERVER["argv"]) );
643 #set_include_path("include/$this->hostname" . PATH_SEPARATOR . get_include_path());
645 if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,9) === "pagename=") {
646 $this->query_string = substr($_SERVER['QUERY_STRING'],9);
647 // removing trailing / - maybe a nginx problem
648 if (substr($this->query_string, 0, 1) == "/")
649 $this->query_string = substr($this->query_string, 1);
650 } elseif((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
651 $this->query_string = substr($_SERVER['QUERY_STRING'],2);
652 // removing trailing / - maybe a nginx problem
653 if (substr($this->query_string, 0, 1) == "/")
654 $this->query_string = substr($this->query_string, 1);
657 if (x($_GET,'pagename'))
658 $this->cmd = trim($_GET['pagename'],'/\\');
659 elseif (x($_GET,'q'))
660 $this->cmd = trim($_GET['q'],'/\\');
664 $this->query_string = str_replace($this->cmd."&",$this->cmd."?", $this->query_string);
667 // unix style "homedir"
669 if(substr($this->cmd,0,1) === '~')
670 $this->cmd = 'profile/' . substr($this->cmd,1);
672 // Diaspora style profile url
674 if(substr($this->cmd,0,2) === 'u/')
675 $this->cmd = 'profile/' . substr($this->cmd,2);
680 * Break the URL path into C style argc/argv style arguments for our
681 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
682 * will be 3 (integer) and $this->argv will contain:
688 * There will always be one argument. If provided a naked domain
689 * URL, $this->argv[0] is set to "home".
693 $this->argv = explode('/',$this->cmd);
694 $this->argc = count($this->argv);
695 if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
696 $this->module = str_replace(".", "_", $this->argv[0]);
697 $this->module = str_replace("-", "_", $this->module);
701 $this->argv = array('home');
702 $this->module = 'home';
706 * See if there is any page number information, and initialise
710 $this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
711 $this->pager['itemspage'] = 50;
712 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
713 if($this->pager['start'] < 0)
714 $this->pager['start'] = 0;
715 $this->pager['total'] = 0;
718 * Detect mobile devices
721 $mobile_detect = new Mobile_Detect();
722 $this->is_mobile = $mobile_detect->isMobile();
723 $this->is_tablet = $mobile_detect->isTablet();
726 $this->is_friendica_app = ($_SERVER['HTTP_USER_AGENT'] == "Apache-HttpClient/UNAVAILABLE (java 1.4)");
729 * register template engines
731 $dc = get_declared_classes();
732 foreach ($dc as $k) {
733 if (in_array("ITemplateEngine", class_implements($k))){
734 $this->register_template_engine($k);
742 function get_basepath() {
744 $basepath = get_config("system", "basepath");
747 $basepath = dirname(__FILE__);
750 $basepath = $_SERVER["DOCUMENT_ROOT"];
753 $basepath = $_SERVER["PWD"];
758 function get_scheme() {
759 return($this->scheme);
762 function get_baseurl($ssl = false) {
764 // Is the function called statically?
765 if (!is_object($this))
766 return(self::$a->get_baseurl($ssl));
768 $scheme = $this->scheme;
770 if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
771 if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
774 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
775 // (and also the login link). Anything seen by an outsider will have it turned off.
777 if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
785 if (get_config('config','hostname') != "")
786 $this->hostname = get_config('config','hostname');
788 $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
789 return $this->baseurl;
792 function set_baseurl($url) {
793 $parsed = @parse_url($url);
795 $this->baseurl = $url;
798 $this->scheme = $parsed['scheme'];
800 $hostname = $parsed['host'];
801 if(x($parsed,'port'))
802 $hostname .= ':' . $parsed['port'];
803 if(x($parsed,'path'))
804 $this->path = trim($parsed['path'],'\\/');
806 if (file_exists(".htpreconfig.php"))
807 @include(".htpreconfig.php");
809 if (get_config('config','hostname') != "")
810 $this->hostname = get_config('config','hostname');
812 if (!isset($this->hostname) OR ($this->hostname == ""))
813 $this->hostname = $hostname;
818 function get_hostname() {
819 if (get_config('config','hostname') != "")
820 $this->hostname = get_config('config','hostname');
822 return $this->hostname;
825 function set_hostname($h) {
826 $this->hostname = $h;
829 function set_path($p) {
830 $this->path = trim(trim($p),'/');
833 function get_path() {
837 function set_pager_total($n) {
838 $this->pager['total'] = intval($n);
841 function set_pager_itemspage($n) {
842 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
843 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
846 function set_pager_page($n) {
847 $this->pager['page'] = $n;
848 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
851 function init_pagehead() {
852 $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
854 // If the update is "deactivated" set it to the highest integer number (~24 days)
856 $interval = 2147483647;
858 if($interval < 10000)
861 // compose the page title from the sitename and the
862 // current module called
863 if (!$this->module=='')
865 $this->page['title'] = $this->config['sitename'].' ('.$this->module.')';
867 $this->page['title'] = $this->config['sitename'];
870 /* put the head template at the beginning of page['htmlhead']
871 * since the code added by the modules frequently depends on it
874 if(!isset($this->page['htmlhead']))
875 $this->page['htmlhead'] = '';
877 // If we're using Smarty, then doing replace_macros() will replace
878 // any unrecognized variables with a blank string. Since we delay
879 // replacing $stylesheet until later, we need to replace it now
880 // with another variable name
881 if($this->theme['template_engine'] === 'smarty3')
882 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
884 $stylesheet = '$stylesheet';
886 $shortcut_icon = get_config("system", "shortcut_icon");
887 if ($shortcut_icon == "")
888 $shortcut_icon = "images/friendica-32.png";
890 $touch_icon = get_config("system", "touch_icon");
891 if ($touch_icon == "")
892 $touch_icon = "images/friendica-128.png";
894 // get data wich is needed for infinite scroll on the network page
895 $invinite_scroll = infinite_scroll_data($this->module);
897 $tpl = get_markup_template('head.tpl');
898 $this->page['htmlhead'] = replace_macros($tpl,array(
899 '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
900 '$local_user' => local_user(),
901 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
902 '$delitem' => t('Delete this item?'),
903 '$comment' => t('Comment'),
904 '$showmore' => t('show more'),
905 '$showfewer' => t('show fewer'),
906 '$update_interval' => $interval,
907 '$shortcut_icon' => $shortcut_icon,
908 '$touch_icon' => $touch_icon,
909 '$stylesheet' => $stylesheet,
910 '$infinite_scroll' => $invinite_scroll,
911 )) . $this->page['htmlhead'];
914 function init_page_end() {
915 if(!isset($this->page['end']))
916 $this->page['end'] = '';
917 $tpl = get_markup_template('end.tpl');
918 $this->page['end'] = replace_macros($tpl,array(
919 '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
920 )) . $this->page['end'];
923 function set_curl_code($code) {
924 $this->curl_code = $code;
927 function get_curl_code() {
928 return $this->curl_code;
931 function set_curl_content_type($content_type) {
932 $this->curl_content_type = $content_type;
935 function get_curl_content_type() {
936 return $this->curl_content_type;
939 function set_curl_headers($headers) {
940 $this->curl_headers = $headers;
943 function get_curl_headers() {
944 return $this->curl_headers;
947 function get_cached_avatar_image($avatar_image){
948 return $avatar_image;
950 // The following code is deactivated. It doesn't seem to make any sense and it slows down the system.
952 if($this->cached_profile_image[$avatar_image])
953 return $this->cached_profile_image[$avatar_image];
955 $path_parts = explode("/",$avatar_image);
956 $common_filename = $path_parts[count($path_parts)-1];
958 if($this->cached_profile_picdate[$common_filename]){
959 $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
961 $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like '%%/%s'",
963 if(! dbm::is_result($r)){
964 $this->cached_profile_image[$avatar_image] = $avatar_image;
966 $this->cached_profile_picdate[$common_filename] = "?rev=".urlencode($r[0]['picdate']);
967 $this->cached_profile_image[$avatar_image] = $avatar_image.$this->cached_profile_picdate[$common_filename];
970 return $this->cached_profile_image[$avatar_image];
976 * @brief Removes the baseurl from an url. This avoids some mixed content problems.
980 * @return string The cleaned url
982 function remove_baseurl($url){
984 // Is the function called statically?
985 if (!is_object($this))
986 return(self::$a->remove_baseurl($url));
988 $url = normalise_link($url);
989 $base = normalise_link($this->get_baseurl());
990 $url = str_replace($base."/", "", $url);
995 * @brief Register template engine class
997 * If $name is "", is used class static property $class::$name
999 * @param string $class
1000 * @param string $name
1002 function register_template_engine($class, $name = '') {
1004 $v = get_class_vars( $class );
1005 if(x($v,"name")) $name = $v['name'];
1008 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
1011 $this->template_engines[$name] = $class;
1015 * @brief Return template engine instance.
1017 * If $name is not defined, return engine defined by theme,
1020 * @param strin $name Template engine name
1021 * @return object Template Engine instance
1023 function template_engine($name = ''){
1025 $template_engine = $name;
1027 $template_engine = 'smarty3';
1028 if (x($this->theme, 'template_engine')) {
1029 $template_engine = $this->theme['template_engine'];
1033 if (isset($this->template_engines[$template_engine])){
1034 if(isset($this->template_engine_instance[$template_engine])){
1035 return $this->template_engine_instance[$template_engine];
1037 $class = $this->template_engines[$template_engine];
1039 $this->template_engine_instance[$template_engine] = $obj;
1044 echo "template engine <tt>$template_engine</tt> is not registered!\n"; killme();
1048 * @brief Returns the active template engine.
1052 function get_template_engine() {
1053 return $this->theme['template_engine'];
1056 function set_template_engine($engine = 'smarty3') {
1057 $this->theme['template_engine'] = $engine;
1059 $this->theme['template_engine'] = 'smarty3';
1063 if(is_writable('view/smarty3/'))
1064 $this->theme['template_engine'] = 'smarty3';
1072 function get_template_ldelim($engine = 'smarty3') {
1073 return $this->ldelim[$engine];
1076 function get_template_rdelim($engine = 'smarty3') {
1077 return $this->rdelim[$engine];
1080 function save_timestamp($stamp, $value) {
1081 $duration = (float)(microtime(true)-$stamp);
1083 if (!isset($this->performance[$value])) {
1084 // Prevent ugly E_NOTICE
1085 $this->performance[$value] = 0;
1088 $this->performance[$value] += (float)$duration;
1089 $this->performance["marktime"] += (float)$duration;
1091 $callstack = $this->callstack();
1093 if (!isset($this->callstack[$value][$callstack])) {
1094 // Prevent ugly E_NOTICE
1095 $this->callstack[$value][$callstack] = 0;
1098 $this->callstack[$value][$callstack] += (float)$duration;
1103 * @brief Returns a string with a callstack. Can be used for logging.
1107 function callstack() {
1108 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 6);
1110 // We remove the first two items from the list since they contain data that we don't need.
1111 array_shift($trace);
1112 array_shift($trace);
1114 $callstack = array();
1115 foreach ($trace AS $func)
1116 $callstack[] = $func["function"];
1118 return implode(", ", $callstack);
1121 function mark_timestamp($mark) {
1122 //$this->performance["markstart"] -= microtime(true) - $this->performance["marktime"];
1123 $this->performance["markstart"] = microtime(true) - $this->performance["markstart"] - $this->performance["marktime"];
1126 function get_useragent() {
1127 return(FRIENDICA_PLATFORM." '".FRIENDICA_CODENAME."' ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION."; ".$this->get_baseurl());
1130 function is_friendica_app() {
1131 return($this->is_friendica_app);
1135 * @brief Checks if the site is called via a backend process
1137 * This isn't a perfect solution. But we need this check very early.
1138 * So we cannot wait until the modules are loaded.
1140 * @return bool Is it a known backend?
1142 function is_backend() {
1144 $backend[] = "_well_known";
1146 $backend[] = "dfrn_notify";
1147 $backend[] = "fetch";
1148 $backend[] = "hcard";
1149 $backend[] = "hostxrd";
1150 $backend[] = "nodeinfo";
1151 $backend[] = "noscrape";
1153 $backend[] = "poco";
1154 $backend[] = "post";
1155 $backend[] = "proxy";
1156 $backend[] = "pubsub";
1157 $backend[] = "pubsubhubbub";
1158 $backend[] = "receive";
1159 $backend[] = "rsd_xml";
1160 $backend[] = "salmon";
1161 $backend[] = "statistics_json";
1164 if (in_array($this->module, $backend))
1167 return($this->backend);
1171 * @brief Checks if the maximum number of database processes is reached
1173 * @return bool Is the limit reached?
1175 function max_processes_reached() {
1177 // Is the function called statically?
1178 if (!is_object($this))
1179 return(self::$a->max_processes_reached());
1181 if ($this->is_backend()) {
1182 $process = "backend";
1183 $max_processes = get_config('system', 'max_processes_backend');
1184 if (intval($max_processes) == 0)
1187 $process = "frontend";
1188 $max_processes = get_config('system', 'max_processes_frontend');
1189 if (intval($max_processes) == 0)
1190 $max_processes = 20;
1193 $processlist = dbm::processlist();
1194 if ($processlist["list"] != "") {
1195 logger("Processcheck: Processes: ".$processlist["amount"]." - Processlist: ".$processlist["list"], LOGGER_DEBUG);
1197 if ($processlist["amount"] > $max_processes) {
1198 logger("Processcheck: Maximum number of processes for ".$process." tasks (".$max_processes.") reached.", LOGGER_DEBUG);
1206 * @brief Checks if the maximum load is reached
1208 * @return bool Is the load reached?
1210 function maxload_reached() {
1212 // Is the function called statically?
1213 if (!is_object($this))
1214 return(self::$a->maxload_reached());
1216 if ($this->is_backend()) {
1217 $process = "backend";
1218 $maxsysload = intval(get_config('system', 'maxloadavg'));
1219 if ($maxsysload < 1)
1222 $process = "frontend";
1223 $maxsysload = intval(get_config('system','maxloadavg_frontend'));
1224 if ($maxsysload < 1)
1228 $load = current_load();
1230 if (intval($load) > $maxsysload) {
1231 logger('system: load '.$load.' for '.$process.' tasks ('.$maxsysload.') too high.');
1239 * @brief Checks if the process is already running
1241 * @param string $taskname The name of the task that will be used for the name of the lockfile
1242 * @param string $task The path and name of the php script
1243 * @param int $timeout The timeout after which a task should be killed
1245 * @return bool Is the process running?
1247 function is_already_running($taskname, $task = "", $timeout = 540) {
1249 $lockpath = get_lockpath();
1250 if ($lockpath != '') {
1251 $pidfile = new pidfile($lockpath, $taskname);
1252 if ($pidfile->is_already_running()) {
1253 logger("Already running");
1254 if ($pidfile->running_time() > $timeout) {
1256 logger("killed stale process");
1257 // Calling a new instance
1259 proc_run(PRIORITY_MEDIUM, $task);
1267 function proc_run($args) {
1269 // Add the php path if it is a php call
1270 if (count($args) && ($args[0] === 'php' OR is_int($args[0]))) {
1272 // If the last worker fork was less than 10 seconds before then don't fork another one.
1273 // This should prevent the forking of masses of workers.
1274 if (get_config("system", "worker")) {
1275 if ((time() - get_config("system", "proc_run_started")) < 10)
1278 // Set the timestamp of the last proc_run
1279 set_config("system", "proc_run_started", time());
1282 $args[0] = ((x($this->config,'php_path')) && (strlen($this->config['php_path'])) ? $this->config['php_path'] : 'php');
1285 // add baseurl to args. cli scripts can't construct it
1286 $args[] = $this->get_baseurl();
1288 for($x = 0; $x < count($args); $x ++)
1289 $args[$x] = escapeshellarg($args[$x]);
1291 $cmdline = implode($args," ");
1293 if(get_config('system','proc_windows'))
1294 proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
1296 proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
1302 * @brief Retrieve the App structure
1304 * Useful in functions which require it but don't get it passed to them
1306 function get_app() {
1313 * @brief Multi-purpose function to check variable state.
1315 * Usage: x($var) or $x($array, 'key')
1317 * returns false if variable/key is not set
1318 * if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
1319 * e.g. x('') or x(0) returns 0;
1321 * @param string|array $s variable to check
1322 * @param string $k key inside the array to check
1326 function x($s,$k = NULL) {
1328 if((is_array($s)) && (array_key_exists($k,$s))) {
1348 * @brief Called from db initialisation if db is dead.
1350 function system_unavailable() {
1351 include('system_unavailable.php');
1357 function clean_urls() {
1359 // if($a->config['system']['clean_urls'])
1366 $base = $a->get_baseurl();
1373 * @brief Returns the baseurl.
1375 * @see App::get_baseurl()
1381 return $a->get_baseurl();
1385 * @brief Return absolut URL for given $path.
1387 * @param string $path
1391 function absurl($path) {
1392 if(strpos($path,'/') === 0)
1393 return z_path() . $path;
1398 * @brief Function to check if request was an AJAX (xmlhttprequest) request.
1402 function is_ajax() {
1403 return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
1406 function check_db() {
1408 $build = get_config('system','build');
1410 set_config('system','build',DB_UPDATE_VERSION);
1411 $build = DB_UPDATE_VERSION;
1413 if($build != DB_UPDATE_VERSION)
1414 proc_run(PRIORITY_CRITICAL, 'include/dbupdate.php');
1420 * Sets the base url for use in cmdline programs which don't have
1421 * $_SERVER variables
1423 function check_url(&$a) {
1425 $url = get_config('system','url');
1427 // if the url isn't set or the stored url is radically different
1428 // than the currently visited url, store the current value accordingly.
1429 // "Radically different" ignores common variations such as http vs https
1430 // and www.example.com vs example.com.
1431 // We will only change the url to an ip address if there is no existing setting
1434 $url = set_config('system','url',$a->get_baseurl());
1435 if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
1436 $url = set_config('system','url',$a->get_baseurl());
1443 * @brief Automatic database updates
1445 function update_db(&$a) {
1446 $build = get_config('system','build');
1448 $build = set_config('system','build',DB_UPDATE_VERSION);
1450 if($build != DB_UPDATE_VERSION) {
1451 $stored = intval($build);
1452 $current = intval(DB_UPDATE_VERSION);
1453 if($stored < $current) {
1454 load_config('database');
1456 // We're reporting a different version than what is currently installed.
1457 // Run any existing update scripts to bring the database up to current.
1459 // make sure that boot.php and update.php are the same release, we might be
1460 // updating right this very second and the correct version of the update.php
1461 // file may not be here yet. This can happen on a very busy site.
1463 if(DB_UPDATE_VERSION == UPDATE_VERSION) {
1464 // Compare the current structure with the defined structure
1466 $t = get_config('database','dbupdate_'.DB_UPDATE_VERSION);
1470 set_config('database','dbupdate_'.DB_UPDATE_VERSION, time());
1472 // run old update routine (wich could modify the schema and
1473 // conflits with new routine)
1474 for ($x = $stored; $x < NEW_UPDATE_ROUTINE_VERSION; $x++) {
1475 $r = run_update_function($x);
1478 if ($stored < NEW_UPDATE_ROUTINE_VERSION) $stored = NEW_UPDATE_ROUTINE_VERSION;
1481 // run new update routine
1482 // it update the structure in one call
1483 $retval = update_structure(false, true);
1491 set_config('database','dbupdate_'.DB_UPDATE_VERSION, 'success');
1494 // run any left update_nnnn functions in update.php
1495 for($x = $stored; $x < $current; $x ++) {
1496 $r = run_update_function($x);
1506 function run_update_function($x) {
1507 if(function_exists('update_' . $x)) {
1509 // There could be a lot of processes running or about to run.
1510 // We want exactly one process to run the update command.
1511 // So store the fact that we're taking responsibility
1512 // after first checking to see if somebody else already has.
1514 // If the update fails or times-out completely you may need to
1515 // delete the config entry to try again.
1517 $t = get_config('database','update_' . $x);
1520 set_config('database','update_' . $x, time());
1522 // call the specific update
1524 $func = 'update_' . $x;
1528 //send the administrator an e-mail
1531 sprintf(t('Update %s failed. See error logs.'), $x)
1535 set_config('database','update_' . $x, 'success');
1536 set_config('system','build', $x + 1);
1540 set_config('database','update_' . $x, 'success');
1541 set_config('system','build', $x + 1);
1548 * @brief Synchronise plugins:
1550 * $a->config['system']['addon'] contains a comma-separated list of names
1551 * of plugins/addons which are used on this system.
1552 * Go through the database list of already installed addons, and if we have
1553 * an entry, but it isn't in the config list, call the uninstall procedure
1554 * and mark it uninstalled in the database (for now we'll remove it).
1555 * Then go through the config list and if we have a plugin that isn't installed,
1556 * call the install procedure and add it to the database.
1561 function check_plugins(&$a) {
1563 $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
1564 if(dbm::is_result($r))
1567 $installed = array();
1569 $plugins = get_config('system','addon');
1570 $plugins_arr = array();
1573 $plugins_arr = explode(',',str_replace(' ', '',$plugins));
1575 $a->plugins = $plugins_arr;
1577 $installed_arr = array();
1579 if(count($installed)) {
1580 foreach($installed as $i) {
1581 if(! in_array($i['name'],$plugins_arr)) {
1582 uninstall_plugin($i['name']);
1585 $installed_arr[] = $i['name'];
1590 if(count($plugins_arr)) {
1591 foreach($plugins_arr as $p) {
1592 if(! in_array($p,$installed_arr)) {
1604 function get_guid($size=16, $prefix = "") {
1606 if ($prefix == "") {
1608 $prefix = hash("crc32", $a->get_hostname());
1611 while (strlen($prefix) < ($size - 13))
1612 $prefix .= mt_rand();
1615 $prefix = substr($prefix, 0, $size - 22);
1616 return(str_replace(".", "", uniqid($prefix, true)));
1618 $prefix = substr($prefix, 0, max($size - 13, 0));
1619 return(uniqid($prefix));
1624 * @brief Wrapper for adding a login box.
1626 * @param bool $register
1627 * If $register == true provide a registration link.
1628 * This will most always depend on the value of $a->config['register_policy'].
1629 * @param bool $hiddens
1632 * Returns the complete html for inserting into the page
1634 * @hooks 'login_hook'
1637 function login($register = false, $hiddens=false) {
1643 'title' => t('Create a New Account'),
1644 'desc' => t('Register')
1648 $noid = get_config('system','no_openid');
1650 $dest_url = $a->query_string;
1653 $tpl = get_markup_template("logout.tpl");
1656 $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
1657 '$baseurl' => $a->get_baseurl(true)
1660 $tpl = get_markup_template("login.tpl");
1661 $_SESSION['return_url'] = $a->query_string;
1662 $a->module = 'login';
1665 $o .= replace_macros($tpl, array(
1667 '$dest_url' => $dest_url,
1668 '$logout' => t('Logout'),
1669 '$login' => t('Login'),
1671 '$lname' => array('username', t('Nickname or Email: ') , '', ''),
1672 '$lpassword' => array('password', t('Password: '), '', ''),
1673 '$lremember' => array('remember', t('Remember me'), 0, ''),
1675 '$openid' => !$noid,
1676 '$lopenid' => array('openid_url', t('Or login using OpenID: '),'',''),
1678 '$hiddens' => $hiddens,
1680 '$register' => $reg,
1682 '$lostpass' => t('Forgot your password?'),
1683 '$lostlink' => t('Password Reset'),
1685 '$tostitle' => t('Website Terms of Service'),
1686 '$toslink' => t('terms of service'),
1688 '$privacytitle' => t('Website Privacy Policy'),
1689 '$privacylink' => t('privacy policy'),
1693 call_hooks('login_hook',$o);
1699 * @brief Used to end the current process, after saving session state.
1702 if (!get_app()->is_backend())
1703 session_write_close();
1709 * @brief Redirect to another URL and terminate this process.
1711 function goaway($s) {
1712 if (!strstr(normalise_link($s), "http://"))
1713 $s = App::get_baseurl()."/".$s;
1715 header("Location: $s");
1721 * @brief Returns the user id of locally logged in user or false.
1723 * @return int|bool user id or false
1725 function local_user() {
1726 if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
1727 return intval($_SESSION['uid']);
1732 * @brief Returns contact id of authenticated site visitor or false
1734 * @return int|bool visitor_id or false
1736 function remote_user() {
1737 if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
1738 return intval($_SESSION['visitor_id']);
1743 * @brief Show an error message to user.
1745 * This function save text in session, to be shown to the user at next page load
1747 * @param string $s - Text of notice
1749 function notice($s) {
1751 if(! x($_SESSION,'sysmsg')) $_SESSION['sysmsg'] = array();
1753 $_SESSION['sysmsg'][] = $s;
1757 * @brief Show an info message to user.
1759 * This function save text in session, to be shown to the user at next page load
1761 * @param string $s - Text of notice
1766 if (local_user() AND get_pconfig(local_user(),'system','ignore_info'))
1769 if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
1771 $_SESSION['sysmsg_info'][] = $s;
1776 * @brief Wrapper around config to limit the text length of an incoming message
1780 function get_max_import_size() {
1782 return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
1786 * @brief Wrap calls to proc_close(proc_open()) and call hook
1787 * so plugins can take part in process :)
1789 * @param (string|integer) $cmd program to run or priority
1791 * next args are passed as $cmd command line
1792 * e.g.: proc_run("ls","-la","/tmp");
1793 * or: proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $drop_id);
1795 * @note $cmd and string args are surrounded with ""
1800 function proc_run($cmd){
1804 $args = func_get_args();
1810 // expand any arrays
1812 foreach($args as $arg) {
1813 if(is_array($arg)) {
1814 foreach($arg as $n) {
1823 $arr = array('args' => $args, 'run_cmd' => true);
1825 call_hooks("proc_run", $arr);
1826 if (!$arr['run_cmd'] OR !count($args))
1829 if (!get_config("system", "worker") OR
1830 (($args[0] != 'php') AND !is_int($args[0]))) {
1831 $a->proc_run($args);
1835 if (is_int($args[0]))
1836 $priority = $args[0];
1838 $priority = PRIORITY_MEDIUM;
1843 $parameters = json_encode($argv);
1844 $found = q("SELECT `id` FROM `workerqueue` WHERE `parameter` = '%s'",
1845 dbesc($parameters));
1848 q("INSERT INTO `workerqueue` (`parameter`, `created`, `priority`)
1849 VALUES ('%s', '%s', %d)",
1851 dbesc(datetime_convert()),
1854 // Should we quit and wait for the poller to be called as a cronjob?
1855 if (get_config("system", "worker_dont_fork"))
1858 // Checking number of workers
1859 $workers = q("SELECT COUNT(*) AS `workers` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
1861 // Get number of allowed number of worker threads
1862 $queues = intval(get_config("system", "worker_queues"));
1867 // If there are already enough workers running, don't fork another one
1868 if ($workers[0]["workers"] >= $queues)
1871 // Now call the poller to execute the jobs that we just added to the queue
1872 $args = array("php", "include/poller.php", "no_cron");
1874 $a->proc_run($args);
1877 function current_theme(){
1878 $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
1884 // Find the theme that belongs to the user whose stuff we are looking at
1886 if($a->profile_uid && ($a->profile_uid != local_user())) {
1887 $r = q("select theme from user where uid = %d limit 1",
1888 intval($a->profile_uid)
1890 if(dbm::is_result($r))
1891 $page_theme = $r[0]['theme'];
1894 // Allow folks to over-rule user themes and always use their own on their own site.
1895 // This works only if the user is on the same server
1897 if($page_theme && local_user() && (local_user() != $a->profile_uid)) {
1898 if(get_pconfig(local_user(),'system','always_my_theme'))
1902 // $mobile_detect = new Mobile_Detect();
1903 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1904 $is_mobile = $a->is_mobile || $a->is_tablet;
1906 $standard_system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1907 $standard_theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $standard_system_theme);
1910 if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
1911 $system_theme = $standard_system_theme;
1912 $theme_name = $standard_theme_name;
1915 $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : $standard_system_theme);
1916 $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
1918 if($theme_name === '---') {
1919 // user has selected to have the mobile theme be the same as the normal one
1920 $system_theme = $standard_system_theme;
1921 $theme_name = $standard_theme_name;
1924 $theme_name = $page_theme;
1929 $system_theme = $standard_system_theme;
1930 $theme_name = $standard_theme_name;
1933 $theme_name = $page_theme;
1937 (file_exists('view/theme/' . $theme_name . '/style.css') ||
1938 file_exists('view/theme/' . $theme_name . '/style.php')))
1939 return($theme_name);
1941 foreach($app_base_themes as $t) {
1942 if(file_exists('view/theme/' . $t . '/style.css')||
1943 file_exists('view/theme/' . $t . '/style.php'))
1947 $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
1948 if(count($fallback))
1949 return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
1954 * @brief Return full URL to theme which is currently in effect.
1956 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1960 function current_theme_url() {
1963 $t = current_theme();
1965 $opts = (($a->profile_uid) ? '?f=&puid=' . $a->profile_uid : '');
1966 if (file_exists('view/theme/' . $t . '/style.php'))
1967 return('view/theme/'.$t.'/style.pcss'.$opts);
1969 return('view/theme/'.$t.'/style.css');
1972 function feed_birthday($uid,$tz) {
1976 * Determine the next birthday, but only if the birthday is published
1977 * in the default profile. We _could_ also look for a private profile that the
1978 * recipient can see, but somebody could get mad at us if they start getting
1979 * public birthday greetings when they haven't made this info public.
1981 * Assuming we are able to publish this info, we are then going to convert
1982 * the start time from the owner's timezone to UTC.
1984 * This will potentially solve the problem found with some social networks
1985 * where birthdays are converted to the viewer's timezone and salutations from
1986 * elsewhere in the world show up on the wrong day. We will convert it to the
1987 * viewer's timezone also, but first we are going to convert it from the birthday
1988 * person's timezone to GMT - so the viewer may find the birthday starting at
1989 * 6:00PM the day before, but that will correspond to midnight to the birthday person.
1999 $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
2003 if(dbm::is_result($p)) {
2004 $tmp_dob = substr($p[0]['dob'],5);
2005 if(intval($tmp_dob)) {
2006 $y = datetime_convert($tz,$tz,'now','Y');
2007 $bd = $y . '-' . $tmp_dob . ' 00:00';
2008 $t_dob = strtotime($bd);
2009 $now = strtotime(datetime_convert($tz,$tz,'now'));
2011 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
2012 $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
2020 * @brief Check if current user has admin role.
2022 * @return bool true if user is an admin
2024 function is_site_admin() {
2027 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
2029 //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
2030 if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && in_array($a->user['email'], $adminlist))
2036 * @brief Returns querystring as string from a mapped array.
2038 * @param array $params mapped array with query parameters
2039 * @param string $name of parameter, default null
2043 function build_querystring($params, $name=null) {
2045 foreach($params as $key=>$val) {
2046 if(is_array($val)) {
2048 $ret .= build_querystring($val, $key);
2050 $ret .= build_querystring($val, $name."[$key]");
2053 $val = urlencode($val);
2055 $ret.=$name."[$key]"."=$val&";
2057 $ret.= "$key=$val&";
2064 function explode_querystring($query) {
2065 $arg_st = strpos($query, '?');
2066 if($arg_st !== false) {
2067 $base = substr($query, 0, $arg_st);
2074 $args = explode('&', substr($query, $arg_st));
2075 foreach($args as $k=>$arg) {
2079 $args = array_values($args);
2084 $args = array_values($args);
2094 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
2096 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
2098 function curPageURL() {
2100 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
2102 if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
2103 $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
2105 $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
2110 function random_digits($digits) {
2112 for($i = 0; $i < $digits; $i++) {
2118 function get_server() {
2119 $server = get_config("system", "directory");
2122 $server = "http://dir.friendi.ca";
2127 function get_cachefile($file, $writemode = true) {
2128 $cache = get_itemcachepath();
2130 if ((! $cache) || (! is_dir($cache)))
2133 $subfolder = $cache."/".substr($file, 0, 2);
2135 $cachepath = $subfolder."/".$file;
2138 if (!is_dir($subfolder)) {
2140 chmod($subfolder, 0777);
2147 function clear_cache($basepath = "", $path = "") {
2149 $basepath = get_itemcachepath();
2153 if (($path == "") OR (!is_dir($path)))
2156 if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
2159 $cachetime = (int)get_config('system','itemcache_duration');
2160 if ($cachetime == 0)
2163 if (is_writable($path)){
2164 if ($dh = opendir($path)) {
2165 while (($file = readdir($dh)) !== false) {
2166 $fullpath = $path."/".$file;
2167 if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
2168 clear_cache($basepath, $fullpath);
2169 if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
2177 function get_itemcachepath() {
2178 // Checking, if the cache is deactivated
2179 $cachetime = (int)get_config('system','itemcache_duration');
2183 $itemcache = get_config('system','itemcache');
2184 if (($itemcache != "") AND is_dir($itemcache) AND is_writable($itemcache))
2187 $temppath = get_temppath();
2189 if ($temppath != "") {
2190 $itemcache = $temppath."/itemcache";
2191 if(!file_exists($itemcache) && !is_dir($itemcache)) {
2195 if (is_dir($itemcache) AND is_writable($itemcache)) {
2196 set_config("system", "itemcache", $itemcache);
2203 function get_lockpath() {
2204 $lockpath = get_config('system','lockpath');
2205 if (($lockpath != "") AND is_dir($lockpath) AND is_writable($lockpath))
2208 $temppath = get_temppath();
2210 if ($temppath != "") {
2211 $lockpath = $temppath."/lock";
2213 if (!is_dir($lockpath))
2215 elseif (!is_writable($lockpath))
2216 $lockpath = $temppath;
2218 if (is_dir($lockpath) AND is_writable($lockpath)) {
2219 set_config("system", "lockpath", $lockpath);
2226 function get_temppath() {
2229 $temppath = get_config("system","temppath");
2230 if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath))
2233 $temppath = sys_get_temp_dir();
2234 if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath)) {
2235 $temppath .= "/".$a->get_hostname();
2236 if (!is_dir($temppath))
2239 if (is_dir($temppath) AND is_writable($temppath)) {
2240 set_config("system", "temppath", $temppath);
2248 function set_template_engine(&$a, $engine = 'internal') {
2249 /// @note This function is no longer necessary, but keep it as a wrapper to the class method
2250 /// to avoid breaking themes again unnecessarily
2252 $a->set_template_engine($engine);
2255 if(!function_exists('exif_imagetype')) {
2256 function exif_imagetype($file) {
2257 $size = getimagesize($file);
2262 function validate_include(&$file) {
2265 $file = realpath($file);
2267 if (strpos($file, getcwd()) !== 0)
2270 $file = str_replace(getcwd()."/", "", $file, $count);
2274 if ($orig_file !== $file)
2278 if (strpos($file, "include/") === 0)
2281 if (strpos($file, "addon/") === 0)
2290 function current_load() {
2291 if (!function_exists('sys_getloadavg'))
2294 $load_arr = sys_getloadavg();
2296 if (!is_array($load_arr))
2299 return max($load_arr[0], $load_arr[1]);
2303 * @brief get c-style args
2308 return get_app()->argc;
2312 * @brief Returns the value of a argv key
2314 * @param int $x argv key
2315 * @return string Value of the argv key
2318 if(array_key_exists($x,get_app()->argv))
2319 return get_app()->argv[$x];
2325 * @brief Get the data which is needed for infinite scroll
2327 * For invinite scroll we need the page number of the actual page
2328 * and the the URI where the content of the next page comes from.
2329 * This data is needed for the js part in main.js.
2330 * Note: infinite scroll does only work for the network page (module)
2332 * @param string $module The name of the module (e.g. "network")
2333 * @return array Of infinite scroll data
2334 * 'pageno' => $pageno The number of the actual page
2335 * 'reload_uri' => $reload_uri The URI of the content we have to load
2337 function infinite_scroll_data($module) {
2339 if (get_pconfig(local_user(),'system','infinite_scroll')
2340 AND ($module == "network") AND ($_GET["mode"] != "minimal")) {
2342 // get the page number
2343 if (is_string($_GET["page"]))
2344 $pageno = $_GET["page"];
2350 // try to get the uri from which we load the content
2351 foreach ($_GET AS $param => $value)
2352 if (($param != "page") AND ($param != "q"))
2353 $reload_uri .= "&".$param."=".urlencode($value);
2355 if (($a->page_offset != "") AND !strstr($reload_uri, "&offset="))
2356 $reload_uri .= "&offset=".urlencode($a->page_offset);
2358 $arr = array("pageno" => $pageno, "reload_uri" => $reload_uri);