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_HIGH', 1);
396 define('PRIORITY_MEDIUM', 2);
397 define('PRIORITY_LOW', 3);
401 // Normally this constant is defined - but not if "pcntl" isn't installed
402 if (!defined("SIGTERM"))
403 define("SIGTERM", 15);
407 * Reverse the effect of magic_quotes_gpc if it is enabled.
408 * Please disable magic_quotes_gpc so we don't have to do this.
409 * See http://php.net/manual/en/security.magicquotes.disabling.php
415 error_reporting(E_ERROR | E_WARNING | E_PARSE);
419 // This has to be quite large to deal with embedded private photos
420 ini_set('pcre.backtrack_limit', 500000);
423 if (get_magic_quotes_gpc()) {
424 $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
425 while (list($key, $val) = each($process)) {
426 foreach ($val as $k => $v) {
427 unset($process[$key][$k]);
429 $process[$key][stripslashes($k)] = $v;
430 $process[] = &$process[$key][stripslashes($k)];
432 $process[$key][stripslashes($k)] = stripslashes($v);
445 * @brief Our main application structure for the life of this page.
447 * Primarily deals with the URL that got us here
448 * and tries to make some sense of it, and
449 * stores our page contents and config storage
450 * and anything else that might need to be passed around
451 * before we spit the page out.
456 public $module_loaded = false;
457 public $query_string;
466 public $page_contact;
468 public $data = array();
469 public $error = false;
479 public $interactive = true;
481 public $apps = array();
483 public $is_mobile = false;
484 public $is_tablet = false;
485 public $is_friendica_app;
486 public $performance = array();
487 public $callstack = array();
488 public $theme_info = array();
489 public $backend = true;
496 // Allow themes to control internal parameters
497 // by changing App values in theme.php
499 public $sourcename = '';
500 public $videowidth = 425;
501 public $videoheight = 350;
502 public $force_max_items = 0;
503 public $theme_thread_allow = true;
504 public $theme_events_in_profile = true;
507 * @brief An array for all theme-controllable parameters
509 * Mostly unimplemented yet. Only options 'template_engine' and
512 public $theme = array(
515 'videoheight' => 350,
516 'force_max_items' => 0,
517 'thread_allow' => true,
519 'template_engine' => 'smarty3',
523 * @brief An array of registered template engines ('name'=>'class name')
525 public $template_engines = array();
527 * @brief An array of instanced template engines ('name'=>'instance')
529 public $template_engine_instance = array();
533 private $ldelim = array(
537 private $rdelim = array(
548 private $curl_content_type;
549 private $curl_headers;
551 private $cached_profile_image;
552 private $cached_profile_picdate;
557 * @brief App constructor.
559 function __construct() {
561 global $default_timezone;
565 if (file_exists(".htpreconfig.php"))
566 @include(".htpreconfig.php");
568 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
570 date_default_timezone_set($this->timezone);
572 $this->performance["start"] = microtime(true);
573 $this->performance["database"] = 0;
574 $this->performance["database_write"] = 0;
575 $this->performance["network"] = 0;
576 $this->performance["file"] = 0;
577 $this->performance["rendering"] = 0;
578 $this->performance["parser"] = 0;
579 $this->performance["marktime"] = 0;
580 $this->performance["markstart"] = microtime(true);
582 $this->callstack["database"] = array();
583 $this->callstack["network"] = array();
584 $this->callstack["file"] = array();
585 $this->callstack["rendering"] = array();
586 $this->callstack["parser"] = array();
588 $this->config = array();
589 $this->page = array();
590 $this->pager= array();
592 $this->query_string = '';
594 $this->process_id = uniqid("log", true);
599 'include' . PATH_SEPARATOR
600 . 'library' . PATH_SEPARATOR
601 . 'library/phpsec' . PATH_SEPARATOR
602 . 'library/langdet' . PATH_SEPARATOR
606 $this->scheme = 'http';
607 if((x($_SERVER,'HTTPS') && $_SERVER['HTTPS']) ||
608 (x($_SERVER['HTTP_FORWARDED']) && preg_match("/proto=https/", $_SERVER['HTTP_FORWARDED'])) ||
609 (x($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
610 (x($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
611 (x($_SERVER['FRONT_END_HTTPS']) && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
612 (x($_SERVER,'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
614 $this->scheme = 'https';
617 if(x($_SERVER,'SERVER_NAME')) {
618 $this->hostname = $_SERVER['SERVER_NAME'];
620 if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
621 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
623 * Figure out if we are running at the top of a domain
624 * or in a sub-directory and adjust accordingly
627 $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
628 if(isset($path) && strlen($path) && ($path != $this->path))
633 $this->hostname = $hostname;
635 if (is_array($_SERVER["argv"]) && $_SERVER["argc"]>1 && substr(end($_SERVER["argv"]), 0, 4)=="http" ) {
636 $this->set_baseurl(array_pop($_SERVER["argv"]) );
640 #set_include_path("include/$this->hostname" . PATH_SEPARATOR . get_include_path());
642 if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,9) === "pagename=") {
643 $this->query_string = substr($_SERVER['QUERY_STRING'],9);
644 // removing trailing / - maybe a nginx problem
645 if (substr($this->query_string, 0, 1) == "/")
646 $this->query_string = substr($this->query_string, 1);
647 } elseif((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
648 $this->query_string = substr($_SERVER['QUERY_STRING'],2);
649 // removing trailing / - maybe a nginx problem
650 if (substr($this->query_string, 0, 1) == "/")
651 $this->query_string = substr($this->query_string, 1);
654 if (x($_GET,'pagename'))
655 $this->cmd = trim($_GET['pagename'],'/\\');
656 elseif (x($_GET,'q'))
657 $this->cmd = trim($_GET['q'],'/\\');
661 $this->query_string = str_replace($this->cmd."&",$this->cmd."?", $this->query_string);
664 // unix style "homedir"
666 if(substr($this->cmd,0,1) === '~')
667 $this->cmd = 'profile/' . substr($this->cmd,1);
669 // Diaspora style profile url
671 if(substr($this->cmd,0,2) === 'u/')
672 $this->cmd = 'profile/' . substr($this->cmd,2);
677 * Break the URL path into C style argc/argv style arguments for our
678 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
679 * will be 3 (integer) and $this->argv will contain:
685 * There will always be one argument. If provided a naked domain
686 * URL, $this->argv[0] is set to "home".
690 $this->argv = explode('/',$this->cmd);
691 $this->argc = count($this->argv);
692 if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
693 $this->module = str_replace(".", "_", $this->argv[0]);
694 $this->module = str_replace("-", "_", $this->module);
698 $this->argv = array('home');
699 $this->module = 'home';
703 * See if there is any page number information, and initialise
707 $this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
708 $this->pager['itemspage'] = 50;
709 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
710 if($this->pager['start'] < 0)
711 $this->pager['start'] = 0;
712 $this->pager['total'] = 0;
715 * Detect mobile devices
718 $mobile_detect = new Mobile_Detect();
719 $this->is_mobile = $mobile_detect->isMobile();
720 $this->is_tablet = $mobile_detect->isTablet();
723 $this->is_friendica_app = ($_SERVER['HTTP_USER_AGENT'] == "Apache-HttpClient/UNAVAILABLE (java 1.4)");
726 * register template engines
728 $dc = get_declared_classes();
729 foreach ($dc as $k) {
730 if (in_array("ITemplateEngine", class_implements($k))){
731 $this->register_template_engine($k);
739 function get_basepath() {
741 $basepath = get_config("system", "basepath");
744 $basepath = dirname(__FILE__);
747 $basepath = $_SERVER["DOCUMENT_ROOT"];
750 $basepath = $_SERVER["PWD"];
755 function get_scheme() {
756 return($this->scheme);
759 function get_baseurl($ssl = false) {
761 // Is the function called statically?
762 if (!is_object($this))
763 return(self::$a->get_baseurl($ssl));
765 $scheme = $this->scheme;
767 if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
768 if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
771 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
772 // (and also the login link). Anything seen by an outsider will have it turned off.
774 if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
782 if (get_config('config','hostname') != "")
783 $this->hostname = get_config('config','hostname');
785 $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
786 return $this->baseurl;
789 function set_baseurl($url) {
790 $parsed = @parse_url($url);
792 $this->baseurl = $url;
795 $this->scheme = $parsed['scheme'];
797 $hostname = $parsed['host'];
798 if(x($parsed,'port'))
799 $hostname .= ':' . $parsed['port'];
800 if(x($parsed,'path'))
801 $this->path = trim($parsed['path'],'\\/');
803 if (file_exists(".htpreconfig.php"))
804 @include(".htpreconfig.php");
806 if (get_config('config','hostname') != "")
807 $this->hostname = get_config('config','hostname');
809 if (!isset($this->hostname) OR ($this->hostname == ""))
810 $this->hostname = $hostname;
815 function get_hostname() {
816 if (get_config('config','hostname') != "")
817 $this->hostname = get_config('config','hostname');
819 return $this->hostname;
822 function set_hostname($h) {
823 $this->hostname = $h;
826 function set_path($p) {
827 $this->path = trim(trim($p),'/');
830 function get_path() {
834 function set_pager_total($n) {
835 $this->pager['total'] = intval($n);
838 function set_pager_itemspage($n) {
839 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
840 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
843 function set_pager_page($n) {
844 $this->pager['page'] = $n;
845 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
848 function init_pagehead() {
849 $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
851 // If the update is "deactivated" set it to the highest integer number (~24 days)
853 $interval = 2147483647;
855 if($interval < 10000)
858 // compose the page title from the sitename and the
859 // current module called
860 if (!$this->module=='')
862 $this->page['title'] = $this->config['sitename'].' ('.$this->module.')';
864 $this->page['title'] = $this->config['sitename'];
867 /* put the head template at the beginning of page['htmlhead']
868 * since the code added by the modules frequently depends on it
871 if(!isset($this->page['htmlhead']))
872 $this->page['htmlhead'] = '';
874 // If we're using Smarty, then doing replace_macros() will replace
875 // any unrecognized variables with a blank string. Since we delay
876 // replacing $stylesheet until later, we need to replace it now
877 // with another variable name
878 if($this->theme['template_engine'] === 'smarty3')
879 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
881 $stylesheet = '$stylesheet';
883 $shortcut_icon = get_config("system", "shortcut_icon");
884 if ($shortcut_icon == "")
885 $shortcut_icon = "images/friendica-32.png";
887 $touch_icon = get_config("system", "touch_icon");
888 if ($touch_icon == "")
889 $touch_icon = "images/friendica-128.png";
891 // get data wich is needed for infinite scroll on the network page
892 $invinite_scroll = infinite_scroll_data($this->module);
894 $tpl = get_markup_template('head.tpl');
895 $this->page['htmlhead'] = replace_macros($tpl,array(
896 '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
897 '$local_user' => local_user(),
898 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
899 '$delitem' => t('Delete this item?'),
900 '$comment' => t('Comment'),
901 '$showmore' => t('show more'),
902 '$showfewer' => t('show fewer'),
903 '$update_interval' => $interval,
904 '$shortcut_icon' => $shortcut_icon,
905 '$touch_icon' => $touch_icon,
906 '$stylesheet' => $stylesheet,
907 '$infinite_scroll' => $invinite_scroll,
908 )) . $this->page['htmlhead'];
911 function init_page_end() {
912 if(!isset($this->page['end']))
913 $this->page['end'] = '';
914 $tpl = get_markup_template('end.tpl');
915 $this->page['end'] = replace_macros($tpl,array(
916 '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
917 )) . $this->page['end'];
920 function set_curl_code($code) {
921 $this->curl_code = $code;
924 function get_curl_code() {
925 return $this->curl_code;
928 function set_curl_content_type($content_type) {
929 $this->curl_content_type = $content_type;
932 function get_curl_content_type() {
933 return $this->curl_content_type;
936 function set_curl_headers($headers) {
937 $this->curl_headers = $headers;
940 function get_curl_headers() {
941 return $this->curl_headers;
944 function get_cached_avatar_image($avatar_image){
945 return $avatar_image;
947 // The following code is deactivated. It doesn't seem to make any sense and it slows down the system.
949 if($this->cached_profile_image[$avatar_image])
950 return $this->cached_profile_image[$avatar_image];
952 $path_parts = explode("/",$avatar_image);
953 $common_filename = $path_parts[count($path_parts)-1];
955 if($this->cached_profile_picdate[$common_filename]){
956 $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
958 $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like '%%/%s'",
960 if(! dbm::is_result($r)){
961 $this->cached_profile_image[$avatar_image] = $avatar_image;
963 $this->cached_profile_picdate[$common_filename] = "?rev=".urlencode($r[0]['picdate']);
964 $this->cached_profile_image[$avatar_image] = $avatar_image.$this->cached_profile_picdate[$common_filename];
967 return $this->cached_profile_image[$avatar_image];
973 * @brief Removes the baseurl from an url. This avoids some mixed content problems.
977 * @return string The cleaned url
979 function remove_baseurl($url){
981 // Is the function called statically?
982 if (!is_object($this))
983 return(self::$a->remove_baseurl($url));
985 $url = normalise_link($url);
986 $base = normalise_link($this->get_baseurl());
987 $url = str_replace($base."/", "", $url);
992 * @brief Register template engine class
994 * If $name is "", is used class static property $class::$name
996 * @param string $class
997 * @param string $name
999 function register_template_engine($class, $name = '') {
1001 $v = get_class_vars( $class );
1002 if(x($v,"name")) $name = $v['name'];
1005 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
1008 $this->template_engines[$name] = $class;
1012 * @brief Return template engine instance.
1014 * If $name is not defined, return engine defined by theme,
1017 * @param strin $name Template engine name
1018 * @return object Template Engine instance
1020 function template_engine($name = ''){
1022 $template_engine = $name;
1024 $template_engine = 'smarty3';
1025 if (x($this->theme, 'template_engine')) {
1026 $template_engine = $this->theme['template_engine'];
1030 if (isset($this->template_engines[$template_engine])){
1031 if(isset($this->template_engine_instance[$template_engine])){
1032 return $this->template_engine_instance[$template_engine];
1034 $class = $this->template_engines[$template_engine];
1036 $this->template_engine_instance[$template_engine] = $obj;
1041 echo "template engine <tt>$template_engine</tt> is not registered!\n"; killme();
1045 * @brief Returns the active template engine.
1049 function get_template_engine() {
1050 return $this->theme['template_engine'];
1053 function set_template_engine($engine = 'smarty3') {
1054 $this->theme['template_engine'] = $engine;
1056 $this->theme['template_engine'] = 'smarty3';
1060 if(is_writable('view/smarty3/'))
1061 $this->theme['template_engine'] = 'smarty3';
1069 function get_template_ldelim($engine = 'smarty3') {
1070 return $this->ldelim[$engine];
1073 function get_template_rdelim($engine = 'smarty3') {
1074 return $this->rdelim[$engine];
1077 function save_timestamp($stamp, $value) {
1078 $duration = (float)(microtime(true)-$stamp);
1080 if (!isset($this->performance[$value])) {
1081 // Prevent ugly E_NOTICE
1082 $this->performance[$value] = 0;
1085 $this->performance[$value] += (float)$duration;
1086 $this->performance["marktime"] += (float)$duration;
1088 $callstack = $this->callstack();
1090 if (!isset($this->callstack[$value][$callstack])) {
1091 // Prevent ugly E_NOTICE
1092 $this->callstack[$value][$callstack] = 0;
1095 $this->callstack[$value][$callstack] += (float)$duration;
1100 * @brief Returns a string with a callstack. Can be used for logging.
1104 function callstack() {
1105 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 6);
1107 // We remove the first two items from the list since they contain data that we don't need.
1108 array_shift($trace);
1109 array_shift($trace);
1111 $callstack = array();
1112 foreach ($trace AS $func)
1113 $callstack[] = $func["function"];
1115 return implode(", ", $callstack);
1118 function mark_timestamp($mark) {
1119 //$this->performance["markstart"] -= microtime(true) - $this->performance["marktime"];
1120 $this->performance["markstart"] = microtime(true) - $this->performance["markstart"] - $this->performance["marktime"];
1123 function get_useragent() {
1124 return(FRIENDICA_PLATFORM." '".FRIENDICA_CODENAME."' ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION."; ".$this->get_baseurl());
1127 function is_friendica_app() {
1128 return($this->is_friendica_app);
1132 * @brief Checks if the site is called via a backend process
1134 * This isn't a perfect solution. But we need this check very early.
1135 * So we cannot wait until the modules are loaded.
1137 * @return bool Is it a known backend?
1139 function is_backend() {
1141 $backend[] = "_well_known";
1143 $backend[] = "dfrn_notify";
1144 $backend[] = "fetch";
1145 $backend[] = "hcard";
1146 $backend[] = "hostxrd";
1147 $backend[] = "nodeinfo";
1148 $backend[] = "noscrape";
1150 $backend[] = "poco";
1151 $backend[] = "post";
1152 $backend[] = "proxy";
1153 $backend[] = "pubsub";
1154 $backend[] = "pubsubhubbub";
1155 $backend[] = "receive";
1156 $backend[] = "rsd_xml";
1157 $backend[] = "salmon";
1158 $backend[] = "statistics_json";
1161 if (in_array($this->module, $backend))
1164 return($this->backend);
1168 * @brief Checks if the maximum number of database processes is reached
1170 * @return bool Is the limit reached?
1172 function max_processes_reached() {
1174 // Is the function called statically?
1175 if (!is_object($this))
1176 return(self::$a->max_processes_reached());
1178 if ($this->is_backend()) {
1179 $process = "backend";
1180 $max_processes = get_config('system', 'max_processes_backend');
1181 if (intval($max_processes) == 0)
1184 $process = "frontend";
1185 $max_processes = get_config('system', 'max_processes_frontend');
1186 if (intval($max_processes) == 0)
1187 $max_processes = 20;
1190 $processlist = dbm::processlist();
1191 if ($processlist["list"] != "") {
1192 logger("Processcheck: Processes: ".$processlist["amount"]." - Processlist: ".$processlist["list"], LOGGER_DEBUG);
1194 if ($processlist["amount"] > $max_processes) {
1195 logger("Processcheck: Maximum number of processes for ".$process." tasks (".$max_processes.") reached.", LOGGER_DEBUG);
1203 * @brief Checks if the maximum load is reached
1205 * @return bool Is the load reached?
1207 function maxload_reached() {
1209 // Is the function called statically?
1210 if (!is_object($this))
1211 return(self::$a->maxload_reached());
1213 if ($this->is_backend()) {
1214 $process = "backend";
1215 $maxsysload = intval(get_config('system', 'maxloadavg'));
1216 if ($maxsysload < 1)
1219 $process = "frontend";
1220 $maxsysload = intval(get_config('system','maxloadavg_frontend'));
1221 if ($maxsysload < 1)
1225 $load = current_load();
1227 if (intval($load) > $maxsysload) {
1228 logger('system: load '.$load.' for '.$process.' tasks ('.$maxsysload.') too high.');
1236 * @brief Checks if the process is already running
1238 * @param string $taskname The name of the task that will be used for the name of the lockfile
1239 * @param string $task The path and name of the php script
1240 * @param int $timeout The timeout after which a task should be killed
1242 * @return bool Is the process running?
1244 function is_already_running($taskname, $task = "", $timeout = 540) {
1246 $lockpath = get_lockpath();
1247 if ($lockpath != '') {
1248 $pidfile = new pidfile($lockpath, $taskname);
1249 if ($pidfile->is_already_running()) {
1250 logger("Already running");
1251 if ($pidfile->running_time() > $timeout) {
1253 logger("killed stale process");
1254 // Calling a new instance
1256 proc_run(PRIORITY_MEDIUM, $task);
1264 function proc_run($args) {
1266 // Add the php path if it is a php call
1267 if (count($args) && ($args[0] === 'php' OR is_int($args[0])))
1268 $args[0] = ((x($this->config,'php_path')) && (strlen($this->config['php_path'])) ? $this->config['php_path'] : 'php');
1270 // add baseurl to args. cli scripts can't construct it
1271 $args[] = $this->get_baseurl();
1273 for($x = 0; $x < count($args); $x ++)
1274 $args[$x] = escapeshellarg($args[$x]);
1276 $cmdline = implode($args," ");
1278 if(get_config('system','proc_windows'))
1279 proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
1281 proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
1287 * @brief Retrieve the App structure
1289 * Useful in functions which require it but don't get it passed to them
1291 function get_app() {
1298 * @brief Multi-purpose function to check variable state.
1300 * Usage: x($var) or $x($array, 'key')
1302 * returns false if variable/key is not set
1303 * if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
1304 * e.g. x('') or x(0) returns 0;
1306 * @param string|array $s variable to check
1307 * @param string $k key inside the array to check
1311 function x($s,$k = NULL) {
1313 if((is_array($s)) && (array_key_exists($k,$s))) {
1333 * @brief Called from db initialisation if db is dead.
1335 function system_unavailable() {
1336 include('system_unavailable.php');
1342 function clean_urls() {
1344 // if($a->config['system']['clean_urls'])
1351 $base = $a->get_baseurl();
1358 * @brief Returns the baseurl.
1360 * @see App::get_baseurl()
1366 return $a->get_baseurl();
1370 * @brief Return absolut URL for given $path.
1372 * @param string $path
1376 function absurl($path) {
1377 if(strpos($path,'/') === 0)
1378 return z_path() . $path;
1383 * @brief Function to check if request was an AJAX (xmlhttprequest) request.
1387 function is_ajax() {
1388 return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
1391 function check_db() {
1393 $build = get_config('system','build');
1395 set_config('system','build',DB_UPDATE_VERSION);
1396 $build = DB_UPDATE_VERSION;
1398 if($build != DB_UPDATE_VERSION)
1399 proc_run(PRIORITY_HIGH, 'include/dbupdate.php');
1405 * Sets the base url for use in cmdline programs which don't have
1406 * $_SERVER variables
1408 function check_url(&$a) {
1410 $url = get_config('system','url');
1412 // if the url isn't set or the stored url is radically different
1413 // than the currently visited url, store the current value accordingly.
1414 // "Radically different" ignores common variations such as http vs https
1415 // and www.example.com vs example.com.
1416 // We will only change the url to an ip address if there is no existing setting
1419 $url = set_config('system','url',$a->get_baseurl());
1420 if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
1421 $url = set_config('system','url',$a->get_baseurl());
1428 * @brief Automatic database updates
1430 function update_db(&$a) {
1431 $build = get_config('system','build');
1433 $build = set_config('system','build',DB_UPDATE_VERSION);
1435 if($build != DB_UPDATE_VERSION) {
1436 $stored = intval($build);
1437 $current = intval(DB_UPDATE_VERSION);
1438 if($stored < $current) {
1439 load_config('database');
1441 // We're reporting a different version than what is currently installed.
1442 // Run any existing update scripts to bring the database up to current.
1444 // make sure that boot.php and update.php are the same release, we might be
1445 // updating right this very second and the correct version of the update.php
1446 // file may not be here yet. This can happen on a very busy site.
1448 if(DB_UPDATE_VERSION == UPDATE_VERSION) {
1449 // Compare the current structure with the defined structure
1451 $t = get_config('database','dbupdate_'.DB_UPDATE_VERSION);
1455 set_config('database','dbupdate_'.DB_UPDATE_VERSION, time());
1457 // run old update routine (wich could modify the schema and
1458 // conflits with new routine)
1459 for ($x = $stored; $x < NEW_UPDATE_ROUTINE_VERSION; $x++) {
1460 $r = run_update_function($x);
1463 if ($stored < NEW_UPDATE_ROUTINE_VERSION) $stored = NEW_UPDATE_ROUTINE_VERSION;
1466 // run new update routine
1467 // it update the structure in one call
1468 $retval = update_structure(false, true);
1476 set_config('database','dbupdate_'.DB_UPDATE_VERSION, 'success');
1479 // run any left update_nnnn functions in update.php
1480 for($x = $stored; $x < $current; $x ++) {
1481 $r = run_update_function($x);
1491 function run_update_function($x) {
1492 if(function_exists('update_' . $x)) {
1494 // There could be a lot of processes running or about to run.
1495 // We want exactly one process to run the update command.
1496 // So store the fact that we're taking responsibility
1497 // after first checking to see if somebody else already has.
1499 // If the update fails or times-out completely you may need to
1500 // delete the config entry to try again.
1502 $t = get_config('database','update_' . $x);
1505 set_config('database','update_' . $x, time());
1507 // call the specific update
1509 $func = 'update_' . $x;
1513 //send the administrator an e-mail
1516 sprintf(t('Update %s failed. See error logs.'), $x)
1520 set_config('database','update_' . $x, 'success');
1521 set_config('system','build', $x + 1);
1525 set_config('database','update_' . $x, 'success');
1526 set_config('system','build', $x + 1);
1533 * @brief Synchronise plugins:
1535 * $a->config['system']['addon'] contains a comma-separated list of names
1536 * of plugins/addons which are used on this system.
1537 * Go through the database list of already installed addons, and if we have
1538 * an entry, but it isn't in the config list, call the uninstall procedure
1539 * and mark it uninstalled in the database (for now we'll remove it).
1540 * Then go through the config list and if we have a plugin that isn't installed,
1541 * call the install procedure and add it to the database.
1546 function check_plugins(&$a) {
1548 $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
1549 if(dbm::is_result($r))
1552 $installed = array();
1554 $plugins = get_config('system','addon');
1555 $plugins_arr = array();
1558 $plugins_arr = explode(',',str_replace(' ', '',$plugins));
1560 $a->plugins = $plugins_arr;
1562 $installed_arr = array();
1564 if(count($installed)) {
1565 foreach($installed as $i) {
1566 if(! in_array($i['name'],$plugins_arr)) {
1567 uninstall_plugin($i['name']);
1570 $installed_arr[] = $i['name'];
1575 if(count($plugins_arr)) {
1576 foreach($plugins_arr as $p) {
1577 if(! in_array($p,$installed_arr)) {
1589 function get_guid($size=16, $prefix = "") {
1591 if ($prefix == "") {
1593 $prefix = hash("crc32", $a->get_hostname());
1596 while (strlen($prefix) < ($size - 13))
1597 $prefix .= mt_rand();
1600 $prefix = substr($prefix, 0, $size - 22);
1601 return(str_replace(".", "", uniqid($prefix, true)));
1603 $prefix = substr($prefix, 0, max($size - 13, 0));
1604 return(uniqid($prefix));
1609 * @brief Wrapper for adding a login box.
1611 * @param bool $register
1612 * If $register == true provide a registration link.
1613 * This will most always depend on the value of $a->config['register_policy'].
1614 * @param bool $hiddens
1617 * Returns the complete html for inserting into the page
1619 * @hooks 'login_hook'
1622 function login($register = false, $hiddens=false) {
1628 'title' => t('Create a New Account'),
1629 'desc' => t('Register')
1633 $noid = get_config('system','no_openid');
1635 $dest_url = $a->query_string;
1638 $tpl = get_markup_template("logout.tpl");
1641 $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
1642 '$baseurl' => $a->get_baseurl(true)
1645 $tpl = get_markup_template("login.tpl");
1646 $_SESSION['return_url'] = $a->query_string;
1647 $a->module = 'login';
1650 $o .= replace_macros($tpl, array(
1652 '$dest_url' => $dest_url,
1653 '$logout' => t('Logout'),
1654 '$login' => t('Login'),
1656 '$lname' => array('username', t('Nickname or Email: ') , '', ''),
1657 '$lpassword' => array('password', t('Password: '), '', ''),
1658 '$lremember' => array('remember', t('Remember me'), 0, ''),
1660 '$openid' => !$noid,
1661 '$lopenid' => array('openid_url', t('Or login using OpenID: '),'',''),
1663 '$hiddens' => $hiddens,
1665 '$register' => $reg,
1667 '$lostpass' => t('Forgot your password?'),
1668 '$lostlink' => t('Password Reset'),
1670 '$tostitle' => t('Website Terms of Service'),
1671 '$toslink' => t('terms of service'),
1673 '$privacytitle' => t('Website Privacy Policy'),
1674 '$privacylink' => t('privacy policy'),
1678 call_hooks('login_hook',$o);
1684 * @brief Used to end the current process, after saving session state.
1687 session_write_close();
1692 * @brief Redirect to another URL and terminate this process.
1694 function goaway($s) {
1695 if (!strstr(normalise_link($s), "http://"))
1696 $s = App::get_baseurl()."/".$s;
1698 header("Location: $s");
1704 * @brief Returns the user id of locally logged in user or false.
1706 * @return int|bool user id or false
1708 function local_user() {
1709 if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
1710 return intval($_SESSION['uid']);
1715 * @brief Returns contact id of authenticated site visitor or false
1717 * @return int|bool visitor_id or false
1719 function remote_user() {
1720 if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
1721 return intval($_SESSION['visitor_id']);
1726 * @brief Show an error message to user.
1728 * This function save text in session, to be shown to the user at next page load
1730 * @param string $s - Text of notice
1732 function notice($s) {
1734 if(! x($_SESSION,'sysmsg')) $_SESSION['sysmsg'] = array();
1736 $_SESSION['sysmsg'][] = $s;
1740 * @brief Show an info message to user.
1742 * This function save text in session, to be shown to the user at next page load
1744 * @param string $s - Text of notice
1749 if (local_user() AND get_pconfig(local_user(),'system','ignore_info'))
1752 if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
1754 $_SESSION['sysmsg_info'][] = $s;
1759 * @brief Wrapper around config to limit the text length of an incoming message
1763 function get_max_import_size() {
1765 return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
1769 * @brief Wrap calls to proc_close(proc_open()) and call hook
1770 * so plugins can take part in process :)
1772 * @param (string|integer) $cmd program to run or priority
1774 * next args are passed as $cmd command line
1775 * e.g.: proc_run("ls","-la","/tmp");
1776 * or: proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $drop_id);
1778 * @note $cmd and string args are surrounded with ""
1783 function proc_run($cmd){
1787 $args = func_get_args();
1793 // expand any arrays
1795 foreach($args as $arg) {
1796 if(is_array($arg)) {
1797 foreach($arg as $n) {
1806 $arr = array('args' => $args, 'run_cmd' => true);
1808 call_hooks("proc_run", $arr);
1809 if (!$arr['run_cmd'] OR !count($args))
1812 if (!get_config("system", "worker") OR
1813 (($args[0] != 'php') AND !is_int($args[0]))) {
1814 $a->proc_run($args);
1818 if (is_int($args[0]))
1819 $priority = $args[0];
1821 $priority = PRIORITY_MEDIUM;
1826 $parameters = json_encode($argv);
1827 $found = q("SELECT `id` FROM `workerqueue` WHERE `parameter` = '%s'",
1828 dbesc($parameters));
1831 q("INSERT INTO `workerqueue` (`parameter`, `created`, `priority`)
1832 VALUES ('%s', '%s', %d)",
1834 dbesc(datetime_convert()),
1837 // Should we quit and wait for the poller to be called as a cronjob?
1838 if (get_config("system", "worker_dont_fork"))
1841 // Checking number of workers
1842 $workers = q("SELECT COUNT(*) AS `workers` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
1844 // Get number of allowed number of worker threads
1845 $queues = intval(get_config("system", "worker_queues"));
1850 // If there are already enough workers running, don't fork another one
1851 if ($workers[0]["workers"] >= $queues)
1854 // Now call the poller to execute the jobs that we just added to the queue
1855 $args = array("php", "include/poller.php", "no_cron");
1857 $a->proc_run($args);
1860 function current_theme(){
1861 $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
1867 // Find the theme that belongs to the user whose stuff we are looking at
1869 if($a->profile_uid && ($a->profile_uid != local_user())) {
1870 $r = q("select theme from user where uid = %d limit 1",
1871 intval($a->profile_uid)
1873 if(dbm::is_result($r))
1874 $page_theme = $r[0]['theme'];
1877 // Allow folks to over-rule user themes and always use their own on their own site.
1878 // This works only if the user is on the same server
1880 if($page_theme && local_user() && (local_user() != $a->profile_uid)) {
1881 if(get_pconfig(local_user(),'system','always_my_theme'))
1885 // $mobile_detect = new Mobile_Detect();
1886 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1887 $is_mobile = $a->is_mobile || $a->is_tablet;
1889 $standard_system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1890 $standard_theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $standard_system_theme);
1893 if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
1894 $system_theme = $standard_system_theme;
1895 $theme_name = $standard_theme_name;
1898 $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : $standard_system_theme);
1899 $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
1901 if($theme_name === '---') {
1902 // user has selected to have the mobile theme be the same as the normal one
1903 $system_theme = $standard_system_theme;
1904 $theme_name = $standard_theme_name;
1907 $theme_name = $page_theme;
1912 $system_theme = $standard_system_theme;
1913 $theme_name = $standard_theme_name;
1916 $theme_name = $page_theme;
1920 (file_exists('view/theme/' . $theme_name . '/style.css') ||
1921 file_exists('view/theme/' . $theme_name . '/style.php')))
1922 return($theme_name);
1924 foreach($app_base_themes as $t) {
1925 if(file_exists('view/theme/' . $t . '/style.css')||
1926 file_exists('view/theme/' . $t . '/style.php'))
1930 $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
1931 if(count($fallback))
1932 return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
1937 * @brief Return full URL to theme which is currently in effect.
1939 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1943 function current_theme_url() {
1946 $t = current_theme();
1948 $opts = (($a->profile_uid) ? '?f=&puid=' . $a->profile_uid : '');
1949 if (file_exists('view/theme/' . $t . '/style.php'))
1950 return('view/theme/'.$t.'/style.pcss'.$opts);
1952 return('view/theme/'.$t.'/style.css');
1955 function feed_birthday($uid,$tz) {
1959 * Determine the next birthday, but only if the birthday is published
1960 * in the default profile. We _could_ also look for a private profile that the
1961 * recipient can see, but somebody could get mad at us if they start getting
1962 * public birthday greetings when they haven't made this info public.
1964 * Assuming we are able to publish this info, we are then going to convert
1965 * the start time from the owner's timezone to UTC.
1967 * This will potentially solve the problem found with some social networks
1968 * where birthdays are converted to the viewer's timezone and salutations from
1969 * elsewhere in the world show up on the wrong day. We will convert it to the
1970 * viewer's timezone also, but first we are going to convert it from the birthday
1971 * person's timezone to GMT - so the viewer may find the birthday starting at
1972 * 6:00PM the day before, but that will correspond to midnight to the birthday person.
1982 $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
1986 if(dbm::is_result($p)) {
1987 $tmp_dob = substr($p[0]['dob'],5);
1988 if(intval($tmp_dob)) {
1989 $y = datetime_convert($tz,$tz,'now','Y');
1990 $bd = $y . '-' . $tmp_dob . ' 00:00';
1991 $t_dob = strtotime($bd);
1992 $now = strtotime(datetime_convert($tz,$tz,'now'));
1994 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
1995 $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
2003 * @brief Check if current user has admin role.
2005 * @return bool true if user is an admin
2007 function is_site_admin() {
2010 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
2012 //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
2013 if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && in_array($a->user['email'], $adminlist))
2019 * @brief Returns querystring as string from a mapped array.
2021 * @param array $params mapped array with query parameters
2022 * @param string $name of parameter, default null
2026 function build_querystring($params, $name=null) {
2028 foreach($params as $key=>$val) {
2029 if(is_array($val)) {
2031 $ret .= build_querystring($val, $key);
2033 $ret .= build_querystring($val, $name."[$key]");
2036 $val = urlencode($val);
2038 $ret.=$name."[$key]"."=$val&";
2040 $ret.= "$key=$val&";
2047 function explode_querystring($query) {
2048 $arg_st = strpos($query, '?');
2049 if($arg_st !== false) {
2050 $base = substr($query, 0, $arg_st);
2057 $args = explode('&', substr($query, $arg_st));
2058 foreach($args as $k=>$arg) {
2062 $args = array_values($args);
2067 $args = array_values($args);
2077 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
2079 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
2081 function curPageURL() {
2083 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
2085 if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
2086 $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
2088 $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
2093 function random_digits($digits) {
2095 for($i = 0; $i < $digits; $i++) {
2101 function get_server() {
2102 $server = get_config("system", "directory");
2105 $server = "http://dir.friendi.ca";
2110 function get_cachefile($file, $writemode = true) {
2111 $cache = get_itemcachepath();
2113 if ((! $cache) || (! is_dir($cache)))
2116 $subfolder = $cache."/".substr($file, 0, 2);
2118 $cachepath = $subfolder."/".$file;
2121 if (!is_dir($subfolder)) {
2123 chmod($subfolder, 0777);
2130 function clear_cache($basepath = "", $path = "") {
2132 $basepath = get_itemcachepath();
2136 if (($path == "") OR (!is_dir($path)))
2139 if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
2142 $cachetime = (int)get_config('system','itemcache_duration');
2143 if ($cachetime == 0)
2146 if (is_writable($path)){
2147 if ($dh = opendir($path)) {
2148 while (($file = readdir($dh)) !== false) {
2149 $fullpath = $path."/".$file;
2150 if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
2151 clear_cache($basepath, $fullpath);
2152 if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
2160 function get_itemcachepath() {
2161 // Checking, if the cache is deactivated
2162 $cachetime = (int)get_config('system','itemcache_duration');
2166 $itemcache = get_config('system','itemcache');
2167 if (($itemcache != "") AND is_dir($itemcache) AND is_writable($itemcache))
2170 $temppath = get_temppath();
2172 if ($temppath != "") {
2173 $itemcache = $temppath."/itemcache";
2174 if(!file_exists($itemcache) && !is_dir($itemcache)) {
2178 if (is_dir($itemcache) AND is_writable($itemcache)) {
2179 set_config("system", "itemcache", $itemcache);
2186 function get_lockpath() {
2187 $lockpath = get_config('system','lockpath');
2188 if (($lockpath != "") AND is_dir($lockpath) AND is_writable($lockpath))
2191 $temppath = get_temppath();
2193 if ($temppath != "") {
2194 $lockpath = $temppath."/lock";
2196 if (!is_dir($lockpath))
2198 elseif (!is_writable($lockpath))
2199 $lockpath = $temppath;
2201 if (is_dir($lockpath) AND is_writable($lockpath)) {
2202 set_config("system", "lockpath", $lockpath);
2209 function get_temppath() {
2212 $temppath = get_config("system","temppath");
2213 if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath))
2216 $temppath = sys_get_temp_dir();
2217 if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath)) {
2218 $temppath .= "/".$a->get_hostname();
2219 if (!is_dir($temppath))
2222 if (is_dir($temppath) AND is_writable($temppath)) {
2223 set_config("system", "temppath", $temppath);
2231 function set_template_engine(&$a, $engine = 'internal') {
2232 /// @note This function is no longer necessary, but keep it as a wrapper to the class method
2233 /// to avoid breaking themes again unnecessarily
2235 $a->set_template_engine($engine);
2238 if(!function_exists('exif_imagetype')) {
2239 function exif_imagetype($file) {
2240 $size = getimagesize($file);
2245 function validate_include(&$file) {
2248 $file = realpath($file);
2250 if (strpos($file, getcwd()) !== 0)
2253 $file = str_replace(getcwd()."/", "", $file, $count);
2257 if ($orig_file !== $file)
2261 if (strpos($file, "include/") === 0)
2264 if (strpos($file, "addon/") === 0)
2273 function current_load() {
2274 if (!function_exists('sys_getloadavg'))
2277 $load_arr = sys_getloadavg();
2279 if (!is_array($load_arr))
2282 return max($load_arr[0], $load_arr[1]);
2286 * @brief get c-style args
2291 return get_app()->argc;
2295 * @brief Returns the value of a argv key
2297 * @param int $x argv key
2298 * @return string Value of the argv key
2301 if(array_key_exists($x,get_app()->argv))
2302 return get_app()->argv[$x];
2308 * @brief Get the data which is needed for infinite scroll
2310 * For invinite scroll we need the page number of the actual page
2311 * and the the URI where the content of the next page comes from.
2312 * This data is needed for the js part in main.js.
2313 * Note: infinite scroll does only work for the network page (module)
2315 * @param string $module The name of the module (e.g. "network")
2316 * @return array Of infinite scroll data
2317 * 'pageno' => $pageno The number of the actual page
2318 * 'reload_uri' => $reload_uri The URI of the content we have to load
2320 function infinite_scroll_data($module) {
2322 if (get_pconfig(local_user(),'system','infinite_scroll')
2323 AND ($module == "network") AND ($_GET["mode"] != "minimal")) {
2325 // get the page number
2326 if (is_string($_GET["page"]))
2327 $pageno = $_GET["page"];
2333 // try to get the uri from which we load the content
2334 foreach ($_GET AS $param => $value)
2335 if (($param != "page") AND ($param != "q"))
2336 $reload_uri .= "&".$param."=".urlencode($value);
2338 if (($a->page_offset != "") AND !strstr($reload_uri, "&offset="))
2339 $reload_uri .= "&offset=".urlencode($a->page_offset);
2341 $arr = array("pageno" => $pageno, "reload_uri" => $reload_uri);