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', 1200 );
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_SYSTEM', 10);
397 define('PRIORITY_HIGH', 20);
398 define('PRIORITY_MEDIUM', 30);
399 define('PRIORITY_LOW', 40);
403 // Normally this constant is defined - but not if "pcntl" isn't installed
404 if (!defined("SIGTERM"))
405 define("SIGTERM", 15);
409 * Reverse the effect of magic_quotes_gpc if it is enabled.
410 * Please disable magic_quotes_gpc so we don't have to do this.
411 * See http://php.net/manual/en/security.magicquotes.disabling.php
417 error_reporting(E_ERROR | E_WARNING | E_PARSE);
421 // This has to be quite large to deal with embedded private photos
422 ini_set('pcre.backtrack_limit', 500000);
425 if (get_magic_quotes_gpc()) {
426 $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
427 while (list($key, $val) = each($process)) {
428 foreach ($val as $k => $v) {
429 unset($process[$key][$k]);
431 $process[$key][stripslashes($k)] = $v;
432 $process[] = &$process[$key][stripslashes($k)];
434 $process[$key][stripslashes($k)] = stripslashes($v);
447 * @brief Our main application structure for the life of this page.
449 * Primarily deals with the URL that got us here
450 * and tries to make some sense of it, and
451 * stores our page contents and config storage
452 * and anything else that might need to be passed around
453 * before we spit the page out.
458 public $module_loaded = false;
459 public $query_string;
468 public $page_contact;
470 public $data = array();
471 public $error = false;
481 public $interactive = true;
483 public $apps = array();
485 public $is_mobile = false;
486 public $is_tablet = false;
487 public $is_friendica_app;
488 public $performance = array();
489 public $callstack = array();
490 public $theme_info = array();
491 public $backend = true;
498 // Allow themes to control internal parameters
499 // by changing App values in theme.php
501 public $sourcename = '';
502 public $videowidth = 425;
503 public $videoheight = 350;
504 public $force_max_items = 0;
505 public $theme_thread_allow = true;
506 public $theme_events_in_profile = true;
509 * @brief An array for all theme-controllable parameters
511 * Mostly unimplemented yet. Only options 'template_engine' and
514 public $theme = array(
517 'videoheight' => 350,
518 'force_max_items' => 0,
519 'thread_allow' => true,
521 'template_engine' => 'smarty3',
525 * @brief An array of registered template engines ('name'=>'class name')
527 public $template_engines = array();
529 * @brief An array of instanced template engines ('name'=>'instance')
531 public $template_engine_instance = array();
535 private $ldelim = array(
539 private $rdelim = array(
550 private $curl_content_type;
551 private $curl_headers;
553 private $cached_profile_image;
554 private $cached_profile_picdate;
559 * @brief App constructor.
561 function __construct() {
563 global $default_timezone;
567 if (file_exists(".htpreconfig.php"))
568 @include(".htpreconfig.php");
570 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
572 date_default_timezone_set($this->timezone);
574 $this->performance["start"] = microtime(true);
575 $this->performance["database"] = 0;
576 $this->performance["database_write"] = 0;
577 $this->performance["network"] = 0;
578 $this->performance["file"] = 0;
579 $this->performance["rendering"] = 0;
580 $this->performance["parser"] = 0;
581 $this->performance["marktime"] = 0;
582 $this->performance["markstart"] = microtime(true);
584 $this->callstack["database"] = array();
585 $this->callstack["network"] = array();
586 $this->callstack["file"] = array();
587 $this->callstack["rendering"] = array();
588 $this->callstack["parser"] = array();
590 $this->config = array();
591 $this->page = array();
592 $this->pager= array();
594 $this->query_string = '';
596 $this->process_id = uniqid("log", true);
601 'include' . PATH_SEPARATOR
602 . 'library' . PATH_SEPARATOR
603 . 'library/phpsec' . PATH_SEPARATOR
604 . 'library/langdet' . PATH_SEPARATOR
608 $this->scheme = 'http';
609 if((x($_SERVER,'HTTPS') && $_SERVER['HTTPS']) ||
610 (x($_SERVER['HTTP_FORWARDED']) && preg_match("/proto=https/", $_SERVER['HTTP_FORWARDED'])) ||
611 (x($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
612 (x($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
613 (x($_SERVER['FRONT_END_HTTPS']) && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
614 (x($_SERVER,'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
616 $this->scheme = 'https';
619 if(x($_SERVER,'SERVER_NAME')) {
620 $this->hostname = $_SERVER['SERVER_NAME'];
622 if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
623 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
625 * Figure out if we are running at the top of a domain
626 * or in a sub-directory and adjust accordingly
629 $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
630 if(isset($path) && strlen($path) && ($path != $this->path))
635 $this->hostname = $hostname;
637 if (is_array($_SERVER["argv"]) && $_SERVER["argc"]>1 && substr(end($_SERVER["argv"]), 0, 4)=="http" ) {
638 $this->set_baseurl(array_pop($_SERVER["argv"]) );
642 #set_include_path("include/$this->hostname" . PATH_SEPARATOR . get_include_path());
644 if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,9) === "pagename=") {
645 $this->query_string = substr($_SERVER['QUERY_STRING'],9);
646 // removing trailing / - maybe a nginx problem
647 if (substr($this->query_string, 0, 1) == "/")
648 $this->query_string = substr($this->query_string, 1);
649 } elseif((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
650 $this->query_string = substr($_SERVER['QUERY_STRING'],2);
651 // removing trailing / - maybe a nginx problem
652 if (substr($this->query_string, 0, 1) == "/")
653 $this->query_string = substr($this->query_string, 1);
656 if (x($_GET,'pagename'))
657 $this->cmd = trim($_GET['pagename'],'/\\');
658 elseif (x($_GET,'q'))
659 $this->cmd = trim($_GET['q'],'/\\');
663 $this->query_string = str_replace($this->cmd."&",$this->cmd."?", $this->query_string);
666 // unix style "homedir"
668 if(substr($this->cmd,0,1) === '~')
669 $this->cmd = 'profile/' . substr($this->cmd,1);
671 // Diaspora style profile url
673 if(substr($this->cmd,0,2) === 'u/')
674 $this->cmd = 'profile/' . substr($this->cmd,2);
679 * Break the URL path into C style argc/argv style arguments for our
680 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
681 * will be 3 (integer) and $this->argv will contain:
687 * There will always be one argument. If provided a naked domain
688 * URL, $this->argv[0] is set to "home".
692 $this->argv = explode('/',$this->cmd);
693 $this->argc = count($this->argv);
694 if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
695 $this->module = str_replace(".", "_", $this->argv[0]);
696 $this->module = str_replace("-", "_", $this->module);
700 $this->argv = array('home');
701 $this->module = 'home';
705 * See if there is any page number information, and initialise
709 $this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
710 $this->pager['itemspage'] = 50;
711 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
712 if($this->pager['start'] < 0)
713 $this->pager['start'] = 0;
714 $this->pager['total'] = 0;
717 * Detect mobile devices
720 $mobile_detect = new Mobile_Detect();
721 $this->is_mobile = $mobile_detect->isMobile();
722 $this->is_tablet = $mobile_detect->isTablet();
725 $this->is_friendica_app = ($_SERVER['HTTP_USER_AGENT'] == "Apache-HttpClient/UNAVAILABLE (java 1.4)");
728 * register template engines
730 $dc = get_declared_classes();
731 foreach ($dc as $k) {
732 if (in_array("ITemplateEngine", class_implements($k))){
733 $this->register_template_engine($k);
741 function get_basepath() {
743 $basepath = get_config("system", "basepath");
746 $basepath = dirname(__FILE__);
749 $basepath = $_SERVER["DOCUMENT_ROOT"];
752 $basepath = $_SERVER["PWD"];
757 function get_scheme() {
758 return($this->scheme);
761 function get_baseurl($ssl = false) {
763 // Is the function called statically?
764 if (!is_object($this))
765 return(self::$a->get_baseurl($ssl));
767 $scheme = $this->scheme;
769 if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
770 if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
773 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
774 // (and also the login link). Anything seen by an outsider will have it turned off.
776 if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
784 if (get_config('config','hostname') != "")
785 $this->hostname = get_config('config','hostname');
787 $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
788 return $this->baseurl;
791 function set_baseurl($url) {
792 $parsed = @parse_url($url);
794 $this->baseurl = $url;
797 $this->scheme = $parsed['scheme'];
799 $hostname = $parsed['host'];
800 if(x($parsed,'port'))
801 $hostname .= ':' . $parsed['port'];
802 if(x($parsed,'path'))
803 $this->path = trim($parsed['path'],'\\/');
805 if (file_exists(".htpreconfig.php"))
806 @include(".htpreconfig.php");
808 if (get_config('config','hostname') != "")
809 $this->hostname = get_config('config','hostname');
811 if (!isset($this->hostname) OR ($this->hostname == ""))
812 $this->hostname = $hostname;
817 function get_hostname() {
818 if (get_config('config','hostname') != "")
819 $this->hostname = get_config('config','hostname');
821 return $this->hostname;
824 function set_hostname($h) {
825 $this->hostname = $h;
828 function set_path($p) {
829 $this->path = trim(trim($p),'/');
832 function get_path() {
836 function set_pager_total($n) {
837 $this->pager['total'] = intval($n);
840 function set_pager_itemspage($n) {
841 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
842 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
845 function set_pager_page($n) {
846 $this->pager['page'] = $n;
847 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
850 function init_pagehead() {
851 $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
853 // If the update is "deactivated" set it to the highest integer number (~24 days)
855 $interval = 2147483647;
857 if($interval < 10000)
860 // compose the page title from the sitename and the
861 // current module called
862 if (!$this->module=='')
864 $this->page['title'] = $this->config['sitename'].' ('.$this->module.')';
866 $this->page['title'] = $this->config['sitename'];
869 /* put the head template at the beginning of page['htmlhead']
870 * since the code added by the modules frequently depends on it
873 if(!isset($this->page['htmlhead']))
874 $this->page['htmlhead'] = '';
876 // If we're using Smarty, then doing replace_macros() will replace
877 // any unrecognized variables with a blank string. Since we delay
878 // replacing $stylesheet until later, we need to replace it now
879 // with another variable name
880 if($this->theme['template_engine'] === 'smarty3')
881 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
883 $stylesheet = '$stylesheet';
885 $shortcut_icon = get_config("system", "shortcut_icon");
886 if ($shortcut_icon == "")
887 $shortcut_icon = "images/friendica-32.png";
889 $touch_icon = get_config("system", "touch_icon");
890 if ($touch_icon == "")
891 $touch_icon = "images/friendica-128.png";
893 // get data wich is needed for infinite scroll on the network page
894 $invinite_scroll = infinite_scroll_data($this->module);
896 $tpl = get_markup_template('head.tpl');
897 $this->page['htmlhead'] = replace_macros($tpl,array(
898 '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
899 '$local_user' => local_user(),
900 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
901 '$delitem' => t('Delete this item?'),
902 '$comment' => t('Comment'),
903 '$showmore' => t('show more'),
904 '$showfewer' => t('show fewer'),
905 '$update_interval' => $interval,
906 '$shortcut_icon' => $shortcut_icon,
907 '$touch_icon' => $touch_icon,
908 '$stylesheet' => $stylesheet,
909 '$infinite_scroll' => $invinite_scroll,
910 )) . $this->page['htmlhead'];
913 function init_page_end() {
914 if(!isset($this->page['end']))
915 $this->page['end'] = '';
916 $tpl = get_markup_template('end.tpl');
917 $this->page['end'] = replace_macros($tpl,array(
918 '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
919 )) . $this->page['end'];
922 function set_curl_code($code) {
923 $this->curl_code = $code;
926 function get_curl_code() {
927 return $this->curl_code;
930 function set_curl_content_type($content_type) {
931 $this->curl_content_type = $content_type;
934 function get_curl_content_type() {
935 return $this->curl_content_type;
938 function set_curl_headers($headers) {
939 $this->curl_headers = $headers;
942 function get_curl_headers() {
943 return $this->curl_headers;
946 function get_cached_avatar_image($avatar_image){
947 return $avatar_image;
949 // The following code is deactivated. It doesn't seem to make any sense and it slows down the system.
951 if($this->cached_profile_image[$avatar_image])
952 return $this->cached_profile_image[$avatar_image];
954 $path_parts = explode("/",$avatar_image);
955 $common_filename = $path_parts[count($path_parts)-1];
957 if($this->cached_profile_picdate[$common_filename]){
958 $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
960 $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like '%%/%s'",
962 if(! dbm::is_result($r)){
963 $this->cached_profile_image[$avatar_image] = $avatar_image;
965 $this->cached_profile_picdate[$common_filename] = "?rev=".urlencode($r[0]['picdate']);
966 $this->cached_profile_image[$avatar_image] = $avatar_image.$this->cached_profile_picdate[$common_filename];
969 return $this->cached_profile_image[$avatar_image];
975 * @brief Removes the baseurl from an url. This avoids some mixed content problems.
979 * @return string The cleaned url
981 function remove_baseurl($url){
983 // Is the function called statically?
984 if (!is_object($this))
985 return(self::$a->remove_baseurl($url));
987 $url = normalise_link($url);
988 $base = normalise_link($this->get_baseurl());
989 $url = str_replace($base."/", "", $url);
994 * @brief Register template engine class
996 * If $name is "", is used class static property $class::$name
998 * @param string $class
999 * @param string $name
1001 function register_template_engine($class, $name = '') {
1003 $v = get_class_vars( $class );
1004 if(x($v,"name")) $name = $v['name'];
1007 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
1010 $this->template_engines[$name] = $class;
1014 * @brief Return template engine instance.
1016 * If $name is not defined, return engine defined by theme,
1019 * @param strin $name Template engine name
1020 * @return object Template Engine instance
1022 function template_engine($name = ''){
1024 $template_engine = $name;
1026 $template_engine = 'smarty3';
1027 if (x($this->theme, 'template_engine')) {
1028 $template_engine = $this->theme['template_engine'];
1032 if (isset($this->template_engines[$template_engine])){
1033 if(isset($this->template_engine_instance[$template_engine])){
1034 return $this->template_engine_instance[$template_engine];
1036 $class = $this->template_engines[$template_engine];
1038 $this->template_engine_instance[$template_engine] = $obj;
1043 echo "template engine <tt>$template_engine</tt> is not registered!\n"; killme();
1047 * @brief Returns the active template engine.
1051 function get_template_engine() {
1052 return $this->theme['template_engine'];
1055 function set_template_engine($engine = 'smarty3') {
1056 $this->theme['template_engine'] = $engine;
1058 $this->theme['template_engine'] = 'smarty3';
1062 if(is_writable('view/smarty3/'))
1063 $this->theme['template_engine'] = 'smarty3';
1071 function get_template_ldelim($engine = 'smarty3') {
1072 return $this->ldelim[$engine];
1075 function get_template_rdelim($engine = 'smarty3') {
1076 return $this->rdelim[$engine];
1079 function save_timestamp($stamp, $value) {
1080 $duration = (float)(microtime(true)-$stamp);
1082 if (!isset($this->performance[$value])) {
1083 // Prevent ugly E_NOTICE
1084 $this->performance[$value] = 0;
1087 $this->performance[$value] += (float)$duration;
1088 $this->performance["marktime"] += (float)$duration;
1090 $callstack = $this->callstack();
1092 if (!isset($this->callstack[$value][$callstack])) {
1093 // Prevent ugly E_NOTICE
1094 $this->callstack[$value][$callstack] = 0;
1097 $this->callstack[$value][$callstack] += (float)$duration;
1102 * @brief Returns a string with a callstack. Can be used for logging.
1106 function callstack() {
1107 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 6);
1109 // We remove the first two items from the list since they contain data that we don't need.
1110 array_shift($trace);
1111 array_shift($trace);
1113 $callstack = array();
1114 foreach ($trace AS $func)
1115 $callstack[] = $func["function"];
1117 return implode(", ", $callstack);
1120 function mark_timestamp($mark) {
1121 //$this->performance["markstart"] -= microtime(true) - $this->performance["marktime"];
1122 $this->performance["markstart"] = microtime(true) - $this->performance["markstart"] - $this->performance["marktime"];
1125 function get_useragent() {
1126 return(FRIENDICA_PLATFORM." '".FRIENDICA_CODENAME."' ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION."; ".$this->get_baseurl());
1129 function is_friendica_app() {
1130 return($this->is_friendica_app);
1134 * @brief Checks if the site is called via a backend process
1136 * This isn't a perfect solution. But we need this check very early.
1137 * So we cannot wait until the modules are loaded.
1139 * @return bool Is it a known backend?
1141 function is_backend() {
1143 $backend[] = "_well_known";
1145 $backend[] = "dfrn_notify";
1146 $backend[] = "fetch";
1147 $backend[] = "hcard";
1148 $backend[] = "hostxrd";
1149 $backend[] = "nodeinfo";
1150 $backend[] = "noscrape";
1152 $backend[] = "poco";
1153 $backend[] = "post";
1154 $backend[] = "proxy";
1155 $backend[] = "pubsub";
1156 $backend[] = "pubsubhubbub";
1157 $backend[] = "receive";
1158 $backend[] = "rsd_xml";
1159 $backend[] = "salmon";
1160 $backend[] = "statistics_json";
1163 if (in_array($this->module, $backend))
1166 return($this->backend);
1170 * @brief Checks if the maximum number of database processes is reached
1172 * @return bool Is the limit reached?
1174 function max_processes_reached() {
1176 // Is the function called statically?
1177 if (!is_object($this))
1178 return(self::$a->max_processes_reached());
1180 if ($this->is_backend()) {
1181 $process = "backend";
1182 $max_processes = get_config('system', 'max_processes_backend');
1183 if (intval($max_processes) == 0)
1186 $process = "frontend";
1187 $max_processes = get_config('system', 'max_processes_frontend');
1188 if (intval($max_processes) == 0)
1189 $max_processes = 20;
1192 $processlist = dbm::processlist();
1193 if ($processlist["list"] != "") {
1194 logger("Processcheck: Processes: ".$processlist["amount"]." - Processlist: ".$processlist["list"], LOGGER_DEBUG);
1196 if ($processlist["amount"] > $max_processes) {
1197 logger("Processcheck: Maximum number of processes for ".$process." tasks (".$max_processes.") reached.", LOGGER_DEBUG);
1205 * @brief Checks if the maximum load is reached
1207 * @return bool Is the load reached?
1209 function maxload_reached() {
1211 // Is the function called statically?
1212 if (!is_object($this))
1213 return(self::$a->maxload_reached());
1215 if ($this->is_backend()) {
1216 $process = "backend";
1217 $maxsysload = intval(get_config('system', 'maxloadavg'));
1218 if ($maxsysload < 1)
1221 $process = "frontend";
1222 $maxsysload = intval(get_config('system','maxloadavg_frontend'));
1223 if ($maxsysload < 1)
1227 $load = current_load();
1229 if (intval($load) > $maxsysload) {
1230 logger('system: load '.$load.' for '.$process.' tasks ('.$maxsysload.') too high.');
1238 * @brief Checks if the process is already running
1240 * @param string $taskname The name of the task that will be used for the name of the lockfile
1241 * @param string $task The path and name of the php script
1242 * @param int $timeout The timeout after which a task should be killed
1244 * @return bool Is the process running?
1246 function is_already_running($taskname, $task = "", $timeout = 540) {
1248 $lockpath = get_lockpath();
1249 if ($lockpath != '') {
1250 $pidfile = new pidfile($lockpath, $taskname);
1251 if ($pidfile->is_already_running()) {
1252 logger("Already running");
1253 if ($pidfile->running_time() > $timeout) {
1255 logger("killed stale process");
1256 // Calling a new instance
1258 proc_run(PRIORITY_MEDIUM, $task);
1266 function proc_run($args) {
1268 // Add the php path if it is a php call
1269 if (count($args) && ($args[0] === 'php' OR is_int($args[0])))
1270 $args[0] = ((x($this->config,'php_path')) && (strlen($this->config['php_path'])) ? $this->config['php_path'] : 'php');
1272 // add baseurl to args. cli scripts can't construct it
1273 $args[] = $this->get_baseurl();
1275 for($x = 0; $x < count($args); $x ++)
1276 $args[$x] = escapeshellarg($args[$x]);
1278 $cmdline = implode($args," ");
1280 if(get_config('system','proc_windows'))
1281 proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
1283 proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
1289 * @brief Retrieve the App structure
1291 * Useful in functions which require it but don't get it passed to them
1293 function get_app() {
1300 * @brief Multi-purpose function to check variable state.
1302 * Usage: x($var) or $x($array, 'key')
1304 * returns false if variable/key is not set
1305 * if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
1306 * e.g. x('') or x(0) returns 0;
1308 * @param string|array $s variable to check
1309 * @param string $k key inside the array to check
1313 function x($s,$k = NULL) {
1315 if((is_array($s)) && (array_key_exists($k,$s))) {
1335 * @brief Called from db initialisation if db is dead.
1337 function system_unavailable() {
1338 include('system_unavailable.php');
1344 function clean_urls() {
1346 // if($a->config['system']['clean_urls'])
1353 $base = $a->get_baseurl();
1360 * @brief Returns the baseurl.
1362 * @see App::get_baseurl()
1368 return $a->get_baseurl();
1372 * @brief Return absolut URL for given $path.
1374 * @param string $path
1378 function absurl($path) {
1379 if(strpos($path,'/') === 0)
1380 return z_path() . $path;
1385 * @brief Function to check if request was an AJAX (xmlhttprequest) request.
1389 function is_ajax() {
1390 return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
1393 function check_db() {
1395 $build = get_config('system','build');
1397 set_config('system','build',DB_UPDATE_VERSION);
1398 $build = DB_UPDATE_VERSION;
1400 if($build != DB_UPDATE_VERSION)
1401 proc_run(PRIORITY_SYSTEM, 'include/dbupdate.php');
1407 * Sets the base url for use in cmdline programs which don't have
1408 * $_SERVER variables
1410 function check_url(&$a) {
1412 $url = get_config('system','url');
1414 // if the url isn't set or the stored url is radically different
1415 // than the currently visited url, store the current value accordingly.
1416 // "Radically different" ignores common variations such as http vs https
1417 // and www.example.com vs example.com.
1418 // We will only change the url to an ip address if there is no existing setting
1421 $url = set_config('system','url',$a->get_baseurl());
1422 if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
1423 $url = set_config('system','url',$a->get_baseurl());
1430 * @brief Automatic database updates
1432 function update_db(&$a) {
1433 $build = get_config('system','build');
1435 $build = set_config('system','build',DB_UPDATE_VERSION);
1437 if($build != DB_UPDATE_VERSION) {
1438 $stored = intval($build);
1439 $current = intval(DB_UPDATE_VERSION);
1440 if($stored < $current) {
1441 load_config('database');
1443 // We're reporting a different version than what is currently installed.
1444 // Run any existing update scripts to bring the database up to current.
1446 // make sure that boot.php and update.php are the same release, we might be
1447 // updating right this very second and the correct version of the update.php
1448 // file may not be here yet. This can happen on a very busy site.
1450 if(DB_UPDATE_VERSION == UPDATE_VERSION) {
1451 // Compare the current structure with the defined structure
1453 $t = get_config('database','dbupdate_'.DB_UPDATE_VERSION);
1457 set_config('database','dbupdate_'.DB_UPDATE_VERSION, time());
1459 // run old update routine (wich could modify the schema and
1460 // conflits with new routine)
1461 for ($x = $stored; $x < NEW_UPDATE_ROUTINE_VERSION; $x++) {
1462 $r = run_update_function($x);
1465 if ($stored < NEW_UPDATE_ROUTINE_VERSION) $stored = NEW_UPDATE_ROUTINE_VERSION;
1468 // run new update routine
1469 // it update the structure in one call
1470 $retval = update_structure(false, true);
1478 set_config('database','dbupdate_'.DB_UPDATE_VERSION, 'success');
1481 // run any left update_nnnn functions in update.php
1482 for($x = $stored; $x < $current; $x ++) {
1483 $r = run_update_function($x);
1493 function run_update_function($x) {
1494 if(function_exists('update_' . $x)) {
1496 // There could be a lot of processes running or about to run.
1497 // We want exactly one process to run the update command.
1498 // So store the fact that we're taking responsibility
1499 // after first checking to see if somebody else already has.
1501 // If the update fails or times-out completely you may need to
1502 // delete the config entry to try again.
1504 $t = get_config('database','update_' . $x);
1507 set_config('database','update_' . $x, time());
1509 // call the specific update
1511 $func = 'update_' . $x;
1515 //send the administrator an e-mail
1518 sprintf(t('Update %s failed. See error logs.'), $x)
1522 set_config('database','update_' . $x, 'success');
1523 set_config('system','build', $x + 1);
1527 set_config('database','update_' . $x, 'success');
1528 set_config('system','build', $x + 1);
1535 * @brief Synchronise plugins:
1537 * $a->config['system']['addon'] contains a comma-separated list of names
1538 * of plugins/addons which are used on this system.
1539 * Go through the database list of already installed addons, and if we have
1540 * an entry, but it isn't in the config list, call the uninstall procedure
1541 * and mark it uninstalled in the database (for now we'll remove it).
1542 * Then go through the config list and if we have a plugin that isn't installed,
1543 * call the install procedure and add it to the database.
1548 function check_plugins(&$a) {
1550 $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
1551 if(dbm::is_result($r))
1554 $installed = array();
1556 $plugins = get_config('system','addon');
1557 $plugins_arr = array();
1560 $plugins_arr = explode(',',str_replace(' ', '',$plugins));
1562 $a->plugins = $plugins_arr;
1564 $installed_arr = array();
1566 if(count($installed)) {
1567 foreach($installed as $i) {
1568 if(! in_array($i['name'],$plugins_arr)) {
1569 uninstall_plugin($i['name']);
1572 $installed_arr[] = $i['name'];
1577 if(count($plugins_arr)) {
1578 foreach($plugins_arr as $p) {
1579 if(! in_array($p,$installed_arr)) {
1591 function get_guid($size=16, $prefix = "") {
1593 if ($prefix == "") {
1595 $prefix = hash("crc32", $a->get_hostname());
1598 while (strlen($prefix) < ($size - 13))
1599 $prefix .= mt_rand();
1602 $prefix = substr($prefix, 0, $size - 22);
1603 return(str_replace(".", "", uniqid($prefix, true)));
1605 $prefix = substr($prefix, 0, max($size - 13, 0));
1606 return(uniqid($prefix));
1611 * @brief Wrapper for adding a login box.
1613 * @param bool $register
1614 * If $register == true provide a registration link.
1615 * This will most always depend on the value of $a->config['register_policy'].
1616 * @param bool $hiddens
1619 * Returns the complete html for inserting into the page
1621 * @hooks 'login_hook'
1624 function login($register = false, $hiddens=false) {
1630 'title' => t('Create a New Account'),
1631 'desc' => t('Register')
1635 $noid = get_config('system','no_openid');
1637 $dest_url = $a->query_string;
1640 $tpl = get_markup_template("logout.tpl");
1643 $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
1644 '$baseurl' => $a->get_baseurl(true)
1647 $tpl = get_markup_template("login.tpl");
1648 $_SESSION['return_url'] = $a->query_string;
1649 $a->module = 'login';
1652 $o .= replace_macros($tpl, array(
1654 '$dest_url' => $dest_url,
1655 '$logout' => t('Logout'),
1656 '$login' => t('Login'),
1658 '$lname' => array('username', t('Nickname or Email: ') , '', ''),
1659 '$lpassword' => array('password', t('Password: '), '', ''),
1660 '$lremember' => array('remember', t('Remember me'), 0, ''),
1662 '$openid' => !$noid,
1663 '$lopenid' => array('openid_url', t('Or login using OpenID: '),'',''),
1665 '$hiddens' => $hiddens,
1667 '$register' => $reg,
1669 '$lostpass' => t('Forgot your password?'),
1670 '$lostlink' => t('Password Reset'),
1672 '$tostitle' => t('Website Terms of Service'),
1673 '$toslink' => t('terms of service'),
1675 '$privacytitle' => t('Website Privacy Policy'),
1676 '$privacylink' => t('privacy policy'),
1680 call_hooks('login_hook',$o);
1686 * @brief Used to end the current process, after saving session state.
1689 session_write_close();
1694 * @brief Redirect to another URL and terminate this process.
1696 function goaway($s) {
1697 if (!strstr(normalise_link($s), "http://"))
1698 $s = App::get_baseurl()."/".$s;
1700 header("Location: $s");
1706 * @brief Returns the user id of locally logged in user or false.
1708 * @return int|bool user id or false
1710 function local_user() {
1711 if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
1712 return intval($_SESSION['uid']);
1717 * @brief Returns contact id of authenticated site visitor or false
1719 * @return int|bool visitor_id or false
1721 function remote_user() {
1722 if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
1723 return intval($_SESSION['visitor_id']);
1728 * @brief Show an error message to user.
1730 * This function save text in session, to be shown to the user at next page load
1732 * @param string $s - Text of notice
1734 function notice($s) {
1736 if(! x($_SESSION,'sysmsg')) $_SESSION['sysmsg'] = array();
1738 $_SESSION['sysmsg'][] = $s;
1742 * @brief Show an info message to user.
1744 * This function save text in session, to be shown to the user at next page load
1746 * @param string $s - Text of notice
1751 if (local_user() AND get_pconfig(local_user(),'system','ignore_info'))
1754 if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
1756 $_SESSION['sysmsg_info'][] = $s;
1761 * @brief Wrapper around config to limit the text length of an incoming message
1765 function get_max_import_size() {
1767 return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
1771 * @brief Wrap calls to proc_close(proc_open()) and call hook
1772 * so plugins can take part in process :)
1774 * @param (string|integer) $cmd program to run or priority
1776 * next args are passed as $cmd command line
1777 * e.g.: proc_run("ls","-la","/tmp");
1778 * or: proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $drop_id);
1780 * @note $cmd and string args are surrounded with ""
1785 function proc_run($cmd){
1789 $args = func_get_args();
1795 // expand any arrays
1797 foreach($args as $arg) {
1798 if(is_array($arg)) {
1799 foreach($arg as $n) {
1808 $arr = array('args' => $args, 'run_cmd' => true);
1810 call_hooks("proc_run", $arr);
1811 if (!$arr['run_cmd'] OR !count($args))
1814 if (!get_config("system", "worker") OR
1815 (($args[0] != 'php') AND !is_int($args[0]))) {
1816 $a->proc_run($args);
1820 if (is_int($args[0]))
1821 $priority = $args[0];
1823 $priority = PRIORITY_MEDIUM;
1828 $parameters = json_encode($argv);
1829 $found = q("SELECT `id` FROM `workerqueue` WHERE `parameter` = '%s'",
1830 dbesc($parameters));
1833 q("INSERT INTO `workerqueue` (`parameter`, `created`, `priority`)
1834 VALUES ('%s', '%s', %d)",
1836 dbesc(datetime_convert()),
1839 // Should we quit and wait for the poller to be called as a cronjob?
1840 if (get_config("system", "worker_dont_fork"))
1843 // Checking number of workers
1844 $workers = q("SELECT COUNT(*) AS `workers` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
1846 // Get number of allowed number of worker threads
1847 $queues = intval(get_config("system", "worker_queues"));
1852 // If there are already enough workers running, don't fork another one
1853 if ($workers[0]["workers"] >= $queues)
1856 // Now call the poller to execute the jobs that we just added to the queue
1857 $args = array("php", "include/poller.php", "no_cron");
1859 $a->proc_run($args);
1862 function current_theme(){
1863 $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
1869 // Find the theme that belongs to the user whose stuff we are looking at
1871 if($a->profile_uid && ($a->profile_uid != local_user())) {
1872 $r = q("select theme from user where uid = %d limit 1",
1873 intval($a->profile_uid)
1875 if(dbm::is_result($r))
1876 $page_theme = $r[0]['theme'];
1879 // Allow folks to over-rule user themes and always use their own on their own site.
1880 // This works only if the user is on the same server
1882 if($page_theme && local_user() && (local_user() != $a->profile_uid)) {
1883 if(get_pconfig(local_user(),'system','always_my_theme'))
1887 // $mobile_detect = new Mobile_Detect();
1888 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1889 $is_mobile = $a->is_mobile || $a->is_tablet;
1891 $standard_system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1892 $standard_theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $standard_system_theme);
1895 if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
1896 $system_theme = $standard_system_theme;
1897 $theme_name = $standard_theme_name;
1900 $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : $standard_system_theme);
1901 $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
1903 if($theme_name === '---') {
1904 // user has selected to have the mobile theme be the same as the normal one
1905 $system_theme = $standard_system_theme;
1906 $theme_name = $standard_theme_name;
1909 $theme_name = $page_theme;
1914 $system_theme = $standard_system_theme;
1915 $theme_name = $standard_theme_name;
1918 $theme_name = $page_theme;
1922 (file_exists('view/theme/' . $theme_name . '/style.css') ||
1923 file_exists('view/theme/' . $theme_name . '/style.php')))
1924 return($theme_name);
1926 foreach($app_base_themes as $t) {
1927 if(file_exists('view/theme/' . $t . '/style.css')||
1928 file_exists('view/theme/' . $t . '/style.php'))
1932 $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
1933 if(count($fallback))
1934 return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
1939 * @brief Return full URL to theme which is currently in effect.
1941 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1945 function current_theme_url() {
1948 $t = current_theme();
1950 $opts = (($a->profile_uid) ? '?f=&puid=' . $a->profile_uid : '');
1951 if (file_exists('view/theme/' . $t . '/style.php'))
1952 return('view/theme/'.$t.'/style.pcss'.$opts);
1954 return('view/theme/'.$t.'/style.css');
1957 function feed_birthday($uid,$tz) {
1961 * Determine the next birthday, but only if the birthday is published
1962 * in the default profile. We _could_ also look for a private profile that the
1963 * recipient can see, but somebody could get mad at us if they start getting
1964 * public birthday greetings when they haven't made this info public.
1966 * Assuming we are able to publish this info, we are then going to convert
1967 * the start time from the owner's timezone to UTC.
1969 * This will potentially solve the problem found with some social networks
1970 * where birthdays are converted to the viewer's timezone and salutations from
1971 * elsewhere in the world show up on the wrong day. We will convert it to the
1972 * viewer's timezone also, but first we are going to convert it from the birthday
1973 * person's timezone to GMT - so the viewer may find the birthday starting at
1974 * 6:00PM the day before, but that will correspond to midnight to the birthday person.
1984 $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
1988 if(dbm::is_result($p)) {
1989 $tmp_dob = substr($p[0]['dob'],5);
1990 if(intval($tmp_dob)) {
1991 $y = datetime_convert($tz,$tz,'now','Y');
1992 $bd = $y . '-' . $tmp_dob . ' 00:00';
1993 $t_dob = strtotime($bd);
1994 $now = strtotime(datetime_convert($tz,$tz,'now'));
1996 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
1997 $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
2005 * @brief Check if current user has admin role.
2007 * @return bool true if user is an admin
2009 function is_site_admin() {
2012 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
2014 //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
2015 if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && in_array($a->user['email'], $adminlist))
2021 * @brief Returns querystring as string from a mapped array.
2023 * @param array $params mapped array with query parameters
2024 * @param string $name of parameter, default null
2028 function build_querystring($params, $name=null) {
2030 foreach($params as $key=>$val) {
2031 if(is_array($val)) {
2033 $ret .= build_querystring($val, $key);
2035 $ret .= build_querystring($val, $name."[$key]");
2038 $val = urlencode($val);
2040 $ret.=$name."[$key]"."=$val&";
2042 $ret.= "$key=$val&";
2049 function explode_querystring($query) {
2050 $arg_st = strpos($query, '?');
2051 if($arg_st !== false) {
2052 $base = substr($query, 0, $arg_st);
2059 $args = explode('&', substr($query, $arg_st));
2060 foreach($args as $k=>$arg) {
2064 $args = array_values($args);
2069 $args = array_values($args);
2079 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
2081 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
2083 function curPageURL() {
2085 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
2087 if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
2088 $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
2090 $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
2095 function random_digits($digits) {
2097 for($i = 0; $i < $digits; $i++) {
2103 function get_server() {
2104 $server = get_config("system", "directory");
2107 $server = "http://dir.friendi.ca";
2112 function get_cachefile($file, $writemode = true) {
2113 $cache = get_itemcachepath();
2115 if ((! $cache) || (! is_dir($cache)))
2118 $subfolder = $cache."/".substr($file, 0, 2);
2120 $cachepath = $subfolder."/".$file;
2123 if (!is_dir($subfolder)) {
2125 chmod($subfolder, 0777);
2132 function clear_cache($basepath = "", $path = "") {
2134 $basepath = get_itemcachepath();
2138 if (($path == "") OR (!is_dir($path)))
2141 if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
2144 $cachetime = (int)get_config('system','itemcache_duration');
2145 if ($cachetime == 0)
2148 if (is_writable($path)){
2149 if ($dh = opendir($path)) {
2150 while (($file = readdir($dh)) !== false) {
2151 $fullpath = $path."/".$file;
2152 if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
2153 clear_cache($basepath, $fullpath);
2154 if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
2162 function get_itemcachepath() {
2163 // Checking, if the cache is deactivated
2164 $cachetime = (int)get_config('system','itemcache_duration');
2168 $itemcache = get_config('system','itemcache');
2169 if (($itemcache != "") AND is_dir($itemcache) AND is_writable($itemcache))
2172 $temppath = get_temppath();
2174 if ($temppath != "") {
2175 $itemcache = $temppath."/itemcache";
2176 if(!file_exists($itemcache) && !is_dir($itemcache)) {
2180 if (is_dir($itemcache) AND is_writable($itemcache)) {
2181 set_config("system", "itemcache", $itemcache);
2188 function get_lockpath() {
2189 $lockpath = get_config('system','lockpath');
2190 if (($lockpath != "") AND is_dir($lockpath) AND is_writable($lockpath))
2193 $temppath = get_temppath();
2195 if ($temppath != "") {
2196 $lockpath = $temppath."/lock";
2198 if (!is_dir($lockpath))
2200 elseif (!is_writable($lockpath))
2201 $lockpath = $temppath;
2203 if (is_dir($lockpath) AND is_writable($lockpath)) {
2204 set_config("system", "lockpath", $lockpath);
2211 function get_temppath() {
2214 $temppath = get_config("system","temppath");
2215 if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath))
2218 $temppath = sys_get_temp_dir();
2219 if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath)) {
2220 $temppath .= "/".$a->get_hostname();
2221 if (!is_dir($temppath))
2224 if (is_dir($temppath) AND is_writable($temppath)) {
2225 set_config("system", "temppath", $temppath);
2233 function set_template_engine(&$a, $engine = 'internal') {
2234 /// @note This function is no longer necessary, but keep it as a wrapper to the class method
2235 /// to avoid breaking themes again unnecessarily
2237 $a->set_template_engine($engine);
2240 if(!function_exists('exif_imagetype')) {
2241 function exif_imagetype($file) {
2242 $size = getimagesize($file);
2247 function validate_include(&$file) {
2250 $file = realpath($file);
2252 if (strpos($file, getcwd()) !== 0)
2255 $file = str_replace(getcwd()."/", "", $file, $count);
2259 if ($orig_file !== $file)
2263 if (strpos($file, "include/") === 0)
2266 if (strpos($file, "addon/") === 0)
2275 function current_load() {
2276 if (!function_exists('sys_getloadavg'))
2279 $load_arr = sys_getloadavg();
2281 if (!is_array($load_arr))
2284 return max($load_arr[0], $load_arr[1]);
2288 * @brief get c-style args
2293 return get_app()->argc;
2297 * @brief Returns the value of a argv key
2299 * @param int $x argv key
2300 * @return string Value of the argv key
2303 if(array_key_exists($x,get_app()->argv))
2304 return get_app()->argv[$x];
2310 * @brief Get the data which is needed for infinite scroll
2312 * For invinite scroll we need the page number of the actual page
2313 * and the the URI where the content of the next page comes from.
2314 * This data is needed for the js part in main.js.
2315 * Note: infinite scroll does only work for the network page (module)
2317 * @param string $module The name of the module (e.g. "network")
2318 * @return array Of infinite scroll data
2319 * 'pageno' => $pageno The number of the actual page
2320 * 'reload_uri' => $reload_uri The URI of the content we have to load
2322 function infinite_scroll_data($module) {
2324 if (get_pconfig(local_user(),'system','infinite_scroll')
2325 AND ($module == "network") AND ($_GET["mode"] != "minimal")) {
2327 // get the page number
2328 if (is_string($_GET["page"]))
2329 $pageno = $_GET["page"];
2335 // try to get the uri from which we load the content
2336 foreach ($_GET AS $param => $value)
2337 if (($param != "page") AND ($param != "q"))
2338 $reload_uri .= "&".$param."=".urlencode($value);
2340 if (($a->page_offset != "") AND !strstr($reload_uri, "&offset="))
2341 $reload_uri .= "&offset=".urlencode($a->page_offset);
2343 $arr = array("pageno" => $pageno, "reload_uri" => $reload_uri);