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/config.php');
21 require_once('include/network.php');
22 require_once('include/plugin.php');
23 require_once('include/text.php');
24 require_once('include/datetime.php');
25 require_once('include/pgettext.php');
26 require_once('include/nav.php');
27 require_once('include/cache.php');
28 require_once('library/Mobile_Detect/Mobile_Detect.php');
29 require_once('include/features.php');
30 require_once('include/identity.php');
32 require_once('update.php');
33 require_once('include/dbstructure.php');
35 define ( 'FRIENDICA_PLATFORM', 'Friendica');
36 define ( 'FRIENDICA_CODENAME', 'Asparagus');
37 define ( 'FRIENDICA_VERSION', '3.5-dev' );
38 define ( 'DFRN_PROTOCOL_VERSION', '2.23' );
39 define ( 'DB_UPDATE_VERSION', 1191 );
42 * @brief Constant with a HTML line break.
44 * Contains a HTML line break (br) element and a real carriage return with line
45 * feed for the source.
46 * This can be used in HTML and JavaScript where needed a line break.
48 define ( 'EOL', "<br />\r\n" );
49 define ( 'ATOM_TIME', 'Y-m-d\TH:i:s\Z' );
54 * Image storage quality. Lower numbers save space at cost of image detail.
55 * For ease of upgrade, please do not change here. Change jpeg quality with
56 * $a->config['system']['jpeg_quality'] = n;
57 * in .htconfig.php, where n is netween 1 and 100, and with very poor results
62 define ( 'JPEG_QUALITY', 100 );
64 * $a->config['system']['png_quality'] from 0 (uncompressed) to 9
66 define ( 'PNG_QUALITY', 8 );
70 * An alternate way of limiting picture upload sizes. Specify the maximum pixel
71 * length that pictures are allowed to be (for non-square pictures, it will apply
72 * to the longest side). Pictures longer than this length will be resized to be
73 * this length (on the longest side, the other side will be scaled appropriately).
74 * Modify this value using
76 * $a->config['system']['max_image_length'] = n;
80 * If you don't want to set a maximum length, set to -1. The default value is
81 * defined by 'MAX_IMAGE_LENGTH' below.
84 define ( 'MAX_IMAGE_LENGTH', -1 );
91 define ( 'DEFAULT_DB_ENGINE', 'MyISAM' );
94 * SSL redirection policies
97 define ( 'SSL_POLICY_NONE', 0 );
98 define ( 'SSL_POLICY_FULL', 1 );
99 define ( 'SSL_POLICY_SELFSIGN', 2 );
106 define ( 'LOGGER_NORMAL', 0 );
107 define ( 'LOGGER_TRACE', 1 );
108 define ( 'LOGGER_DEBUG', 2 );
109 define ( 'LOGGER_DATA', 3 );
110 define ( 'LOGGER_ALL', 4 );
116 define ( 'CACHE_MONTH', 0 );
117 define ( 'CACHE_WEEK', 1 );
118 define ( 'CACHE_DAY', 2 );
119 define ( 'CACHE_HOUR', 3 );
122 * registration policies
125 define ( 'REGISTER_CLOSED', 0 );
126 define ( 'REGISTER_APPROVE', 1 );
127 define ( 'REGISTER_OPEN', 2 );
133 define ( 'CONTACT_IS_FOLLOWER', 1);
134 define ( 'CONTACT_IS_SHARING', 2);
135 define ( 'CONTACT_IS_FRIEND', 3);
139 * DB update return values
142 define ( 'UPDATE_SUCCESS', 0);
143 define ( 'UPDATE_FAILED', 1);
150 * PAGE_NORMAL is a typical personal profile account
151 * PAGE_SOAPBOX automatically approves all friend requests as CONTACT_IS_SHARING, (readonly)
152 * PAGE_COMMUNITY automatically approves all friend requests as CONTACT_IS_SHARING, but with
153 * write access to wall and comments (no email and not included in page owner's ACL lists)
154 * PAGE_FREELOVE automatically approves all friend requests as full friends (CONTACT_IS_FRIEND).
158 define ( 'PAGE_NORMAL', 0 );
159 define ( 'PAGE_SOAPBOX', 1 );
160 define ( 'PAGE_COMMUNITY', 2 );
161 define ( 'PAGE_FREELOVE', 3 );
162 define ( 'PAGE_BLOG', 4 );
163 define ( 'PAGE_PRVGROUP', 5 );
166 * Type of the community page
168 define ( 'CP_NO_COMMUNITY_PAGE', -1 );
169 define ( 'CP_USERS_ON_SERVER', 0 );
170 define ( 'CP_GLOBAL_COMMUNITY', 1 );
173 * Network and protocol family types
176 define ( 'NETWORK_DFRN', 'dfrn'); // Friendica, Mistpark, other DFRN implementations
177 define ( 'NETWORK_ZOT', 'zot!'); // Zot!
178 define ( 'NETWORK_OSTATUS', 'stat'); // status.net, identi.ca, GNU-social, other OStatus implementations
179 define ( 'NETWORK_FEED', 'feed'); // RSS/Atom feeds with no known "post/notify" protocol
180 define ( 'NETWORK_DIASPORA', 'dspr'); // Diaspora
181 define ( 'NETWORK_MAIL', 'mail'); // IMAP/POP
182 define ( 'NETWORK_MAIL2', 'mai2'); // extended IMAP/POP
183 define ( 'NETWORK_FACEBOOK', 'face'); // Facebook API
184 define ( 'NETWORK_LINKEDIN', 'lnkd'); // LinkedIn
185 define ( 'NETWORK_XMPP', 'xmpp'); // XMPP
186 define ( 'NETWORK_MYSPACE', 'mysp'); // MySpace
187 define ( 'NETWORK_GPLUS', 'goog'); // Google+
188 define ( 'NETWORK_PUMPIO', 'pump'); // pump.io
189 define ( 'NETWORK_TWITTER', 'twit'); // Twitter
190 define ( 'NETWORK_DIASPORA2', 'dspc'); // Diaspora connector
191 define ( 'NETWORK_STATUSNET', 'stac'); // Statusnet connector
192 define ( 'NETWORK_APPNET', 'apdn'); // app.net
193 define ( 'NETWORK_NEWS', 'nntp'); // Network News Transfer Protocol
194 define ( 'NETWORK_ICALENDAR', 'ical'); // iCalendar
195 define ( 'NETWORK_PHANTOM', 'unkn'); // Place holder
198 * These numbers are used in stored permissions
199 * and existing allocations MUST NEVER BE CHANGED
200 * OR RE-ASSIGNED! You may only add to them.
203 $netgroup_ids = array(
204 NETWORK_DFRN => (-1),
206 NETWORK_OSTATUS => (-3),
207 NETWORK_FEED => (-4),
208 NETWORK_DIASPORA => (-5),
209 NETWORK_MAIL => (-6),
210 NETWORK_MAIL2 => (-7),
211 NETWORK_FACEBOOK => (-8),
212 NETWORK_LINKEDIN => (-9),
213 NETWORK_XMPP => (-10),
214 NETWORK_MYSPACE => (-11),
215 NETWORK_GPLUS => (-12),
216 NETWORK_PUMPIO => (-13),
217 NETWORK_TWITTER => (-14),
218 NETWORK_DIASPORA2 => (-15),
219 NETWORK_STATUSNET => (-16),
220 NETWORK_APPNET => (-17),
221 NETWORK_NEWS => (-18),
222 NETWORK_ICALENDAR => (-19),
224 NETWORK_PHANTOM => (-127),
229 * Maximum number of "people who like (or don't like) this" that we will list by name
232 define ( 'MAX_LIKERS', 75);
235 * Communication timeout
238 define ( 'ZCURL_TIMEOUT' , (-1));
242 * email notification options
245 define ( 'NOTIFY_INTRO', 0x0001 );
246 define ( 'NOTIFY_CONFIRM', 0x0002 );
247 define ( 'NOTIFY_WALL', 0x0004 );
248 define ( 'NOTIFY_COMMENT', 0x0008 );
249 define ( 'NOTIFY_MAIL', 0x0010 );
250 define ( 'NOTIFY_SUGGEST', 0x0020 );
251 define ( 'NOTIFY_PROFILE', 0x0040 );
252 define ( 'NOTIFY_TAGSELF', 0x0080 );
253 define ( 'NOTIFY_TAGSHARE', 0x0100 );
254 define ( 'NOTIFY_POKE', 0x0200 );
255 define ( 'NOTIFY_SHARE', 0x0400 );
257 define ( 'NOTIFY_SYSTEM', 0x8000 );
264 define ( 'TERM_UNKNOWN', 0 );
265 define ( 'TERM_HASHTAG', 1 );
266 define ( 'TERM_MENTION', 2 );
267 define ( 'TERM_CATEGORY', 3 );
268 define ( 'TERM_PCATEGORY', 4 );
269 define ( 'TERM_FILE', 5 );
270 define ( 'TERM_SAVEDSEARCH', 6 );
271 define ( 'TERM_CONVERSATION', 7 );
273 define ( 'TERM_OBJ_POST', 1 );
274 define ( 'TERM_OBJ_PHOTO', 2 );
279 * various namespaces we may need to parse
282 define ( 'NAMESPACE_ZOT', 'http://purl.org/zot' );
283 define ( 'NAMESPACE_DFRN' , 'http://purl.org/macgirvin/dfrn/1.0' );
284 define ( 'NAMESPACE_THREAD' , 'http://purl.org/syndication/thread/1.0' );
285 define ( 'NAMESPACE_TOMB' , 'http://purl.org/atompub/tombstones/1.0' );
286 define ( 'NAMESPACE_ACTIVITY', 'http://activitystrea.ms/spec/1.0/' );
287 define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/' );
288 define ( 'NAMESPACE_MEDIA', 'http://purl.org/syndication/atommedia' );
289 define ( 'NAMESPACE_SALMON_ME', 'http://salmon-protocol.org/ns/magic-env' );
290 define ( 'NAMESPACE_OSTATUSSUB', 'http://ostatus.org/schema/1.0/subscribe' );
291 define ( 'NAMESPACE_GEORSS', 'http://www.georss.org/georss' );
292 define ( 'NAMESPACE_POCO', 'http://portablecontacts.net/spec/1.0' );
293 define ( 'NAMESPACE_FEED', 'http://schemas.google.com/g/2010#updates-from' );
294 define ( 'NAMESPACE_OSTATUS', 'http://ostatus.org/schema/1.0' );
295 define ( 'NAMESPACE_STATUSNET', 'http://status.net/schema/api/1/' );
296 define ( 'NAMESPACE_ATOM1', 'http://www.w3.org/2005/Atom' );
298 * activity stream defines
301 define ( 'ACTIVITY_LIKE', NAMESPACE_ACTIVITY_SCHEMA . 'like' );
302 define ( 'ACTIVITY_DISLIKE', NAMESPACE_DFRN . '/dislike' );
303 define ( 'ACTIVITY_ATTEND', NAMESPACE_ZOT . '/activity/attendyes' );
304 define ( 'ACTIVITY_ATTENDNO', NAMESPACE_ZOT . '/activity/attendno' );
305 define ( 'ACTIVITY_ATTENDMAYBE', NAMESPACE_ZOT . '/activity/attendmaybe' );
307 define ( 'ACTIVITY_OBJ_HEART', NAMESPACE_DFRN . '/heart' );
309 define ( 'ACTIVITY_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
310 define ( 'ACTIVITY_REQ_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'request-friend' );
311 define ( 'ACTIVITY_UNFRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'remove-friend' );
312 define ( 'ACTIVITY_FOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'follow' );
313 define ( 'ACTIVITY_UNFOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'stop-following' );
314 define ( 'ACTIVITY_JOIN', NAMESPACE_ACTIVITY_SCHEMA . 'join' );
316 define ( 'ACTIVITY_POST', NAMESPACE_ACTIVITY_SCHEMA . 'post' );
317 define ( 'ACTIVITY_UPDATE', NAMESPACE_ACTIVITY_SCHEMA . 'update' );
318 define ( 'ACTIVITY_TAG', NAMESPACE_ACTIVITY_SCHEMA . 'tag' );
319 define ( 'ACTIVITY_FAVORITE', NAMESPACE_ACTIVITY_SCHEMA . 'favorite' );
320 define ( 'ACTIVITY_SHARE', NAMESPACE_ACTIVITY_SCHEMA . 'share' );
322 define ( 'ACTIVITY_POKE', NAMESPACE_ZOT . '/activity/poke' );
323 define ( 'ACTIVITY_MOOD', NAMESPACE_ZOT . '/activity/mood' );
325 define ( 'ACTIVITY_OBJ_BOOKMARK', NAMESPACE_ACTIVITY_SCHEMA . 'bookmark' );
326 define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
327 define ( 'ACTIVITY_OBJ_NOTE', NAMESPACE_ACTIVITY_SCHEMA . 'note' );
328 define ( 'ACTIVITY_OBJ_PERSON', NAMESPACE_ACTIVITY_SCHEMA . 'person' );
329 define ( 'ACTIVITY_OBJ_IMAGE', NAMESPACE_ACTIVITY_SCHEMA . 'image' );
330 define ( 'ACTIVITY_OBJ_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
331 define ( 'ACTIVITY_OBJ_VIDEO', NAMESPACE_ACTIVITY_SCHEMA . 'video' );
332 define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
333 define ( 'ACTIVITY_OBJ_ALBUM', NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
334 define ( 'ACTIVITY_OBJ_EVENT', NAMESPACE_ACTIVITY_SCHEMA . 'event' );
335 define ( 'ACTIVITY_OBJ_GROUP', NAMESPACE_ACTIVITY_SCHEMA . 'group' );
336 define ( 'ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN . '/tagterm' );
337 define ( 'ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN . '/profile' );
338 define ( 'ACTIVITY_OBJ_QUESTION', 'http://activityschema.org/object/question' );
341 * item weight for query ordering
344 define ( 'GRAVITY_PARENT', 0);
345 define ( 'GRAVITY_LIKE', 3);
346 define ( 'GRAVITY_COMMENT', 6);
350 * Reverse the effect of magic_quotes_gpc if it is enabled.
351 * Please disable magic_quotes_gpc so we don't have to do this.
352 * See http://php.net/manual/en/security.magicquotes.disabling.php
358 error_reporting(E_ERROR | E_WARNING | E_PARSE);
362 // This has to be quite large to deal with embedded private photos
363 ini_set('pcre.backtrack_limit', 500000);
366 if (get_magic_quotes_gpc()) {
367 $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
368 while (list($key, $val) = each($process)) {
369 foreach ($val as $k => $v) {
370 unset($process[$key][$k]);
372 $process[$key][stripslashes($k)] = $v;
373 $process[] = &$process[$key][stripslashes($k)];
375 $process[$key][stripslashes($k)] = stripslashes($v);
388 * @brief Our main application structure for the life of this page.
390 * Primarily deals with the URL that got us here
391 * and tries to make some sense of it, and
392 * stores our page contents and config storage
393 * and anything else that might need to be passed around
394 * before we spit the page out.
399 public $module_loaded = false;
400 public $query_string;
409 public $page_contact;
411 public $data = array();
412 public $error = false;
422 public $interactive = true;
424 public $apps = array();
428 public $is_friendica_app;
429 public $performance = array();
436 // Allow themes to control internal parameters
437 // by changing App values in theme.php
439 public $sourcename = '';
440 public $videowidth = 425;
441 public $videoheight = 350;
442 public $force_max_items = 0;
443 public $theme_thread_allow = true;
444 public $theme_events_in_profile = true;
447 * @brief An array for all theme-controllable parameters
449 * Mostly unimplemented yet. Only options 'template_engine' and
452 public $theme = array(
455 'videoheight' => 350,
456 'force_max_items' => 0,
457 'thread_allow' => true,
459 'template_engine' => 'smarty3',
463 * @brief An array of registered template engines ('name'=>'class name')
465 public $template_engines = array();
467 * @brief An array of instanced template engines ('name'=>'instance')
469 public $template_engine_instance = array();
471 private $ldelim = array(
475 private $rdelim = array(
486 private $curl_content_type;
487 private $curl_headers;
489 private $cached_profile_image;
490 private $cached_profile_picdate;
495 function __construct() {
497 global $default_timezone;
501 if (file_exists(".htpreconfig.php"))
502 @include(".htpreconfig.php");
504 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
506 date_default_timezone_set($this->timezone);
508 $this->performance["start"] = microtime(true);
509 $this->performance["database"] = 0;
510 $this->performance["network"] = 0;
511 $this->performance["file"] = 0;
512 $this->performance["rendering"] = 0;
513 $this->performance["parser"] = 0;
514 $this->performance["marktime"] = 0;
515 $this->performance["markstart"] = microtime(true);
517 $this->config = array();
518 $this->page = array();
519 $this->pager= array();
521 $this->query_string = '';
526 'include' . PATH_SEPARATOR
527 . 'library' . PATH_SEPARATOR
528 . 'library/phpsec' . PATH_SEPARATOR
529 . 'library/langdet' . PATH_SEPARATOR
533 $this->scheme = 'http';
534 if(x($_SERVER,'HTTPS') && $_SERVER['HTTPS'])
535 $this->scheme = 'https';
536 elseif(x($_SERVER,'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443))
537 $this->scheme = 'https';
539 if(x($_SERVER,'SERVER_NAME')) {
540 $this->hostname = $_SERVER['SERVER_NAME'];
542 // See bug 437 - this didn't work so disabling it
543 //if(stristr($this->hostname,'xn--')) {
544 // PHP or webserver may have converted idn to punycode, so
545 // convert punycode back to utf-8
546 // require_once('library/simplepie/idn/idna_convert.class.php');
547 // $x = new idna_convert();
548 // $this->hostname = $x->decode($_SERVER['SERVER_NAME']);
551 if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
552 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
554 * Figure out if we are running at the top of a domain
555 * or in a sub-directory and adjust accordingly
558 $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
559 if(isset($path) && strlen($path) && ($path != $this->path))
564 $this->hostname = $hostname;
566 if (is_array($_SERVER["argv"]) && $_SERVER["argc"]>1 && substr(end($_SERVER["argv"]), 0, 4)=="http" ) {
567 $this->set_baseurl(array_pop($_SERVER["argv"]) );
571 #set_include_path("include/$this->hostname" . PATH_SEPARATOR . get_include_path());
573 if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,9) === "pagename=") {
574 $this->query_string = substr($_SERVER['QUERY_STRING'],9);
575 // removing trailing / - maybe a nginx problem
576 if (substr($this->query_string, 0, 1) == "/")
577 $this->query_string = substr($this->query_string, 1);
578 } elseif((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
579 $this->query_string = substr($_SERVER['QUERY_STRING'],2);
580 // removing trailing / - maybe a nginx problem
581 if (substr($this->query_string, 0, 1) == "/")
582 $this->query_string = substr($this->query_string, 1);
585 if (x($_GET,'pagename'))
586 $this->cmd = trim($_GET['pagename'],'/\\');
587 elseif (x($_GET,'q'))
588 $this->cmd = trim($_GET['q'],'/\\');
592 $this->query_string = str_replace($this->cmd."&",$this->cmd."?", $this->query_string);
595 // unix style "homedir"
597 if(substr($this->cmd,0,1) === '~')
598 $this->cmd = 'profile/' . substr($this->cmd,1);
600 // Diaspora style profile url
602 if(substr($this->cmd,0,2) === 'u/')
603 $this->cmd = 'profile/' . substr($this->cmd,2);
608 * Break the URL path into C style argc/argv style arguments for our
609 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
610 * will be 3 (integer) and $this->argv will contain:
616 * There will always be one argument. If provided a naked domain
617 * URL, $this->argv[0] is set to "home".
621 $this->argv = explode('/',$this->cmd);
622 $this->argc = count($this->argv);
623 if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
624 $this->module = str_replace(".", "_", $this->argv[0]);
625 $this->module = str_replace("-", "_", $this->module);
629 $this->argv = array('home');
630 $this->module = 'home';
634 * See if there is any page number information, and initialise
638 $this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
639 $this->pager['itemspage'] = 50;
640 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
641 if($this->pager['start'] < 0)
642 $this->pager['start'] = 0;
643 $this->pager['total'] = 0;
646 * Detect mobile devices
649 $mobile_detect = new Mobile_Detect();
650 $this->is_mobile = $mobile_detect->isMobile();
651 $this->is_tablet = $mobile_detect->isTablet();
654 $this->is_friendica_app = ($_SERVER['HTTP_USER_AGENT'] == "Apache-HttpClient/UNAVAILABLE (java 1.4)");
657 * register template engines
659 $dc = get_declared_classes();
660 foreach ($dc as $k) {
661 if (in_array("ITemplateEngine", class_implements($k))){
662 $this->register_template_engine($k);
668 function get_basepath() {
670 $basepath = get_config("system", "basepath");
673 $basepath = dirname(__FILE__);
676 $basepath = $_SERVER["DOCUMENT_ROOT"];
679 $basepath = $_SERVER["PWD"];
684 function get_scheme() {
685 return($this->scheme);
688 function get_baseurl($ssl = false) {
690 $scheme = $this->scheme;
692 if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
693 if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
696 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
697 // (and also the login link). Anything seen by an outsider will have it turned off.
699 if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
707 if (get_config('config','hostname') != "")
708 $this->hostname = get_config('config','hostname');
710 $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
711 return $this->baseurl;
714 function set_baseurl($url) {
715 $parsed = @parse_url($url);
717 $this->baseurl = $url;
720 $this->scheme = $parsed['scheme'];
722 $hostname = $parsed['host'];
723 if(x($parsed,'port'))
724 $hostname .= ':' . $parsed['port'];
725 if(x($parsed,'path'))
726 $this->path = trim($parsed['path'],'\\/');
728 if (file_exists(".htpreconfig.php"))
729 @include(".htpreconfig.php");
731 if (get_config('config','hostname') != "")
732 $this->hostname = get_config('config','hostname');
734 if (!isset($this->hostname) OR ($this->hostname == ""))
735 $this->hostname = $hostname;
740 function get_hostname() {
741 if (get_config('config','hostname') != "")
742 $this->hostname = get_config('config','hostname');
744 return $this->hostname;
747 function set_hostname($h) {
748 $this->hostname = $h;
751 function set_path($p) {
752 $this->path = trim(trim($p),'/');
755 function get_path() {
759 function set_pager_total($n) {
760 $this->pager['total'] = intval($n);
763 function set_pager_itemspage($n) {
764 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
765 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
768 function set_pager_page($n) {
769 $this->pager['page'] = $n;
770 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
773 function init_pagehead() {
774 $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
776 // If the update is "deactivated" set it to the highest integer number (~24 days)
778 $interval = 2147483647;
780 if($interval < 10000)
783 // compose the page title from the sitename and the
784 // current module called
785 if (!$this->module=='')
787 $this->page['title'] = $this->config['sitename'].' ('.$this->module.')';
789 $this->page['title'] = $this->config['sitename'];
792 /* put the head template at the beginning of page['htmlhead']
793 * since the code added by the modules frequently depends on it
796 if(!isset($this->page['htmlhead']))
797 $this->page['htmlhead'] = '';
799 // If we're using Smarty, then doing replace_macros() will replace
800 // any unrecognized variables with a blank string. Since we delay
801 // replacing $stylesheet until later, we need to replace it now
802 // with another variable name
803 if($this->theme['template_engine'] === 'smarty3')
804 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
806 $stylesheet = '$stylesheet';
808 $shortcut_icon = get_config("system", "shortcut_icon");
809 if ($shortcut_icon == "")
810 $shortcut_icon = $this->get_baseurl()."/images/friendica-32.png";
812 $touch_icon = get_config("system", "touch_icon");
813 if ($touch_icon == "")
814 $touch_icon = $this->get_baseurl()."/images/friendica-128.png";
816 $tpl = get_markup_template('head.tpl');
817 $this->page['htmlhead'] = replace_macros($tpl,array(
818 '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
819 '$local_user' => local_user(),
820 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
821 '$delitem' => t('Delete this item?'),
822 '$comment' => t('Comment'),
823 '$showmore' => t('show more'),
824 '$showfewer' => t('show fewer'),
825 '$update_interval' => $interval,
826 '$shortcut_icon' => $shortcut_icon,
827 '$touch_icon' => $touch_icon,
828 '$stylesheet' => $stylesheet
829 )) . $this->page['htmlhead'];
832 function init_page_end() {
833 if(!isset($this->page['end']))
834 $this->page['end'] = '';
835 $tpl = get_markup_template('end.tpl');
836 $this->page['end'] = replace_macros($tpl,array(
837 '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
838 )) . $this->page['end'];
841 function set_curl_code($code) {
842 $this->curl_code = $code;
845 function get_curl_code() {
846 return $this->curl_code;
849 function set_curl_content_type($content_type) {
850 $this->curl_content_type = $content_type;
853 function get_curl_content_type() {
854 return $this->curl_content_type;
857 function set_curl_headers($headers) {
858 $this->curl_headers = $headers;
861 function get_curl_headers() {
862 return $this->curl_headers;
865 function get_cached_avatar_image($avatar_image){
866 if($this->cached_profile_image[$avatar_image])
867 return $this->cached_profile_image[$avatar_image];
869 $path_parts = explode("/",$avatar_image);
870 $common_filename = $path_parts[count($path_parts)-1];
872 if($this->cached_profile_picdate[$common_filename]){
873 $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
875 $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like '%%/%s'",
878 $this->cached_profile_image[$avatar_image] = $avatar_image;
880 $this->cached_profile_picdate[$common_filename] = "?rev=".urlencode($r[0]['picdate']);
881 $this->cached_profile_image[$avatar_image] = $avatar_image.$this->cached_profile_picdate[$common_filename];
884 return $this->cached_profile_image[$avatar_image];
889 * @brief Register template engine class
891 * If $name is "", is used class static property $class::$name
893 * @param string $class
894 * @param string $name
896 function register_template_engine($class, $name = '') {
898 $v = get_class_vars( $class );
899 if(x($v,"name")) $name = $v['name'];
902 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
905 $this->template_engines[$name] = $class;
909 * @brief Return template engine instance.
911 * If $name is not defined, return engine defined by theme,
914 * @param strin $name Template engine name
915 * @return object Template Engine instance
917 function template_engine($name = ''){
919 $template_engine = $name;
921 $template_engine = 'smarty3';
922 if (x($this->theme, 'template_engine')) {
923 $template_engine = $this->theme['template_engine'];
927 if (isset($this->template_engines[$template_engine])){
928 if(isset($this->template_engine_instance[$template_engine])){
929 return $this->template_engine_instance[$template_engine];
931 $class = $this->template_engines[$template_engine];
933 $this->template_engine_instance[$template_engine] = $obj;
938 echo "template engine <tt>$template_engine</tt> is not registered!\n"; killme();
942 * @brief Returns the active template engine.
946 function get_template_engine() {
947 return $this->theme['template_engine'];
950 function set_template_engine($engine = 'smarty3') {
951 $this->theme['template_engine'] = $engine;
953 $this->theme['template_engine'] = 'smarty3';
957 if(is_writable('view/smarty3/'))
958 $this->theme['template_engine'] = 'smarty3';
966 function get_template_ldelim($engine = 'smarty3') {
967 return $this->ldelim[$engine];
970 function get_template_rdelim($engine = 'smarty3') {
971 return $this->rdelim[$engine];
974 function save_timestamp($stamp, $value) {
975 $duration = (float)(microtime(true)-$stamp);
977 $this->performance[$value] += (float)$duration;
978 $this->performance["marktime"] += (float)$duration;
981 function mark_timestamp($mark) {
982 //$this->performance["markstart"] -= microtime(true) - $this->performance["marktime"];
983 $this->performance["markstart"] = microtime(true) - $this->performance["markstart"] - $this->performance["marktime"];
986 function get_useragent() {
987 return(FRIENDICA_PLATFORM." '".FRIENDICA_CODENAME."' ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION."; ".$this->get_baseurl());
990 function is_friendica_app() {
991 return($this->is_friendica_app);
997 * @brief Retrieve the App structure
999 * Useful in functions which require it but don't get it passed to them
1001 function get_app() {
1008 * @brief Multi-purpose function to check variable state.
1010 * Usage: x($var) or $x($array, 'key')
1012 * returns false if variable/key is not set
1013 * if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
1014 * e.g. x('') or x(0) returns 0;
1016 * @param string|array $s variable to check
1017 * @param string $k key inside the array to check
1021 function x($s,$k = NULL) {
1023 if((is_array($s)) && (array_key_exists($k,$s))) {
1043 * @brief Called from db initialisation if db is dead.
1045 function system_unavailable() {
1046 include('system_unavailable.php');
1052 function clean_urls() {
1054 // if($a->config['system']['clean_urls'])
1061 $base = $a->get_baseurl();
1068 * @brief Returns the baseurl.
1070 * @see App::get_baseurl()
1076 return $a->get_baseurl();
1080 * @brief Return absolut URL for given $path.
1082 * @param string $path
1086 function absurl($path) {
1087 if(strpos($path,'/') === 0)
1088 return z_path() . $path;
1093 * @brief Function to check if request was an AJAX (xmlhttprequest) request.
1097 function is_ajax() {
1098 return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
1101 function check_db() {
1103 $build = get_config('system','build');
1105 set_config('system','build',DB_UPDATE_VERSION);
1106 $build = DB_UPDATE_VERSION;
1108 if($build != DB_UPDATE_VERSION)
1109 proc_run('php', 'include/dbupdate.php');
1115 * Sets the base url for use in cmdline programs which don't have
1116 * $_SERVER variables
1118 function check_url(&$a) {
1120 $url = get_config('system','url');
1122 // if the url isn't set or the stored url is radically different
1123 // than the currently visited url, store the current value accordingly.
1124 // "Radically different" ignores common variations such as http vs https
1125 // and www.example.com vs example.com.
1126 // We will only change the url to an ip address if there is no existing setting
1129 $url = set_config('system','url',$a->get_baseurl());
1130 if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
1131 $url = set_config('system','url',$a->get_baseurl());
1138 * @brief Automatic database updates
1140 function update_db(&$a) {
1141 $build = get_config('system','build');
1143 $build = set_config('system','build',DB_UPDATE_VERSION);
1145 if($build != DB_UPDATE_VERSION) {
1146 $stored = intval($build);
1147 $current = intval(DB_UPDATE_VERSION);
1148 if($stored < $current) {
1149 load_config('database');
1151 // We're reporting a different version than what is currently installed.
1152 // Run any existing update scripts to bring the database up to current.
1154 // make sure that boot.php and update.php are the same release, we might be
1155 // updating right this very second and the correct version of the update.php
1156 // file may not be here yet. This can happen on a very busy site.
1158 if(DB_UPDATE_VERSION == UPDATE_VERSION) {
1159 // Compare the current structure with the defined structure
1161 $t = get_config('database','dbupdate_'.DB_UPDATE_VERSION);
1165 set_config('database','dbupdate_'.DB_UPDATE_VERSION, time());
1167 // run old update routine (wich could modify the schema and
1168 // conflits with new routine)
1169 for ($x = $stored; $x < NEW_UPDATE_ROUTINE_VERSION; $x++) {
1170 $r = run_update_function($x);
1173 if ($stored < NEW_UPDATE_ROUTINE_VERSION) $stored = NEW_UPDATE_ROUTINE_VERSION;
1176 // run new update routine
1177 // it update the structure in one call
1178 $retval = update_structure(false, true);
1186 set_config('database','dbupdate_'.DB_UPDATE_VERSION, 'success');
1189 // run any left update_nnnn functions in update.php
1190 for($x = $stored; $x < $current; $x ++) {
1191 $r = run_update_function($x);
1201 function run_update_function($x) {
1202 if(function_exists('update_' . $x)) {
1204 // There could be a lot of processes running or about to run.
1205 // We want exactly one process to run the update command.
1206 // So store the fact that we're taking responsibility
1207 // after first checking to see if somebody else already has.
1209 // If the update fails or times-out completely you may need to
1210 // delete the config entry to try again.
1212 $t = get_config('database','update_' . $x);
1215 set_config('database','update_' . $x, time());
1217 // call the specific update
1219 $func = 'update_' . $x;
1223 //send the administrator an e-mail
1226 sprintf(t('Update %s failed. See error logs.'), $x)
1230 set_config('database','update_' . $x, 'success');
1231 set_config('system','build', $x + 1);
1235 set_config('database','update_' . $x, 'success');
1236 set_config('system','build', $x + 1);
1243 function check_plugins(&$a) {
1247 * Synchronise plugins:
1249 * $a->config['system']['addon'] contains a comma-separated list of names
1250 * of plugins/addons which are used on this system.
1251 * Go through the database list of already installed addons, and if we have
1252 * an entry, but it isn't in the config list, call the uninstall procedure
1253 * and mark it uninstalled in the database (for now we'll remove it).
1254 * Then go through the config list and if we have a plugin that isn't installed,
1255 * call the install procedure and add it to the database.
1259 $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
1263 $installed = array();
1265 $plugins = get_config('system','addon');
1266 $plugins_arr = array();
1269 $plugins_arr = explode(',',str_replace(' ', '',$plugins));
1271 $a->plugins = $plugins_arr;
1273 $installed_arr = array();
1275 if(count($installed)) {
1276 foreach($installed as $i) {
1277 if(! in_array($i['name'],$plugins_arr)) {
1278 uninstall_plugin($i['name']);
1281 $installed_arr[] = $i['name'];
1286 if(count($plugins_arr)) {
1287 foreach($plugins_arr as $p) {
1288 if(! in_array($p,$installed_arr)) {
1300 function get_guid($size=16, $prefix = "") {
1302 if ($prefix == "") {
1304 $prefix = hash("crc32", $a->get_hostname());
1307 while (strlen($prefix) < ($size - 13))
1308 $prefix .= mt_rand();
1311 $prefix = substr($prefix, 0, $size - 22);
1312 return(str_replace(".", "", uniqid($prefix, true)));
1314 $prefix = substr($prefix, 0, $size - 13);
1315 return(uniqid($prefix));
1320 * @brief Wrapper for adding a login box.
1322 * @param bool $register
1323 * If $register == true provide a registration link.
1324 * This will most always depend on the value of $a->config['register_policy'].
1325 * @param bool $hiddens
1328 * Returns the complete html for inserting into the page
1330 * @hooks 'login_hook'
1333 function login($register = false, $hiddens=false) {
1339 'title' => t('Create a New Account'),
1340 'desc' => t('Register')
1344 $noid = get_config('system','no_openid');
1346 $dest_url = $a->get_baseurl(true) . '/' . $a->query_string;
1349 $tpl = get_markup_template("logout.tpl");
1352 $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
1353 '$baseurl' => $a->get_baseurl(true)
1356 $tpl = get_markup_template("login.tpl");
1357 $_SESSION['return_url'] = $a->query_string;
1358 $a->module = 'login';
1361 $o .= replace_macros($tpl, array(
1363 '$dest_url' => $dest_url,
1364 '$logout' => t('Logout'),
1365 '$login' => t('Login'),
1367 '$lname' => array('username', t('Nickname or Email address: ') , '', ''),
1368 '$lpassword' => array('password', t('Password: '), '', ''),
1369 '$lremember' => array('remember', t('Remember me'), 0, ''),
1371 '$openid' => !$noid,
1372 '$lopenid' => array('openid_url', t('Or login using OpenID: '),'',''),
1374 '$hiddens' => $hiddens,
1376 '$register' => $reg,
1378 '$lostpass' => t('Forgot your password?'),
1379 '$lostlink' => t('Password Reset'),
1381 '$tostitle' => t('Website Terms of Service'),
1382 '$toslink' => t('terms of service'),
1384 '$privacytitle' => t('Website Privacy Policy'),
1385 '$privacylink' => t('privacy policy'),
1389 call_hooks('login_hook',$o);
1395 * @brief Used to end the current process, after saving session state.
1398 session_write_close();
1403 * @brief Redirect to another URL and terminate this process.
1405 function goaway($s) {
1406 header("Location: $s");
1412 * @brief Returns the user id of locally logged in user or false.
1414 * @return int|bool user id or false
1416 function local_user() {
1417 if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
1418 return intval($_SESSION['uid']);
1423 * @brief Returns contact id of authenticated site visitor or false
1425 * @return int|bool visitor_id or false
1427 function remote_user() {
1428 if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
1429 return intval($_SESSION['visitor_id']);
1434 * @brief Show an error message to user.
1436 * This function save text in session, to be shown to the user at next page load
1438 * @param string $s - Text of notice
1440 function notice($s) {
1442 if(! x($_SESSION,'sysmsg')) $_SESSION['sysmsg'] = array();
1444 $_SESSION['sysmsg'][] = $s;
1448 * @brief Show an info message to user.
1450 * This function save text in session, to be shown to the user at next page load
1452 * @param string $s - Text of notice
1457 if (local_user() AND get_pconfig(local_user(),'system','ignore_info'))
1460 if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
1462 $_SESSION['sysmsg_info'][] = $s;
1467 * @brief Wrapper around config to limit the text length of an incoming message
1471 function get_max_import_size() {
1473 return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
1477 * @brief Wrap calls to proc_close(proc_open()) and call hook
1478 * so plugins can take part in process :)
1480 * @param string $cmd program to run
1482 * next args are passed as $cmd command line
1483 * e.g.: proc_run("ls","-la","/tmp");
1485 * @note $cmd and string args are surrounded with ""
1490 function proc_run($cmd){
1494 $args = func_get_args();
1500 // expand any arrays
1502 foreach($args as $arg) {
1503 if(is_array($arg)) {
1504 foreach($arg as $n) {
1514 $arr = array('args' => $args, 'run_cmd' => true);
1516 call_hooks("proc_run", $arr);
1517 if(! $arr['run_cmd'])
1520 if(count($args) && $args[0] === 'php') {
1522 if (get_config("system", "worker")) {
1526 $parameters = json_encode($argv);
1527 $found = q("SELECT `id` FROM `workerqueue` WHERE `parameter` = '%s'",
1528 dbesc($parameters));
1531 q("INSERT INTO `workerqueue` (`parameter`, `created`, `priority`)
1532 VALUES ('%s', '%s', %d)",
1534 dbesc(datetime_convert()),
1537 // Should we quit and wait for the poller to be called as a cronjob?
1538 if (get_config("system", "worker_dont_fork"))
1541 // Checking number of workers
1542 $workers = q("SELECT COUNT(*) AS `workers` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
1544 // Get number of allowed number of worker threads
1545 $queues = intval(get_config("system", "worker_queues"));
1550 // If there are already enough workers running, don't fork another one
1551 if ($workers[0]["workers"] >= $queues)
1554 // Now call the poller to execute the jobs that we just added to the queue
1555 $args = array("php", "include/poller.php", "no_cron");
1558 $args[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
1561 // add baseurl to args. cli scripts can't construct it
1562 $args[] = $a->get_baseurl();
1564 for($x = 0; $x < count($args); $x ++)
1565 $args[$x] = escapeshellarg($args[$x]);
1567 $cmdline = implode($args," ");
1569 if(get_config('system','proc_windows'))
1570 proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
1572 proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
1575 function current_theme(){
1576 $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
1582 // Find the theme that belongs to the user whose stuff we are looking at
1584 if($a->profile_uid && ($a->profile_uid != local_user())) {
1585 $r = q("select theme from user where uid = %d limit 1",
1586 intval($a->profile_uid)
1589 $page_theme = $r[0]['theme'];
1592 // Allow folks to over-rule user themes and always use their own on their own site.
1593 // This works only if the user is on the same server
1595 if($page_theme && local_user() && (local_user() != $a->profile_uid)) {
1596 if(get_pconfig(local_user(),'system','always_my_theme'))
1600 // $mobile_detect = new Mobile_Detect();
1601 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1602 $is_mobile = $a->is_mobile || $a->is_tablet;
1604 $standard_system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1605 $standard_theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $standard_system_theme);
1608 if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
1609 $system_theme = $standard_system_theme;
1610 $theme_name = $standard_theme_name;
1613 $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : $standard_system_theme);
1614 $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
1616 if($theme_name === '---') {
1617 // user has selected to have the mobile theme be the same as the normal one
1618 $system_theme = $standard_system_theme;
1619 $theme_name = $standard_theme_name;
1622 $theme_name = $page_theme;
1627 $system_theme = $standard_system_theme;
1628 $theme_name = $standard_theme_name;
1631 $theme_name = $page_theme;
1635 (file_exists('view/theme/' . $theme_name . '/style.css') ||
1636 file_exists('view/theme/' . $theme_name . '/style.php')))
1637 return($theme_name);
1639 foreach($app_base_themes as $t) {
1640 if(file_exists('view/theme/' . $t . '/style.css')||
1641 file_exists('view/theme/' . $t . '/style.php'))
1645 $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
1646 if(count($fallback))
1647 return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
1652 * @brief Return full URL to theme which is currently in effect.
1654 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1658 function current_theme_url() {
1661 $t = current_theme();
1663 $opts = (($a->profile_uid) ? '?f=&puid=' . $a->profile_uid : '');
1664 if (file_exists('view/theme/' . $t . '/style.php'))
1665 return($a->get_baseurl() . '/view/theme/' . $t . '/style.pcss' . $opts);
1667 return($a->get_baseurl() . '/view/theme/' . $t . '/style.css');
1670 function feed_birthday($uid,$tz) {
1674 * Determine the next birthday, but only if the birthday is published
1675 * in the default profile. We _could_ also look for a private profile that the
1676 * recipient can see, but somebody could get mad at us if they start getting
1677 * public birthday greetings when they haven't made this info public.
1679 * Assuming we are able to publish this info, we are then going to convert
1680 * the start time from the owner's timezone to UTC.
1682 * This will potentially solve the problem found with some social networks
1683 * where birthdays are converted to the viewer's timezone and salutations from
1684 * elsewhere in the world show up on the wrong day. We will convert it to the
1685 * viewer's timezone also, but first we are going to convert it from the birthday
1686 * person's timezone to GMT - so the viewer may find the birthday starting at
1687 * 6:00PM the day before, but that will correspond to midnight to the birthday person.
1697 $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
1701 if($p && count($p)) {
1702 $tmp_dob = substr($p[0]['dob'],5);
1703 if(intval($tmp_dob)) {
1704 $y = datetime_convert($tz,$tz,'now','Y');
1705 $bd = $y . '-' . $tmp_dob . ' 00:00';
1706 $t_dob = strtotime($bd);
1707 $now = strtotime(datetime_convert($tz,$tz,'now'));
1709 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
1710 $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
1718 * @brief Check if current user has admin role.
1720 * @return bool true if user is an admin
1722 function is_site_admin() {
1725 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
1727 //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
1728 if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && in_array($a->user['email'], $adminlist))
1734 function load_contact_links($uid) {
1740 if(! $uid || x($a->contacts,'empty'))
1743 $r = q("SELECT `id`,`network`,`url`,`thumb`, `rel` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `thumb` != ''",
1748 $url = normalise_link($rr['url']);
1752 $ret['empty'] = true;
1754 $a->contacts = $ret;
1759 * @brief Returns querystring as string from a mapped array.
1761 * @param array $params mapped array with query parameters
1762 * @param string $name of parameter, default null
1766 function build_querystring($params, $name=null) {
1768 foreach($params as $key=>$val) {
1769 if(is_array($val)) {
1771 $ret .= build_querystring($val, $key);
1773 $ret .= build_querystring($val, $name."[$key]");
1776 $val = urlencode($val);
1778 $ret.=$name."[$key]"."=$val&";
1780 $ret.= "$key=$val&";
1787 function explode_querystring($query) {
1788 $arg_st = strpos($query, '?');
1789 if($arg_st !== false) {
1790 $base = substr($query, 0, $arg_st);
1797 $args = explode('&', substr($query, $arg_st));
1798 foreach($args as $k=>$arg) {
1802 $args = array_values($args);
1807 $args = array_values($args);
1817 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
1819 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
1821 function curPageURL() {
1823 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
1825 if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
1826 $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
1828 $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
1833 function random_digits($digits) {
1835 for($i = 0; $i < $digits; $i++) {
1841 function get_server() {
1842 $server = get_config("system", "directory");
1845 $server = "http://dir.friendi.ca";
1850 function get_cachefile($file, $writemode = true) {
1851 $cache = get_itemcachepath();
1853 if ((! $cache) || (! is_dir($cache)))
1856 $subfolder = $cache."/".substr($file, 0, 2);
1858 $cachepath = $subfolder."/".$file;
1861 if (!is_dir($subfolder)) {
1863 chmod($subfolder, 0777);
1870 function clear_cache($basepath = "", $path = "") {
1872 $basepath = get_itemcachepath();
1876 if (($path == "") OR (!is_dir($path)))
1879 if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
1882 $cachetime = (int)get_config('system','itemcache_duration');
1883 if ($cachetime == 0)
1886 if (is_writable($path)){
1887 if ($dh = opendir($path)) {
1888 while (($file = readdir($dh)) !== false) {
1889 $fullpath = $path."/".$file;
1890 if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
1891 clear_cache($basepath, $fullpath);
1892 if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
1900 function get_itemcachepath() {
1901 // Checking, if the cache is deactivated
1902 $cachetime = (int)get_config('system','itemcache_duration');
1906 $itemcache = get_config('system','itemcache');
1907 if (($itemcache != "") AND is_dir($itemcache) AND is_writable($itemcache))
1910 $temppath = get_temppath();
1912 if ($temppath != "") {
1913 $itemcache = $temppath."/itemcache";
1914 if(!file_exists($itemcache) && !is_dir($itemcache)) {
1918 if (is_dir($itemcache) AND is_writable($itemcache)) {
1919 set_config("system", "itemcache", $itemcache);
1926 function get_lockpath() {
1927 $lockpath = get_config('system','lockpath');
1928 if (($lockpath != "") AND is_dir($lockpath) AND is_writable($lockpath))
1931 $temppath = get_temppath();
1933 if ($temppath != "") {
1934 $lockpath = $temppath."/lock";
1936 if (!is_dir($lockpath))
1938 elseif (!is_writable($lockpath))
1939 $lockpath = $temppath;
1941 if (is_dir($lockpath) AND is_writable($lockpath)) {
1942 set_config("system", "lockpath", $lockpath);
1949 function get_temppath() {
1952 $temppath = get_config("system","temppath");
1953 if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath))
1956 $temppath = sys_get_temp_dir();
1957 if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath)) {
1958 $temppath .= "/".$a->get_hostname();
1959 if (!is_dir($temppath))
1962 if (is_dir($temppath) AND is_writable($temppath)) {
1963 set_config("system", "temppath", $temppath);
1971 function set_template_engine(&$a, $engine = 'internal') {
1972 // This function is no longer necessary, but keep it as a wrapper to the class method
1973 // to avoid breaking themes again unnecessarily
1975 $a->set_template_engine($engine);
1978 if(!function_exists('exif_imagetype')) {
1979 function exif_imagetype($file) {
1980 $size = getimagesize($file);
1985 function validate_include(&$file) {
1988 $file = realpath($file);
1990 if (strpos($file, getcwd()) !== 0)
1993 $file = str_replace(getcwd()."/", "", $file, $count);
1997 if ($orig_file !== $file)
2001 if (strpos($file, "include/") === 0)
2004 if (strpos($file, "addon/") === 0)
2013 function current_load() {
2014 if (!function_exists('sys_getloadavg'))
2017 $load_arr = sys_getloadavg();
2019 if (!is_array($load_arr))
2022 return max($load_arr);