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 );
40 define ( 'EOL', "<br />\r\n" );
41 define ( 'ATOM_TIME', 'Y-m-d\TH:i:s\Z' );
46 * Image storage quality. Lower numbers save space at cost of image detail.
47 * For ease of upgrade, please do not change here. Change jpeg quality with
48 * $a->config['system']['jpeg_quality'] = n;
49 * in .htconfig.php, where n is netween 1 and 100, and with very poor results
54 define ( 'JPEG_QUALITY', 100 );
56 * $a->config['system']['png_quality'] from 0 (uncompressed) to 9
58 define ( 'PNG_QUALITY', 8 );
62 * An alternate way of limiting picture upload sizes. Specify the maximum pixel
63 * length that pictures are allowed to be (for non-square pictures, it will apply
64 * to the longest side). Pictures longer than this length will be resized to be
65 * this length (on the longest side, the other side will be scaled appropriately).
66 * Modify this value using
68 * $a->config['system']['max_image_length'] = n;
72 * If you don't want to set a maximum length, set to -1. The default value is
73 * defined by 'MAX_IMAGE_LENGTH' below.
76 define ( 'MAX_IMAGE_LENGTH', -1 );
83 define ( 'DEFAULT_DB_ENGINE', 'MyISAM' );
86 * SSL redirection policies
89 define ( 'SSL_POLICY_NONE', 0 );
90 define ( 'SSL_POLICY_FULL', 1 );
91 define ( 'SSL_POLICY_SELFSIGN', 2 );
98 define ( 'LOGGER_NORMAL', 0 );
99 define ( 'LOGGER_TRACE', 1 );
100 define ( 'LOGGER_DEBUG', 2 );
101 define ( 'LOGGER_DATA', 3 );
102 define ( 'LOGGER_ALL', 4 );
108 define ( 'CACHE_MONTH', 0 );
109 define ( 'CACHE_WEEK', 1 );
110 define ( 'CACHE_DAY', 2 );
111 define ( 'CACHE_HOUR', 3 );
114 * registration policies
117 define ( 'REGISTER_CLOSED', 0 );
118 define ( 'REGISTER_APPROVE', 1 );
119 define ( 'REGISTER_OPEN', 2 );
125 define ( 'CONTACT_IS_FOLLOWER', 1);
126 define ( 'CONTACT_IS_SHARING', 2);
127 define ( 'CONTACT_IS_FRIEND', 3);
131 * DB update return values
134 define ( 'UPDATE_SUCCESS', 0);
135 define ( 'UPDATE_FAILED', 1);
142 * PAGE_NORMAL is a typical personal profile account
143 * PAGE_SOAPBOX automatically approves all friend requests as CONTACT_IS_SHARING, (readonly)
144 * PAGE_COMMUNITY automatically approves all friend requests as CONTACT_IS_SHARING, but with
145 * write access to wall and comments (no email and not included in page owner's ACL lists)
146 * PAGE_FREELOVE automatically approves all friend requests as full friends (CONTACT_IS_FRIEND).
150 define ( 'PAGE_NORMAL', 0 );
151 define ( 'PAGE_SOAPBOX', 1 );
152 define ( 'PAGE_COMMUNITY', 2 );
153 define ( 'PAGE_FREELOVE', 3 );
154 define ( 'PAGE_BLOG', 4 );
155 define ( 'PAGE_PRVGROUP', 5 );
157 // Type of the community page
158 define ( 'CP_NO_COMMUNITY_PAGE', -1 );
159 define ( 'CP_USERS_ON_SERVER', 0 );
160 define ( 'CP_GLOBAL_COMMUNITY', 1 );
163 * Network and protocol family types
166 define ( 'NETWORK_DFRN', 'dfrn'); // Friendica, Mistpark, other DFRN implementations
167 define ( 'NETWORK_ZOT', 'zot!'); // Zot!
168 define ( 'NETWORK_OSTATUS', 'stat'); // status.net, identi.ca, GNU-social, other OStatus implementations
169 define ( 'NETWORK_FEED', 'feed'); // RSS/Atom feeds with no known "post/notify" protocol
170 define ( 'NETWORK_DIASPORA', 'dspr'); // Diaspora
171 define ( 'NETWORK_MAIL', 'mail'); // IMAP/POP
172 define ( 'NETWORK_MAIL2', 'mai2'); // extended IMAP/POP
173 define ( 'NETWORK_FACEBOOK', 'face'); // Facebook API
174 define ( 'NETWORK_LINKEDIN', 'lnkd'); // LinkedIn
175 define ( 'NETWORK_XMPP', 'xmpp'); // XMPP
176 define ( 'NETWORK_MYSPACE', 'mysp'); // MySpace
177 define ( 'NETWORK_GPLUS', 'goog'); // Google+
178 define ( 'NETWORK_PUMPIO', 'pump'); // pump.io
179 define ( 'NETWORK_TWITTER', 'twit'); // Twitter
180 define ( 'NETWORK_DIASPORA2', 'dspc'); // Diaspora connector
181 define ( 'NETWORK_STATUSNET', 'stac'); // Statusnet connector
182 define ( 'NETWORK_APPNET', 'apdn'); // app.net
183 define ( 'NETWORK_NEWS', 'nntp'); // Network News Transfer Protocol
184 define ( 'NETWORK_ICALENDAR', 'ical'); // iCalendar
185 define ( 'NETWORK_PHANTOM', 'unkn'); // Place holder
188 * These numbers are used in stored permissions
189 * and existing allocations MUST NEVER BE CHANGED
190 * OR RE-ASSIGNED! You may only add to them.
193 $netgroup_ids = array(
194 NETWORK_DFRN => (-1),
196 NETWORK_OSTATUS => (-3),
197 NETWORK_FEED => (-4),
198 NETWORK_DIASPORA => (-5),
199 NETWORK_MAIL => (-6),
200 NETWORK_MAIL2 => (-7),
201 NETWORK_FACEBOOK => (-8),
202 NETWORK_LINKEDIN => (-9),
203 NETWORK_XMPP => (-10),
204 NETWORK_MYSPACE => (-11),
205 NETWORK_GPLUS => (-12),
206 NETWORK_PUMPIO => (-13),
207 NETWORK_TWITTER => (-14),
208 NETWORK_DIASPORA2 => (-15),
209 NETWORK_STATUSNET => (-16),
210 NETWORK_APPNET => (-17),
211 NETWORK_NEWS => (-18),
212 NETWORK_ICALENDAR => (-19),
214 NETWORK_PHANTOM => (-127),
219 * Maximum number of "people who like (or don't like) this" that we will list by name
222 define ( 'MAX_LIKERS', 75);
225 * Communication timeout
228 define ( 'ZCURL_TIMEOUT' , (-1));
232 * email notification options
235 define ( 'NOTIFY_INTRO', 0x0001 );
236 define ( 'NOTIFY_CONFIRM', 0x0002 );
237 define ( 'NOTIFY_WALL', 0x0004 );
238 define ( 'NOTIFY_COMMENT', 0x0008 );
239 define ( 'NOTIFY_MAIL', 0x0010 );
240 define ( 'NOTIFY_SUGGEST', 0x0020 );
241 define ( 'NOTIFY_PROFILE', 0x0040 );
242 define ( 'NOTIFY_TAGSELF', 0x0080 );
243 define ( 'NOTIFY_TAGSHARE', 0x0100 );
244 define ( 'NOTIFY_POKE', 0x0200 );
245 define ( 'NOTIFY_SHARE', 0x0400 );
247 define ( 'NOTIFY_SYSTEM', 0x8000 );
254 define ( 'TERM_UNKNOWN', 0 );
255 define ( 'TERM_HASHTAG', 1 );
256 define ( 'TERM_MENTION', 2 );
257 define ( 'TERM_CATEGORY', 3 );
258 define ( 'TERM_PCATEGORY', 4 );
259 define ( 'TERM_FILE', 5 );
260 define ( 'TERM_SAVEDSEARCH', 6 );
261 define ( 'TERM_CONVERSATION', 7 );
263 define ( 'TERM_OBJ_POST', 1 );
264 define ( 'TERM_OBJ_PHOTO', 2 );
269 * various namespaces we may need to parse
272 define ( 'NAMESPACE_ZOT', 'http://purl.org/zot' );
273 define ( 'NAMESPACE_DFRN' , 'http://purl.org/macgirvin/dfrn/1.0' );
274 define ( 'NAMESPACE_THREAD' , 'http://purl.org/syndication/thread/1.0' );
275 define ( 'NAMESPACE_TOMB' , 'http://purl.org/atompub/tombstones/1.0' );
276 define ( 'NAMESPACE_ACTIVITY', 'http://activitystrea.ms/spec/1.0/' );
277 define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/' );
278 define ( 'NAMESPACE_MEDIA', 'http://purl.org/syndication/atommedia' );
279 define ( 'NAMESPACE_SALMON_ME', 'http://salmon-protocol.org/ns/magic-env' );
280 define ( 'NAMESPACE_OSTATUSSUB', 'http://ostatus.org/schema/1.0/subscribe' );
281 define ( 'NAMESPACE_GEORSS', 'http://www.georss.org/georss' );
282 define ( 'NAMESPACE_POCO', 'http://portablecontacts.net/spec/1.0' );
283 define ( 'NAMESPACE_FEED', 'http://schemas.google.com/g/2010#updates-from' );
284 define ( 'NAMESPACE_OSTATUS', 'http://ostatus.org/schema/1.0' );
285 define ( 'NAMESPACE_STATUSNET', 'http://status.net/schema/api/1/' );
286 define ( 'NAMESPACE_ATOM1', 'http://www.w3.org/2005/Atom' );
288 * activity stream defines
291 define ( 'ACTIVITY_LIKE', NAMESPACE_ACTIVITY_SCHEMA . 'like' );
292 define ( 'ACTIVITY_DISLIKE', NAMESPACE_DFRN . '/dislike' );
293 define ( 'ACTIVITY_ATTEND', NAMESPACE_ZOT . '/activity/attendyes' );
294 define ( 'ACTIVITY_ATTENDNO', NAMESPACE_ZOT . '/activity/attendno' );
295 define ( 'ACTIVITY_ATTENDMAYBE', NAMESPACE_ZOT . '/activity/attendmaybe' );
297 define ( 'ACTIVITY_OBJ_HEART', NAMESPACE_DFRN . '/heart' );
299 define ( 'ACTIVITY_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
300 define ( 'ACTIVITY_REQ_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'request-friend' );
301 define ( 'ACTIVITY_UNFRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'remove-friend' );
302 define ( 'ACTIVITY_FOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'follow' );
303 define ( 'ACTIVITY_UNFOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'stop-following' );
304 define ( 'ACTIVITY_JOIN', NAMESPACE_ACTIVITY_SCHEMA . 'join' );
306 define ( 'ACTIVITY_POST', NAMESPACE_ACTIVITY_SCHEMA . 'post' );
307 define ( 'ACTIVITY_UPDATE', NAMESPACE_ACTIVITY_SCHEMA . 'update' );
308 define ( 'ACTIVITY_TAG', NAMESPACE_ACTIVITY_SCHEMA . 'tag' );
309 define ( 'ACTIVITY_FAVORITE', NAMESPACE_ACTIVITY_SCHEMA . 'favorite' );
310 define ( 'ACTIVITY_SHARE', NAMESPACE_ACTIVITY_SCHEMA . 'share' );
312 define ( 'ACTIVITY_POKE', NAMESPACE_ZOT . '/activity/poke' );
313 define ( 'ACTIVITY_MOOD', NAMESPACE_ZOT . '/activity/mood' );
315 define ( 'ACTIVITY_OBJ_BOOKMARK', NAMESPACE_ACTIVITY_SCHEMA . 'bookmark' );
316 define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
317 define ( 'ACTIVITY_OBJ_NOTE', NAMESPACE_ACTIVITY_SCHEMA . 'note' );
318 define ( 'ACTIVITY_OBJ_PERSON', NAMESPACE_ACTIVITY_SCHEMA . 'person' );
319 define ( 'ACTIVITY_OBJ_IMAGE', NAMESPACE_ACTIVITY_SCHEMA . 'image' );
320 define ( 'ACTIVITY_OBJ_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
321 define ( 'ACTIVITY_OBJ_VIDEO', NAMESPACE_ACTIVITY_SCHEMA . 'video' );
322 define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
323 define ( 'ACTIVITY_OBJ_ALBUM', NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
324 define ( 'ACTIVITY_OBJ_EVENT', NAMESPACE_ACTIVITY_SCHEMA . 'event' );
325 define ( 'ACTIVITY_OBJ_GROUP', NAMESPACE_ACTIVITY_SCHEMA . 'group' );
326 define ( 'ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN . '/tagterm' );
327 define ( 'ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN . '/profile' );
328 define ( 'ACTIVITY_OBJ_QUESTION', 'http://activityschema.org/object/question' );
331 * item weight for query ordering
334 define ( 'GRAVITY_PARENT', 0);
335 define ( 'GRAVITY_LIKE', 3);
336 define ( 'GRAVITY_COMMENT', 6);
340 * Reverse the effect of magic_quotes_gpc if it is enabled.
341 * Please disable magic_quotes_gpc so we don't have to do this.
342 * See http://php.net/manual/en/security.magicquotes.disabling.php
348 error_reporting(E_ERROR | E_WARNING | E_PARSE);
352 // This has to be quite large to deal with embedded private photos
353 ini_set('pcre.backtrack_limit', 500000);
356 if (get_magic_quotes_gpc()) {
357 $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
358 while (list($key, $val) = each($process)) {
359 foreach ($val as $k => $v) {
360 unset($process[$key][$k]);
362 $process[$key][stripslashes($k)] = $v;
363 $process[] = &$process[$key][stripslashes($k)];
365 $process[$key][stripslashes($k)] = stripslashes($v);
378 * @brief Our main application structure for the life of this page.
380 * Primarily deals with the URL that got us here
381 * and tries to make some sense of it, and
382 * stores our page contents and config storage
383 * and anything else that might need to be passed around
384 * before we spit the page out.
389 public $module_loaded = false;
390 public $query_string;
399 public $page_contact;
401 public $data = array();
402 public $error = false;
412 public $interactive = true;
414 public $apps = array();
418 public $is_friendica_app;
419 public $performance = array();
426 // Allow themes to control internal parameters
427 // by changing App values in theme.php
429 public $sourcename = '';
430 public $videowidth = 425;
431 public $videoheight = 350;
432 public $force_max_items = 0;
433 public $theme_thread_allow = true;
434 public $theme_events_in_profile = true;
437 * @brief An array for all theme-controllable parameters
439 * Mostly unimplemented yet. Only options 'template_engine' and
442 public $theme = array(
445 'videoheight' => 350,
446 'force_max_items' => 0,
447 'thread_allow' => true,
449 'template_engine' => 'smarty3',
453 * @brief An array of registered template engines ('name'=>'class name')
455 public $template_engines = array();
457 * @brief An array of instanced template engines ('name'=>'instance')
459 public $template_engine_instance = array();
461 private $ldelim = array(
465 private $rdelim = array(
476 private $curl_content_type;
477 private $curl_headers;
479 private $cached_profile_image;
480 private $cached_profile_picdate;
485 function __construct() {
487 global $default_timezone;
491 if (file_exists(".htpreconfig.php"))
492 @include(".htpreconfig.php");
494 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
496 date_default_timezone_set($this->timezone);
498 $this->performance["start"] = microtime(true);
499 $this->performance["database"] = 0;
500 $this->performance["network"] = 0;
501 $this->performance["file"] = 0;
502 $this->performance["rendering"] = 0;
503 $this->performance["parser"] = 0;
504 $this->performance["marktime"] = 0;
505 $this->performance["markstart"] = microtime(true);
507 $this->config = array();
508 $this->page = array();
509 $this->pager= array();
511 $this->query_string = '';
516 'include' . PATH_SEPARATOR
517 . 'library' . PATH_SEPARATOR
518 . 'library/phpsec' . PATH_SEPARATOR
519 . 'library/langdet' . PATH_SEPARATOR
523 $this->scheme = 'http';
524 if(x($_SERVER,'HTTPS') && $_SERVER['HTTPS'])
525 $this->scheme = 'https';
526 elseif(x($_SERVER,'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443))
527 $this->scheme = 'https';
529 if(x($_SERVER,'SERVER_NAME')) {
530 $this->hostname = $_SERVER['SERVER_NAME'];
532 // See bug 437 - this didn't work so disabling it
533 //if(stristr($this->hostname,'xn--')) {
534 // PHP or webserver may have converted idn to punycode, so
535 // convert punycode back to utf-8
536 // require_once('library/simplepie/idn/idna_convert.class.php');
537 // $x = new idna_convert();
538 // $this->hostname = $x->decode($_SERVER['SERVER_NAME']);
541 if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
542 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
544 * Figure out if we are running at the top of a domain
545 * or in a sub-directory and adjust accordingly
548 $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
549 if(isset($path) && strlen($path) && ($path != $this->path))
554 $this->hostname = $hostname;
556 if (is_array($_SERVER["argv"]) && $_SERVER["argc"]>1 && substr(end($_SERVER["argv"]), 0, 4)=="http" ) {
557 $this->set_baseurl(array_pop($_SERVER["argv"]) );
561 #set_include_path("include/$this->hostname" . PATH_SEPARATOR . get_include_path());
563 if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,9) === "pagename=") {
564 $this->query_string = substr($_SERVER['QUERY_STRING'],9);
565 // removing trailing / - maybe a nginx problem
566 if (substr($this->query_string, 0, 1) == "/")
567 $this->query_string = substr($this->query_string, 1);
568 } elseif((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
569 $this->query_string = substr($_SERVER['QUERY_STRING'],2);
570 // removing trailing / - maybe a nginx problem
571 if (substr($this->query_string, 0, 1) == "/")
572 $this->query_string = substr($this->query_string, 1);
575 if (x($_GET,'pagename'))
576 $this->cmd = trim($_GET['pagename'],'/\\');
577 elseif (x($_GET,'q'))
578 $this->cmd = trim($_GET['q'],'/\\');
582 $this->query_string = str_replace($this->cmd."&",$this->cmd."?", $this->query_string);
585 // unix style "homedir"
587 if(substr($this->cmd,0,1) === '~')
588 $this->cmd = 'profile/' . substr($this->cmd,1);
590 // Diaspora style profile url
592 if(substr($this->cmd,0,2) === 'u/')
593 $this->cmd = 'profile/' . substr($this->cmd,2);
598 * Break the URL path into C style argc/argv style arguments for our
599 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
600 * will be 3 (integer) and $this->argv will contain:
606 * There will always be one argument. If provided a naked domain
607 * URL, $this->argv[0] is set to "home".
611 $this->argv = explode('/',$this->cmd);
612 $this->argc = count($this->argv);
613 if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
614 $this->module = str_replace(".", "_", $this->argv[0]);
615 $this->module = str_replace("-", "_", $this->module);
619 $this->argv = array('home');
620 $this->module = 'home';
624 * See if there is any page number information, and initialise
628 $this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
629 $this->pager['itemspage'] = 50;
630 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
631 if($this->pager['start'] < 0)
632 $this->pager['start'] = 0;
633 $this->pager['total'] = 0;
636 * Detect mobile devices
639 $mobile_detect = new Mobile_Detect();
640 $this->is_mobile = $mobile_detect->isMobile();
641 $this->is_tablet = $mobile_detect->isTablet();
644 $this->is_friendica_app = ($_SERVER['HTTP_USER_AGENT'] == "Apache-HttpClient/UNAVAILABLE (java 1.4)");
647 * register template engines
649 $dc = get_declared_classes();
650 foreach ($dc as $k) {
651 if (in_array("ITemplateEngine", class_implements($k))){
652 $this->register_template_engine($k);
658 function get_basepath() {
660 $basepath = get_config("system", "basepath");
663 $basepath = dirname(__FILE__);
666 $basepath = $_SERVER["DOCUMENT_ROOT"];
669 $basepath = $_SERVER["PWD"];
674 function get_scheme() {
675 return($this->scheme);
678 function get_baseurl($ssl = false) {
680 $scheme = $this->scheme;
682 if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
683 if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
686 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
687 // (and also the login link). Anything seen by an outsider will have it turned off.
689 if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
697 if (get_config('config','hostname') != "")
698 $this->hostname = get_config('config','hostname');
700 $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
701 return $this->baseurl;
704 function set_baseurl($url) {
705 $parsed = @parse_url($url);
707 $this->baseurl = $url;
710 $this->scheme = $parsed['scheme'];
712 $hostname = $parsed['host'];
713 if(x($parsed,'port'))
714 $hostname .= ':' . $parsed['port'];
715 if(x($parsed,'path'))
716 $this->path = trim($parsed['path'],'\\/');
718 if (file_exists(".htpreconfig.php"))
719 @include(".htpreconfig.php");
721 if (get_config('config','hostname') != "")
722 $this->hostname = get_config('config','hostname');
724 if (!isset($this->hostname) OR ($this->hostname == ""))
725 $this->hostname = $hostname;
730 function get_hostname() {
731 if (get_config('config','hostname') != "")
732 $this->hostname = get_config('config','hostname');
734 return $this->hostname;
737 function set_hostname($h) {
738 $this->hostname = $h;
741 function set_path($p) {
742 $this->path = trim(trim($p),'/');
745 function get_path() {
749 function set_pager_total($n) {
750 $this->pager['total'] = intval($n);
753 function set_pager_itemspage($n) {
754 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
755 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
758 function set_pager_page($n) {
759 $this->pager['page'] = $n;
760 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
763 function init_pagehead() {
764 $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
766 // If the update is "deactivated" set it to the highest integer number (~24 days)
768 $interval = 2147483647;
770 if($interval < 10000)
773 // compose the page title from the sitename and the
774 // current module called
775 if (!$this->module=='')
777 $this->page['title'] = $this->config['sitename'].' ('.$this->module.')';
779 $this->page['title'] = $this->config['sitename'];
782 /* put the head template at the beginning of page['htmlhead']
783 * since the code added by the modules frequently depends on it
786 if(!isset($this->page['htmlhead']))
787 $this->page['htmlhead'] = '';
789 // If we're using Smarty, then doing replace_macros() will replace
790 // any unrecognized variables with a blank string. Since we delay
791 // replacing $stylesheet until later, we need to replace it now
792 // with another variable name
793 if($this->theme['template_engine'] === 'smarty3')
794 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
796 $stylesheet = '$stylesheet';
798 $shortcut_icon = get_config("system", "shortcut_icon");
799 if ($shortcut_icon == "")
800 $shortcut_icon = $this->get_baseurl()."/images/friendica-32.png";
802 $touch_icon = get_config("system", "touch_icon");
803 if ($touch_icon == "")
804 $touch_icon = $this->get_baseurl()."/images/friendica-128.png";
806 $tpl = get_markup_template('head.tpl');
807 $this->page['htmlhead'] = replace_macros($tpl,array(
808 '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
809 '$local_user' => local_user(),
810 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
811 '$delitem' => t('Delete this item?'),
812 '$comment' => t('Comment'),
813 '$showmore' => t('show more'),
814 '$showfewer' => t('show fewer'),
815 '$update_interval' => $interval,
816 '$shortcut_icon' => $shortcut_icon,
817 '$touch_icon' => $touch_icon,
818 '$stylesheet' => $stylesheet
819 )) . $this->page['htmlhead'];
822 function init_page_end() {
823 if(!isset($this->page['end']))
824 $this->page['end'] = '';
825 $tpl = get_markup_template('end.tpl');
826 $this->page['end'] = replace_macros($tpl,array(
827 '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
828 )) . $this->page['end'];
831 function set_curl_code($code) {
832 $this->curl_code = $code;
835 function get_curl_code() {
836 return $this->curl_code;
839 function set_curl_content_type($content_type) {
840 $this->curl_content_type = $content_type;
843 function get_curl_content_type() {
844 return $this->curl_content_type;
847 function set_curl_headers($headers) {
848 $this->curl_headers = $headers;
851 function get_curl_headers() {
852 return $this->curl_headers;
855 function get_cached_avatar_image($avatar_image){
856 if($this->cached_profile_image[$avatar_image])
857 return $this->cached_profile_image[$avatar_image];
859 $path_parts = explode("/",$avatar_image);
860 $common_filename = $path_parts[count($path_parts)-1];
862 if($this->cached_profile_picdate[$common_filename]){
863 $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
865 $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like '%%/%s'",
868 $this->cached_profile_image[$avatar_image] = $avatar_image;
870 $this->cached_profile_picdate[$common_filename] = "?rev=".urlencode($r[0]['picdate']);
871 $this->cached_profile_image[$avatar_image] = $avatar_image.$this->cached_profile_picdate[$common_filename];
874 return $this->cached_profile_image[$avatar_image];
879 * @brief Register template engine class
881 * If $name is "", is used class static property $class::$name
883 * @param string $class
884 * @param string $name
886 function register_template_engine($class, $name = '') {
888 $v = get_class_vars( $class );
889 if(x($v,"name")) $name = $v['name'];
892 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
895 $this->template_engines[$name] = $class;
899 * @brief Return template engine instance.
901 * If $name is not defined, return engine defined by theme,
904 * @param strin $name Template engine name
905 * @return object Template Engine instance
907 function template_engine($name = ''){
909 $template_engine = $name;
911 $template_engine = 'smarty3';
912 if (x($this->theme, 'template_engine')) {
913 $template_engine = $this->theme['template_engine'];
917 if (isset($this->template_engines[$template_engine])){
918 if(isset($this->template_engine_instance[$template_engine])){
919 return $this->template_engine_instance[$template_engine];
921 $class = $this->template_engines[$template_engine];
923 $this->template_engine_instance[$template_engine] = $obj;
928 echo "template engine <tt>$template_engine</tt> is not registered!\n"; killme();
932 * @brief Returns the active template engine.
936 function get_template_engine() {
937 return $this->theme['template_engine'];
940 function set_template_engine($engine = 'smarty3') {
941 $this->theme['template_engine'] = $engine;
943 $this->theme['template_engine'] = 'smarty3';
947 if(is_writable('view/smarty3/'))
948 $this->theme['template_engine'] = 'smarty3';
956 function get_template_ldelim($engine = 'smarty3') {
957 return $this->ldelim[$engine];
960 function get_template_rdelim($engine = 'smarty3') {
961 return $this->rdelim[$engine];
964 function save_timestamp($stamp, $value) {
965 $duration = (float)(microtime(true)-$stamp);
967 $this->performance[$value] += (float)$duration;
968 $this->performance["marktime"] += (float)$duration;
971 function mark_timestamp($mark) {
972 //$this->performance["markstart"] -= microtime(true) - $this->performance["marktime"];
973 $this->performance["markstart"] = microtime(true) - $this->performance["markstart"] - $this->performance["marktime"];
976 function get_useragent() {
977 return(FRIENDICA_PLATFORM." '".FRIENDICA_CODENAME."' ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION."; ".$this->get_baseurl());
980 function is_friendica_app() {
981 return($this->is_friendica_app);
987 * @brief Retrieve the App structure
989 * Useful in functions which require it but don't get it passed to them
998 * @brief Multi-purpose function to check variable state.
1000 * Usage: x($var) or $x($array, 'key')
1002 * returns false if variable/key is not set
1003 * if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
1004 * e.g. x('') or x(0) returns 0;
1006 * @param string|array $s variable to check
1007 * @param string $k key inside the array to check
1011 function x($s,$k = NULL) {
1013 if((is_array($s)) && (array_key_exists($k,$s))) {
1033 * @brief Called from db initialisation if db is dead.
1035 function system_unavailable() {
1036 include('system_unavailable.php');
1042 function clean_urls() {
1044 // if($a->config['system']['clean_urls'])
1051 $base = $a->get_baseurl();
1058 * @brief Returns the baseurl.
1060 * @see App::get_baseurl()
1066 return $a->get_baseurl();
1070 * @brief Return absolut URL for given $path.
1072 * @param string $path
1076 function absurl($path) {
1077 if(strpos($path,'/') === 0)
1078 return z_path() . $path;
1083 * @brief Function to check if request was an AJAX (xmlhttprequest) request.
1087 function is_ajax() {
1088 return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
1091 function check_db() {
1093 $build = get_config('system','build');
1095 set_config('system','build',DB_UPDATE_VERSION);
1096 $build = DB_UPDATE_VERSION;
1098 if($build != DB_UPDATE_VERSION)
1099 proc_run('php', 'include/dbupdate.php');
1105 * Sets the base url for use in cmdline programs which don't have
1106 * $_SERVER variables
1108 function check_url(&$a) {
1110 $url = get_config('system','url');
1112 // if the url isn't set or the stored url is radically different
1113 // than the currently visited url, store the current value accordingly.
1114 // "Radically different" ignores common variations such as http vs https
1115 // and www.example.com vs example.com.
1116 // We will only change the url to an ip address if there is no existing setting
1119 $url = set_config('system','url',$a->get_baseurl());
1120 if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
1121 $url = set_config('system','url',$a->get_baseurl());
1128 * @brief Automatic database updates
1130 function update_db(&$a) {
1131 $build = get_config('system','build');
1133 $build = set_config('system','build',DB_UPDATE_VERSION);
1135 if($build != DB_UPDATE_VERSION) {
1136 $stored = intval($build);
1137 $current = intval(DB_UPDATE_VERSION);
1138 if($stored < $current) {
1139 load_config('database');
1141 // We're reporting a different version than what is currently installed.
1142 // Run any existing update scripts to bring the database up to current.
1144 // make sure that boot.php and update.php are the same release, we might be
1145 // updating right this very second and the correct version of the update.php
1146 // file may not be here yet. This can happen on a very busy site.
1148 if(DB_UPDATE_VERSION == UPDATE_VERSION) {
1149 // Compare the current structure with the defined structure
1151 $t = get_config('database','dbupdate_'.DB_UPDATE_VERSION);
1155 set_config('database','dbupdate_'.DB_UPDATE_VERSION, time());
1157 // run old update routine (wich could modify the schema and
1158 // conflits with new routine)
1159 for ($x = $stored; $x < NEW_UPDATE_ROUTINE_VERSION; $x++) {
1160 $r = run_update_function($x);
1163 if ($stored < NEW_UPDATE_ROUTINE_VERSION) $stored = NEW_UPDATE_ROUTINE_VERSION;
1166 // run new update routine
1167 // it update the structure in one call
1168 $retval = update_structure(false, true);
1176 set_config('database','dbupdate_'.DB_UPDATE_VERSION, 'success');
1179 // run any left update_nnnn functions in update.php
1180 for($x = $stored; $x < $current; $x ++) {
1181 $r = run_update_function($x);
1191 function run_update_function($x) {
1192 if(function_exists('update_' . $x)) {
1194 // There could be a lot of processes running or about to run.
1195 // We want exactly one process to run the update command.
1196 // So store the fact that we're taking responsibility
1197 // after first checking to see if somebody else already has.
1199 // If the update fails or times-out completely you may need to
1200 // delete the config entry to try again.
1202 $t = get_config('database','update_' . $x);
1205 set_config('database','update_' . $x, time());
1207 // call the specific update
1209 $func = 'update_' . $x;
1213 //send the administrator an e-mail
1216 sprintf(t('Update %s failed. See error logs.'), $x)
1220 set_config('database','update_' . $x, 'success');
1221 set_config('system','build', $x + 1);
1225 set_config('database','update_' . $x, 'success');
1226 set_config('system','build', $x + 1);
1233 function check_plugins(&$a) {
1237 * Synchronise plugins:
1239 * $a->config['system']['addon'] contains a comma-separated list of names
1240 * of plugins/addons which are used on this system.
1241 * Go through the database list of already installed addons, and if we have
1242 * an entry, but it isn't in the config list, call the uninstall procedure
1243 * and mark it uninstalled in the database (for now we'll remove it).
1244 * Then go through the config list and if we have a plugin that isn't installed,
1245 * call the install procedure and add it to the database.
1249 $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
1253 $installed = array();
1255 $plugins = get_config('system','addon');
1256 $plugins_arr = array();
1259 $plugins_arr = explode(',',str_replace(' ', '',$plugins));
1261 $a->plugins = $plugins_arr;
1263 $installed_arr = array();
1265 if(count($installed)) {
1266 foreach($installed as $i) {
1267 if(! in_array($i['name'],$plugins_arr)) {
1268 uninstall_plugin($i['name']);
1271 $installed_arr[] = $i['name'];
1276 if(count($plugins_arr)) {
1277 foreach($plugins_arr as $p) {
1278 if(! in_array($p,$installed_arr)) {
1290 function get_guid($size=16, $prefix = "") {
1292 if ($prefix == "") {
1294 $prefix = hash("crc32", $a->get_hostname());
1297 while (strlen($prefix) < ($size - 13))
1298 $prefix .= mt_rand();
1301 $prefix = substr($prefix, 0, $size - 22);
1302 return(str_replace(".", "", uniqid($prefix, true)));
1304 $prefix = substr($prefix, 0, $size - 13);
1305 return(uniqid($prefix));
1310 * @brief Wrapper for adding a login box.
1312 * @param bool $register
1313 * If $register == true provide a registration link.
1314 * This will most always depend on the value of $a->config['register_policy'].
1315 * @param bool $hiddens
1318 * Returns the complete html for inserting into the page
1320 function login($register = false, $hiddens=false) {
1326 'title' => t('Create a New Account'),
1327 'desc' => t('Register')
1331 $noid = get_config('system','no_openid');
1333 $dest_url = $a->get_baseurl(true) . '/' . $a->query_string;
1336 $tpl = get_markup_template("logout.tpl");
1339 $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
1340 '$baseurl' => $a->get_baseurl(true)
1343 $tpl = get_markup_template("login.tpl");
1344 $_SESSION['return_url'] = $a->query_string;
1345 $a->module = 'login';
1348 $o .= replace_macros($tpl, array(
1350 '$dest_url' => $dest_url,
1351 '$logout' => t('Logout'),
1352 '$login' => t('Login'),
1354 '$lname' => array('username', t('Nickname or Email address: ') , '', ''),
1355 '$lpassword' => array('password', t('Password: '), '', ''),
1356 '$lremember' => array('remember', t('Remember me'), 0, ''),
1358 '$openid' => !$noid,
1359 '$lopenid' => array('openid_url', t('Or login using OpenID: '),'',''),
1361 '$hiddens' => $hiddens,
1363 '$register' => $reg,
1365 '$lostpass' => t('Forgot your password?'),
1366 '$lostlink' => t('Password Reset'),
1368 '$tostitle' => t('Website Terms of Service'),
1369 '$toslink' => t('terms of service'),
1371 '$privacytitle' => t('Website Privacy Policy'),
1372 '$privacylink' => t('privacy policy'),
1376 call_hooks('login_hook',$o);
1382 * @brief Used to end the current process, after saving session state.
1385 session_write_close();
1390 * @brief Redirect to another URL and terminate this process.
1392 function goaway($s) {
1393 header("Location: $s");
1399 * @brief Returns the user id of locally logged in user or false.
1401 * @return int|bool user id or false
1403 function local_user() {
1404 if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
1405 return intval($_SESSION['uid']);
1410 /* @brief Returns contact id of authenticated site visitor or false
1412 * @return int|bool visitor_id or false
1414 function remote_user() {
1415 if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
1416 return intval($_SESSION['visitor_id']);
1421 * @brief Show an error message to user.
1423 * This function save text in session, to be shown to the user at next page load
1425 * @param string $s - Text of notice
1427 function notice($s) {
1429 if(! x($_SESSION,'sysmsg')) $_SESSION['sysmsg'] = array();
1431 $_SESSION['sysmsg'][] = $s;
1435 * @brief Show an info message to user.
1437 * This function save text in session, to be shown to the user at next page load
1439 * @param string $s - Text of notice
1444 if (local_user() AND get_pconfig(local_user(),'system','ignore_info'))
1447 if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
1449 $_SESSION['sysmsg_info'][] = $s;
1454 * @brief Wrapper around config to limit the text length of an incoming message
1458 function get_max_import_size() {
1460 return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
1465 * Wrap calls to proc_close(proc_open()) and call hook
1466 * so plugins can take part in process :)
1469 * $cmd program to run
1470 * next args are passed as $cmd command line
1472 * e.g.: proc_run("ls","-la","/tmp");
1474 * $cmd and string args are surrounded with ""
1476 function proc_run($cmd){
1480 $args = func_get_args();
1486 // expand any arrays
1488 foreach($args as $arg) {
1489 if(is_array($arg)) {
1490 foreach($arg as $n) {
1500 $arr = array('args' => $args, 'run_cmd' => true);
1502 call_hooks("proc_run", $arr);
1503 if(! $arr['run_cmd'])
1506 if(count($args) && $args[0] === 'php') {
1508 if (get_config("system", "worker")) {
1512 $parameters = json_encode($argv);
1513 $found = q("SELECT `id` FROM `workerqueue` WHERE `parameter` = '%s'",
1514 dbesc($parameters));
1517 q("INSERT INTO `workerqueue` (`parameter`, `created`, `priority`)
1518 VALUES ('%s', '%s', %d)",
1520 dbesc(datetime_convert()),
1523 // Should we quit and wait for the poller to be called as a cronjob?
1524 if (get_config("system", "worker_dont_fork"))
1527 // Checking number of workers
1528 $workers = q("SELECT COUNT(*) AS `workers` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
1530 // Get number of allowed number of worker threads
1531 $queues = intval(get_config("system", "worker_queues"));
1536 // If there are already enough workers running, don't fork another one
1537 if ($workers[0]["workers"] >= $queues)
1540 // Now call the poller to execute the jobs that we just added to the queue
1541 $args = array("php", "include/poller.php", "no_cron");
1544 $args[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
1547 // add baseurl to args. cli scripts can't construct it
1548 $args[] = $a->get_baseurl();
1550 for($x = 0; $x < count($args); $x ++)
1551 $args[$x] = escapeshellarg($args[$x]);
1553 $cmdline = implode($args," ");
1555 if(get_config('system','proc_windows'))
1556 proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
1558 proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
1561 function current_theme(){
1562 $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
1568 // Find the theme that belongs to the user whose stuff we are looking at
1570 if($a->profile_uid && ($a->profile_uid != local_user())) {
1571 $r = q("select theme from user where uid = %d limit 1",
1572 intval($a->profile_uid)
1575 $page_theme = $r[0]['theme'];
1578 // Allow folks to over-rule user themes and always use their own on their own site.
1579 // This works only if the user is on the same server
1581 if($page_theme && local_user() && (local_user() != $a->profile_uid)) {
1582 if(get_pconfig(local_user(),'system','always_my_theme'))
1586 // $mobile_detect = new Mobile_Detect();
1587 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1588 $is_mobile = $a->is_mobile || $a->is_tablet;
1590 $standard_system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1591 $standard_theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $standard_system_theme);
1594 if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
1595 $system_theme = $standard_system_theme;
1596 $theme_name = $standard_theme_name;
1599 $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : $standard_system_theme);
1600 $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
1602 if($theme_name === '---') {
1603 // user has selected to have the mobile theme be the same as the normal one
1604 $system_theme = $standard_system_theme;
1605 $theme_name = $standard_theme_name;
1608 $theme_name = $page_theme;
1613 $system_theme = $standard_system_theme;
1614 $theme_name = $standard_theme_name;
1617 $theme_name = $page_theme;
1621 (file_exists('view/theme/' . $theme_name . '/style.css') ||
1622 file_exists('view/theme/' . $theme_name . '/style.php')))
1623 return($theme_name);
1625 foreach($app_base_themes as $t) {
1626 if(file_exists('view/theme/' . $t . '/style.css')||
1627 file_exists('view/theme/' . $t . '/style.php'))
1631 $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
1632 if(count($fallback))
1633 return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
1638 * @brief Return full URL to theme which is currently in effect.
1640 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1644 function current_theme_url() {
1647 $t = current_theme();
1649 $opts = (($a->profile_uid) ? '?f=&puid=' . $a->profile_uid : '');
1650 if (file_exists('view/theme/' . $t . '/style.php'))
1651 return($a->get_baseurl() . '/view/theme/' . $t . '/style.pcss' . $opts);
1653 return($a->get_baseurl() . '/view/theme/' . $t . '/style.css');
1656 function feed_birthday($uid,$tz) {
1660 * Determine the next birthday, but only if the birthday is published
1661 * in the default profile. We _could_ also look for a private profile that the
1662 * recipient can see, but somebody could get mad at us if they start getting
1663 * public birthday greetings when they haven't made this info public.
1665 * Assuming we are able to publish this info, we are then going to convert
1666 * the start time from the owner's timezone to UTC.
1668 * This will potentially solve the problem found with some social networks
1669 * where birthdays are converted to the viewer's timezone and salutations from
1670 * elsewhere in the world show up on the wrong day. We will convert it to the
1671 * viewer's timezone also, but first we are going to convert it from the birthday
1672 * person's timezone to GMT - so the viewer may find the birthday starting at
1673 * 6:00PM the day before, but that will correspond to midnight to the birthday person.
1683 $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
1687 if($p && count($p)) {
1688 $tmp_dob = substr($p[0]['dob'],5);
1689 if(intval($tmp_dob)) {
1690 $y = datetime_convert($tz,$tz,'now','Y');
1691 $bd = $y . '-' . $tmp_dob . ' 00:00';
1692 $t_dob = strtotime($bd);
1693 $now = strtotime(datetime_convert($tz,$tz,'now'));
1695 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
1696 $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
1704 * @brief Check if current user has admin role.
1706 * @return bool true if user is an admin
1708 function is_site_admin() {
1711 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
1713 //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
1714 if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && in_array($a->user['email'], $adminlist))
1720 function load_contact_links($uid) {
1726 if(! $uid || x($a->contacts,'empty'))
1729 $r = q("SELECT `id`,`network`,`url`,`thumb`, `rel` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `thumb` != ''",
1734 $url = normalise_link($rr['url']);
1738 $ret['empty'] = true;
1740 $a->contacts = $ret;
1745 * @brief Returns querystring as string from a mapped array.
1747 * @param array $params mapped array with query parameters
1748 * @param string $name of parameter, default null
1752 function build_querystring($params, $name=null) {
1754 foreach($params as $key=>$val) {
1755 if(is_array($val)) {
1757 $ret .= build_querystring($val, $key);
1759 $ret .= build_querystring($val, $name."[$key]");
1762 $val = urlencode($val);
1764 $ret.=$name."[$key]"."=$val&";
1766 $ret.= "$key=$val&";
1773 function explode_querystring($query) {
1774 $arg_st = strpos($query, '?');
1775 if($arg_st !== false) {
1776 $base = substr($query, 0, $arg_st);
1783 $args = explode('&', substr($query, $arg_st));
1784 foreach($args as $k=>$arg) {
1788 $args = array_values($args);
1793 $args = array_values($args);
1803 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
1805 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
1807 function curPageURL() {
1809 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
1811 if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
1812 $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
1814 $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
1819 function random_digits($digits) {
1821 for($i = 0; $i < $digits; $i++) {
1827 function get_server() {
1828 $server = get_config("system", "directory");
1831 $server = "http://dir.friendi.ca";
1836 function get_cachefile($file, $writemode = true) {
1837 $cache = get_itemcachepath();
1839 if ((! $cache) || (! is_dir($cache)))
1842 $subfolder = $cache."/".substr($file, 0, 2);
1844 $cachepath = $subfolder."/".$file;
1847 if (!is_dir($subfolder)) {
1849 chmod($subfolder, 0777);
1856 function clear_cache($basepath = "", $path = "") {
1858 $basepath = get_itemcachepath();
1862 if (($path == "") OR (!is_dir($path)))
1865 if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
1868 $cachetime = (int)get_config('system','itemcache_duration');
1869 if ($cachetime == 0)
1872 if (is_writable($path)){
1873 if ($dh = opendir($path)) {
1874 while (($file = readdir($dh)) !== false) {
1875 $fullpath = $path."/".$file;
1876 if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
1877 clear_cache($basepath, $fullpath);
1878 if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
1886 function get_itemcachepath() {
1887 // Checking, if the cache is deactivated
1888 $cachetime = (int)get_config('system','itemcache_duration');
1892 $itemcache = get_config('system','itemcache');
1893 if (($itemcache != "") AND is_dir($itemcache) AND is_writable($itemcache))
1896 $temppath = get_temppath();
1898 if ($temppath != "") {
1899 $itemcache = $temppath."/itemcache";
1900 if(!file_exists($itemcache) && !is_dir($itemcache)) {
1904 if (is_dir($itemcache) AND is_writable($itemcache)) {
1905 set_config("system", "itemcache", $itemcache);
1912 function get_lockpath() {
1913 $lockpath = get_config('system','lockpath');
1914 if (($lockpath != "") AND is_dir($lockpath) AND is_writable($lockpath))
1917 $temppath = get_temppath();
1919 if ($temppath != "") {
1920 $lockpath = $temppath."/lock";
1922 if (!is_dir($lockpath))
1924 elseif (!is_writable($lockpath))
1925 $lockpath = $temppath;
1927 if (is_dir($lockpath) AND is_writable($lockpath)) {
1928 set_config("system", "lockpath", $lockpath);
1935 function get_temppath() {
1938 $temppath = get_config("system","temppath");
1939 if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath))
1942 $temppath = sys_get_temp_dir();
1943 if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath)) {
1944 $temppath .= "/".$a->get_hostname();
1945 if (!is_dir($temppath))
1948 if (is_dir($temppath) AND is_writable($temppath)) {
1949 set_config("system", "temppath", $temppath);
1957 function set_template_engine(&$a, $engine = 'internal') {
1958 // This function is no longer necessary, but keep it as a wrapper to the class method
1959 // to avoid breaking themes again unnecessarily
1961 $a->set_template_engine($engine);
1964 if(!function_exists('exif_imagetype')) {
1965 function exif_imagetype($file) {
1966 $size = getimagesize($file);
1971 function validate_include(&$file) {
1974 $file = realpath($file);
1976 if (strpos($file, getcwd()) !== 0)
1979 $file = str_replace(getcwd()."/", "", $file, $count);
1983 if ($orig_file !== $file)
1987 if (strpos($file, "include/") === 0)
1990 if (strpos($file, "addon/") === 0)
1999 function current_load() {
2000 if (!function_exists('sys_getloadavg'))
2003 $load_arr = sys_getloadavg();
2005 if (!is_array($load_arr))
2008 return max($load_arr);