3 require_once('include/config.php');
4 require_once('include/network.php');
5 require_once('include/plugin.php');
6 require_once('include/text.php');
7 require_once('include/datetime.php');
8 require_once('include/pgettext.php');
9 require_once('include/nav.php');
10 require_once('include/cache.php');
11 require_once('library/Mobile_Detect/Mobile_Detect.php');
12 require_once('include/features.php');
13 require_once('include/identity.php');
15 require_once('update.php');
16 require_once('include/dbstructure.php');
18 define ( 'FRIENDICA_PLATFORM', 'Friendica');
19 define ( 'FRIENDICA_CODENAME', 'Lily of the valley');
20 define ( 'FRIENDICA_VERSION', '3.4.3-dev' );
21 define ( 'DFRN_PROTOCOL_VERSION', '2.23' );
22 define ( 'DB_UPDATE_VERSION', 1191 );
23 define ( 'EOL', "<br />\r\n" );
24 define ( 'ATOM_TIME', 'Y-m-d\TH:i:s\Z' );
29 * Image storage quality. Lower numbers save space at cost of image detail.
30 * For ease of upgrade, please do not change here. Change jpeg quality with
31 * $a->config['system']['jpeg_quality'] = n;
32 * in .htconfig.php, where n is netween 1 and 100, and with very poor results
37 define ( 'JPEG_QUALITY', 100 );
39 * $a->config['system']['png_quality'] from 0 (uncompressed) to 9
41 define ( 'PNG_QUALITY', 8 );
45 * An alternate way of limiting picture upload sizes. Specify the maximum pixel
46 * length that pictures are allowed to be (for non-square pictures, it will apply
47 * to the longest side). Pictures longer than this length will be resized to be
48 * this length (on the longest side, the other side will be scaled appropriately).
49 * Modify this value using
51 * $a->config['system']['max_image_length'] = n;
55 * If you don't want to set a maximum length, set to -1. The default value is
56 * defined by 'MAX_IMAGE_LENGTH' below.
59 define ( 'MAX_IMAGE_LENGTH', -1 );
66 define ( 'DEFAULT_DB_ENGINE', 'MyISAM' );
69 * SSL redirection policies
72 define ( 'SSL_POLICY_NONE', 0 );
73 define ( 'SSL_POLICY_FULL', 1 );
74 define ( 'SSL_POLICY_SELFSIGN', 2 );
81 define ( 'LOGGER_NORMAL', 0 );
82 define ( 'LOGGER_TRACE', 1 );
83 define ( 'LOGGER_DEBUG', 2 );
84 define ( 'LOGGER_DATA', 3 );
85 define ( 'LOGGER_ALL', 4 );
91 define ( 'CACHE_MONTH', 0 );
92 define ( 'CACHE_WEEK', 1 );
93 define ( 'CACHE_DAY', 2 );
94 define ( 'CACHE_HOUR', 3 );
97 * registration policies
100 define ( 'REGISTER_CLOSED', 0 );
101 define ( 'REGISTER_APPROVE', 1 );
102 define ( 'REGISTER_OPEN', 2 );
108 define ( 'CONTACT_IS_FOLLOWER', 1);
109 define ( 'CONTACT_IS_SHARING', 2);
110 define ( 'CONTACT_IS_FRIEND', 3);
114 * DB update return values
117 define ( 'UPDATE_SUCCESS', 0);
118 define ( 'UPDATE_FAILED', 1);
125 * PAGE_NORMAL is a typical personal profile account
126 * PAGE_SOAPBOX automatically approves all friend requests as CONTACT_IS_SHARING, (readonly)
127 * PAGE_COMMUNITY automatically approves all friend requests as CONTACT_IS_SHARING, but with
128 * write access to wall and comments (no email and not included in page owner's ACL lists)
129 * PAGE_FREELOVE automatically approves all friend requests as full friends (CONTACT_IS_FRIEND).
133 define ( 'PAGE_NORMAL', 0 );
134 define ( 'PAGE_SOAPBOX', 1 );
135 define ( 'PAGE_COMMUNITY', 2 );
136 define ( 'PAGE_FREELOVE', 3 );
137 define ( 'PAGE_BLOG', 4 );
138 define ( 'PAGE_PRVGROUP', 5 );
140 // Type of the community page
141 define ( 'CP_NO_COMMUNITY_PAGE', -1 );
142 define ( 'CP_USERS_ON_SERVER', 0 );
143 define ( 'CP_GLOBAL_COMMUNITY', 1 );
146 * Network and protocol family types
149 define ( 'NETWORK_DFRN', 'dfrn'); // Friendica, Mistpark, other DFRN implementations
150 define ( 'NETWORK_ZOT', 'zot!'); // Zot!
151 define ( 'NETWORK_OSTATUS', 'stat'); // status.net, identi.ca, GNU-social, other OStatus implementations
152 define ( 'NETWORK_FEED', 'feed'); // RSS/Atom feeds with no known "post/notify" protocol
153 define ( 'NETWORK_DIASPORA', 'dspr'); // Diaspora
154 define ( 'NETWORK_MAIL', 'mail'); // IMAP/POP
155 define ( 'NETWORK_MAIL2', 'mai2'); // extended IMAP/POP
156 define ( 'NETWORK_FACEBOOK', 'face'); // Facebook API
157 define ( 'NETWORK_LINKEDIN', 'lnkd'); // LinkedIn
158 define ( 'NETWORK_XMPP', 'xmpp'); // XMPP
159 define ( 'NETWORK_MYSPACE', 'mysp'); // MySpace
160 define ( 'NETWORK_GPLUS', 'goog'); // Google+
161 define ( 'NETWORK_PUMPIO', 'pump'); // pump.io
162 define ( 'NETWORK_TWITTER', 'twit'); // Twitter
163 define ( 'NETWORK_DIASPORA2', 'dspc'); // Diaspora connector
164 define ( 'NETWORK_STATUSNET', 'stac'); // Statusnet connector
165 define ( 'NETWORK_APPNET', 'apdn'); // app.net
166 define ( 'NETWORK_NEWS', 'nntp'); // Network News Transfer Protocol
167 define ( 'NETWORK_ICALENDAR', 'ical'); // iCalendar
168 define ( 'NETWORK_PHANTOM', 'unkn'); // Place holder
171 * These numbers are used in stored permissions
172 * and existing allocations MUST NEVER BE CHANGED
173 * OR RE-ASSIGNED! You may only add to them.
176 $netgroup_ids = array(
177 NETWORK_DFRN => (-1),
179 NETWORK_OSTATUS => (-3),
180 NETWORK_FEED => (-4),
181 NETWORK_DIASPORA => (-5),
182 NETWORK_MAIL => (-6),
183 NETWORK_MAIL2 => (-7),
184 NETWORK_FACEBOOK => (-8),
185 NETWORK_LINKEDIN => (-9),
186 NETWORK_XMPP => (-10),
187 NETWORK_MYSPACE => (-11),
188 NETWORK_GPLUS => (-12),
189 NETWORK_PUMPIO => (-13),
190 NETWORK_TWITTER => (-14),
191 NETWORK_DIASPORA2 => (-15),
192 NETWORK_STATUSNET => (-16),
193 NETWORK_APPNET => (-17),
194 NETWORK_NEWS => (-18),
195 NETWORK_ICALENDAR => (-19),
197 NETWORK_PHANTOM => (-127),
202 * Maximum number of "people who like (or don't like) this" that we will list by name
205 define ( 'MAX_LIKERS', 75);
208 * Communication timeout
211 define ( 'ZCURL_TIMEOUT' , (-1));
215 * email notification options
218 define ( 'NOTIFY_INTRO', 0x0001 );
219 define ( 'NOTIFY_CONFIRM', 0x0002 );
220 define ( 'NOTIFY_WALL', 0x0004 );
221 define ( 'NOTIFY_COMMENT', 0x0008 );
222 define ( 'NOTIFY_MAIL', 0x0010 );
223 define ( 'NOTIFY_SUGGEST', 0x0020 );
224 define ( 'NOTIFY_PROFILE', 0x0040 );
225 define ( 'NOTIFY_TAGSELF', 0x0080 );
226 define ( 'NOTIFY_TAGSHARE', 0x0100 );
227 define ( 'NOTIFY_POKE', 0x0200 );
228 define ( 'NOTIFY_SHARE', 0x0400 );
230 define ( 'NOTIFY_SYSTEM', 0x8000 );
237 define ( 'TERM_UNKNOWN', 0 );
238 define ( 'TERM_HASHTAG', 1 );
239 define ( 'TERM_MENTION', 2 );
240 define ( 'TERM_CATEGORY', 3 );
241 define ( 'TERM_PCATEGORY', 4 );
242 define ( 'TERM_FILE', 5 );
243 define ( 'TERM_SAVEDSEARCH', 6 );
244 define ( 'TERM_CONVERSATION', 7 );
246 define ( 'TERM_OBJ_POST', 1 );
247 define ( 'TERM_OBJ_PHOTO', 2 );
252 * various namespaces we may need to parse
255 define ( 'NAMESPACE_ZOT', 'http://purl.org/zot' );
256 define ( 'NAMESPACE_DFRN' , 'http://purl.org/macgirvin/dfrn/1.0' );
257 define ( 'NAMESPACE_THREAD' , 'http://purl.org/syndication/thread/1.0' );
258 define ( 'NAMESPACE_TOMB' , 'http://purl.org/atompub/tombstones/1.0' );
259 define ( 'NAMESPACE_ACTIVITY', 'http://activitystrea.ms/spec/1.0/' );
260 define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/' );
261 define ( 'NAMESPACE_MEDIA', 'http://purl.org/syndication/atommedia' );
262 define ( 'NAMESPACE_SALMON_ME', 'http://salmon-protocol.org/ns/magic-env' );
263 define ( 'NAMESPACE_OSTATUSSUB', 'http://ostatus.org/schema/1.0/subscribe' );
264 define ( 'NAMESPACE_GEORSS', 'http://www.georss.org/georss' );
265 define ( 'NAMESPACE_POCO', 'http://portablecontacts.net/spec/1.0' );
266 define ( 'NAMESPACE_FEED', 'http://schemas.google.com/g/2010#updates-from' );
267 define ( 'NAMESPACE_OSTATUS', 'http://ostatus.org/schema/1.0' );
268 define ( 'NAMESPACE_STATUSNET', 'http://status.net/schema/api/1/' );
269 define ( 'NAMESPACE_ATOM1', 'http://www.w3.org/2005/Atom' );
271 * activity stream defines
274 define ( 'ACTIVITY_LIKE', NAMESPACE_ACTIVITY_SCHEMA . 'like' );
275 define ( 'ACTIVITY_DISLIKE', NAMESPACE_DFRN . '/dislike' );
276 define ( 'ACTIVITY_ATTEND', NAMESPACE_ZOT . '/activity/attendyes' );
277 define ( 'ACTIVITY_ATTENDNO', NAMESPACE_ZOT . '/activity/attendno' );
278 define ( 'ACTIVITY_ATTENDMAYBE', NAMESPACE_ZOT . '/activity/attendmaybe' );
280 define ( 'ACTIVITY_OBJ_HEART', NAMESPACE_DFRN . '/heart' );
282 define ( 'ACTIVITY_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
283 define ( 'ACTIVITY_REQ_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'request-friend' );
284 define ( 'ACTIVITY_UNFRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'remove-friend' );
285 define ( 'ACTIVITY_FOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'follow' );
286 define ( 'ACTIVITY_UNFOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'stop-following' );
287 define ( 'ACTIVITY_JOIN', NAMESPACE_ACTIVITY_SCHEMA . 'join' );
289 define ( 'ACTIVITY_POST', NAMESPACE_ACTIVITY_SCHEMA . 'post' );
290 define ( 'ACTIVITY_UPDATE', NAMESPACE_ACTIVITY_SCHEMA . 'update' );
291 define ( 'ACTIVITY_TAG', NAMESPACE_ACTIVITY_SCHEMA . 'tag' );
292 define ( 'ACTIVITY_FAVORITE', NAMESPACE_ACTIVITY_SCHEMA . 'favorite' );
293 define ( 'ACTIVITY_SHARE', NAMESPACE_ACTIVITY_SCHEMA . 'share' );
295 define ( 'ACTIVITY_POKE', NAMESPACE_ZOT . '/activity/poke' );
296 define ( 'ACTIVITY_MOOD', NAMESPACE_ZOT . '/activity/mood' );
298 define ( 'ACTIVITY_OBJ_BOOKMARK', NAMESPACE_ACTIVITY_SCHEMA . 'bookmark' );
299 define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
300 define ( 'ACTIVITY_OBJ_NOTE', NAMESPACE_ACTIVITY_SCHEMA . 'note' );
301 define ( 'ACTIVITY_OBJ_PERSON', NAMESPACE_ACTIVITY_SCHEMA . 'person' );
302 define ( 'ACTIVITY_OBJ_IMAGE', NAMESPACE_ACTIVITY_SCHEMA . 'image' );
303 define ( 'ACTIVITY_OBJ_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
304 define ( 'ACTIVITY_OBJ_VIDEO', NAMESPACE_ACTIVITY_SCHEMA . 'video' );
305 define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
306 define ( 'ACTIVITY_OBJ_ALBUM', NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
307 define ( 'ACTIVITY_OBJ_EVENT', NAMESPACE_ACTIVITY_SCHEMA . 'event' );
308 define ( 'ACTIVITY_OBJ_GROUP', NAMESPACE_ACTIVITY_SCHEMA . 'group' );
309 define ( 'ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN . '/tagterm' );
310 define ( 'ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN . '/profile' );
311 define ( 'ACTIVITY_OBJ_QUESTION', 'http://activityschema.org/object/question' );
314 * item weight for query ordering
317 define ( 'GRAVITY_PARENT', 0);
318 define ( 'GRAVITY_LIKE', 3);
319 define ( 'GRAVITY_COMMENT', 6);
323 * Reverse the effect of magic_quotes_gpc if it is enabled.
324 * Please disable magic_quotes_gpc so we don't have to do this.
325 * See http://php.net/manual/en/security.magicquotes.disabling.php
331 error_reporting(E_ERROR | E_WARNING | E_PARSE);
335 // This has to be quite large to deal with embedded private photos
336 ini_set('pcre.backtrack_limit', 500000);
339 if (get_magic_quotes_gpc()) {
340 $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
341 while (list($key, $val) = each($process)) {
342 foreach ($val as $k => $v) {
343 unset($process[$key][$k]);
345 $process[$key][stripslashes($k)] = $v;
346 $process[] = &$process[$key][stripslashes($k)];
348 $process[$key][stripslashes($k)] = stripslashes($v);
361 * Our main application structure for the life of this page
362 * Primarily deals with the URL that got us here
363 * and tries to make some sense of it, and
364 * stores our page contents and config storage
365 * and anything else that might need to be passed around
366 * before we spit the page out.
370 if(! class_exists('App')) {
373 public $module_loaded = false;
374 public $query_string;
383 public $page_contact;
385 public $data = array();
386 public $error = false;
396 public $interactive = true;
398 public $apps = array();
402 public $is_friendica_app;
403 public $performance = array();
410 // Allow themes to control internal parameters
411 // by changing App values in theme.php
413 public $sourcename = '';
414 public $videowidth = 425;
415 public $videoheight = 350;
416 public $force_max_items = 0;
417 public $theme_thread_allow = true;
418 public $theme_events_in_profile = true;
420 // An array for all theme-controllable parameters
421 // Mostly unimplemented yet. Only options 'stylesheet' and
424 public $theme = array(
427 'videoheight' => 350,
428 'force_max_items' => 0,
429 'thread_allow' => true,
431 'template_engine' => 'smarty3',
434 // array of registered template engines ('name'=>'class name')
435 public $template_engines = array();
436 // array of instanced template engines ('name'=>'instance')
437 public $template_engine_instance = array();
439 private $ldelim = array(
443 private $rdelim = array(
454 private $curl_content_type;
455 private $curl_headers;
457 private $cached_profile_image;
458 private $cached_profile_picdate;
460 function __construct() {
462 global $default_timezone;
466 if (file_exists(".htpreconfig.php"))
467 @include(".htpreconfig.php");
469 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
471 date_default_timezone_set($this->timezone);
473 $this->performance["start"] = microtime(true);
474 $this->performance["database"] = 0;
475 $this->performance["network"] = 0;
476 $this->performance["file"] = 0;
477 $this->performance["rendering"] = 0;
478 $this->performance["parser"] = 0;
479 $this->performance["marktime"] = 0;
480 $this->performance["markstart"] = microtime(true);
482 $this->config = array();
483 $this->page = array();
484 $this->pager= array();
486 $this->query_string = '';
491 'include' . PATH_SEPARATOR
492 . 'library' . PATH_SEPARATOR
493 . 'library/phpsec' . PATH_SEPARATOR
494 . 'library/langdet' . PATH_SEPARATOR
498 $this->scheme = 'http';
499 if(x($_SERVER,'HTTPS') && $_SERVER['HTTPS'])
500 $this->scheme = 'https';
501 elseif(x($_SERVER,'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443))
502 $this->scheme = 'https';
504 if(x($_SERVER,'SERVER_NAME')) {
505 $this->hostname = $_SERVER['SERVER_NAME'];
507 // See bug 437 - this didn't work so disabling it
508 //if(stristr($this->hostname,'xn--')) {
509 // PHP or webserver may have converted idn to punycode, so
510 // convert punycode back to utf-8
511 // require_once('library/simplepie/idn/idna_convert.class.php');
512 // $x = new idna_convert();
513 // $this->hostname = $x->decode($_SERVER['SERVER_NAME']);
516 if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
517 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
519 * Figure out if we are running at the top of a domain
520 * or in a sub-directory and adjust accordingly
523 $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
524 if(isset($path) && strlen($path) && ($path != $this->path))
529 $this->hostname = $hostname;
531 if (is_array($_SERVER["argv"]) && $_SERVER["argc"]>1 && substr(end($_SERVER["argv"]), 0, 4)=="http" ) {
532 $this->set_baseurl(array_pop($_SERVER["argv"]) );
536 #set_include_path("include/$this->hostname" . PATH_SEPARATOR . get_include_path());
538 if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,9) === "pagename=") {
539 $this->query_string = substr($_SERVER['QUERY_STRING'],9);
540 // removing trailing / - maybe a nginx problem
541 if (substr($this->query_string, 0, 1) == "/")
542 $this->query_string = substr($this->query_string, 1);
543 } elseif((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
544 $this->query_string = substr($_SERVER['QUERY_STRING'],2);
545 // removing trailing / - maybe a nginx problem
546 if (substr($this->query_string, 0, 1) == "/")
547 $this->query_string = substr($this->query_string, 1);
550 if (x($_GET,'pagename'))
551 $this->cmd = trim($_GET['pagename'],'/\\');
552 elseif (x($_GET,'q'))
553 $this->cmd = trim($_GET['q'],'/\\');
557 $this->query_string = str_replace($this->cmd."&",$this->cmd."?", $this->query_string);
560 // unix style "homedir"
562 if(substr($this->cmd,0,1) === '~')
563 $this->cmd = 'profile/' . substr($this->cmd,1);
565 // Diaspora style profile url
567 if(substr($this->cmd,0,2) === 'u/')
568 $this->cmd = 'profile/' . substr($this->cmd,2);
573 * Break the URL path into C style argc/argv style arguments for our
574 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
575 * will be 3 (integer) and $this->argv will contain:
581 * There will always be one argument. If provided a naked domain
582 * URL, $this->argv[0] is set to "home".
586 $this->argv = explode('/',$this->cmd);
587 $this->argc = count($this->argv);
588 if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
589 $this->module = str_replace(".", "_", $this->argv[0]);
590 $this->module = str_replace("-", "_", $this->module);
594 $this->argv = array('home');
595 $this->module = 'home';
599 * See if there is any page number information, and initialise
603 $this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
604 $this->pager['itemspage'] = 50;
605 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
606 if($this->pager['start'] < 0)
607 $this->pager['start'] = 0;
608 $this->pager['total'] = 0;
611 * Detect mobile devices
614 $mobile_detect = new Mobile_Detect();
615 $this->is_mobile = $mobile_detect->isMobile();
616 $this->is_tablet = $mobile_detect->isTablet();
619 $this->is_friendica_app = ($_SERVER['HTTP_USER_AGENT'] == "Apache-HttpClient/UNAVAILABLE (java 1.4)");
622 * register template engines
624 $dc = get_declared_classes();
625 foreach ($dc as $k) {
626 if (in_array("ITemplateEngine", class_implements($k))){
627 $this->register_template_engine($k);
633 function get_basepath() {
635 $basepath = get_config("system", "basepath");
638 $basepath = $_SERVER["DOCUMENT_ROOT"];
641 $basepath = $_SERVER["PWD"];
646 function get_scheme() {
647 return($this->scheme);
650 function get_baseurl($ssl = false) {
652 $scheme = $this->scheme;
654 if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
655 if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
658 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
659 // (and also the login link). Anything seen by an outsider will have it turned off.
661 if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
669 if (get_config('config','hostname') != "")
670 $this->hostname = get_config('config','hostname');
672 $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
673 return $this->baseurl;
676 function set_baseurl($url) {
677 $parsed = @parse_url($url);
679 $this->baseurl = $url;
682 $this->scheme = $parsed['scheme'];
684 $hostname = $parsed['host'];
685 if(x($parsed,'port'))
686 $hostname .= ':' . $parsed['port'];
687 if(x($parsed,'path'))
688 $this->path = trim($parsed['path'],'\\/');
690 if (file_exists(".htpreconfig.php"))
691 @include(".htpreconfig.php");
693 if (get_config('config','hostname') != "")
694 $this->hostname = get_config('config','hostname');
696 if (!isset($this->hostname) OR ($this->hostname == ""))
697 $this->hostname = $hostname;
702 function get_hostname() {
703 if (get_config('config','hostname') != "")
704 $this->hostname = get_config('config','hostname');
706 return $this->hostname;
709 function set_hostname($h) {
710 $this->hostname = $h;
713 function set_path($p) {
714 $this->path = trim(trim($p),'/');
717 function get_path() {
721 function set_pager_total($n) {
722 $this->pager['total'] = intval($n);
725 function set_pager_itemspage($n) {
726 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
727 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
730 function set_pager_page($n) {
731 $this->pager['page'] = $n;
732 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
735 function init_pagehead() {
736 $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
738 // If the update is "deactivated" set it to the highest integer number (~24 days)
740 $interval = 2147483647;
742 if($interval < 10000)
745 // compose the page title from the sitename and the
746 // current module called
747 if (!$this->module=='')
749 $this->page['title'] = $this->config['sitename'].' ('.$this->module.')';
751 $this->page['title'] = $this->config['sitename'];
754 /* put the head template at the beginning of page['htmlhead']
755 * since the code added by the modules frequently depends on it
758 if(!isset($this->page['htmlhead']))
759 $this->page['htmlhead'] = '';
761 // If we're using Smarty, then doing replace_macros() will replace
762 // any unrecognized variables with a blank string. Since we delay
763 // replacing $stylesheet until later, we need to replace it now
764 // with another variable name
765 if($this->theme['template_engine'] === 'smarty3')
766 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
768 $stylesheet = '$stylesheet';
770 $shortcut_icon = get_config("system", "shortcut_icon");
771 if ($shortcut_icon == "")
772 $shortcut_icon = $this->get_baseurl()."/images/friendica-32.png";
774 $touch_icon = get_config("system", "touch_icon");
775 if ($touch_icon == "")
776 $touch_icon = $this->get_baseurl()."/images/friendica-128.png";
778 $tpl = get_markup_template('head.tpl');
779 $this->page['htmlhead'] = replace_macros($tpl,array(
780 '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
781 '$local_user' => local_user(),
782 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
783 '$delitem' => t('Delete this item?'),
784 '$comment' => t('Comment'),
785 '$showmore' => t('show more'),
786 '$showfewer' => t('show fewer'),
787 '$update_interval' => $interval,
788 '$shortcut_icon' => $shortcut_icon,
789 '$touch_icon' => $touch_icon,
790 '$stylesheet' => $stylesheet
791 )) . $this->page['htmlhead'];
794 function init_page_end() {
795 if(!isset($this->page['end']))
796 $this->page['end'] = '';
797 $tpl = get_markup_template('end.tpl');
798 $this->page['end'] = replace_macros($tpl,array(
799 '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
800 )) . $this->page['end'];
803 function set_curl_code($code) {
804 $this->curl_code = $code;
807 function get_curl_code() {
808 return $this->curl_code;
811 function set_curl_content_type($content_type) {
812 $this->curl_content_type = $content_type;
815 function get_curl_content_type() {
816 return $this->curl_content_type;
819 function set_curl_headers($headers) {
820 $this->curl_headers = $headers;
823 function get_curl_headers() {
824 return $this->curl_headers;
827 function get_cached_avatar_image($avatar_image){
828 if($this->cached_profile_image[$avatar_image])
829 return $this->cached_profile_image[$avatar_image];
831 $path_parts = explode("/",$avatar_image);
832 $common_filename = $path_parts[count($path_parts)-1];
834 if($this->cached_profile_picdate[$common_filename]){
835 $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
837 $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like '%%/%s'",
840 $this->cached_profile_image[$avatar_image] = $avatar_image;
842 $this->cached_profile_picdate[$common_filename] = "?rev=".urlencode($r[0]['picdate']);
843 $this->cached_profile_image[$avatar_image] = $avatar_image.$this->cached_profile_picdate[$common_filename];
846 return $this->cached_profile_image[$avatar_image];
851 * register template engine class
852 * if $name is "", is used class static property $class::$name
853 * @param string $class
854 * @param string $name
856 function register_template_engine($class, $name = '') {
858 $v = get_class_vars( $class );
859 if(x($v,"name")) $name = $v['name'];
862 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
865 $this->template_engines[$name] = $class;
869 * return template engine instance. If $name is not defined,
870 * return engine defined by theme, or default
872 * @param strin $name Template engine name
873 * @return object Template Engine instance
875 function template_engine($name = ''){
877 $template_engine = $name;
879 $template_engine = 'smarty3';
880 if (x($this->theme, 'template_engine')) {
881 $template_engine = $this->theme['template_engine'];
885 if (isset($this->template_engines[$template_engine])){
886 if(isset($this->template_engine_instance[$template_engine])){
887 return $this->template_engine_instance[$template_engine];
889 $class = $this->template_engines[$template_engine];
891 $this->template_engine_instance[$template_engine] = $obj;
896 echo "template engine <tt>$template_engine</tt> is not registered!\n"; killme();
899 function get_template_engine() {
900 return $this->theme['template_engine'];
903 function set_template_engine($engine = 'smarty3') {
904 $this->theme['template_engine'] = $engine;
906 $this->theme['template_engine'] = 'smarty3';
910 if(is_writable('view/smarty3/'))
911 $this->theme['template_engine'] = 'smarty3';
919 function get_template_ldelim($engine = 'smarty3') {
920 return $this->ldelim[$engine];
923 function get_template_rdelim($engine = 'smarty3') {
924 return $this->rdelim[$engine];
927 function save_timestamp($stamp, $value) {
928 $duration = (float)(microtime(true)-$stamp);
930 $this->performance[$value] += (float)$duration;
931 $this->performance["marktime"] += (float)$duration;
934 function mark_timestamp($mark) {
935 //$this->performance["markstart"] -= microtime(true) - $this->performance["marktime"];
936 $this->performance["markstart"] = microtime(true) - $this->performance["markstart"] - $this->performance["marktime"];
939 function get_useragent() {
940 return(FRIENDICA_PLATFORM." '".FRIENDICA_CODENAME."' ".FRIENDICA_VERSION."-".DB_UPDATE_VERSION."; ".$this->get_baseurl());
943 function is_friendica_app() {
944 return($this->is_friendica_app);
950 // retrieve the App structure
951 // useful in functions which require it but don't get it passed to them
953 if(! function_exists('get_app')) {
961 // Multi-purpose function to check variable state.
962 // Usage: x($var) or $x($array,'key')
963 // returns false if variable/key is not set
964 // if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
965 // e.g. x('') or x(0) returns 0;
967 if(! function_exists('x')) {
968 function x($s,$k = NULL) {
970 if((is_array($s)) && (array_key_exists($k,$s))) {
989 // called from db initialisation if db is dead.
991 if(! function_exists('system_unavailable')) {
992 function system_unavailable() {
993 include('system_unavailable.php');
1001 function clean_urls() {
1003 // if($a->config['system']['clean_urls'])
1010 $base = $a->get_baseurl();
1018 return $a->get_baseurl();
1021 function absurl($path) {
1022 if(strpos($path,'/') === 0)
1023 return z_path() . $path;
1027 function is_ajax() {
1028 return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
1031 function check_db() {
1033 $build = get_config('system','build');
1035 set_config('system','build',DB_UPDATE_VERSION);
1036 $build = DB_UPDATE_VERSION;
1038 if($build != DB_UPDATE_VERSION)
1039 proc_run('php', 'include/dbupdate.php');
1046 // Sets the base url for use in cmdline programs which don't have
1047 // $_SERVER variables
1049 if(! function_exists('check_url')) {
1050 function check_url(&$a) {
1052 $url = get_config('system','url');
1054 // if the url isn't set or the stored url is radically different
1055 // than the currently visited url, store the current value accordingly.
1056 // "Radically different" ignores common variations such as http vs https
1057 // and www.example.com vs example.com.
1058 // We will only change the url to an ip address if there is no existing setting
1061 $url = set_config('system','url',$a->get_baseurl());
1062 if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
1063 $url = set_config('system','url',$a->get_baseurl());
1070 // Automatic database updates
1072 if(! function_exists('update_db')) {
1073 function update_db(&$a) {
1074 $build = get_config('system','build');
1076 $build = set_config('system','build',DB_UPDATE_VERSION);
1078 if($build != DB_UPDATE_VERSION) {
1079 $stored = intval($build);
1080 $current = intval(DB_UPDATE_VERSION);
1081 if($stored < $current) {
1082 load_config('database');
1084 // We're reporting a different version than what is currently installed.
1085 // Run any existing update scripts to bring the database up to current.
1087 // make sure that boot.php and update.php are the same release, we might be
1088 // updating right this very second and the correct version of the update.php
1089 // file may not be here yet. This can happen on a very busy site.
1091 if(DB_UPDATE_VERSION == UPDATE_VERSION) {
1092 // Compare the current structure with the defined structure
1094 $t = get_config('database','dbupdate_'.DB_UPDATE_VERSION);
1098 set_config('database','dbupdate_'.DB_UPDATE_VERSION, time());
1100 // run old update routine (wich could modify the schema and
1101 // conflits with new routine)
1102 for ($x = $stored; $x < NEW_UPDATE_ROUTINE_VERSION; $x++) {
1103 $r = run_update_function($x);
1106 if ($stored < NEW_UPDATE_ROUTINE_VERSION) $stored = NEW_UPDATE_ROUTINE_VERSION;
1109 // run new update routine
1110 // it update the structure in one call
1111 $retval = update_structure(false, true);
1119 set_config('database','dbupdate_'.DB_UPDATE_VERSION, 'success');
1122 // run any left update_nnnn functions in update.php
1123 for($x = $stored; $x < $current; $x ++) {
1124 $r = run_update_function($x);
1134 if(!function_exists('run_update_function')){
1135 function run_update_function($x) {
1136 if(function_exists('update_' . $x)) {
1138 // There could be a lot of processes running or about to run.
1139 // We want exactly one process to run the update command.
1140 // So store the fact that we're taking responsibility
1141 // after first checking to see if somebody else already has.
1143 // If the update fails or times-out completely you may need to
1144 // delete the config entry to try again.
1146 $t = get_config('database','update_' . $x);
1149 set_config('database','update_' . $x, time());
1151 // call the specific update
1153 $func = 'update_' . $x;
1157 //send the administrator an e-mail
1160 sprintf(t('Update %s failed. See error logs.'), $x)
1164 set_config('database','update_' . $x, 'success');
1165 set_config('system','build', $x + 1);
1169 set_config('database','update_' . $x, 'success');
1170 set_config('system','build', $x + 1);
1178 if(! function_exists('check_plugins')) {
1179 function check_plugins(&$a) {
1183 * Synchronise plugins:
1185 * $a->config['system']['addon'] contains a comma-separated list of names
1186 * of plugins/addons which are used on this system.
1187 * Go through the database list of already installed addons, and if we have
1188 * an entry, but it isn't in the config list, call the uninstall procedure
1189 * and mark it uninstalled in the database (for now we'll remove it).
1190 * Then go through the config list and if we have a plugin that isn't installed,
1191 * call the install procedure and add it to the database.
1195 $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
1199 $installed = array();
1201 $plugins = get_config('system','addon');
1202 $plugins_arr = array();
1205 $plugins_arr = explode(',',str_replace(' ', '',$plugins));
1207 $a->plugins = $plugins_arr;
1209 $installed_arr = array();
1211 if(count($installed)) {
1212 foreach($installed as $i) {
1213 if(! in_array($i['name'],$plugins_arr)) {
1214 uninstall_plugin($i['name']);
1217 $installed_arr[] = $i['name'];
1222 if(count($plugins_arr)) {
1223 foreach($plugins_arr as $p) {
1224 if(! in_array($p,$installed_arr)) {
1237 function get_guid($size=16, $prefix = "") {
1239 if ($prefix == "") {
1241 $prefix = hash("crc32", $a->get_hostname());
1244 while (strlen($prefix) < ($size - 13))
1245 $prefix .= mt_rand();
1248 $prefix = substr($prefix, 0, $size - 22);
1249 return(str_replace(".", "", uniqid($prefix, true)));
1251 $prefix = substr($prefix, 0, max($size - 13, 0));
1252 return(uniqid($prefix));
1256 // wrapper for adding a login box. If $register == true provide a registration
1257 // link. This will most always depend on the value of $a->config['register_policy'].
1258 // returns the complete html for inserting into the page
1260 if(! function_exists('login')) {
1261 function login($register = false, $hiddens=false) {
1267 'title' => t('Create a New Account'),
1268 'desc' => t('Register')
1272 $noid = get_config('system','no_openid');
1274 $dest_url = $a->get_baseurl(true) . '/' . $a->query_string;
1277 $tpl = get_markup_template("logout.tpl");
1280 $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
1281 '$baseurl' => $a->get_baseurl(true)
1284 $tpl = get_markup_template("login.tpl");
1285 $_SESSION['return_url'] = $a->query_string;
1286 $a->module = 'login';
1289 $o .= replace_macros($tpl, array(
1291 '$dest_url' => $dest_url,
1292 '$logout' => t('Logout'),
1293 '$login' => t('Login'),
1295 '$lname' => array('username', t('Nickname or Email address: ') , '', ''),
1296 '$lpassword' => array('password', t('Password: '), '', ''),
1297 '$lremember' => array('remember', t('Remember me'), 0, ''),
1299 '$openid' => !$noid,
1300 '$lopenid' => array('openid_url', t('Or login using OpenID: '),'',''),
1302 '$hiddens' => $hiddens,
1304 '$register' => $reg,
1306 '$lostpass' => t('Forgot your password?'),
1307 '$lostlink' => t('Password Reset'),
1309 '$tostitle' => t('Website Terms of Service'),
1310 '$toslink' => t('terms of service'),
1312 '$privacytitle' => t('Website Privacy Policy'),
1313 '$privacylink' => t('privacy policy'),
1317 call_hooks('login_hook',$o);
1323 // Used to end the current process, after saving session state.
1325 if(! function_exists('killme')) {
1327 session_write_close();
1332 // redirect to another URL and terminate this process.
1334 if(! function_exists('goaway')) {
1335 function goaway($s) {
1336 header("Location: $s");
1342 // Returns the uid of locally logged in user or false.
1344 if(! function_exists('local_user')) {
1345 function local_user() {
1346 if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
1347 return intval($_SESSION['uid']);
1352 // Returns contact id of authenticated site visitor or false
1354 if(! function_exists('remote_user')) {
1355 function remote_user() {
1356 if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
1357 return intval($_SESSION['visitor_id']);
1362 // contents of $s are displayed prominently on the page the next time
1363 // a page is loaded. Usually used for errors or alerts.
1365 if(! function_exists('notice')) {
1367 * Show an error message to user.
1369 * This function save text in session, to be shown to the user at next page load
1371 * @param string $s - Text of notice
1373 function notice($s) {
1375 if(! x($_SESSION,'sysmsg')) $_SESSION['sysmsg'] = array();
1377 $_SESSION['sysmsg'][] = $s;
1380 if(! function_exists('info')) {
1382 * Show an info message to user.
1384 * This function save text in session, to be shown to the user at next page load
1386 * @param string $s - Text of notice
1391 if (local_user() AND get_pconfig(local_user(),'system','ignore_info'))
1394 if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
1396 $_SESSION['sysmsg_info'][] = $s;
1401 // wrapper around config to limit the text length of an incoming message
1403 if(! function_exists('get_max_import_size')) {
1404 function get_max_import_size() {
1406 return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
1412 * Wrap calls to proc_close(proc_open()) and call hook
1413 * so plugins can take part in process :)
1416 * $cmd program to run
1417 * next args are passed as $cmd command line
1419 * e.g.: proc_run("ls","-la","/tmp");
1421 * $cmd and string args are surrounded with ""
1424 if(! function_exists('proc_run')) {
1425 function proc_run($cmd){
1429 $args = func_get_args();
1435 // expand any arrays
1437 foreach($args as $arg) {
1438 if(is_array($arg)) {
1439 foreach($arg as $n) {
1449 $arr = array('args' => $args, 'run_cmd' => true);
1451 call_hooks("proc_run", $arr);
1452 if(! $arr['run_cmd'])
1455 if(count($args) && $args[0] === 'php') {
1457 if (get_config("system", "worker")) {
1461 $parameters = json_encode($argv);
1462 $found = q("SELECT `id` FROM `workerqueue` WHERE `parameter` = '%s'",
1463 dbesc($parameters));
1466 q("INSERT INTO `workerqueue` (`parameter`, `created`, `priority`)
1467 VALUES ('%s', '%s', %d)",
1469 dbesc(datetime_convert()),
1472 // Should we quit and wait for the poller to be called as a cronjob?
1473 if (get_config("system", "worker_dont_fork"))
1476 // Checking number of workers
1477 $workers = q("SELECT COUNT(*) AS `workers` FROM `workerqueue` WHERE `executed` != '0000-00-00 00:00:00'");
1479 // Get number of allowed number of worker threads
1480 $queues = intval(get_config("system", "worker_queues"));
1485 // If there are already enough workers running, don't fork another one
1486 if ($workers[0]["workers"] >= $queues)
1489 // Now call the poller to execute the jobs that we just added to the queue
1490 $args = array("php", "include/poller.php", "no_cron");
1493 $args[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
1496 // add baseurl to args. cli scripts can't construct it
1497 $args[] = $a->get_baseurl();
1499 for($x = 0; $x < count($args); $x ++)
1500 $args[$x] = escapeshellarg($args[$x]);
1502 $cmdline = implode($args," ");
1504 if(get_config('system','proc_windows'))
1505 proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
1507 proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
1511 if(! function_exists('current_theme')) {
1512 function current_theme(){
1513 $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
1519 // Find the theme that belongs to the user whose stuff we are looking at
1521 if($a->profile_uid && ($a->profile_uid != local_user())) {
1522 $r = q("select theme from user where uid = %d limit 1",
1523 intval($a->profile_uid)
1526 $page_theme = $r[0]['theme'];
1529 // Allow folks to over-rule user themes and always use their own on their own site.
1530 // This works only if the user is on the same server
1532 if($page_theme && local_user() && (local_user() != $a->profile_uid)) {
1533 if(get_pconfig(local_user(),'system','always_my_theme'))
1537 // $mobile_detect = new Mobile_Detect();
1538 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1539 $is_mobile = $a->is_mobile || $a->is_tablet;
1541 $standard_system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1542 $standard_theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $standard_system_theme);
1545 if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
1546 $system_theme = $standard_system_theme;
1547 $theme_name = $standard_theme_name;
1550 $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : $standard_system_theme);
1551 $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
1553 if($theme_name === '---') {
1554 // user has selected to have the mobile theme be the same as the normal one
1555 $system_theme = $standard_system_theme;
1556 $theme_name = $standard_theme_name;
1559 $theme_name = $page_theme;
1564 $system_theme = $standard_system_theme;
1565 $theme_name = $standard_theme_name;
1568 $theme_name = $page_theme;
1572 (file_exists('view/theme/' . $theme_name . '/style.css') ||
1573 file_exists('view/theme/' . $theme_name . '/style.php')))
1574 return($theme_name);
1576 foreach($app_base_themes as $t) {
1577 if(file_exists('view/theme/' . $t . '/style.css')||
1578 file_exists('view/theme/' . $t . '/style.php'))
1582 $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
1583 if(count($fallback))
1584 return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
1590 * Return full URL to theme which is currently in effect.
1591 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1593 if(! function_exists('current_theme_url')) {
1594 function current_theme_url() {
1597 $t = current_theme();
1599 $opts = (($a->profile_uid) ? '?f=&puid=' . $a->profile_uid : '');
1600 if (file_exists('view/theme/' . $t . '/style.php'))
1601 return($a->get_baseurl() . '/view/theme/' . $t . '/style.pcss' . $opts);
1603 return($a->get_baseurl() . '/view/theme/' . $t . '/style.css');
1607 if(! function_exists('feed_birthday')) {
1608 function feed_birthday($uid,$tz) {
1612 * Determine the next birthday, but only if the birthday is published
1613 * in the default profile. We _could_ also look for a private profile that the
1614 * recipient can see, but somebody could get mad at us if they start getting
1615 * public birthday greetings when they haven't made this info public.
1617 * Assuming we are able to publish this info, we are then going to convert
1618 * the start time from the owner's timezone to UTC.
1620 * This will potentially solve the problem found with some social networks
1621 * where birthdays are converted to the viewer's timezone and salutations from
1622 * elsewhere in the world show up on the wrong day. We will convert it to the
1623 * viewer's timezone also, but first we are going to convert it from the birthday
1624 * person's timezone to GMT - so the viewer may find the birthday starting at
1625 * 6:00PM the day before, but that will correspond to midnight to the birthday person.
1635 $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
1639 if($p && count($p)) {
1640 $tmp_dob = substr($p[0]['dob'],5);
1641 if(intval($tmp_dob)) {
1642 $y = datetime_convert($tz,$tz,'now','Y');
1643 $bd = $y . '-' . $tmp_dob . ' 00:00';
1644 $t_dob = strtotime($bd);
1645 $now = strtotime(datetime_convert($tz,$tz,'now'));
1647 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
1648 $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
1656 if(! function_exists('is_site_admin')) {
1657 function is_site_admin() {
1660 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
1662 //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
1663 if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && in_array($a->user['email'], $adminlist))
1670 if(! function_exists('load_contact_links')) {
1671 function load_contact_links($uid) {
1677 if(! $uid || x($a->contacts,'empty'))
1680 $r = q("SELECT `id`,`network`,`url`,`thumb`, `rel` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `thumb` != ''",
1685 $url = normalise_link($rr['url']);
1689 $ret['empty'] = true;
1691 $a->contacts = $ret;
1697 * returns querystring as string from a mapped array
1699 * @param params Array
1702 function build_querystring($params, $name=null) {
1704 foreach($params as $key=>$val) {
1705 if(is_array($val)) {
1707 $ret .= build_querystring($val, $key);
1709 $ret .= build_querystring($val, $name."[$key]");
1712 $val = urlencode($val);
1714 $ret.=$name."[$key]"."=$val&";
1716 $ret.= "$key=$val&";
1723 function explode_querystring($query) {
1724 $arg_st = strpos($query, '?');
1725 if($arg_st !== false) {
1726 $base = substr($query, 0, $arg_st);
1733 $args = explode('&', substr($query, $arg_st));
1734 foreach($args as $k=>$arg) {
1738 $args = array_values($args);
1743 $args = array_values($args);
1753 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
1755 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
1757 function curPageURL() {
1759 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
1761 if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
1762 $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
1764 $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
1769 function random_digits($digits) {
1771 for($i = 0; $i < $digits; $i++) {
1777 function get_server() {
1778 $server = get_config("system", "directory");
1781 $server = "http://dir.friendi.ca";
1786 function get_cachefile($file, $writemode = true) {
1787 $cache = get_itemcachepath();
1789 if ((! $cache) || (! is_dir($cache)))
1792 $subfolder = $cache."/".substr($file, 0, 2);
1794 $cachepath = $subfolder."/".$file;
1797 if (!is_dir($subfolder)) {
1799 chmod($subfolder, 0777);
1806 function clear_cache($basepath = "", $path = "") {
1808 $basepath = get_itemcachepath();
1812 if (($path == "") OR (!is_dir($path)))
1815 if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
1818 $cachetime = (int)get_config('system','itemcache_duration');
1819 if ($cachetime == 0)
1822 if (is_writable($path)){
1823 if ($dh = opendir($path)) {
1824 while (($file = readdir($dh)) !== false) {
1825 $fullpath = $path."/".$file;
1826 if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
1827 clear_cache($basepath, $fullpath);
1828 if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
1836 function get_itemcachepath() {
1837 // Checking, if the cache is deactivated
1838 $cachetime = (int)get_config('system','itemcache_duration');
1842 $itemcache = get_config('system','itemcache');
1843 if (($itemcache != "") AND is_dir($itemcache) AND is_writable($itemcache))
1846 $temppath = get_temppath();
1848 if ($temppath != "") {
1849 $itemcache = $temppath."/itemcache";
1850 if(!file_exists($itemcache) && !is_dir($itemcache)) {
1854 if (is_dir($itemcache) AND is_writable($itemcache)) {
1855 set_config("system", "itemcache", $itemcache);
1862 function get_lockpath() {
1863 $lockpath = get_config('system','lockpath');
1864 if (($lockpath != "") AND is_dir($lockpath) AND is_writable($lockpath))
1867 $temppath = get_temppath();
1869 if ($temppath != "") {
1870 $lockpath = $temppath."/lock";
1872 if (!is_dir($lockpath))
1874 elseif (!is_writable($lockpath))
1875 $lockpath = $temppath;
1877 if (is_dir($lockpath) AND is_writable($lockpath)) {
1878 set_config("system", "lockpath", $lockpath);
1885 function get_temppath() {
1888 $temppath = get_config("system","temppath");
1889 if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath))
1892 $temppath = sys_get_temp_dir();
1893 if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath)) {
1894 $temppath .= "/".$a->get_hostname();
1895 if (!is_dir($temppath))
1898 if (is_dir($temppath) AND is_writable($temppath)) {
1899 set_config("system", "temppath", $temppath);
1907 function set_template_engine(&$a, $engine = 'internal') {
1908 // This function is no longer necessary, but keep it as a wrapper to the class method
1909 // to avoid breaking themes again unnecessarily
1911 $a->set_template_engine($engine);
1914 if(!function_exists('exif_imagetype')) {
1915 function exif_imagetype($file) {
1916 $size = getimagesize($file);
1921 function validate_include(&$file) {
1924 $file = realpath($file);
1926 if (strpos($file, getcwd()) !== 0)
1929 $file = str_replace(getcwd()."/", "", $file, $count);
1933 if ($orig_file !== $file)
1937 if (strpos($file, "include/") === 0)
1940 if (strpos($file, "addon/") === 0)