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', 1194 );
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' );
53 * @brief Image storage quality.
55 * Lower numbers save space at cost of image detail.
56 * For ease of upgrade, please do not change here. Change jpeg quality with
57 * $a->config['system']['jpeg_quality'] = n;
58 * in .htconfig.php, where n is netween 1 and 100, and with very poor results
63 define ( 'JPEG_QUALITY', 100 );
65 * $a->config['system']['png_quality'] from 0 (uncompressed) to 9
67 define ( 'PNG_QUALITY', 8 );
71 * An alternate way of limiting picture upload sizes. Specify the maximum pixel
72 * length that pictures are allowed to be (for non-square pictures, it will apply
73 * to the longest side). Pictures longer than this length will be resized to be
74 * this length (on the longest side, the other side will be scaled appropriately).
75 * Modify this value using
77 * $a->config['system']['max_image_length'] = n;
81 * If you don't want to set a maximum length, set to -1. The default value is
82 * defined by 'MAX_IMAGE_LENGTH' below.
85 define ( 'MAX_IMAGE_LENGTH', -1 );
92 define ( 'DEFAULT_DB_ENGINE', 'MyISAM' );
97 * SSL redirection policies
100 define ( 'SSL_POLICY_NONE', 0 );
101 define ( 'SSL_POLICY_FULL', 1 );
102 define ( 'SSL_POLICY_SELFSIGN', 2 );
111 define ( 'LOGGER_NORMAL', 0 );
112 define ( 'LOGGER_TRACE', 1 );
113 define ( 'LOGGER_DEBUG', 2 );
114 define ( 'LOGGER_DATA', 3 );
115 define ( 'LOGGER_ALL', 4 );
124 define ( 'CACHE_MONTH', 0 );
125 define ( 'CACHE_WEEK', 1 );
126 define ( 'CACHE_DAY', 2 );
127 define ( 'CACHE_HOUR', 3 );
133 * Registration policies
136 define ( 'REGISTER_CLOSED', 0 );
137 define ( 'REGISTER_APPROVE', 1 );
138 define ( 'REGISTER_OPEN', 2 );
147 define ( 'CONTACT_IS_FOLLOWER', 1);
148 define ( 'CONTACT_IS_SHARING', 2);
149 define ( 'CONTACT_IS_FRIEND', 3);
155 * DB update return values
158 define ( 'UPDATE_SUCCESS', 0);
159 define ( 'UPDATE_FAILED', 1);
164 * @name page/profile types
166 * PAGE_NORMAL is a typical personal profile account
167 * PAGE_SOAPBOX automatically approves all friend requests as CONTACT_IS_SHARING, (readonly)
168 * PAGE_COMMUNITY automatically approves all friend requests as CONTACT_IS_SHARING, but with
169 * write access to wall and comments (no email and not included in page owner's ACL lists)
170 * PAGE_FREELOVE automatically approves all friend requests as full friends (CONTACT_IS_FRIEND).
174 define ( 'PAGE_NORMAL', 0 );
175 define ( 'PAGE_SOAPBOX', 1 );
176 define ( 'PAGE_COMMUNITY', 2 );
177 define ( 'PAGE_FREELOVE', 3 );
178 define ( 'PAGE_BLOG', 4 );
179 define ( 'PAGE_PRVGROUP', 5 );
185 * Type of the community page
188 define ( 'CP_NO_COMMUNITY_PAGE', -1 );
189 define ( 'CP_USERS_ON_SERVER', 0 );
190 define ( 'CP_GLOBAL_COMMUNITY', 1 );
196 * Network and protocol family types
199 define ( 'NETWORK_DFRN', 'dfrn'); // Friendica, Mistpark, other DFRN implementations
200 define ( 'NETWORK_ZOT', 'zot!'); // Zot!
201 define ( 'NETWORK_OSTATUS', 'stat'); // status.net, identi.ca, GNU-social, other OStatus implementations
202 define ( 'NETWORK_FEED', 'feed'); // RSS/Atom feeds with no known "post/notify" protocol
203 define ( 'NETWORK_DIASPORA', 'dspr'); // Diaspora
204 define ( 'NETWORK_MAIL', 'mail'); // IMAP/POP
205 define ( 'NETWORK_MAIL2', 'mai2'); // extended IMAP/POP
206 define ( 'NETWORK_FACEBOOK', 'face'); // Facebook API
207 define ( 'NETWORK_LINKEDIN', 'lnkd'); // LinkedIn
208 define ( 'NETWORK_XMPP', 'xmpp'); // XMPP
209 define ( 'NETWORK_MYSPACE', 'mysp'); // MySpace
210 define ( 'NETWORK_GPLUS', 'goog'); // Google+
211 define ( 'NETWORK_PUMPIO', 'pump'); // pump.io
212 define ( 'NETWORK_TWITTER', 'twit'); // Twitter
213 define ( 'NETWORK_DIASPORA2', 'dspc'); // Diaspora connector
214 define ( 'NETWORK_STATUSNET', 'stac'); // Statusnet connector
215 define ( 'NETWORK_APPNET', 'apdn'); // app.net
216 define ( 'NETWORK_NEWS', 'nntp'); // Network News Transfer Protocol
217 define ( 'NETWORK_ICALENDAR', 'ical'); // iCalendar
218 define ( 'NETWORK_PHANTOM', 'unkn'); // Place holder
222 * These numbers are used in stored permissions
223 * and existing allocations MUST NEVER BE CHANGED
224 * OR RE-ASSIGNED! You may only add to them.
227 $netgroup_ids = array(
228 NETWORK_DFRN => (-1),
230 NETWORK_OSTATUS => (-3),
231 NETWORK_FEED => (-4),
232 NETWORK_DIASPORA => (-5),
233 NETWORK_MAIL => (-6),
234 NETWORK_MAIL2 => (-7),
235 NETWORK_FACEBOOK => (-8),
236 NETWORK_LINKEDIN => (-9),
237 NETWORK_XMPP => (-10),
238 NETWORK_MYSPACE => (-11),
239 NETWORK_GPLUS => (-12),
240 NETWORK_PUMPIO => (-13),
241 NETWORK_TWITTER => (-14),
242 NETWORK_DIASPORA2 => (-15),
243 NETWORK_STATUSNET => (-16),
244 NETWORK_APPNET => (-17),
245 NETWORK_NEWS => (-18),
246 NETWORK_ICALENDAR => (-19),
248 NETWORK_PHANTOM => (-127),
253 * Maximum number of "people who like (or don't like) this" that we will list by name
256 define ( 'MAX_LIKERS', 75);
259 * Communication timeout
262 define ( 'ZCURL_TIMEOUT' , (-1));
268 * Email notification options
271 define ( 'NOTIFY_INTRO', 0x0001 );
272 define ( 'NOTIFY_CONFIRM', 0x0002 );
273 define ( 'NOTIFY_WALL', 0x0004 );
274 define ( 'NOTIFY_COMMENT', 0x0008 );
275 define ( 'NOTIFY_MAIL', 0x0010 );
276 define ( 'NOTIFY_SUGGEST', 0x0020 );
277 define ( 'NOTIFY_PROFILE', 0x0040 );
278 define ( 'NOTIFY_TAGSELF', 0x0080 );
279 define ( 'NOTIFY_TAGSHARE', 0x0100 );
280 define ( 'NOTIFY_POKE', 0x0200 );
281 define ( 'NOTIFY_SHARE', 0x0400 );
283 define ( 'NOTIFY_SYSTEM', 0x8000 );
293 define ( 'TERM_UNKNOWN', 0 );
294 define ( 'TERM_HASHTAG', 1 );
295 define ( 'TERM_MENTION', 2 );
296 define ( 'TERM_CATEGORY', 3 );
297 define ( 'TERM_PCATEGORY', 4 );
298 define ( 'TERM_FILE', 5 );
299 define ( 'TERM_SAVEDSEARCH', 6 );
300 define ( 'TERM_CONVERSATION', 7 );
302 define ( 'TERM_OBJ_POST', 1 );
303 define ( 'TERM_OBJ_PHOTO', 2 );
310 * Various namespaces we may need to parse
313 define ( 'NAMESPACE_ZOT', 'http://purl.org/zot' );
314 define ( 'NAMESPACE_DFRN' , 'http://purl.org/macgirvin/dfrn/1.0' );
315 define ( 'NAMESPACE_THREAD' , 'http://purl.org/syndication/thread/1.0' );
316 define ( 'NAMESPACE_TOMB' , 'http://purl.org/atompub/tombstones/1.0' );
317 define ( 'NAMESPACE_ACTIVITY', 'http://activitystrea.ms/spec/1.0/' );
318 define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/' );
319 define ( 'NAMESPACE_MEDIA', 'http://purl.org/syndication/atommedia' );
320 define ( 'NAMESPACE_SALMON_ME', 'http://salmon-protocol.org/ns/magic-env' );
321 define ( 'NAMESPACE_OSTATUSSUB', 'http://ostatus.org/schema/1.0/subscribe' );
322 define ( 'NAMESPACE_GEORSS', 'http://www.georss.org/georss' );
323 define ( 'NAMESPACE_POCO', 'http://portablecontacts.net/spec/1.0' );
324 define ( 'NAMESPACE_FEED', 'http://schemas.google.com/g/2010#updates-from' );
325 define ( 'NAMESPACE_OSTATUS', 'http://ostatus.org/schema/1.0' );
326 define ( 'NAMESPACE_STATUSNET', 'http://status.net/schema/api/1/' );
327 define ( 'NAMESPACE_ATOM1', 'http://www.w3.org/2005/Atom' );
333 * Activity stream defines
336 define ( 'ACTIVITY_LIKE', NAMESPACE_ACTIVITY_SCHEMA . 'like' );
337 define ( 'ACTIVITY_DISLIKE', NAMESPACE_DFRN . '/dislike' );
338 define ( 'ACTIVITY_ATTEND', NAMESPACE_ZOT . '/activity/attendyes' );
339 define ( 'ACTIVITY_ATTENDNO', NAMESPACE_ZOT . '/activity/attendno' );
340 define ( 'ACTIVITY_ATTENDMAYBE', NAMESPACE_ZOT . '/activity/attendmaybe' );
342 define ( 'ACTIVITY_OBJ_HEART', NAMESPACE_DFRN . '/heart' );
344 define ( 'ACTIVITY_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
345 define ( 'ACTIVITY_REQ_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'request-friend' );
346 define ( 'ACTIVITY_UNFRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'remove-friend' );
347 define ( 'ACTIVITY_FOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'follow' );
348 define ( 'ACTIVITY_UNFOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'stop-following' );
349 define ( 'ACTIVITY_JOIN', NAMESPACE_ACTIVITY_SCHEMA . 'join' );
351 define ( 'ACTIVITY_POST', NAMESPACE_ACTIVITY_SCHEMA . 'post' );
352 define ( 'ACTIVITY_UPDATE', NAMESPACE_ACTIVITY_SCHEMA . 'update' );
353 define ( 'ACTIVITY_TAG', NAMESPACE_ACTIVITY_SCHEMA . 'tag' );
354 define ( 'ACTIVITY_FAVORITE', NAMESPACE_ACTIVITY_SCHEMA . 'favorite' );
355 define ( 'ACTIVITY_SHARE', NAMESPACE_ACTIVITY_SCHEMA . 'share' );
357 define ( 'ACTIVITY_POKE', NAMESPACE_ZOT . '/activity/poke' );
358 define ( 'ACTIVITY_MOOD', NAMESPACE_ZOT . '/activity/mood' );
360 define ( 'ACTIVITY_OBJ_BOOKMARK', NAMESPACE_ACTIVITY_SCHEMA . 'bookmark' );
361 define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
362 define ( 'ACTIVITY_OBJ_NOTE', NAMESPACE_ACTIVITY_SCHEMA . 'note' );
363 define ( 'ACTIVITY_OBJ_PERSON', NAMESPACE_ACTIVITY_SCHEMA . 'person' );
364 define ( 'ACTIVITY_OBJ_IMAGE', NAMESPACE_ACTIVITY_SCHEMA . 'image' );
365 define ( 'ACTIVITY_OBJ_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
366 define ( 'ACTIVITY_OBJ_VIDEO', NAMESPACE_ACTIVITY_SCHEMA . 'video' );
367 define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
368 define ( 'ACTIVITY_OBJ_ALBUM', NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
369 define ( 'ACTIVITY_OBJ_EVENT', NAMESPACE_ACTIVITY_SCHEMA . 'event' );
370 define ( 'ACTIVITY_OBJ_GROUP', NAMESPACE_ACTIVITY_SCHEMA . 'group' );
371 define ( 'ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN . '/tagterm' );
372 define ( 'ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN . '/profile' );
373 define ( 'ACTIVITY_OBJ_QUESTION', 'http://activityschema.org/object/question' );
379 * Item weight for query ordering
382 define ( 'GRAVITY_PARENT', 0);
383 define ( 'GRAVITY_LIKE', 3);
384 define ( 'GRAVITY_COMMENT', 6);
390 * Reverse the effect of magic_quotes_gpc if it is enabled.
391 * Please disable magic_quotes_gpc so we don't have to do this.
392 * See http://php.net/manual/en/security.magicquotes.disabling.php
398 error_reporting(E_ERROR | E_WARNING | E_PARSE);
402 // This has to be quite large to deal with embedded private photos
403 ini_set('pcre.backtrack_limit', 500000);
406 if (get_magic_quotes_gpc()) {
407 $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
408 while (list($key, $val) = each($process)) {
409 foreach ($val as $k => $v) {
410 unset($process[$key][$k]);
412 $process[$key][stripslashes($k)] = $v;
413 $process[] = &$process[$key][stripslashes($k)];
415 $process[$key][stripslashes($k)] = stripslashes($v);
428 * @brief Our main application structure for the life of this page.
430 * Primarily deals with the URL that got us here
431 * and tries to make some sense of it, and
432 * stores our page contents and config storage
433 * and anything else that might need to be passed around
434 * before we spit the page out.
439 public $module_loaded = false;
440 public $query_string;
449 public $page_contact;
451 public $data = array();
452 public $error = false;
462 public $interactive = true;
464 public $apps = array();
468 public $is_friendica_app;
469 public $performance = array();
470 public $callstack = array();
477 // Allow themes to control internal parameters
478 // by changing App values in theme.php
480 public $sourcename = '';
481 public $videowidth = 425;
482 public $videoheight = 350;
483 public $force_max_items = 0;
484 public $theme_thread_allow = true;
485 public $theme_events_in_profile = true;
488 * @brief An array for all theme-controllable parameters
490 * Mostly unimplemented yet. Only options 'template_engine' and
493 public $theme = array(
496 'videoheight' => 350,
497 'force_max_items' => 0,
498 'thread_allow' => true,
500 'template_engine' => 'smarty3',
504 * @brief An array of registered template engines ('name'=>'class name')
506 public $template_engines = array();
508 * @brief An array of instanced template engines ('name'=>'instance')
510 public $template_engine_instance = array();
512 private $ldelim = array(
516 private $rdelim = array(
527 private $curl_content_type;
528 private $curl_headers;
530 private $cached_profile_image;
531 private $cached_profile_picdate;
536 * @brief App constructor.
538 function __construct() {
540 global $default_timezone;
544 if (file_exists(".htpreconfig.php"))
545 @include(".htpreconfig.php");
547 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
549 date_default_timezone_set($this->timezone);
551 $this->performance["start"] = microtime(true);
552 $this->performance["database"] = 0;
553 $this->performance["network"] = 0;
554 $this->performance["file"] = 0;
555 $this->performance["rendering"] = 0;
556 $this->performance["parser"] = 0;
557 $this->performance["marktime"] = 0;
558 $this->performance["markstart"] = microtime(true);
560 $this->callstack["database"] = array();
561 $this->callstack["network"] = array();
562 $this->callstack["file"] = array();
563 $this->callstack["rendering"] = array();
564 $this->callstack["parser"] = array();
566 $this->config = array();
567 $this->page = array();
568 $this->pager= array();
570 $this->query_string = '';
575 'include' . PATH_SEPARATOR
576 . 'library' . PATH_SEPARATOR
577 . 'library/phpsec' . PATH_SEPARATOR
578 . 'library/langdet' . PATH_SEPARATOR
582 $this->scheme = 'http';
583 if(x($_SERVER,'HTTPS') && $_SERVER['HTTPS'])
584 $this->scheme = 'https';
585 elseif(x($_SERVER,'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443))
586 $this->scheme = 'https';
588 if(x($_SERVER,'SERVER_NAME')) {
589 $this->hostname = $_SERVER['SERVER_NAME'];
591 // See bug 437 - this didn't work so disabling it
592 //if(stristr($this->hostname,'xn--')) {
593 // PHP or webserver may have converted idn to punycode, so
594 // convert punycode back to utf-8
595 // require_once('library/simplepie/idn/idna_convert.class.php');
596 // $x = new idna_convert();
597 // $this->hostname = $x->decode($_SERVER['SERVER_NAME']);
600 if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
601 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
603 * Figure out if we are running at the top of a domain
604 * or in a sub-directory and adjust accordingly
607 $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
608 if(isset($path) && strlen($path) && ($path != $this->path))
613 $this->hostname = $hostname;
615 if (is_array($_SERVER["argv"]) && $_SERVER["argc"]>1 && substr(end($_SERVER["argv"]), 0, 4)=="http" ) {
616 $this->set_baseurl(array_pop($_SERVER["argv"]) );
620 #set_include_path("include/$this->hostname" . PATH_SEPARATOR . get_include_path());
622 if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,9) === "pagename=") {
623 $this->query_string = substr($_SERVER['QUERY_STRING'],9);
624 // removing trailing / - maybe a nginx problem
625 if (substr($this->query_string, 0, 1) == "/")
626 $this->query_string = substr($this->query_string, 1);
627 } elseif((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
628 $this->query_string = substr($_SERVER['QUERY_STRING'],2);
629 // removing trailing / - maybe a nginx problem
630 if (substr($this->query_string, 0, 1) == "/")
631 $this->query_string = substr($this->query_string, 1);
634 if (x($_GET,'pagename'))
635 $this->cmd = trim($_GET['pagename'],'/\\');
636 elseif (x($_GET,'q'))
637 $this->cmd = trim($_GET['q'],'/\\');
641 $this->query_string = str_replace($this->cmd."&",$this->cmd."?", $this->query_string);
644 // unix style "homedir"
646 if(substr($this->cmd,0,1) === '~')
647 $this->cmd = 'profile/' . substr($this->cmd,1);
649 // Diaspora style profile url
651 if(substr($this->cmd,0,2) === 'u/')
652 $this->cmd = 'profile/' . substr($this->cmd,2);
657 * Break the URL path into C style argc/argv style arguments for our
658 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
659 * will be 3 (integer) and $this->argv will contain:
665 * There will always be one argument. If provided a naked domain
666 * URL, $this->argv[0] is set to "home".
670 $this->argv = explode('/',$this->cmd);
671 $this->argc = count($this->argv);
672 if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
673 $this->module = str_replace(".", "_", $this->argv[0]);
674 $this->module = str_replace("-", "_", $this->module);
678 $this->argv = array('home');
679 $this->module = 'home';
683 * See if there is any page number information, and initialise
687 $this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
688 $this->pager['itemspage'] = 50;
689 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
690 if($this->pager['start'] < 0)
691 $this->pager['start'] = 0;
692 $this->pager['total'] = 0;
695 * Detect mobile devices
698 $mobile_detect = new Mobile_Detect();
699 $this->is_mobile = $mobile_detect->isMobile();
700 $this->is_tablet = $mobile_detect->isTablet();
703 $this->is_friendica_app = ($_SERVER['HTTP_USER_AGENT'] == "Apache-HttpClient/UNAVAILABLE (java 1.4)");
706 * register template engines
708 $dc = get_declared_classes();
709 foreach ($dc as $k) {
710 if (in_array("ITemplateEngine", class_implements($k))){
711 $this->register_template_engine($k);
719 function get_basepath() {
721 $basepath = get_config("system", "basepath");
724 $basepath = dirname(__FILE__);
727 $basepath = $_SERVER["DOCUMENT_ROOT"];
730 $basepath = $_SERVER["PWD"];
735 function get_scheme() {
736 return($this->scheme);
739 function get_baseurl($ssl = false) {
741 // Is the function called statically?
742 if (!is_object($this))
743 return(self::$a->get_baseurl($ssl));
745 $scheme = $this->scheme;
747 if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
748 if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
751 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
752 // (and also the login link). Anything seen by an outsider will have it turned off.
754 if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
762 if (get_config('config','hostname') != "")
763 $this->hostname = get_config('config','hostname');
765 $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
766 return $this->baseurl;
769 function set_baseurl($url) {
770 $parsed = @parse_url($url);
772 $this->baseurl = $url;
775 $this->scheme = $parsed['scheme'];
777 $hostname = $parsed['host'];
778 if(x($parsed,'port'))
779 $hostname .= ':' . $parsed['port'];
780 if(x($parsed,'path'))
781 $this->path = trim($parsed['path'],'\\/');
783 if (file_exists(".htpreconfig.php"))
784 @include(".htpreconfig.php");
786 if (get_config('config','hostname') != "")
787 $this->hostname = get_config('config','hostname');
789 if (!isset($this->hostname) OR ($this->hostname == ""))
790 $this->hostname = $hostname;
795 function get_hostname() {
796 if (get_config('config','hostname') != "")
797 $this->hostname = get_config('config','hostname');
799 return $this->hostname;
802 function set_hostname($h) {
803 $this->hostname = $h;
806 function set_path($p) {
807 $this->path = trim(trim($p),'/');
810 function get_path() {
814 function set_pager_total($n) {
815 $this->pager['total'] = intval($n);
818 function set_pager_itemspage($n) {
819 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
820 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
823 function set_pager_page($n) {
824 $this->pager['page'] = $n;
825 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
828 function init_pagehead() {
829 $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
831 // If the update is "deactivated" set it to the highest integer number (~24 days)
833 $interval = 2147483647;
835 if($interval < 10000)
838 // compose the page title from the sitename and the
839 // current module called
840 if (!$this->module=='')
842 $this->page['title'] = $this->config['sitename'].' ('.$this->module.')';
844 $this->page['title'] = $this->config['sitename'];
847 /* put the head template at the beginning of page['htmlhead']
848 * since the code added by the modules frequently depends on it
851 if(!isset($this->page['htmlhead']))
852 $this->page['htmlhead'] = '';
854 // If we're using Smarty, then doing replace_macros() will replace
855 // any unrecognized variables with a blank string. Since we delay
856 // replacing $stylesheet until later, we need to replace it now
857 // with another variable name
858 if($this->theme['template_engine'] === 'smarty3')
859 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
861 $stylesheet = '$stylesheet';
863 $shortcut_icon = get_config("system", "shortcut_icon");
864 if ($shortcut_icon == "")
865 $shortcut_icon = $this->get_baseurl()."/images/friendica-32.png";
867 $touch_icon = get_config("system", "touch_icon");
868 if ($touch_icon == "")
869 $touch_icon = $this->get_baseurl()."/images/friendica-128.png";
871 $tpl = get_markup_template('head.tpl');
872 $this->page['htmlhead'] = replace_macros($tpl,array(
873 '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
874 '$local_user' => local_user(),
875 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
876 '$delitem' => t('Delete this item?'),
877 '$comment' => t('Comment'),
878 '$showmore' => t('show more'),
879 '$showfewer' => t('show fewer'),
880 '$update_interval' => $interval,
881 '$shortcut_icon' => $shortcut_icon,
882 '$touch_icon' => $touch_icon,
883 '$stylesheet' => $stylesheet
884 )) . $this->page['htmlhead'];
887 function init_page_end() {
888 if(!isset($this->page['end']))
889 $this->page['end'] = '';
890 $tpl = get_markup_template('end.tpl');
891 $this->page['end'] = replace_macros($tpl,array(
892 '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
893 )) . $this->page['end'];
896 function set_curl_code($code) {
897 $this->curl_code = $code;
900 function get_curl_code() {
901 return $this->curl_code;
904 function set_curl_content_type($content_type) {
905 $this->curl_content_type = $content_type;
908 function get_curl_content_type() {
909 return $this->curl_content_type;
912 function set_curl_headers($headers) {
913 $this->curl_headers = $headers;
916 function get_curl_headers() {
917 return $this->curl_headers;
920 function get_cached_avatar_image($avatar_image){
921 return $avatar_image;
923 // The following code is deactivated. It doesn't seem to make any sense and it slows down the system.
925 if($this->cached_profile_image[$avatar_image])
926 return $this->cached_profile_image[$avatar_image];
928 $path_parts = explode("/",$avatar_image);
929 $common_filename = $path_parts[count($path_parts)-1];
931 if($this->cached_profile_picdate[$common_filename]){
932 $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
934 $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like '%%/%s'",
937 $this->cached_profile_image[$avatar_image] = $avatar_image;
939 $this->cached_profile_picdate[$common_filename] = "?rev=".urlencode($r[0]['picdate']);
940 $this->cached_profile_image[$avatar_image] = $avatar_image.$this->cached_profile_picdate[$common_filename];
943 return $this->cached_profile_image[$avatar_image];
949 * @brief Register template engine class
951 * If $name is "", is used class static property $class::$name
953 * @param string $class
954 * @param string $name
956 function register_template_engine($class, $name = '') {
958 $v = get_class_vars( $class );
959 if(x($v,"name")) $name = $v['name'];
962 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
965 $this->template_engines[$name] = $class;
969 * @brief Return template engine instance.
971 * If $name is not defined, return engine defined by theme,
974 * @param strin $name Template engine name
975 * @return object Template Engine instance
977 function template_engine($name = ''){
979 $template_engine = $name;
981 $template_engine = 'smarty3';
982 if (x($this->theme, 'template_engine')) {
983 $template_engine = $this->theme['template_engine'];
987 if (isset($this->template_engines[$template_engine])){
988 if(isset($this->template_engine_instance[$template_engine])){
989 return $this->template_engine_instance[$template_engine];
991 $class = $this->template_engines[$template_engine];
993 $this->template_engine_instance[$template_engine] = $obj;
998 echo "template engine <tt>$template_engine</tt> is not registered!\n"; killme();
1002 * @brief Returns the active template engine.
1006 function get_template_engine() {
1007 return $this->theme['template_engine'];
1010 function set_template_engine($engine = 'smarty3') {
1011 $this->theme['template_engine'] = $engine;
1013 $this->theme['template_engine'] = 'smarty3';
1017 if(is_writable('view/smarty3/'))
1018 $this->theme['template_engine'] = 'smarty3';
1026 function get_template_ldelim($engine = 'smarty3') {
1027 return $this->ldelim[$engine];
1030 function get_template_rdelim($engine = 'smarty3') {
1031 return $this->rdelim[$engine];
1034 function save_timestamp($stamp, $value) {
1035 $duration = (float)(microtime(true)-$stamp);
1037 $this->performance[$value] += (float)$duration;
1038 $this->performance["marktime"] += (float)$duration;
1040 // Trace the different functions with their timestamps
1041 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5);
1043 array_shift($trace);
1045 $function = array();
1046 foreach ($trace AS $func)
1047 $function[] = $func["function"];
1049 $function = implode(", ", $function);
1051 $this->callstack[$value][$function] += (float)$duration;
1055 function mark_timestamp($mark) {
1056 //$this->performance["markstart"] -= microtime(true) - $this->performance["marktime"];
1057 $this->performance["markstart"] = microtime(true) - $this->performance["markstart"] - $this->performance["marktime"];
1060 function get_useragent() {
1061 return(FRIENDICA_PLATFORM." '".FRIENDICA_CODENAME."' ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION."; ".$this->get_baseurl());
1064 function is_friendica_app() {
1065 return($this->is_friendica_app);
1071 * @brief Retrieve the App structure
1073 * Useful in functions which require it but don't get it passed to them
1075 function get_app() {
1082 * @brief Multi-purpose function to check variable state.
1084 * Usage: x($var) or $x($array, 'key')
1086 * returns false if variable/key is not set
1087 * if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
1088 * e.g. x('') or x(0) returns 0;
1090 * @param string|array $s variable to check
1091 * @param string $k key inside the array to check
1095 function x($s,$k = NULL) {
1097 if((is_array($s)) && (array_key_exists($k,$s))) {
1117 * @brief Called from db initialisation if db is dead.
1119 function system_unavailable() {
1120 include('system_unavailable.php');
1126 function clean_urls() {
1128 // if($a->config['system']['clean_urls'])
1135 $base = $a->get_baseurl();
1142 * @brief Returns the baseurl.
1144 * @see App::get_baseurl()
1150 return $a->get_baseurl();
1154 * @brief Return absolut URL for given $path.
1156 * @param string $path
1160 function absurl($path) {
1161 if(strpos($path,'/') === 0)
1162 return z_path() . $path;
1167 * @brief Function to check if request was an AJAX (xmlhttprequest) request.
1171 function is_ajax() {
1172 return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
1175 function check_db() {
1177 $build = get_config('system','build');
1179 set_config('system','build',DB_UPDATE_VERSION);
1180 $build = DB_UPDATE_VERSION;
1182 if($build != DB_UPDATE_VERSION)
1183 proc_run('php', 'include/dbupdate.php');
1189 * Sets the base url for use in cmdline programs which don't have
1190 * $_SERVER variables
1192 function check_url(&$a) {
1194 $url = get_config('system','url');
1196 // if the url isn't set or the stored url is radically different
1197 // than the currently visited url, store the current value accordingly.
1198 // "Radically different" ignores common variations such as http vs https
1199 // and www.example.com vs example.com.
1200 // We will only change the url to an ip address if there is no existing setting
1203 $url = set_config('system','url',$a->get_baseurl());
1204 if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
1205 $url = set_config('system','url',$a->get_baseurl());
1212 * @brief Automatic database updates
1214 function update_db(&$a) {
1215 $build = get_config('system','build');
1217 $build = set_config('system','build',DB_UPDATE_VERSION);
1219 if($build != DB_UPDATE_VERSION) {
1220 $stored = intval($build);
1221 $current = intval(DB_UPDATE_VERSION);
1222 if($stored < $current) {
1223 load_config('database');
1225 // We're reporting a different version than what is currently installed.
1226 // Run any existing update scripts to bring the database up to current.
1228 // make sure that boot.php and update.php are the same release, we might be
1229 // updating right this very second and the correct version of the update.php
1230 // file may not be here yet. This can happen on a very busy site.
1232 if(DB_UPDATE_VERSION == UPDATE_VERSION) {
1233 // Compare the current structure with the defined structure
1235 $t = get_config('database','dbupdate_'.DB_UPDATE_VERSION);
1239 set_config('database','dbupdate_'.DB_UPDATE_VERSION, time());
1241 // run old update routine (wich could modify the schema and
1242 // conflits with new routine)
1243 for ($x = $stored; $x < NEW_UPDATE_ROUTINE_VERSION; $x++) {
1244 $r = run_update_function($x);
1247 if ($stored < NEW_UPDATE_ROUTINE_VERSION) $stored = NEW_UPDATE_ROUTINE_VERSION;
1250 // run new update routine
1251 // it update the structure in one call
1252 $retval = update_structure(false, true);
1260 set_config('database','dbupdate_'.DB_UPDATE_VERSION, 'success');
1263 // run any left update_nnnn functions in update.php
1264 for($x = $stored; $x < $current; $x ++) {
1265 $r = run_update_function($x);
1275 function run_update_function($x) {
1276 if(function_exists('update_' . $x)) {
1278 // There could be a lot of processes running or about to run.
1279 // We want exactly one process to run the update command.
1280 // So store the fact that we're taking responsibility
1281 // after first checking to see if somebody else already has.
1283 // If the update fails or times-out completely you may need to
1284 // delete the config entry to try again.
1286 $t = get_config('database','update_' . $x);
1289 set_config('database','update_' . $x, time());
1291 // call the specific update
1293 $func = 'update_' . $x;
1297 //send the administrator an e-mail
1300 sprintf(t('Update %s failed. See error logs.'), $x)
1304 set_config('database','update_' . $x, 'success');
1305 set_config('system','build', $x + 1);
1309 set_config('database','update_' . $x, 'success');
1310 set_config('system','build', $x + 1);
1317 * @brief Synchronise plugins:
1319 * $a->config['system']['addon'] contains a comma-separated list of names
1320 * of plugins/addons which are used on this system.
1321 * Go through the database list of already installed addons, and if we have
1322 * an entry, but it isn't in the config list, call the uninstall procedure
1323 * and mark it uninstalled in the database (for now we'll remove it).
1324 * Then go through the config list and if we have a plugin that isn't installed,
1325 * call the install procedure and add it to the database.
1330 function check_plugins(&$a) {
1332 $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
1336 $installed = array();
1338 $plugins = get_config('system','addon');
1339 $plugins_arr = array();
1342 $plugins_arr = explode(',',str_replace(' ', '',$plugins));
1344 $a->plugins = $plugins_arr;
1346 $installed_arr = array();
1348 if(count($installed)) {
1349 foreach($installed as $i) {
1350 if(! in_array($i['name'],$plugins_arr)) {
1351 uninstall_plugin($i['name']);
1354 $installed_arr[] = $i['name'];
1359 if(count($plugins_arr)) {
1360 foreach($plugins_arr as $p) {
1361 if(! in_array($p,$installed_arr)) {
1373 function get_guid($size=16, $prefix = "") {
1375 if ($prefix == "") {
1377 $prefix = hash("crc32", $a->get_hostname());
1380 while (strlen($prefix) < ($size - 13))
1381 $prefix .= mt_rand();
1384 $prefix = substr($prefix, 0, $size - 22);
1385 return(str_replace(".", "", uniqid($prefix, true)));
1387 $prefix = substr($prefix, 0, max($size - 13, 0));
1388 return(uniqid($prefix));
1393 * @brief Wrapper for adding a login box.
1395 * @param bool $register
1396 * If $register == true provide a registration link.
1397 * This will most always depend on the value of $a->config['register_policy'].
1398 * @param bool $hiddens
1401 * Returns the complete html for inserting into the page
1403 * @hooks 'login_hook'
1406 function login($register = false, $hiddens=false) {
1412 'title' => t('Create a New Account'),
1413 'desc' => t('Register')
1417 $noid = get_config('system','no_openid');
1419 $dest_url = $a->get_baseurl(true) . '/' . $a->query_string;
1422 $tpl = get_markup_template("logout.tpl");
1425 $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
1426 '$baseurl' => $a->get_baseurl(true)
1429 $tpl = get_markup_template("login.tpl");
1430 $_SESSION['return_url'] = $a->query_string;
1431 $a->module = 'login';
1434 $o .= replace_macros($tpl, array(
1436 '$dest_url' => $dest_url,
1437 '$logout' => t('Logout'),
1438 '$login' => t('Login'),
1440 '$lname' => array('username', t('Nickname or Email address: ') , '', ''),
1441 '$lpassword' => array('password', t('Password: '), '', ''),
1442 '$lremember' => array('remember', t('Remember me'), 0, ''),
1444 '$openid' => !$noid,
1445 '$lopenid' => array('openid_url', t('Or login using OpenID: '),'',''),
1447 '$hiddens' => $hiddens,
1449 '$register' => $reg,
1451 '$lostpass' => t('Forgot your password?'),
1452 '$lostlink' => t('Password Reset'),
1454 '$tostitle' => t('Website Terms of Service'),
1455 '$toslink' => t('terms of service'),
1457 '$privacytitle' => t('Website Privacy Policy'),
1458 '$privacylink' => t('privacy policy'),
1462 call_hooks('login_hook',$o);
1468 * @brief Used to end the current process, after saving session state.
1471 session_write_close();
1476 * @brief Redirect to another URL and terminate this process.
1478 function goaway($s) {
1479 header("Location: $s");
1485 * @brief Returns the user id of locally logged in user or false.
1487 * @return int|bool user id or false
1489 function local_user() {
1490 if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
1491 return intval($_SESSION['uid']);
1496 * @brief Returns contact id of authenticated site visitor or false
1498 * @return int|bool visitor_id or false
1500 function remote_user() {
1501 if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
1502 return intval($_SESSION['visitor_id']);
1507 * @brief Show an error message to user.
1509 * This function save text in session, to be shown to the user at next page load
1511 * @param string $s - Text of notice
1513 function notice($s) {
1515 if(! x($_SESSION,'sysmsg')) $_SESSION['sysmsg'] = array();
1517 $_SESSION['sysmsg'][] = $s;
1521 * @brief Show an info message to user.
1523 * This function save text in session, to be shown to the user at next page load
1525 * @param string $s - Text of notice
1530 if (local_user() AND get_pconfig(local_user(),'system','ignore_info'))
1533 if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
1535 $_SESSION['sysmsg_info'][] = $s;
1540 * @brief Wrapper around config to limit the text length of an incoming message
1544 function get_max_import_size() {
1546 return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
1550 * @brief Wrap calls to proc_close(proc_open()) and call hook
1551 * so plugins can take part in process :)
1553 * @param string $cmd program to run
1555 * next args are passed as $cmd command line
1556 * e.g.: proc_run("ls","-la","/tmp");
1558 * @note $cmd and string args are surrounded with ""
1563 function proc_run($cmd){
1567 $args = func_get_args();
1573 // expand any arrays
1575 foreach($args as $arg) {
1576 if(is_array($arg)) {
1577 foreach($arg as $n) {
1587 $arr = array('args' => $args, 'run_cmd' => true);
1589 call_hooks("proc_run", $arr);
1590 if(! $arr['run_cmd'])
1593 if(count($args) && $args[0] === 'php') {
1595 if (get_config("system", "worker")) {
1599 $parameters = json_encode($argv);
1600 $found = q("SELECT `id` FROM `workerqueue` WHERE `parameter` = '%s'",
1601 dbesc($parameters));
1604 q("INSERT INTO `workerqueue` (`parameter`, `created`, `priority`)
1605 VALUES ('%s', '%s', %d)",
1607 dbesc(datetime_convert()),
1610 // Should we quit and wait for the poller to be called as a cronjob?
1611 if (get_config("system", "worker_dont_fork"))
1614 // Checking number of workers
1615 $workers = q("SELECT COUNT(*) AS `workers` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
1617 // Get number of allowed number of worker threads
1618 $queues = intval(get_config("system", "worker_queues"));
1623 // If there are already enough workers running, don't fork another one
1624 if ($workers[0]["workers"] >= $queues)
1627 // Now call the poller to execute the jobs that we just added to the queue
1628 $args = array("php", "include/poller.php", "no_cron");
1631 $args[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
1634 // add baseurl to args. cli scripts can't construct it
1635 $args[] = $a->get_baseurl();
1637 for($x = 0; $x < count($args); $x ++)
1638 $args[$x] = escapeshellarg($args[$x]);
1640 $cmdline = implode($args," ");
1642 if(get_config('system','proc_windows'))
1643 proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
1645 proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
1648 function current_theme(){
1649 $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
1655 // Find the theme that belongs to the user whose stuff we are looking at
1657 if($a->profile_uid && ($a->profile_uid != local_user())) {
1658 $r = q("select theme from user where uid = %d limit 1",
1659 intval($a->profile_uid)
1662 $page_theme = $r[0]['theme'];
1665 // Allow folks to over-rule user themes and always use their own on their own site.
1666 // This works only if the user is on the same server
1668 if($page_theme && local_user() && (local_user() != $a->profile_uid)) {
1669 if(get_pconfig(local_user(),'system','always_my_theme'))
1673 // $mobile_detect = new Mobile_Detect();
1674 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1675 $is_mobile = $a->is_mobile || $a->is_tablet;
1677 $standard_system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1678 $standard_theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $standard_system_theme);
1681 if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
1682 $system_theme = $standard_system_theme;
1683 $theme_name = $standard_theme_name;
1686 $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : $standard_system_theme);
1687 $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
1689 if($theme_name === '---') {
1690 // user has selected to have the mobile theme be the same as the normal one
1691 $system_theme = $standard_system_theme;
1692 $theme_name = $standard_theme_name;
1695 $theme_name = $page_theme;
1700 $system_theme = $standard_system_theme;
1701 $theme_name = $standard_theme_name;
1704 $theme_name = $page_theme;
1708 (file_exists('view/theme/' . $theme_name . '/style.css') ||
1709 file_exists('view/theme/' . $theme_name . '/style.php')))
1710 return($theme_name);
1712 foreach($app_base_themes as $t) {
1713 if(file_exists('view/theme/' . $t . '/style.css')||
1714 file_exists('view/theme/' . $t . '/style.php'))
1718 $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
1719 if(count($fallback))
1720 return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
1725 * @brief Return full URL to theme which is currently in effect.
1727 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1731 function current_theme_url() {
1734 $t = current_theme();
1736 $opts = (($a->profile_uid) ? '?f=&puid=' . $a->profile_uid : '');
1737 if (file_exists('view/theme/' . $t . '/style.php'))
1738 return($a->get_baseurl() . '/view/theme/' . $t . '/style.pcss' . $opts);
1740 return($a->get_baseurl() . '/view/theme/' . $t . '/style.css');
1743 function feed_birthday($uid,$tz) {
1747 * Determine the next birthday, but only if the birthday is published
1748 * in the default profile. We _could_ also look for a private profile that the
1749 * recipient can see, but somebody could get mad at us if they start getting
1750 * public birthday greetings when they haven't made this info public.
1752 * Assuming we are able to publish this info, we are then going to convert
1753 * the start time from the owner's timezone to UTC.
1755 * This will potentially solve the problem found with some social networks
1756 * where birthdays are converted to the viewer's timezone and salutations from
1757 * elsewhere in the world show up on the wrong day. We will convert it to the
1758 * viewer's timezone also, but first we are going to convert it from the birthday
1759 * person's timezone to GMT - so the viewer may find the birthday starting at
1760 * 6:00PM the day before, but that will correspond to midnight to the birthday person.
1770 $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
1774 if($p && count($p)) {
1775 $tmp_dob = substr($p[0]['dob'],5);
1776 if(intval($tmp_dob)) {
1777 $y = datetime_convert($tz,$tz,'now','Y');
1778 $bd = $y . '-' . $tmp_dob . ' 00:00';
1779 $t_dob = strtotime($bd);
1780 $now = strtotime(datetime_convert($tz,$tz,'now'));
1782 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
1783 $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
1791 * @brief Check if current user has admin role.
1793 * @return bool true if user is an admin
1795 function is_site_admin() {
1798 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
1800 //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
1801 if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && in_array($a->user['email'], $adminlist))
1807 function load_contact_links($uid) {
1813 if(! $uid || x($a->contacts,'empty'))
1816 $r = q("SELECT `id`,`network`,`url`,`thumb`, `rel` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `thumb` != ''",
1821 $url = normalise_link($rr['url']);
1825 $ret['empty'] = true;
1827 $a->contacts = $ret;
1832 * @brief Returns querystring as string from a mapped array.
1834 * @param array $params mapped array with query parameters
1835 * @param string $name of parameter, default null
1839 function build_querystring($params, $name=null) {
1841 foreach($params as $key=>$val) {
1842 if(is_array($val)) {
1844 $ret .= build_querystring($val, $key);
1846 $ret .= build_querystring($val, $name."[$key]");
1849 $val = urlencode($val);
1851 $ret.=$name."[$key]"."=$val&";
1853 $ret.= "$key=$val&";
1860 function explode_querystring($query) {
1861 $arg_st = strpos($query, '?');
1862 if($arg_st !== false) {
1863 $base = substr($query, 0, $arg_st);
1870 $args = explode('&', substr($query, $arg_st));
1871 foreach($args as $k=>$arg) {
1875 $args = array_values($args);
1880 $args = array_values($args);
1890 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
1892 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
1894 function curPageURL() {
1896 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
1898 if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
1899 $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
1901 $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
1906 function random_digits($digits) {
1908 for($i = 0; $i < $digits; $i++) {
1914 function get_server() {
1915 $server = get_config("system", "directory");
1918 $server = "http://dir.friendi.ca";
1923 function get_cachefile($file, $writemode = true) {
1924 $cache = get_itemcachepath();
1926 if ((! $cache) || (! is_dir($cache)))
1929 $subfolder = $cache."/".substr($file, 0, 2);
1931 $cachepath = $subfolder."/".$file;
1934 if (!is_dir($subfolder)) {
1936 chmod($subfolder, 0777);
1943 function clear_cache($basepath = "", $path = "") {
1945 $basepath = get_itemcachepath();
1949 if (($path == "") OR (!is_dir($path)))
1952 if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
1955 $cachetime = (int)get_config('system','itemcache_duration');
1956 if ($cachetime == 0)
1959 if (is_writable($path)){
1960 if ($dh = opendir($path)) {
1961 while (($file = readdir($dh)) !== false) {
1962 $fullpath = $path."/".$file;
1963 if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
1964 clear_cache($basepath, $fullpath);
1965 if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
1973 function get_itemcachepath() {
1974 // Checking, if the cache is deactivated
1975 $cachetime = (int)get_config('system','itemcache_duration');
1979 $itemcache = get_config('system','itemcache');
1980 if (($itemcache != "") AND is_dir($itemcache) AND is_writable($itemcache))
1983 $temppath = get_temppath();
1985 if ($temppath != "") {
1986 $itemcache = $temppath."/itemcache";
1987 if(!file_exists($itemcache) && !is_dir($itemcache)) {
1991 if (is_dir($itemcache) AND is_writable($itemcache)) {
1992 set_config("system", "itemcache", $itemcache);
1999 function get_lockpath() {
2000 $lockpath = get_config('system','lockpath');
2001 if (($lockpath != "") AND is_dir($lockpath) AND is_writable($lockpath))
2004 $temppath = get_temppath();
2006 if ($temppath != "") {
2007 $lockpath = $temppath."/lock";
2009 if (!is_dir($lockpath))
2011 elseif (!is_writable($lockpath))
2012 $lockpath = $temppath;
2014 if (is_dir($lockpath) AND is_writable($lockpath)) {
2015 set_config("system", "lockpath", $lockpath);
2022 function get_temppath() {
2025 $temppath = get_config("system","temppath");
2026 if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath))
2029 $temppath = sys_get_temp_dir();
2030 if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath)) {
2031 $temppath .= "/".$a->get_hostname();
2032 if (!is_dir($temppath))
2035 if (is_dir($temppath) AND is_writable($temppath)) {
2036 set_config("system", "temppath", $temppath);
2044 function set_template_engine(&$a, $engine = 'internal') {
2045 /// @note This function is no longer necessary, but keep it as a wrapper to the class method
2046 /// to avoid breaking themes again unnecessarily
2048 $a->set_template_engine($engine);
2051 if(!function_exists('exif_imagetype')) {
2052 function exif_imagetype($file) {
2053 $size = getimagesize($file);
2058 function validate_include(&$file) {
2061 $file = realpath($file);
2063 if (strpos($file, getcwd()) !== 0)
2066 $file = str_replace(getcwd()."/", "", $file, $count);
2070 if ($orig_file !== $file)
2074 if (strpos($file, "include/") === 0)
2077 if (strpos($file, "addon/") === 0)
2086 function current_load() {
2087 if (!function_exists('sys_getloadavg'))
2090 $load_arr = sys_getloadavg();
2092 if (!is_array($load_arr))
2095 return max($load_arr);
2099 * @brief get c-style args
2104 return get_app()->argc;
2108 * @brief Returns the value of a argv key
2110 * @param int $x argv key
2111 * @return string Value of the argv key
2114 if(array_key_exists($x,get_app()->argv))
2115 return get_app()->argv[$x];