4 * This file defines some global constants and includes the central App class.
10 * Friendica is a communications platform for integrated social communications
11 * utilising decentralised communications and linkage to several indie social
12 * projects - as well as popular mainstream providers.
14 * Our mission is to free our friends and families from the clutches of
15 * data-harvesting corporations, and pave the way to a future where social
16 * communications are free and open and flow between alternate providers as
17 * easily as email does today.
20 require_once('include/autoloader.php');
22 require_once('include/config.php');
23 require_once('include/network.php');
24 require_once('include/plugin.php');
25 require_once('include/text.php');
26 require_once('include/datetime.php');
27 require_once('include/pgettext.php');
28 require_once('include/nav.php');
29 require_once('include/cache.php');
30 require_once('library/Mobile_Detect/Mobile_Detect.php');
31 require_once('include/features.php');
32 require_once('include/identity.php');
34 require_once('update.php');
35 require_once('include/dbstructure.php');
37 define ( 'FRIENDICA_PLATFORM', 'Friendica');
38 define ( 'FRIENDICA_CODENAME', 'Asparagus');
39 define ( 'FRIENDICA_VERSION', '3.5-dev' );
40 define ( 'DFRN_PROTOCOL_VERSION', '2.23' );
41 define ( 'DB_UPDATE_VERSION', 1194 );
44 * @brief Constant with a HTML line break.
46 * Contains a HTML line break (br) element and a real carriage return with line
47 * feed for the source.
48 * This can be used in HTML and JavaScript where needed a line break.
50 define ( 'EOL', "<br />\r\n" );
51 define ( 'ATOM_TIME', 'Y-m-d\TH:i:s\Z' );
55 * @brief Image storage quality.
57 * Lower numbers save space at cost of image detail.
58 * For ease of upgrade, please do not change here. Change jpeg quality with
59 * $a->config['system']['jpeg_quality'] = n;
60 * in .htconfig.php, where n is netween 1 and 100, and with very poor results
65 define ( 'JPEG_QUALITY', 100 );
67 * $a->config['system']['png_quality'] from 0 (uncompressed) to 9
69 define ( 'PNG_QUALITY', 8 );
73 * An alternate way of limiting picture upload sizes. Specify the maximum pixel
74 * length that pictures are allowed to be (for non-square pictures, it will apply
75 * to the longest side). Pictures longer than this length will be resized to be
76 * this length (on the longest side, the other side will be scaled appropriately).
77 * Modify this value using
79 * $a->config['system']['max_image_length'] = n;
83 * If you don't want to set a maximum length, set to -1. The default value is
84 * defined by 'MAX_IMAGE_LENGTH' below.
87 define ( 'MAX_IMAGE_LENGTH', -1 );
94 define ( 'DEFAULT_DB_ENGINE', 'MyISAM' );
99 * SSL redirection policies
102 define ( 'SSL_POLICY_NONE', 0 );
103 define ( 'SSL_POLICY_FULL', 1 );
104 define ( 'SSL_POLICY_SELFSIGN', 2 );
113 define ( 'LOGGER_NORMAL', 0 );
114 define ( 'LOGGER_TRACE', 1 );
115 define ( 'LOGGER_DEBUG', 2 );
116 define ( 'LOGGER_DATA', 3 );
117 define ( 'LOGGER_ALL', 4 );
126 define ( 'CACHE_MONTH', 0 );
127 define ( 'CACHE_WEEK', 1 );
128 define ( 'CACHE_DAY', 2 );
129 define ( 'CACHE_HOUR', 3 );
135 * Registration policies
138 define ( 'REGISTER_CLOSED', 0 );
139 define ( 'REGISTER_APPROVE', 1 );
140 define ( 'REGISTER_OPEN', 2 );
149 define ( 'CONTACT_IS_FOLLOWER', 1);
150 define ( 'CONTACT_IS_SHARING', 2);
151 define ( 'CONTACT_IS_FRIEND', 3);
157 * DB update return values
160 define ( 'UPDATE_SUCCESS', 0);
161 define ( 'UPDATE_FAILED', 1);
166 * @name page/profile types
168 * PAGE_NORMAL is a typical personal profile account
169 * PAGE_SOAPBOX automatically approves all friend requests as CONTACT_IS_SHARING, (readonly)
170 * PAGE_COMMUNITY automatically approves all friend requests as CONTACT_IS_SHARING, but with
171 * write access to wall and comments (no email and not included in page owner's ACL lists)
172 * PAGE_FREELOVE automatically approves all friend requests as full friends (CONTACT_IS_FRIEND).
176 define ( 'PAGE_NORMAL', 0 );
177 define ( 'PAGE_SOAPBOX', 1 );
178 define ( 'PAGE_COMMUNITY', 2 );
179 define ( 'PAGE_FREELOVE', 3 );
180 define ( 'PAGE_BLOG', 4 );
181 define ( 'PAGE_PRVGROUP', 5 );
187 * Type of the community page
190 define ( 'CP_NO_COMMUNITY_PAGE', -1 );
191 define ( 'CP_USERS_ON_SERVER', 0 );
192 define ( 'CP_GLOBAL_COMMUNITY', 1 );
198 * Network and protocol family types
201 define ( 'NETWORK_DFRN', 'dfrn'); // Friendica, Mistpark, other DFRN implementations
202 define ( 'NETWORK_ZOT', 'zot!'); // Zot!
203 define ( 'NETWORK_OSTATUS', 'stat'); // status.net, identi.ca, GNU-social, other OStatus implementations
204 define ( 'NETWORK_FEED', 'feed'); // RSS/Atom feeds with no known "post/notify" protocol
205 define ( 'NETWORK_DIASPORA', 'dspr'); // Diaspora
206 define ( 'NETWORK_MAIL', 'mail'); // IMAP/POP
207 define ( 'NETWORK_MAIL2', 'mai2'); // extended IMAP/POP
208 define ( 'NETWORK_FACEBOOK', 'face'); // Facebook API
209 define ( 'NETWORK_LINKEDIN', 'lnkd'); // LinkedIn
210 define ( 'NETWORK_XMPP', 'xmpp'); // XMPP
211 define ( 'NETWORK_MYSPACE', 'mysp'); // MySpace
212 define ( 'NETWORK_GPLUS', 'goog'); // Google+
213 define ( 'NETWORK_PUMPIO', 'pump'); // pump.io
214 define ( 'NETWORK_TWITTER', 'twit'); // Twitter
215 define ( 'NETWORK_DIASPORA2', 'dspc'); // Diaspora connector
216 define ( 'NETWORK_STATUSNET', 'stac'); // Statusnet connector
217 define ( 'NETWORK_APPNET', 'apdn'); // app.net
218 define ( 'NETWORK_NEWS', 'nntp'); // Network News Transfer Protocol
219 define ( 'NETWORK_ICALENDAR', 'ical'); // iCalendar
220 define ( 'NETWORK_PHANTOM', 'unkn'); // Place holder
224 * These numbers are used in stored permissions
225 * and existing allocations MUST NEVER BE CHANGED
226 * OR RE-ASSIGNED! You may only add to them.
229 $netgroup_ids = array(
230 NETWORK_DFRN => (-1),
232 NETWORK_OSTATUS => (-3),
233 NETWORK_FEED => (-4),
234 NETWORK_DIASPORA => (-5),
235 NETWORK_MAIL => (-6),
236 NETWORK_MAIL2 => (-7),
237 NETWORK_FACEBOOK => (-8),
238 NETWORK_LINKEDIN => (-9),
239 NETWORK_XMPP => (-10),
240 NETWORK_MYSPACE => (-11),
241 NETWORK_GPLUS => (-12),
242 NETWORK_PUMPIO => (-13),
243 NETWORK_TWITTER => (-14),
244 NETWORK_DIASPORA2 => (-15),
245 NETWORK_STATUSNET => (-16),
246 NETWORK_APPNET => (-17),
247 NETWORK_NEWS => (-18),
248 NETWORK_ICALENDAR => (-19),
250 NETWORK_PHANTOM => (-127),
255 * Maximum number of "people who like (or don't like) this" that we will list by name
258 define ( 'MAX_LIKERS', 75);
261 * Communication timeout
264 define ( 'ZCURL_TIMEOUT' , (-1));
270 * Email notification options
273 define ( 'NOTIFY_INTRO', 0x0001 );
274 define ( 'NOTIFY_CONFIRM', 0x0002 );
275 define ( 'NOTIFY_WALL', 0x0004 );
276 define ( 'NOTIFY_COMMENT', 0x0008 );
277 define ( 'NOTIFY_MAIL', 0x0010 );
278 define ( 'NOTIFY_SUGGEST', 0x0020 );
279 define ( 'NOTIFY_PROFILE', 0x0040 );
280 define ( 'NOTIFY_TAGSELF', 0x0080 );
281 define ( 'NOTIFY_TAGSHARE', 0x0100 );
282 define ( 'NOTIFY_POKE', 0x0200 );
283 define ( 'NOTIFY_SHARE', 0x0400 );
285 define ( 'NOTIFY_SYSTEM', 0x8000 );
295 define ( 'TERM_UNKNOWN', 0 );
296 define ( 'TERM_HASHTAG', 1 );
297 define ( 'TERM_MENTION', 2 );
298 define ( 'TERM_CATEGORY', 3 );
299 define ( 'TERM_PCATEGORY', 4 );
300 define ( 'TERM_FILE', 5 );
301 define ( 'TERM_SAVEDSEARCH', 6 );
302 define ( 'TERM_CONVERSATION', 7 );
304 define ( 'TERM_OBJ_POST', 1 );
305 define ( 'TERM_OBJ_PHOTO', 2 );
312 * Various namespaces we may need to parse
315 define ( 'NAMESPACE_ZOT', 'http://purl.org/zot' );
316 define ( 'NAMESPACE_DFRN' , 'http://purl.org/macgirvin/dfrn/1.0' );
317 define ( 'NAMESPACE_THREAD' , 'http://purl.org/syndication/thread/1.0' );
318 define ( 'NAMESPACE_TOMB' , 'http://purl.org/atompub/tombstones/1.0' );
319 define ( 'NAMESPACE_ACTIVITY', 'http://activitystrea.ms/spec/1.0/' );
320 define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/' );
321 define ( 'NAMESPACE_MEDIA', 'http://purl.org/syndication/atommedia' );
322 define ( 'NAMESPACE_SALMON_ME', 'http://salmon-protocol.org/ns/magic-env' );
323 define ( 'NAMESPACE_OSTATUSSUB', 'http://ostatus.org/schema/1.0/subscribe' );
324 define ( 'NAMESPACE_GEORSS', 'http://www.georss.org/georss' );
325 define ( 'NAMESPACE_POCO', 'http://portablecontacts.net/spec/1.0' );
326 define ( 'NAMESPACE_FEED', 'http://schemas.google.com/g/2010#updates-from' );
327 define ( 'NAMESPACE_OSTATUS', 'http://ostatus.org/schema/1.0' );
328 define ( 'NAMESPACE_STATUSNET', 'http://status.net/schema/api/1/' );
329 define ( 'NAMESPACE_ATOM1', 'http://www.w3.org/2005/Atom' );
335 * Activity stream defines
338 define ( 'ACTIVITY_LIKE', NAMESPACE_ACTIVITY_SCHEMA . 'like' );
339 define ( 'ACTIVITY_DISLIKE', NAMESPACE_DFRN . '/dislike' );
340 define ( 'ACTIVITY_ATTEND', NAMESPACE_ZOT . '/activity/attendyes' );
341 define ( 'ACTIVITY_ATTENDNO', NAMESPACE_ZOT . '/activity/attendno' );
342 define ( 'ACTIVITY_ATTENDMAYBE', NAMESPACE_ZOT . '/activity/attendmaybe' );
344 define ( 'ACTIVITY_OBJ_HEART', NAMESPACE_DFRN . '/heart' );
346 define ( 'ACTIVITY_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
347 define ( 'ACTIVITY_REQ_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'request-friend' );
348 define ( 'ACTIVITY_UNFRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'remove-friend' );
349 define ( 'ACTIVITY_FOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'follow' );
350 define ( 'ACTIVITY_UNFOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'stop-following' );
351 define ( 'ACTIVITY_JOIN', NAMESPACE_ACTIVITY_SCHEMA . 'join' );
353 define ( 'ACTIVITY_POST', NAMESPACE_ACTIVITY_SCHEMA . 'post' );
354 define ( 'ACTIVITY_UPDATE', NAMESPACE_ACTIVITY_SCHEMA . 'update' );
355 define ( 'ACTIVITY_TAG', NAMESPACE_ACTIVITY_SCHEMA . 'tag' );
356 define ( 'ACTIVITY_FAVORITE', NAMESPACE_ACTIVITY_SCHEMA . 'favorite' );
357 define ( 'ACTIVITY_SHARE', NAMESPACE_ACTIVITY_SCHEMA . 'share' );
359 define ( 'ACTIVITY_POKE', NAMESPACE_ZOT . '/activity/poke' );
360 define ( 'ACTIVITY_MOOD', NAMESPACE_ZOT . '/activity/mood' );
362 define ( 'ACTIVITY_OBJ_BOOKMARK', NAMESPACE_ACTIVITY_SCHEMA . 'bookmark' );
363 define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
364 define ( 'ACTIVITY_OBJ_NOTE', NAMESPACE_ACTIVITY_SCHEMA . 'note' );
365 define ( 'ACTIVITY_OBJ_PERSON', NAMESPACE_ACTIVITY_SCHEMA . 'person' );
366 define ( 'ACTIVITY_OBJ_IMAGE', NAMESPACE_ACTIVITY_SCHEMA . 'image' );
367 define ( 'ACTIVITY_OBJ_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
368 define ( 'ACTIVITY_OBJ_VIDEO', NAMESPACE_ACTIVITY_SCHEMA . 'video' );
369 define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
370 define ( 'ACTIVITY_OBJ_ALBUM', NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
371 define ( 'ACTIVITY_OBJ_EVENT', NAMESPACE_ACTIVITY_SCHEMA . 'event' );
372 define ( 'ACTIVITY_OBJ_GROUP', NAMESPACE_ACTIVITY_SCHEMA . 'group' );
373 define ( 'ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN . '/tagterm' );
374 define ( 'ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN . '/profile' );
375 define ( 'ACTIVITY_OBJ_QUESTION', 'http://activityschema.org/object/question' );
381 * Item weight for query ordering
384 define ( 'GRAVITY_PARENT', 0);
385 define ( 'GRAVITY_LIKE', 3);
386 define ( 'GRAVITY_COMMENT', 6);
392 * Reverse the effect of magic_quotes_gpc if it is enabled.
393 * Please disable magic_quotes_gpc so we don't have to do this.
394 * See http://php.net/manual/en/security.magicquotes.disabling.php
400 error_reporting(E_ERROR | E_WARNING | E_PARSE);
404 // This has to be quite large to deal with embedded private photos
405 ini_set('pcre.backtrack_limit', 500000);
408 if (get_magic_quotes_gpc()) {
409 $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
410 while (list($key, $val) = each($process)) {
411 foreach ($val as $k => $v) {
412 unset($process[$key][$k]);
414 $process[$key][stripslashes($k)] = $v;
415 $process[] = &$process[$key][stripslashes($k)];
417 $process[$key][stripslashes($k)] = stripslashes($v);
430 * @brief Our main application structure for the life of this page.
432 * Primarily deals with the URL that got us here
433 * and tries to make some sense of it, and
434 * stores our page contents and config storage
435 * and anything else that might need to be passed around
436 * before we spit the page out.
441 public $module_loaded = false;
442 public $query_string;
451 public $page_contact;
453 public $data = array();
454 public $error = false;
464 public $interactive = true;
466 public $apps = array();
470 public $is_friendica_app;
471 public $performance = array();
472 public $callstack = array();
479 // Allow themes to control internal parameters
480 // by changing App values in theme.php
482 public $sourcename = '';
483 public $videowidth = 425;
484 public $videoheight = 350;
485 public $force_max_items = 0;
486 public $theme_thread_allow = true;
487 public $theme_events_in_profile = true;
490 * @brief An array for all theme-controllable parameters
492 * Mostly unimplemented yet. Only options 'template_engine' and
495 public $theme = array(
498 'videoheight' => 350,
499 'force_max_items' => 0,
500 'thread_allow' => true,
502 'template_engine' => 'smarty3',
506 * @brief An array of registered template engines ('name'=>'class name')
508 public $template_engines = array();
510 * @brief An array of instanced template engines ('name'=>'instance')
512 public $template_engine_instance = array();
514 private $ldelim = array(
518 private $rdelim = array(
529 private $curl_content_type;
530 private $curl_headers;
532 private $cached_profile_image;
533 private $cached_profile_picdate;
538 * @brief App constructor.
540 function __construct() {
542 global $default_timezone;
546 if (file_exists(".htpreconfig.php"))
547 @include(".htpreconfig.php");
549 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
551 date_default_timezone_set($this->timezone);
553 $this->performance["start"] = microtime(true);
554 $this->performance["database"] = 0;
555 $this->performance["network"] = 0;
556 $this->performance["file"] = 0;
557 $this->performance["rendering"] = 0;
558 $this->performance["parser"] = 0;
559 $this->performance["marktime"] = 0;
560 $this->performance["markstart"] = microtime(true);
562 $this->callstack["database"] = array();
563 $this->callstack["network"] = array();
564 $this->callstack["file"] = array();
565 $this->callstack["rendering"] = array();
566 $this->callstack["parser"] = array();
568 $this->config = array();
569 $this->page = array();
570 $this->pager= array();
572 $this->query_string = '';
577 'include' . PATH_SEPARATOR
578 . 'library' . PATH_SEPARATOR
579 . 'library/phpsec' . PATH_SEPARATOR
580 . 'library/langdet' . PATH_SEPARATOR
584 $this->scheme = 'http';
585 if(x($_SERVER,'HTTPS') && $_SERVER['HTTPS'])
586 $this->scheme = 'https';
587 elseif(x($_SERVER,'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443))
588 $this->scheme = 'https';
590 if(x($_SERVER,'SERVER_NAME')) {
591 $this->hostname = $_SERVER['SERVER_NAME'];
593 if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
594 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
596 * Figure out if we are running at the top of a domain
597 * or in a sub-directory and adjust accordingly
600 $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
601 if(isset($path) && strlen($path) && ($path != $this->path))
606 $this->hostname = $hostname;
608 if (is_array($_SERVER["argv"]) && $_SERVER["argc"]>1 && substr(end($_SERVER["argv"]), 0, 4)=="http" ) {
609 $this->set_baseurl(array_pop($_SERVER["argv"]) );
613 #set_include_path("include/$this->hostname" . PATH_SEPARATOR . get_include_path());
615 if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,9) === "pagename=") {
616 $this->query_string = substr($_SERVER['QUERY_STRING'],9);
617 // removing trailing / - maybe a nginx problem
618 if (substr($this->query_string, 0, 1) == "/")
619 $this->query_string = substr($this->query_string, 1);
620 } elseif((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
621 $this->query_string = substr($_SERVER['QUERY_STRING'],2);
622 // removing trailing / - maybe a nginx problem
623 if (substr($this->query_string, 0, 1) == "/")
624 $this->query_string = substr($this->query_string, 1);
627 if (x($_GET,'pagename'))
628 $this->cmd = trim($_GET['pagename'],'/\\');
629 elseif (x($_GET,'q'))
630 $this->cmd = trim($_GET['q'],'/\\');
634 $this->query_string = str_replace($this->cmd."&",$this->cmd."?", $this->query_string);
637 // unix style "homedir"
639 if(substr($this->cmd,0,1) === '~')
640 $this->cmd = 'profile/' . substr($this->cmd,1);
642 // Diaspora style profile url
644 if(substr($this->cmd,0,2) === 'u/')
645 $this->cmd = 'profile/' . substr($this->cmd,2);
650 * Break the URL path into C style argc/argv style arguments for our
651 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
652 * will be 3 (integer) and $this->argv will contain:
658 * There will always be one argument. If provided a naked domain
659 * URL, $this->argv[0] is set to "home".
663 $this->argv = explode('/',$this->cmd);
664 $this->argc = count($this->argv);
665 if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
666 $this->module = str_replace(".", "_", $this->argv[0]);
667 $this->module = str_replace("-", "_", $this->module);
671 $this->argv = array('home');
672 $this->module = 'home';
676 * See if there is any page number information, and initialise
680 $this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
681 $this->pager['itemspage'] = 50;
682 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
683 if($this->pager['start'] < 0)
684 $this->pager['start'] = 0;
685 $this->pager['total'] = 0;
688 * Detect mobile devices
691 $mobile_detect = new Mobile_Detect();
692 $this->is_mobile = $mobile_detect->isMobile();
693 $this->is_tablet = $mobile_detect->isTablet();
696 $this->is_friendica_app = ($_SERVER['HTTP_USER_AGENT'] == "Apache-HttpClient/UNAVAILABLE (java 1.4)");
699 * register template engines
701 $dc = get_declared_classes();
702 foreach ($dc as $k) {
703 if (in_array("ITemplateEngine", class_implements($k))){
704 $this->register_template_engine($k);
712 function get_basepath() {
714 $basepath = get_config("system", "basepath");
717 $basepath = dirname(__FILE__);
720 $basepath = $_SERVER["DOCUMENT_ROOT"];
723 $basepath = $_SERVER["PWD"];
728 function get_scheme() {
729 return($this->scheme);
732 function get_baseurl($ssl = false) {
734 // Is the function called statically?
735 if (!is_object($this))
736 return(self::$a->get_baseurl($ssl));
738 $scheme = $this->scheme;
740 if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
741 if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
744 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
745 // (and also the login link). Anything seen by an outsider will have it turned off.
747 if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
755 if (get_config('config','hostname') != "")
756 $this->hostname = get_config('config','hostname');
758 $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
759 return $this->baseurl;
762 function set_baseurl($url) {
763 $parsed = @parse_url($url);
765 $this->baseurl = $url;
768 $this->scheme = $parsed['scheme'];
770 $hostname = $parsed['host'];
771 if(x($parsed,'port'))
772 $hostname .= ':' . $parsed['port'];
773 if(x($parsed,'path'))
774 $this->path = trim($parsed['path'],'\\/');
776 if (file_exists(".htpreconfig.php"))
777 @include(".htpreconfig.php");
779 if (get_config('config','hostname') != "")
780 $this->hostname = get_config('config','hostname');
782 if (!isset($this->hostname) OR ($this->hostname == ""))
783 $this->hostname = $hostname;
788 function get_hostname() {
789 if (get_config('config','hostname') != "")
790 $this->hostname = get_config('config','hostname');
792 return $this->hostname;
795 function set_hostname($h) {
796 $this->hostname = $h;
799 function set_path($p) {
800 $this->path = trim(trim($p),'/');
803 function get_path() {
807 function set_pager_total($n) {
808 $this->pager['total'] = intval($n);
811 function set_pager_itemspage($n) {
812 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
813 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
816 function set_pager_page($n) {
817 $this->pager['page'] = $n;
818 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
821 function init_pagehead() {
822 $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
824 // If the update is "deactivated" set it to the highest integer number (~24 days)
826 $interval = 2147483647;
828 if($interval < 10000)
831 // compose the page title from the sitename and the
832 // current module called
833 if (!$this->module=='')
835 $this->page['title'] = $this->config['sitename'].' ('.$this->module.')';
837 $this->page['title'] = $this->config['sitename'];
840 /* put the head template at the beginning of page['htmlhead']
841 * since the code added by the modules frequently depends on it
844 if(!isset($this->page['htmlhead']))
845 $this->page['htmlhead'] = '';
847 // If we're using Smarty, then doing replace_macros() will replace
848 // any unrecognized variables with a blank string. Since we delay
849 // replacing $stylesheet until later, we need to replace it now
850 // with another variable name
851 if($this->theme['template_engine'] === 'smarty3')
852 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
854 $stylesheet = '$stylesheet';
856 $shortcut_icon = get_config("system", "shortcut_icon");
857 if ($shortcut_icon == "")
858 $shortcut_icon = "images/friendica-32.png";
860 $touch_icon = get_config("system", "touch_icon");
861 if ($touch_icon == "")
862 $touch_icon = "images/friendica-128.png";
864 $tpl = get_markup_template('head.tpl');
865 $this->page['htmlhead'] = replace_macros($tpl,array(
866 '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
867 '$local_user' => local_user(),
868 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
869 '$delitem' => t('Delete this item?'),
870 '$comment' => t('Comment'),
871 '$showmore' => t('show more'),
872 '$showfewer' => t('show fewer'),
873 '$update_interval' => $interval,
874 '$shortcut_icon' => $shortcut_icon,
875 '$touch_icon' => $touch_icon,
876 '$stylesheet' => $stylesheet
877 )) . $this->page['htmlhead'];
880 function init_page_end() {
881 if(!isset($this->page['end']))
882 $this->page['end'] = '';
883 $tpl = get_markup_template('end.tpl');
884 $this->page['end'] = replace_macros($tpl,array(
885 '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
886 )) . $this->page['end'];
889 function set_curl_code($code) {
890 $this->curl_code = $code;
893 function get_curl_code() {
894 return $this->curl_code;
897 function set_curl_content_type($content_type) {
898 $this->curl_content_type = $content_type;
901 function get_curl_content_type() {
902 return $this->curl_content_type;
905 function set_curl_headers($headers) {
906 $this->curl_headers = $headers;
909 function get_curl_headers() {
910 return $this->curl_headers;
913 function get_cached_avatar_image($avatar_image){
914 return $avatar_image;
916 // The following code is deactivated. It doesn't seem to make any sense and it slows down the system.
918 if($this->cached_profile_image[$avatar_image])
919 return $this->cached_profile_image[$avatar_image];
921 $path_parts = explode("/",$avatar_image);
922 $common_filename = $path_parts[count($path_parts)-1];
924 if($this->cached_profile_picdate[$common_filename]){
925 $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
927 $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like '%%/%s'",
930 $this->cached_profile_image[$avatar_image] = $avatar_image;
932 $this->cached_profile_picdate[$common_filename] = "?rev=".urlencode($r[0]['picdate']);
933 $this->cached_profile_image[$avatar_image] = $avatar_image.$this->cached_profile_picdate[$common_filename];
936 return $this->cached_profile_image[$avatar_image];
942 * @brief Removes the baseurl from an url. This avoids some mixed content problems.
946 * @return string The cleaned url
948 function remove_baseurl($url){
950 // Is the function called statically?
951 if (!is_object($this))
952 return(self::$a->remove_baseurl($url));
954 $url = normalise_link($url);
955 $base = normalise_link($this->get_baseurl());
956 $url = str_replace($base."/", "", $url);
961 * @brief Register template engine class
963 * If $name is "", is used class static property $class::$name
965 * @param string $class
966 * @param string $name
968 function register_template_engine($class, $name = '') {
970 $v = get_class_vars( $class );
971 if(x($v,"name")) $name = $v['name'];
974 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
977 $this->template_engines[$name] = $class;
981 * @brief Return template engine instance.
983 * If $name is not defined, return engine defined by theme,
986 * @param strin $name Template engine name
987 * @return object Template Engine instance
989 function template_engine($name = ''){
991 $template_engine = $name;
993 $template_engine = 'smarty3';
994 if (x($this->theme, 'template_engine')) {
995 $template_engine = $this->theme['template_engine'];
999 if (isset($this->template_engines[$template_engine])){
1000 if(isset($this->template_engine_instance[$template_engine])){
1001 return $this->template_engine_instance[$template_engine];
1003 $class = $this->template_engines[$template_engine];
1005 $this->template_engine_instance[$template_engine] = $obj;
1010 echo "template engine <tt>$template_engine</tt> is not registered!\n"; killme();
1014 * @brief Returns the active template engine.
1018 function get_template_engine() {
1019 return $this->theme['template_engine'];
1022 function set_template_engine($engine = 'smarty3') {
1023 $this->theme['template_engine'] = $engine;
1025 $this->theme['template_engine'] = 'smarty3';
1029 if(is_writable('view/smarty3/'))
1030 $this->theme['template_engine'] = 'smarty3';
1038 function get_template_ldelim($engine = 'smarty3') {
1039 return $this->ldelim[$engine];
1042 function get_template_rdelim($engine = 'smarty3') {
1043 return $this->rdelim[$engine];
1046 function save_timestamp($stamp, $value) {
1047 $duration = (float)(microtime(true)-$stamp);
1049 $this->performance[$value] += (float)$duration;
1050 $this->performance["marktime"] += (float)$duration;
1052 $callstack = $this->callstack();
1054 $this->callstack[$value][$callstack] += (float)$duration;
1059 * @brief Returns a string with a callstack. Can be used for logging.
1063 function callstack() {
1064 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 6);
1066 // We remove the first two items from the list since they contain data that we don't need.
1067 array_shift($trace);
1068 array_shift($trace);
1070 $callstack = array();
1071 foreach ($trace AS $func)
1072 $callstack[] = $func["function"];
1074 return implode(", ", $callstack);
1077 function mark_timestamp($mark) {
1078 //$this->performance["markstart"] -= microtime(true) - $this->performance["marktime"];
1079 $this->performance["markstart"] = microtime(true) - $this->performance["markstart"] - $this->performance["marktime"];
1082 function get_useragent() {
1083 return(FRIENDICA_PLATFORM." '".FRIENDICA_CODENAME."' ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION."; ".$this->get_baseurl());
1086 function is_friendica_app() {
1087 return($this->is_friendica_app);
1093 * @brief Retrieve the App structure
1095 * Useful in functions which require it but don't get it passed to them
1097 function get_app() {
1104 * @brief Multi-purpose function to check variable state.
1106 * Usage: x($var) or $x($array, 'key')
1108 * returns false if variable/key is not set
1109 * if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
1110 * e.g. x('') or x(0) returns 0;
1112 * @param string|array $s variable to check
1113 * @param string $k key inside the array to check
1117 function x($s,$k = NULL) {
1119 if((is_array($s)) && (array_key_exists($k,$s))) {
1139 * @brief Called from db initialisation if db is dead.
1141 function system_unavailable() {
1142 include('system_unavailable.php');
1148 function clean_urls() {
1150 // if($a->config['system']['clean_urls'])
1157 $base = $a->get_baseurl();
1164 * @brief Returns the baseurl.
1166 * @see App::get_baseurl()
1172 return $a->get_baseurl();
1176 * @brief Return absolut URL for given $path.
1178 * @param string $path
1182 function absurl($path) {
1183 if(strpos($path,'/') === 0)
1184 return z_path() . $path;
1189 * @brief Function to check if request was an AJAX (xmlhttprequest) request.
1193 function is_ajax() {
1194 return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
1197 function check_db() {
1199 $build = get_config('system','build');
1201 set_config('system','build',DB_UPDATE_VERSION);
1202 $build = DB_UPDATE_VERSION;
1204 if($build != DB_UPDATE_VERSION)
1205 proc_run('php', 'include/dbupdate.php');
1211 * Sets the base url for use in cmdline programs which don't have
1212 * $_SERVER variables
1214 function check_url(&$a) {
1216 $url = get_config('system','url');
1218 // if the url isn't set or the stored url is radically different
1219 // than the currently visited url, store the current value accordingly.
1220 // "Radically different" ignores common variations such as http vs https
1221 // and www.example.com vs example.com.
1222 // We will only change the url to an ip address if there is no existing setting
1225 $url = set_config('system','url',$a->get_baseurl());
1226 if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
1227 $url = set_config('system','url',$a->get_baseurl());
1234 * @brief Automatic database updates
1236 function update_db(&$a) {
1237 $build = get_config('system','build');
1239 $build = set_config('system','build',DB_UPDATE_VERSION);
1241 if($build != DB_UPDATE_VERSION) {
1242 $stored = intval($build);
1243 $current = intval(DB_UPDATE_VERSION);
1244 if($stored < $current) {
1245 load_config('database');
1247 // We're reporting a different version than what is currently installed.
1248 // Run any existing update scripts to bring the database up to current.
1250 // make sure that boot.php and update.php are the same release, we might be
1251 // updating right this very second and the correct version of the update.php
1252 // file may not be here yet. This can happen on a very busy site.
1254 if(DB_UPDATE_VERSION == UPDATE_VERSION) {
1255 // Compare the current structure with the defined structure
1257 $t = get_config('database','dbupdate_'.DB_UPDATE_VERSION);
1261 set_config('database','dbupdate_'.DB_UPDATE_VERSION, time());
1263 // run old update routine (wich could modify the schema and
1264 // conflits with new routine)
1265 for ($x = $stored; $x < NEW_UPDATE_ROUTINE_VERSION; $x++) {
1266 $r = run_update_function($x);
1269 if ($stored < NEW_UPDATE_ROUTINE_VERSION) $stored = NEW_UPDATE_ROUTINE_VERSION;
1272 // run new update routine
1273 // it update the structure in one call
1274 $retval = update_structure(false, true);
1282 set_config('database','dbupdate_'.DB_UPDATE_VERSION, 'success');
1285 // run any left update_nnnn functions in update.php
1286 for($x = $stored; $x < $current; $x ++) {
1287 $r = run_update_function($x);
1297 function run_update_function($x) {
1298 if(function_exists('update_' . $x)) {
1300 // There could be a lot of processes running or about to run.
1301 // We want exactly one process to run the update command.
1302 // So store the fact that we're taking responsibility
1303 // after first checking to see if somebody else already has.
1305 // If the update fails or times-out completely you may need to
1306 // delete the config entry to try again.
1308 $t = get_config('database','update_' . $x);
1311 set_config('database','update_' . $x, time());
1313 // call the specific update
1315 $func = 'update_' . $x;
1319 //send the administrator an e-mail
1322 sprintf(t('Update %s failed. See error logs.'), $x)
1326 set_config('database','update_' . $x, 'success');
1327 set_config('system','build', $x + 1);
1331 set_config('database','update_' . $x, 'success');
1332 set_config('system','build', $x + 1);
1339 * @brief Synchronise plugins:
1341 * $a->config['system']['addon'] contains a comma-separated list of names
1342 * of plugins/addons which are used on this system.
1343 * Go through the database list of already installed addons, and if we have
1344 * an entry, but it isn't in the config list, call the uninstall procedure
1345 * and mark it uninstalled in the database (for now we'll remove it).
1346 * Then go through the config list and if we have a plugin that isn't installed,
1347 * call the install procedure and add it to the database.
1352 function check_plugins(&$a) {
1354 $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
1358 $installed = array();
1360 $plugins = get_config('system','addon');
1361 $plugins_arr = array();
1364 $plugins_arr = explode(',',str_replace(' ', '',$plugins));
1366 $a->plugins = $plugins_arr;
1368 $installed_arr = array();
1370 if(count($installed)) {
1371 foreach($installed as $i) {
1372 if(! in_array($i['name'],$plugins_arr)) {
1373 uninstall_plugin($i['name']);
1376 $installed_arr[] = $i['name'];
1381 if(count($plugins_arr)) {
1382 foreach($plugins_arr as $p) {
1383 if(! in_array($p,$installed_arr)) {
1395 function get_guid($size=16, $prefix = "") {
1397 if ($prefix == "") {
1399 $prefix = hash("crc32", $a->get_hostname());
1402 while (strlen($prefix) < ($size - 13))
1403 $prefix .= mt_rand();
1406 $prefix = substr($prefix, 0, $size - 22);
1407 return(str_replace(".", "", uniqid($prefix, true)));
1409 $prefix = substr($prefix, 0, max($size - 13, 0));
1410 return(uniqid($prefix));
1415 * @brief Wrapper for adding a login box.
1417 * @param bool $register
1418 * If $register == true provide a registration link.
1419 * This will most always depend on the value of $a->config['register_policy'].
1420 * @param bool $hiddens
1423 * Returns the complete html for inserting into the page
1425 * @hooks 'login_hook'
1428 function login($register = false, $hiddens=false) {
1434 'title' => t('Create a New Account'),
1435 'desc' => t('Register')
1439 $noid = get_config('system','no_openid');
1441 $dest_url = $a->query_string;
1444 $tpl = get_markup_template("logout.tpl");
1447 $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
1448 '$baseurl' => $a->get_baseurl(true)
1451 $tpl = get_markup_template("login.tpl");
1452 $_SESSION['return_url'] = $a->query_string;
1453 $a->module = 'login';
1456 $o .= replace_macros($tpl, array(
1458 '$dest_url' => $dest_url,
1459 '$logout' => t('Logout'),
1460 '$login' => t('Login'),
1462 '$lname' => array('username', t('Nickname or Email address: ') , '', ''),
1463 '$lpassword' => array('password', t('Password: '), '', ''),
1464 '$lremember' => array('remember', t('Remember me'), 0, ''),
1466 '$openid' => !$noid,
1467 '$lopenid' => array('openid_url', t('Or login using OpenID: '),'',''),
1469 '$hiddens' => $hiddens,
1471 '$register' => $reg,
1473 '$lostpass' => t('Forgot your password?'),
1474 '$lostlink' => t('Password Reset'),
1476 '$tostitle' => t('Website Terms of Service'),
1477 '$toslink' => t('terms of service'),
1479 '$privacytitle' => t('Website Privacy Policy'),
1480 '$privacylink' => t('privacy policy'),
1484 call_hooks('login_hook',$o);
1490 * @brief Used to end the current process, after saving session state.
1493 session_write_close();
1498 * @brief Redirect to another URL and terminate this process.
1500 function goaway($s) {
1501 header("Location: $s");
1507 * @brief Returns the user id of locally logged in user or false.
1509 * @return int|bool user id or false
1511 function local_user() {
1512 if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
1513 return intval($_SESSION['uid']);
1518 * @brief Returns contact id of authenticated site visitor or false
1520 * @return int|bool visitor_id or false
1522 function remote_user() {
1523 if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
1524 return intval($_SESSION['visitor_id']);
1529 * @brief Show an error message to user.
1531 * This function save text in session, to be shown to the user at next page load
1533 * @param string $s - Text of notice
1535 function notice($s) {
1537 if(! x($_SESSION,'sysmsg')) $_SESSION['sysmsg'] = array();
1539 $_SESSION['sysmsg'][] = $s;
1543 * @brief Show an info message to user.
1545 * This function save text in session, to be shown to the user at next page load
1547 * @param string $s - Text of notice
1552 if (local_user() AND get_pconfig(local_user(),'system','ignore_info'))
1555 if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
1557 $_SESSION['sysmsg_info'][] = $s;
1562 * @brief Wrapper around config to limit the text length of an incoming message
1566 function get_max_import_size() {
1568 return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
1572 * @brief Wrap calls to proc_close(proc_open()) and call hook
1573 * so plugins can take part in process :)
1575 * @param string $cmd program to run
1577 * next args are passed as $cmd command line
1578 * e.g.: proc_run("ls","-la","/tmp");
1580 * @note $cmd and string args are surrounded with ""
1585 function proc_run($cmd){
1589 $args = func_get_args();
1595 // expand any arrays
1597 foreach($args as $arg) {
1598 if(is_array($arg)) {
1599 foreach($arg as $n) {
1609 $arr = array('args' => $args, 'run_cmd' => true);
1611 call_hooks("proc_run", $arr);
1612 if(! $arr['run_cmd'])
1615 if(count($args) && $args[0] === 'php') {
1617 if (get_config("system", "worker")) {
1621 $parameters = json_encode($argv);
1622 $found = q("SELECT `id` FROM `workerqueue` WHERE `parameter` = '%s'",
1623 dbesc($parameters));
1626 q("INSERT INTO `workerqueue` (`parameter`, `created`, `priority`)
1627 VALUES ('%s', '%s', %d)",
1629 dbesc(datetime_convert()),
1632 // Should we quit and wait for the poller to be called as a cronjob?
1633 if (get_config("system", "worker_dont_fork"))
1636 // Checking number of workers
1637 $workers = q("SELECT COUNT(*) AS `workers` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
1639 // Get number of allowed number of worker threads
1640 $queues = intval(get_config("system", "worker_queues"));
1645 // If there are already enough workers running, don't fork another one
1646 if ($workers[0]["workers"] >= $queues)
1649 // Now call the poller to execute the jobs that we just added to the queue
1650 $args = array("php", "include/poller.php", "no_cron");
1653 $args[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
1656 // add baseurl to args. cli scripts can't construct it
1657 $args[] = $a->get_baseurl();
1659 for($x = 0; $x < count($args); $x ++)
1660 $args[$x] = escapeshellarg($args[$x]);
1662 $cmdline = implode($args," ");
1664 if(get_config('system','proc_windows'))
1665 proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
1667 proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
1670 function current_theme(){
1671 $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
1677 // Find the theme that belongs to the user whose stuff we are looking at
1679 if($a->profile_uid && ($a->profile_uid != local_user())) {
1680 $r = q("select theme from user where uid = %d limit 1",
1681 intval($a->profile_uid)
1684 $page_theme = $r[0]['theme'];
1687 // Allow folks to over-rule user themes and always use their own on their own site.
1688 // This works only if the user is on the same server
1690 if($page_theme && local_user() && (local_user() != $a->profile_uid)) {
1691 if(get_pconfig(local_user(),'system','always_my_theme'))
1695 // $mobile_detect = new Mobile_Detect();
1696 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1697 $is_mobile = $a->is_mobile || $a->is_tablet;
1699 $standard_system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1700 $standard_theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $standard_system_theme);
1703 if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
1704 $system_theme = $standard_system_theme;
1705 $theme_name = $standard_theme_name;
1708 $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : $standard_system_theme);
1709 $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
1711 if($theme_name === '---') {
1712 // user has selected to have the mobile theme be the same as the normal one
1713 $system_theme = $standard_system_theme;
1714 $theme_name = $standard_theme_name;
1717 $theme_name = $page_theme;
1722 $system_theme = $standard_system_theme;
1723 $theme_name = $standard_theme_name;
1726 $theme_name = $page_theme;
1730 (file_exists('view/theme/' . $theme_name . '/style.css') ||
1731 file_exists('view/theme/' . $theme_name . '/style.php')))
1732 return($theme_name);
1734 foreach($app_base_themes as $t) {
1735 if(file_exists('view/theme/' . $t . '/style.css')||
1736 file_exists('view/theme/' . $t . '/style.php'))
1740 $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
1741 if(count($fallback))
1742 return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
1747 * @brief Return full URL to theme which is currently in effect.
1749 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1753 function current_theme_url() {
1756 $t = current_theme();
1758 $opts = (($a->profile_uid) ? '?f=&puid=' . $a->profile_uid : '');
1759 if (file_exists('view/theme/' . $t . '/style.php'))
1760 return('view/theme/'.$t.'/style.pcss'.$opts);
1762 return('view/theme/'.$t.'/style.css');
1765 function feed_birthday($uid,$tz) {
1769 * Determine the next birthday, but only if the birthday is published
1770 * in the default profile. We _could_ also look for a private profile that the
1771 * recipient can see, but somebody could get mad at us if they start getting
1772 * public birthday greetings when they haven't made this info public.
1774 * Assuming we are able to publish this info, we are then going to convert
1775 * the start time from the owner's timezone to UTC.
1777 * This will potentially solve the problem found with some social networks
1778 * where birthdays are converted to the viewer's timezone and salutations from
1779 * elsewhere in the world show up on the wrong day. We will convert it to the
1780 * viewer's timezone also, but first we are going to convert it from the birthday
1781 * person's timezone to GMT - so the viewer may find the birthday starting at
1782 * 6:00PM the day before, but that will correspond to midnight to the birthday person.
1792 $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
1796 if($p && count($p)) {
1797 $tmp_dob = substr($p[0]['dob'],5);
1798 if(intval($tmp_dob)) {
1799 $y = datetime_convert($tz,$tz,'now','Y');
1800 $bd = $y . '-' . $tmp_dob . ' 00:00';
1801 $t_dob = strtotime($bd);
1802 $now = strtotime(datetime_convert($tz,$tz,'now'));
1804 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
1805 $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
1813 * @brief Check if current user has admin role.
1815 * @return bool true if user is an admin
1817 function is_site_admin() {
1820 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
1822 //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
1823 if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && in_array($a->user['email'], $adminlist))
1829 function load_contact_links($uid) {
1835 if(! $uid || x($a->contacts,'empty'))
1838 $r = q("SELECT `id`,`network`,`url`,`thumb`, `rel` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `thumb` != ''",
1843 $url = normalise_link($rr['url']);
1847 $ret['empty'] = true;
1849 $a->contacts = $ret;
1854 * @brief Returns querystring as string from a mapped array.
1856 * @param array $params mapped array with query parameters
1857 * @param string $name of parameter, default null
1861 function build_querystring($params, $name=null) {
1863 foreach($params as $key=>$val) {
1864 if(is_array($val)) {
1866 $ret .= build_querystring($val, $key);
1868 $ret .= build_querystring($val, $name."[$key]");
1871 $val = urlencode($val);
1873 $ret.=$name."[$key]"."=$val&";
1875 $ret.= "$key=$val&";
1882 function explode_querystring($query) {
1883 $arg_st = strpos($query, '?');
1884 if($arg_st !== false) {
1885 $base = substr($query, 0, $arg_st);
1892 $args = explode('&', substr($query, $arg_st));
1893 foreach($args as $k=>$arg) {
1897 $args = array_values($args);
1902 $args = array_values($args);
1912 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
1914 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
1916 function curPageURL() {
1918 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
1920 if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
1921 $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
1923 $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
1928 function random_digits($digits) {
1930 for($i = 0; $i < $digits; $i++) {
1936 function get_server() {
1937 $server = get_config("system", "directory");
1940 $server = "http://dir.friendi.ca";
1945 function get_cachefile($file, $writemode = true) {
1946 $cache = get_itemcachepath();
1948 if ((! $cache) || (! is_dir($cache)))
1951 $subfolder = $cache."/".substr($file, 0, 2);
1953 $cachepath = $subfolder."/".$file;
1956 if (!is_dir($subfolder)) {
1958 chmod($subfolder, 0777);
1965 function clear_cache($basepath = "", $path = "") {
1967 $basepath = get_itemcachepath();
1971 if (($path == "") OR (!is_dir($path)))
1974 if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
1977 $cachetime = (int)get_config('system','itemcache_duration');
1978 if ($cachetime == 0)
1981 if (is_writable($path)){
1982 if ($dh = opendir($path)) {
1983 while (($file = readdir($dh)) !== false) {
1984 $fullpath = $path."/".$file;
1985 if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
1986 clear_cache($basepath, $fullpath);
1987 if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
1995 function get_itemcachepath() {
1996 // Checking, if the cache is deactivated
1997 $cachetime = (int)get_config('system','itemcache_duration');
2001 $itemcache = get_config('system','itemcache');
2002 if (($itemcache != "") AND is_dir($itemcache) AND is_writable($itemcache))
2005 $temppath = get_temppath();
2007 if ($temppath != "") {
2008 $itemcache = $temppath."/itemcache";
2009 if(!file_exists($itemcache) && !is_dir($itemcache)) {
2013 if (is_dir($itemcache) AND is_writable($itemcache)) {
2014 set_config("system", "itemcache", $itemcache);
2021 function get_lockpath() {
2022 $lockpath = get_config('system','lockpath');
2023 if (($lockpath != "") AND is_dir($lockpath) AND is_writable($lockpath))
2026 $temppath = get_temppath();
2028 if ($temppath != "") {
2029 $lockpath = $temppath."/lock";
2031 if (!is_dir($lockpath))
2033 elseif (!is_writable($lockpath))
2034 $lockpath = $temppath;
2036 if (is_dir($lockpath) AND is_writable($lockpath)) {
2037 set_config("system", "lockpath", $lockpath);
2044 function get_temppath() {
2047 $temppath = get_config("system","temppath");
2048 if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath))
2051 $temppath = sys_get_temp_dir();
2052 if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath)) {
2053 $temppath .= "/".$a->get_hostname();
2054 if (!is_dir($temppath))
2057 if (is_dir($temppath) AND is_writable($temppath)) {
2058 set_config("system", "temppath", $temppath);
2066 function set_template_engine(&$a, $engine = 'internal') {
2067 /// @note This function is no longer necessary, but keep it as a wrapper to the class method
2068 /// to avoid breaking themes again unnecessarily
2070 $a->set_template_engine($engine);
2073 if(!function_exists('exif_imagetype')) {
2074 function exif_imagetype($file) {
2075 $size = getimagesize($file);
2080 function validate_include(&$file) {
2083 $file = realpath($file);
2085 if (strpos($file, getcwd()) !== 0)
2088 $file = str_replace(getcwd()."/", "", $file, $count);
2092 if ($orig_file !== $file)
2096 if (strpos($file, "include/") === 0)
2099 if (strpos($file, "addon/") === 0)
2108 function current_load() {
2109 if (!function_exists('sys_getloadavg'))
2112 $load_arr = sys_getloadavg();
2114 if (!is_array($load_arr))
2117 return max($load_arr);
2121 * @brief get c-style args
2126 return get_app()->argc;
2130 * @brief Returns the value of a argv key
2132 * @param int $x argv key
2133 * @return string Value of the argv key
2136 if(array_key_exists($x,get_app()->argv))
2137 return get_app()->argv[$x];