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');
14 define ( 'FRIENDICA_PLATFORM', 'Friendica');
15 define ( 'FRIENDICA_VERSION', '3.2.1748' );
16 define ( 'DFRN_PROTOCOL_VERSION', '2.23' );
17 define ( 'DB_UPDATE_VERSION', 1169 );
18 define ( 'EOL', "<br />\r\n" );
19 define ( 'ATOM_TIME', 'Y-m-d\TH:i:s\Z' );
24 * Image storage quality. Lower numbers save space at cost of image detail.
25 * For ease of upgrade, please do not change here. Change jpeg quality with
26 * $a->config['system']['jpeg_quality'] = n;
27 * in .htconfig.php, where n is netween 1 and 100, and with very poor results
32 define ( 'JPEG_QUALITY', 100 );
34 * $a->config['system']['png_quality'] from 0 (uncompressed) to 9
36 define ( 'PNG_QUALITY', 8 );
40 * An alternate way of limiting picture upload sizes. Specify the maximum pixel
41 * length that pictures are allowed to be (for non-square pictures, it will apply
42 * to the longest side). Pictures longer than this length will be resized to be
43 * this length (on the longest side, the other side will be scaled appropriately).
44 * Modify this value using
46 * $a->config['system']['max_image_length'] = n;
50 * If you don't want to set a maximum length, set to -1. The default value is
51 * defined by 'MAX_IMAGE_LENGTH' below.
54 define ( 'MAX_IMAGE_LENGTH', -1 );
61 define ( 'DEFAULT_DB_ENGINE', 'MyISAM' );
64 * SSL redirection policies
67 define ( 'SSL_POLICY_NONE', 0 );
68 define ( 'SSL_POLICY_FULL', 1 );
69 define ( 'SSL_POLICY_SELFSIGN', 2 );
76 define ( 'LOGGER_NORMAL', 0 );
77 define ( 'LOGGER_TRACE', 1 );
78 define ( 'LOGGER_DEBUG', 2 );
79 define ( 'LOGGER_DATA', 3 );
80 define ( 'LOGGER_ALL', 4 );
83 * registration policies
86 define ( 'REGISTER_CLOSED', 0 );
87 define ( 'REGISTER_APPROVE', 1 );
88 define ( 'REGISTER_OPEN', 2 );
94 define ( 'CONTACT_IS_FOLLOWER', 1);
95 define ( 'CONTACT_IS_SHARING', 2);
96 define ( 'CONTACT_IS_FRIEND', 3);
100 * DB update return values
103 define ( 'UPDATE_SUCCESS', 0);
104 define ( 'UPDATE_FAILED', 1);
111 * PAGE_NORMAL is a typical personal profile account
112 * PAGE_SOAPBOX automatically approves all friend requests as CONTACT_IS_SHARING, (readonly)
113 * PAGE_COMMUNITY automatically approves all friend requests as CONTACT_IS_SHARING, but with
114 * write access to wall and comments (no email and not included in page owner's ACL lists)
115 * PAGE_FREELOVE automatically approves all friend requests as full friends (CONTACT_IS_FRIEND).
119 define ( 'PAGE_NORMAL', 0 );
120 define ( 'PAGE_SOAPBOX', 1 );
121 define ( 'PAGE_COMMUNITY', 2 );
122 define ( 'PAGE_FREELOVE', 3 );
123 define ( 'PAGE_BLOG', 4 );
124 define ( 'PAGE_PRVGROUP', 5 );
127 * Network and protocol family types
130 define ( 'NETWORK_DFRN', 'dfrn'); // Friendica, Mistpark, other DFRN implementations
131 define ( 'NETWORK_ZOT', 'zot!'); // Zot!
132 define ( 'NETWORK_OSTATUS', 'stat'); // status.net, identi.ca, GNU-social, other OStatus implementations
133 define ( 'NETWORK_FEED', 'feed'); // RSS/Atom feeds with no known "post/notify" protocol
134 define ( 'NETWORK_DIASPORA', 'dspr'); // Diaspora
135 define ( 'NETWORK_MAIL', 'mail'); // IMAP/POP
136 define ( 'NETWORK_MAIL2', 'mai2'); // extended IMAP/POP
137 define ( 'NETWORK_FACEBOOK', 'face'); // Facebook API
138 define ( 'NETWORK_LINKEDIN', 'lnkd'); // LinkedIn
139 define ( 'NETWORK_XMPP', 'xmpp'); // XMPP
140 define ( 'NETWORK_MYSPACE', 'mysp'); // MySpace
141 define ( 'NETWORK_GPLUS', 'goog'); // Google+
142 define ( 'NETWORK_PUMPIO', 'pump'); // pump.io
143 define ( 'NETWORK_TWITTER', 'twit'); // Twitter
144 define ( 'NETWORK_DIASPORA2', 'dspc'); // Diaspora connector
146 define ( 'NETWORK_PHANTOM', 'unkn'); // Place holder
149 * These numbers are used in stored permissions
150 * and existing allocations MUST NEVER BE CHANGED
151 * OR RE-ASSIGNED! You may only add to them.
154 $netgroup_ids = array(
155 NETWORK_DFRN => (-1),
157 NETWORK_OSTATUS => (-3),
158 NETWORK_FEED => (-4),
159 NETWORK_DIASPORA => (-5),
160 NETWORK_MAIL => (-6),
161 NETWORK_MAIL2 => (-7),
162 NETWORK_FACEBOOK => (-8),
163 NETWORK_LINKEDIN => (-9),
164 NETWORK_XMPP => (-10),
165 NETWORK_MYSPACE => (-11),
166 NETWORK_GPLUS => (-12),
167 NETWORK_PUMPIO => (-13),
168 NETWORK_TWITTER => (-14),
169 NETWORK_DIASPORA2 => (-15),
171 NETWORK_PHANTOM => (-127),
176 * Maximum number of "people who like (or don't like) this" that we will list by name
179 define ( 'MAX_LIKERS', 75);
182 * Communication timeout
185 define ( 'ZCURL_TIMEOUT' , (-1));
189 * email notification options
192 define ( 'NOTIFY_INTRO', 0x0001 );
193 define ( 'NOTIFY_CONFIRM', 0x0002 );
194 define ( 'NOTIFY_WALL', 0x0004 );
195 define ( 'NOTIFY_COMMENT', 0x0008 );
196 define ( 'NOTIFY_MAIL', 0x0010 );
197 define ( 'NOTIFY_SUGGEST', 0x0020 );
198 define ( 'NOTIFY_PROFILE', 0x0040 );
199 define ( 'NOTIFY_TAGSELF', 0x0080 );
200 define ( 'NOTIFY_TAGSHARE', 0x0100 );
201 define ( 'NOTIFY_POKE', 0x0200 );
202 define ( 'NOTIFY_SHARE', 0x0400 );
204 define ( 'NOTIFY_SYSTEM', 0x8000 );
211 define ( 'TERM_UNKNOWN', 0 );
212 define ( 'TERM_HASHTAG', 1 );
213 define ( 'TERM_MENTION', 2 );
214 define ( 'TERM_CATEGORY', 3 );
215 define ( 'TERM_PCATEGORY', 4 );
216 define ( 'TERM_FILE', 5 );
217 define ( 'TERM_SAVEDSEARCH', 6 );
218 define ( 'TERM_CONVERSATION', 7 );
220 define ( 'TERM_OBJ_POST', 1 );
221 define ( 'TERM_OBJ_PHOTO', 2 );
226 * various namespaces we may need to parse
229 define ( 'NAMESPACE_ZOT', 'http://purl.org/zot' );
230 define ( 'NAMESPACE_DFRN' , 'http://purl.org/macgirvin/dfrn/1.0' );
231 define ( 'NAMESPACE_THREAD' , 'http://purl.org/syndication/thread/1.0' );
232 define ( 'NAMESPACE_TOMB' , 'http://purl.org/atompub/tombstones/1.0' );
233 define ( 'NAMESPACE_ACTIVITY', 'http://activitystrea.ms/spec/1.0/' );
234 define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/' );
235 define ( 'NAMESPACE_MEDIA', 'http://purl.org/syndication/atommedia' );
236 define ( 'NAMESPACE_SALMON_ME', 'http://salmon-protocol.org/ns/magic-env' );
237 define ( 'NAMESPACE_OSTATUSSUB', 'http://ostatus.org/schema/1.0/subscribe' );
238 define ( 'NAMESPACE_GEORSS', 'http://www.georss.org/georss' );
239 define ( 'NAMESPACE_POCO', 'http://portablecontacts.net/spec/1.0' );
240 define ( 'NAMESPACE_FEED', 'http://schemas.google.com/g/2010#updates-from' );
241 define ( 'NAMESPACE_OSTATUS', 'http://ostatus.org/schema/1.0' );
242 define ( 'NAMESPACE_STATUSNET', 'http://status.net/schema/api/1/' );
243 define ( 'NAMESPACE_ATOM1', 'http://www.w3.org/2005/Atom' );
245 * activity stream defines
248 define ( 'ACTIVITY_LIKE', NAMESPACE_ACTIVITY_SCHEMA . 'like' );
249 define ( 'ACTIVITY_DISLIKE', NAMESPACE_DFRN . '/dislike' );
250 define ( 'ACTIVITY_OBJ_HEART', NAMESPACE_DFRN . '/heart' );
252 define ( 'ACTIVITY_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
253 define ( 'ACTIVITY_REQ_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'request-friend' );
254 define ( 'ACTIVITY_UNFRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'remove-friend' );
255 define ( 'ACTIVITY_FOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'follow' );
256 define ( 'ACTIVITY_UNFOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'stop-following' );
257 define ( 'ACTIVITY_JOIN', NAMESPACE_ACTIVITY_SCHEMA . 'join' );
259 define ( 'ACTIVITY_POST', NAMESPACE_ACTIVITY_SCHEMA . 'post' );
260 define ( 'ACTIVITY_UPDATE', NAMESPACE_ACTIVITY_SCHEMA . 'update' );
261 define ( 'ACTIVITY_TAG', NAMESPACE_ACTIVITY_SCHEMA . 'tag' );
262 define ( 'ACTIVITY_FAVORITE', NAMESPACE_ACTIVITY_SCHEMA . 'favorite' );
264 define ( 'ACTIVITY_POKE', NAMESPACE_ZOT . '/activity/poke' );
265 define ( 'ACTIVITY_MOOD', NAMESPACE_ZOT . '/activity/mood' );
267 define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
268 define ( 'ACTIVITY_OBJ_NOTE', NAMESPACE_ACTIVITY_SCHEMA . 'note' );
269 define ( 'ACTIVITY_OBJ_PERSON', NAMESPACE_ACTIVITY_SCHEMA . 'person' );
270 define ( 'ACTIVITY_OBJ_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
271 define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
272 define ( 'ACTIVITY_OBJ_ALBUM', NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
273 define ( 'ACTIVITY_OBJ_EVENT', NAMESPACE_ACTIVITY_SCHEMA . 'event' );
274 define ( 'ACTIVITY_OBJ_GROUP', NAMESPACE_ACTIVITY_SCHEMA . 'group' );
275 define ( 'ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN . '/tagterm' );
276 define ( 'ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN . '/profile' );
279 * item weight for query ordering
282 define ( 'GRAVITY_PARENT', 0);
283 define ( 'GRAVITY_LIKE', 3);
284 define ( 'GRAVITY_COMMENT', 6);
288 * Reverse the effect of magic_quotes_gpc if it is enabled.
289 * Please disable magic_quotes_gpc so we don't have to do this.
290 * See http://php.net/manual/en/security.magicquotes.disabling.php
296 error_reporting(E_ERROR | E_WARNING | E_PARSE);
300 // This has to be quite large to deal with embedded private photos
301 ini_set('pcre.backtrack_limit', 500000);
304 if (get_magic_quotes_gpc()) {
305 $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
306 while (list($key, $val) = each($process)) {
307 foreach ($val as $k => $v) {
308 unset($process[$key][$k]);
310 $process[$key][stripslashes($k)] = $v;
311 $process[] = &$process[$key][stripslashes($k)];
313 $process[$key][stripslashes($k)] = stripslashes($v);
326 * Our main application structure for the life of this page
327 * Primarily deals with the URL that got us here
328 * and tries to make some sense of it, and
329 * stores our page contents and config storage
330 * and anything else that might need to be passed around
331 * before we spit the page out.
335 if(! class_exists('App')) {
338 public $module_loaded = false;
339 public $query_string;
347 public $page_contact;
349 public $data = array();
350 public $error = false;
360 public $interactive = true;
362 public $apps = array();
366 public $performance = array();
373 // Allow themes to control internal parameters
374 // by changing App values in theme.php
376 public $sourcename = '';
377 public $videowidth = 425;
378 public $videoheight = 350;
379 public $force_max_items = 0;
380 public $theme_thread_allow = true;
382 // An array for all theme-controllable parameters
383 // Mostly unimplemented yet. Only options 'stylesheet' and
386 public $theme = array(
389 'videoheight' => 350,
390 'force_max_items' => 0,
391 'thread_allow' => true,
393 'template_engine' => 'smarty3',
396 // array of registered template engines ('name'=>'class name')
397 public $template_engines = array();
398 // array of instanced template engines ('name'=>'instance')
399 public $template_engine_instance = array();
401 // Used for reducing load to the ostatus completion
402 public $last_ostatus_conversation_url;
404 private $ldelim = array(
408 private $rdelim = array(
419 private $curl_content_type;
420 private $curl_headers;
422 private $cached_profile_image;
423 private $cached_profile_picdate;
425 function __construct() {
427 global $default_timezone, $argv, $argc;
429 if (file_exists(".htpreconfig.php"))
430 @include(".htpreconfig.php");
432 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
434 date_default_timezone_set($this->timezone);
436 $this->performance["start"] = microtime(true);
437 $this->performance["database"] = 0;
438 $this->performance["network"] = 0;
439 $this->performance["file"] = 0;
440 $this->performance["rendering"] = 0;
441 $this->performance["parser"] = 0;
442 $this->performance["marktime"] = 0;
443 $this->performance["markstart"] = microtime(true);
445 $this->config = array();
446 $this->page = array();
447 $this->pager= array();
449 $this->query_string = '';
454 'include' . PATH_SEPARATOR
455 . 'library' . PATH_SEPARATOR
456 . 'library/phpsec' . PATH_SEPARATOR
457 . 'library/langdet' . PATH_SEPARATOR
461 $this->scheme = 'http';
462 if(x($_SERVER,'HTTPS') && $_SERVER['HTTPS'])
463 $this->scheme = 'https';
464 elseif(x($_SERVER,'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443))
465 $this->scheme = 'https';
467 if(x($_SERVER,'SERVER_NAME')) {
468 $this->hostname = $_SERVER['SERVER_NAME'];
470 // See bug 437 - this didn't work so disabling it
471 //if(stristr($this->hostname,'xn--')) {
472 // PHP or webserver may have converted idn to punycode, so
473 // convert punycode back to utf-8
474 // require_once('library/simplepie/idn/idna_convert.class.php');
475 // $x = new idna_convert();
476 // $this->hostname = $x->decode($_SERVER['SERVER_NAME']);
479 if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
480 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
482 * Figure out if we are running at the top of a domain
483 * or in a sub-directory and adjust accordingly
486 $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
487 if(isset($path) && strlen($path) && ($path != $this->path))
492 $this->hostname = $hostname;
494 if (is_array($argv) && $argc>1 && substr(end($argv), 0, 4)=="http" ) {
495 $this->set_baseurl(array_pop($argv) );
499 set_include_path("include/$this->hostname" . PATH_SEPARATOR . get_include_path());
501 if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
502 $this->query_string = substr($_SERVER['QUERY_STRING'],2);
503 // removing trailing / - maybe a nginx problem
504 if (substr($this->query_string, 0, 1) == "/")
505 $this->query_string = substr($this->query_string, 1);
508 $this->cmd = trim($_GET['q'],'/\\');
510 // unix style "homedir"
512 if(substr($this->cmd,0,1) === '~')
513 $this->cmd = 'profile/' . substr($this->cmd,1);
515 // Diaspora style profile url
517 if(substr($this->cmd,0,2) === 'u/')
518 $this->cmd = 'profile/' . substr($this->cmd,2);
522 * Break the URL path into C style argc/argv style arguments for our
523 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
524 * will be 3 (integer) and $this->argv will contain:
530 * There will always be one argument. If provided a naked domain
531 * URL, $this->argv[0] is set to "home".
535 $this->argv = explode('/',$this->cmd);
536 $this->argc = count($this->argv);
537 if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
538 $this->module = str_replace(".", "_", $this->argv[0]);
539 $this->module = str_replace("-", "_", $this->module);
543 $this->argv = array('home');
544 $this->module = 'home';
548 * See if there is any page number information, and initialise
552 $this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
553 $this->pager['itemspage'] = 50;
554 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
555 if($this->pager['start'] < 0)
556 $this->pager['start'] = 0;
557 $this->pager['total'] = 0;
560 * Detect mobile devices
563 $mobile_detect = new Mobile_Detect();
564 $this->is_mobile = $mobile_detect->isMobile();
565 $this->is_tablet = $mobile_detect->isTablet();
568 * register template engines
570 $dc = get_declared_classes();
571 foreach ($dc as $k) {
572 if (in_array("ITemplateEngine", class_implements($k))){
573 $this->register_template_engine($k);
579 function get_basepath() {
581 $basepath = get_config("system", "basepath");
584 $basepath = $_SERVER["DOCUMENT_ROOT"];
587 $basepath = $_SERVER["PWD"];
592 function get_baseurl($ssl = false) {
594 $scheme = $this->scheme;
596 if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
597 if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
600 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
601 // (and also the login link). Anything seen by an outsider will have it turned off.
603 if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
611 $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
612 return $this->baseurl;
615 function set_baseurl($url) {
616 $parsed = @parse_url($url);
618 $this->baseurl = $url;
621 $this->scheme = $parsed['scheme'];
623 $this->hostname = $parsed['host'];
624 if(x($parsed,'port'))
625 $this->hostname .= ':' . $parsed['port'];
626 if(x($parsed,'path'))
627 $this->path = trim($parsed['path'],'\\/');
632 function get_hostname() {
633 return $this->hostname;
636 function set_hostname($h) {
637 $this->hostname = $h;
640 function set_path($p) {
641 $this->path = trim(trim($p),'/');
644 function get_path() {
648 function set_pager_total($n) {
649 $this->pager['total'] = intval($n);
652 function set_pager_itemspage($n) {
653 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
654 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
657 function set_pager_page($n) {
658 $this->pager['page'] = $n;
659 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
662 function init_pagehead() {
663 $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
664 if($interval < 10000)
667 $this->page['title'] = $this->config['sitename'];
669 /* put the head template at the beginning of page['htmlhead']
670 * since the code added by the modules frequently depends on it
673 if(!isset($this->page['htmlhead']))
674 $this->page['htmlhead'] = '';
676 // If we're using Smarty, then doing replace_macros() will replace
677 // any unrecognized variables with a blank string. Since we delay
678 // replacing $stylesheet until later, we need to replace it now
679 // with another variable name
680 if($this->theme['template_engine'] === 'smarty3')
681 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
683 $stylesheet = '$stylesheet';
685 $tpl = get_markup_template('head.tpl');
686 $this->page['htmlhead'] = replace_macros($tpl,array(
687 '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
688 '$local_user' => local_user(),
689 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
690 '$delitem' => t('Delete this item?'),
691 '$comment' => t('Comment'),
692 '$showmore' => t('show more'),
693 '$showfewer' => t('show fewer'),
694 '$update_interval' => $interval,
695 '$stylesheet' => $stylesheet
696 )) . $this->page['htmlhead'];
699 function init_page_end() {
700 if(!isset($this->page['end']))
701 $this->page['end'] = '';
702 $tpl = get_markup_template('end.tpl');
703 $this->page['end'] = replace_macros($tpl,array(
704 '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
705 )) . $this->page['end'];
708 function set_curl_code($code) {
709 $this->curl_code = $code;
712 function get_curl_code() {
713 return $this->curl_code;
716 function set_curl_content_type($content_type) {
717 $this->curl_content_type = $content_type;
720 function get_curl_content_type() {
721 return $this->curl_content_type;
724 function set_curl_headers($headers) {
725 $this->curl_headers = $headers;
728 function get_curl_headers() {
729 return $this->curl_headers;
732 function get_cached_avatar_image($avatar_image){
733 if($this->cached_profile_image[$avatar_image])
734 return $this->cached_profile_image[$avatar_image];
736 $path_parts = explode("/",$avatar_image);
737 $common_filename = $path_parts[count($path_parts)-1];
739 if($this->cached_profile_picdate[$common_filename]){
740 $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
742 $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like \"%%/%s\"",
745 $this->cached_profile_image[$avatar_image] = $avatar_image;
747 $this->cached_profile_picdate[$common_filename] = "?rev=" . urlencode($r[0]['picdate']);
748 $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
751 return $this->cached_profile_image[$avatar_image];
756 * register template engine class
757 * if $name is "", is used class static property $class::$name
758 * @param string $class
759 * @param string $name
761 function register_template_engine($class, $name = '') {
763 $v = get_class_vars( $class );
764 if(x($v,"name")) $name = $v['name'];
767 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
770 $this->template_engines[$name] = $class;
774 * return template engine instance. If $name is not defined,
775 * return engine defined by theme, or default
777 * @param strin $name Template engine name
778 * @return object Template Engine instance
780 function template_engine($name = ''){
782 $template_engine = $name;
784 $template_engine = 'smarty3';
785 if (x($this->theme, 'template_engine')) {
786 $template_engine = $this->theme['template_engine'];
790 if (isset($this->template_engines[$template_engine])){
791 if(isset($this->template_engine_instance[$template_engine])){
792 return $this->template_engine_instance[$template_engine];
794 $class = $this->template_engines[$template_engine];
796 $this->template_engine_instance[$template_engine] = $obj;
801 echo "template engine <tt>$template_engine</tt> is not registered!\n"; killme();
804 function get_template_engine() {
805 return $this->theme['template_engine'];
808 function set_template_engine($engine = 'smarty3') {
809 $this->theme['template_engine'] = $engine;
811 $this->theme['template_engine'] = 'smarty3';
815 if(is_writable('view/smarty3/'))
816 $this->theme['template_engine'] = 'smarty3';
824 function get_template_ldelim($engine = 'smarty3') {
825 return $this->ldelim[$engine];
828 function get_template_rdelim($engine = 'smarty3') {
829 return $this->rdelim[$engine];
832 function save_timestamp($stamp, $value) {
833 $duration = (float)(microtime(true)-$stamp);
835 $this->performance[$value] += (float)$duration;
836 $this->performance["marktime"] += (float)$duration;
839 function mark_timestamp($mark) {
840 //$this->performance["markstart"] -= microtime(true) - $this->performance["marktime"];
841 $this->performance["markstart"] = microtime(true) - $this->performance["markstart"] - $this->performance["marktime"];
847 // retrieve the App structure
848 // useful in functions which require it but don't get it passed to them
850 if(! function_exists('get_app')) {
858 // Multi-purpose function to check variable state.
859 // Usage: x($var) or $x($array,'key')
860 // returns false if variable/key is not set
861 // if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
862 // e.g. x('') or x(0) returns 0;
864 if(! function_exists('x')) {
865 function x($s,$k = NULL) {
867 if((is_array($s)) && (array_key_exists($k,$s))) {
886 // called from db initialisation if db is dead.
888 if(! function_exists('system_unavailable')) {
889 function system_unavailable() {
890 include('system_unavailable.php');
898 function clean_urls() {
900 // if($a->config['system']['clean_urls'])
907 $base = $a->get_baseurl();
915 return $a->get_baseurl();
918 function absurl($path) {
919 if(strpos($path,'/') === 0)
920 return z_path() . $path;
925 return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
928 function check_db() {
930 $build = get_config('system','build');
932 set_config('system','build',DB_UPDATE_VERSION);
933 $build = DB_UPDATE_VERSION;
935 if($build != DB_UPDATE_VERSION)
936 proc_run('php', 'include/dbupdate.php');
943 // Sets the base url for use in cmdline programs which don't have
944 // $_SERVER variables
946 if(! function_exists('check_url')) {
947 function check_url(&$a) {
949 $url = get_config('system','url');
951 // if the url isn't set or the stored url is radically different
952 // than the currently visited url, store the current value accordingly.
953 // "Radically different" ignores common variations such as http vs https
954 // and www.example.com vs example.com.
955 // We will only change the url to an ip address if there is no existing setting
958 $url = set_config('system','url',$a->get_baseurl());
959 if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
960 $url = set_config('system','url',$a->get_baseurl());
967 // Automatic database updates
969 if(! function_exists('update_db')) {
970 function update_db(&$a) {
972 $build = get_config('system','build');
974 $build = set_config('system','build',DB_UPDATE_VERSION);
976 if($build != DB_UPDATE_VERSION) {
977 $stored = intval($build);
978 $current = intval(DB_UPDATE_VERSION);
979 if(($stored < $current) && file_exists('update.php')) {
981 load_config('database');
983 // We're reporting a different version than what is currently installed.
984 // Run any existing update scripts to bring the database up to current.
986 require_once('update.php');
988 // make sure that boot.php and update.php are the same release, we might be
989 // updating right this very second and the correct version of the update.php
990 // file may not be here yet. This can happen on a very busy site.
992 if(DB_UPDATE_VERSION == UPDATE_VERSION) {
994 for($x = $stored; $x < $current; $x ++) {
995 if(function_exists('update_' . $x)) {
997 // There could be a lot of processes running or about to run.
998 // We want exactly one process to run the update command.
999 // So store the fact that we're taking responsibility
1000 // after first checking to see if somebody else already has.
1002 // If the update fails or times-out completely you may need to
1003 // delete the config entry to try again.
1005 $t = get_config('database','update_' . $x);
1008 set_config('database','update_' . $x, time());
1010 // call the specific update
1012 $func = 'update_' . $x;
1015 //send the administrator an e-mail
1016 $email_tpl = get_intltext_template("update_fail_eml.tpl");
1017 $email_msg = replace_macros($email_tpl, array(
1018 '$sitename' => $a->config['sitename'],
1019 '$siteurl' => $a->get_baseurl(),
1021 '$error' => sprintf( t('Update %s failed. See error logs.'), $x)
1023 $subject=sprintf(t('Update Error at %s'), $a->get_baseurl());
1024 require_once('include/email.php');
1025 $subject = email_header_encode($subject,'UTF-8');
1026 mail($a->config['admin_email'], $subject, $email_msg,
1027 'From: ' . 'Administrator' . '@' . $_SERVER['SERVER_NAME'] . "\n"
1028 . 'Content-type: text/plain; charset=UTF-8' . "\n"
1029 . 'Content-transfer-encoding: 8bit' );
1031 logger('CRITICAL: Update Failed: '. $x);
1035 set_config('database','update_' . $x, 'success');
1036 set_config('system','build', $x + 1);
1049 if(! function_exists('check_plugins')) {
1050 function check_plugins(&$a) {
1054 * Synchronise plugins:
1056 * $a->config['system']['addon'] contains a comma-separated list of names
1057 * of plugins/addons which are used on this system.
1058 * Go through the database list of already installed addons, and if we have
1059 * an entry, but it isn't in the config list, call the uninstall procedure
1060 * and mark it uninstalled in the database (for now we'll remove it).
1061 * Then go through the config list and if we have a plugin that isn't installed,
1062 * call the install procedure and add it to the database.
1066 $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
1070 $installed = array();
1072 $plugins = get_config('system','addon');
1073 $plugins_arr = array();
1076 $plugins_arr = explode(',',str_replace(' ', '',$plugins));
1078 $a->plugins = $plugins_arr;
1080 $installed_arr = array();
1082 if(count($installed)) {
1083 foreach($installed as $i) {
1084 if(! in_array($i['name'],$plugins_arr)) {
1085 uninstall_plugin($i['name']);
1088 $installed_arr[] = $i['name'];
1093 if(count($plugins_arr)) {
1094 foreach($plugins_arr as $p) {
1095 if(! in_array($p,$installed_arr)) {
1109 function get_guid($size=16) {
1110 $exists = true; // assume by default that we don't have a unique guid
1112 $s = random_string($size);
1113 $r = q("select id from guid where guid = '%s' limit 1", dbesc($s));
1117 q("insert into guid ( guid ) values ( '%s' ) ", dbesc($s));
1122 // wrapper for adding a login box. If $register == true provide a registration
1123 // link. This will most always depend on the value of $a->config['register_policy'].
1124 // returns the complete html for inserting into the page
1126 if(! function_exists('login')) {
1127 function login($register = false, $hiddens=false) {
1133 'title' => t('Create a New Account'),
1134 'desc' => t('Register')
1138 $noid = get_config('system','no_openid');
1140 $dest_url = $a->get_baseurl(true) . '/' . $a->query_string;
1143 $tpl = get_markup_template("logout.tpl");
1146 $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
1147 '$baseurl' => $a->get_baseurl(true)
1150 $tpl = get_markup_template("login.tpl");
1151 $_SESSION['return_url'] = $a->query_string;
1152 $a->module = 'login';
1155 $o .= replace_macros($tpl, array(
1157 '$dest_url' => $dest_url,
1158 '$logout' => t('Logout'),
1159 '$login' => t('Login'),
1161 '$lname' => array('username', t('Nickname or Email address: ') , '', ''),
1162 '$lpassword' => array('password', t('Password: '), '', ''),
1163 '$lremember' => array('remember', t('Remember me'), 0, ''),
1165 '$openid' => !$noid,
1166 '$lopenid' => array('openid_url', t('Or login using OpenID: '),'',''),
1168 '$hiddens' => $hiddens,
1170 '$register' => $reg,
1172 '$lostpass' => t('Forgot your password?'),
1173 '$lostlink' => t('Password Reset'),
1175 '$tostitle' => t('Website Terms of Service'),
1176 '$toslink' => t('terms of service'),
1178 '$privacytitle' => t('Website Privacy Policy'),
1179 '$privacylink' => t('privacy policy'),
1183 call_hooks('login_hook',$o);
1189 // Used to end the current process, after saving session state.
1191 if(! function_exists('killme')) {
1193 session_write_close();
1198 // redirect to another URL and terminate this process.
1200 if(! function_exists('goaway')) {
1201 function goaway($s) {
1202 header("Location: $s");
1208 // Returns the uid of locally logged in user or false.
1210 if(! function_exists('local_user')) {
1211 function local_user() {
1212 if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
1213 return intval($_SESSION['uid']);
1218 // Returns contact id of authenticated site visitor or false
1220 if(! function_exists('remote_user')) {
1221 function remote_user() {
1222 if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
1223 return intval($_SESSION['visitor_id']);
1228 // contents of $s are displayed prominently on the page the next time
1229 // a page is loaded. Usually used for errors or alerts.
1231 if(! function_exists('notice')) {
1233 * Show an error message to user.
1235 * This function save text in session, to be shown to the user at next page load
1237 * @param string $s - Text of notice
1239 function notice($s) {
1241 if(! x($_SESSION,'sysmsg')) $_SESSION['sysmsg'] = array();
1243 $_SESSION['sysmsg'][] = $s;
1246 if(! function_exists('info')) {
1248 * Show an info message to user.
1250 * This function save text in session, to be shown to the user at next page load
1252 * @param string $s - Text of notice
1256 if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
1258 $_SESSION['sysmsg_info'][] = $s;
1263 // wrapper around config to limit the text length of an incoming message
1265 if(! function_exists('get_max_import_size')) {
1266 function get_max_import_size() {
1268 return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
1276 * Function : profile_load
1278 * @parameter string $nickname
1279 * @parameter int $profile
1281 * Summary: Loads a profile into the page sidebar.
1282 * The function requires a writeable copy of the main App structure, and the nickname
1283 * of a registered local account.
1285 * If the viewer is an authenticated remote viewer, the profile displayed is the
1286 * one that has been configured for his/her viewing in the Contact manager.
1287 * Passing a non-zero profile ID can also allow a preview of a selected profile
1290 * Profile information is placed in the App structure for later retrieval.
1291 * Honours the owner's chosen theme for display.
1293 * IMPORTANT: Should only be run in the _init() functions of a module. That ensures that
1294 * the theme is chosen before the _init() function of a theme is run, which will usually
1295 * load a lot of theme-specific content
1299 if(! function_exists('profile_load')) {
1300 function profile_load(&$a, $nickname, $profile = 0) {
1302 $user = q("select uid from user where nickname = '%s' limit 1",
1306 if(! ($user && count($user))) {
1307 logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
1308 notice( t('Requested account is not available.') . EOL );
1313 if(remote_user() && count($_SESSION['remote'])) {
1314 foreach($_SESSION['remote'] as $visitor) {
1315 if($visitor['uid'] == $user[0]['uid']) {
1316 $r = q("SELECT `profile-id` FROM `contact` WHERE `id` = %d LIMIT 1",
1317 intval($visitor['cid'])
1320 $profile = $r[0]['profile-id'];
1329 $profile_int = intval($profile);
1330 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `contact`.`avatar-date` AS picdate, `user`.* FROM `profile`
1331 left join `contact` on `contact`.`uid` = `profile`.`uid` LEFT JOIN `user` ON `profile`.`uid` = `user`.`uid`
1332 WHERE `user`.`nickname` = '%s' AND `profile`.`id` = %d and `contact`.`self` = 1 LIMIT 1",
1334 intval($profile_int)
1337 if((! $r) && (! count($r))) {
1338 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `contact`.`avatar-date` AS picdate, `user`.* FROM `profile`
1339 left join `contact` on `contact`.`uid` = `profile`.`uid` LEFT JOIN `user` ON `profile`.`uid` = `user`.`uid`
1340 WHERE `user`.`nickname` = '%s' AND `profile`.`is-default` = 1 and `contact`.`self` = 1 LIMIT 1",
1345 if(($r === false) || (! count($r))) {
1346 logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
1347 notice( t('Requested profile is not available.') . EOL );
1352 // fetch user tags if this isn't the default profile
1354 if(! $r[0]['is-default']) {
1355 $x = q("select `pub_keywords` from `profile` where uid = %d and `is-default` = 1 limit 1",
1356 intval($r[0]['profile_uid'])
1359 $r[0]['pub_keywords'] = $x[0]['pub_keywords'];
1362 $a->profile = $r[0];
1364 $a->profile['mobile-theme'] = get_pconfig($a->profile['profile_uid'], 'system', 'mobile_theme');
1367 $a->page['title'] = $a->profile['name'] . " @ " . $a->config['sitename'];
1368 $_SESSION['theme'] = $a->profile['theme'];
1369 $_SESSION['mobile-theme'] = $a->profile['mobile-theme'];
1372 * load/reload current theme info
1375 $a->set_template_engine(); // reset the template engine to the default in case the user's theme doesn't specify one
1377 $theme_info_file = "view/theme/".current_theme()."/theme.php";
1378 if (file_exists($theme_info_file)){
1379 require_once($theme_info_file);
1382 if(! (x($a->page,'aside')))
1383 $a->page['aside'] = '';
1385 if(local_user() && local_user() == $a->profile['uid']) {
1386 $a->page['aside'] .= replace_macros(get_markup_template('profile_edlink.tpl'),array(
1387 '$editprofile' => t('Edit profile'),
1388 '$profid' => $a->profile['id']
1392 $block = (((get_config('system','block_public')) && (! local_user()) && (! remote_user())) ? true : false);
1394 $a->page['aside'] .= profile_sidebar($a->profile, $block);
1397 $a->page['aside'] .= contact_block();*/
1406 * Function: profile_sidebar
1408 * Formats a profile for display in the sidebar.
1409 * It is very difficult to templatise the HTML completely
1410 * because of all the conditional logic.
1412 * @parameter: array $profile
1414 * Returns HTML string stuitable for sidebar inclusion
1415 * Exceptions: Returns empty string if passed $profile is wrong type or not populated
1420 if(! function_exists('profile_sidebar')) {
1421 function profile_sidebar($profile, $block = 0) {
1430 if((! is_array($profile)) && (! count($profile)))
1433 $profile['picdate'] = urlencode($profile['picdate']);
1435 call_hooks('profile_sidebar_enter', $profile);
1438 // don't show connect link to yourself
1439 $connect = (($profile['uid'] != local_user()) ? t('Connect') : False);
1441 // don't show connect link to authenticated visitors either
1443 if(remote_user() && count($_SESSION['remote'])) {
1444 foreach($_SESSION['remote'] as $visitor) {
1445 if($visitor['uid'] == $profile['uid']) {
1452 if( get_my_url() && $profile['unkmail'] && ($profile['uid'] != local_user()) )
1453 $wallmessage = t('Message');
1455 $wallmessage = false;
1459 // show edit profile to yourself
1460 if ($profile['uid'] == local_user() && feature_enabled(local_user(),'multi_profiles')) {
1461 $profile['edit'] = array($a->get_baseurl(). '/profiles', t('Profiles'),"", t('Manage/edit profiles'));
1463 $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
1466 $profile['menu'] = array(
1467 'chg_photo' => t('Change profile photo'),
1468 'cr_new' => t('Create New Profile'),
1469 'entries' => array(),
1474 foreach($r as $rr) {
1475 $profile['menu']['entries'][] = array(
1476 'photo' => $rr['thumb'],
1478 'alt' => t('Profile Image'),
1479 'profile_name' => $rr['profile-name'],
1480 'isdefault' => $rr['is-default'],
1481 'visibile_to_everybody' => t('visible to everybody'),
1482 'edit_visibility' => t('Edit visibility'),
1490 if ($profile['uid'] == local_user() && !feature_enabled(local_user(),'multi_profiles')) {
1491 $profile['edit'] = array($a->get_baseurl(). '/profiles/'.$profile['id'], t('Edit profile'),"", t('Edit profile'));
1492 $profile['menu'] = array(
1493 'chg_photo' => t('Change profile photo'),
1495 'entries' => array(),
1502 if((x($profile,'address') == 1)
1503 || (x($profile,'locality') == 1)
1504 || (x($profile,'region') == 1)
1505 || (x($profile,'postal-code') == 1)
1506 || (x($profile,'country-name') == 1))
1507 $location = t('Location:');
1509 $gender = ((x($profile,'gender') == 1) ? t('Gender:') : False);
1512 $marital = ((x($profile,'marital') == 1) ? t('Status:') : False);
1514 $homepage = ((x($profile,'homepage') == 1) ? t('Homepage:') : False);
1516 if(($profile['hidewall'] || $block) && (! local_user()) && (! remote_user())) {
1517 $location = $pdesc = $gender = $marital = $homepage = False;
1520 $firstname = ((strpos($profile['name'],' '))
1521 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']);
1522 $lastname = (($firstname === $profile['name']) ? '' : trim(substr($profile['name'],strlen($firstname))));
1525 'podloc' => $a->get_baseurl(),
1526 'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false' ),
1527 'nickname' => $profile['nickname'],
1528 'fullname' => $profile['name'],
1529 'firstname' => $firstname,
1530 'lastname' => $lastname,
1531 'photo300' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/300/' . $profile['uid'] . '.jpg'),
1532 'photo100' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/100/' . $profile['uid'] . '.jpg'),
1533 'photo50' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/50/' . $profile['uid'] . '.jpg'),
1537 $contact_block = contact_block();
1542 foreach($profile as $k => $v) {
1543 $k = str_replace('-','_',$k);
1547 if($a->theme['template_engine'] === 'internal')
1548 $location = template_escape($location);
1551 $tpl = get_markup_template('profile_vcard.tpl');
1552 $o .= replace_macros($tpl, array(
1554 '$connect' => $connect,
1555 '$wallmessage' => $wallmessage,
1556 '$location' => $location,
1557 '$gender' => $gender,
1559 '$marital' => $marital,
1560 '$homepage' => $homepage,
1561 '$diaspora' => $diaspora,
1562 '$contact_block' => $contact_block,
1566 $arr = array('profile' => &$profile, 'entry' => &$o);
1568 call_hooks('profile_sidebar', $arr);
1575 if(! function_exists('get_birthdays')) {
1576 function get_birthdays() {
1581 if(! local_user() || $a->is_mobile || $a->is_tablet)
1584 // $mobile_detect = new Mobile_Detect();
1585 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1590 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
1591 $bd_short = t('F d');
1593 $r = q("SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
1594 LEFT JOIN `contact` ON `contact`.`id` = `event`.`cid`
1595 WHERE `event`.`uid` = %d AND `type` = 'birthday' AND `start` < '%s' AND `finish` > '%s'
1596 ORDER BY `start` ASC ",
1597 intval(local_user()),
1598 dbesc(datetime_convert('UTC','UTC','now + 6 days')),
1599 dbesc(datetime_convert('UTC','UTC','now'))
1602 if($r && count($r)) {
1604 $now = strtotime('now');
1608 foreach($r as $rr) {
1609 if(strlen($rr['name']))
1611 if((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now))
1614 $classtoday = $istoday ? ' birthday-today ' : '';
1616 foreach($r as &$rr) {
1617 if(! strlen($rr['name']))
1622 if(in_array($rr['cid'],$cids))
1624 $cids[] = $rr['cid'];
1626 $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
1629 if($rr['network'] === NETWORK_DFRN) {
1630 $sparkle = " sparkle";
1631 $url = $a->get_baseurl() . '/redir/' . $rr['cid'];
1635 $rr['title'] = $rr['name'];
1636 $rr['date'] = day_translate(datetime_convert('UTC', $a->timezone, $rr['start'], $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . t('[today]') : '');
1637 $rr['startime'] = Null;
1638 $rr['today'] = $today;
1643 $tpl = get_markup_template("birthdays_reminder.tpl");
1644 return replace_macros($tpl, array(
1645 '$baseurl' => $a->get_baseurl(),
1646 '$classtoday' => $classtoday,
1648 '$event_reminders' => t('Birthday Reminders'),
1649 '$event_title' => t('Birthdays this week:'),
1651 '$lbr' => '{', // raw brackets mess up if/endif macro processing
1659 if(! function_exists('get_events')) {
1660 function get_events() {
1662 require_once('include/bbcode.php');
1666 if(! local_user() || $a->is_mobile || $a->is_tablet)
1670 // $mobile_detect = new Mobile_Detect();
1671 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1676 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
1677 $bd_short = t('F d');
1679 $r = q("SELECT `event`.* FROM `event`
1680 WHERE `event`.`uid` = %d AND `type` != 'birthday' AND `start` < '%s' AND `start` > '%s'
1681 ORDER BY `start` ASC ",
1682 intval(local_user()),
1683 dbesc(datetime_convert('UTC','UTC','now + 6 days')),
1684 dbesc(datetime_convert('UTC','UTC','now - 1 days'))
1687 if($r && count($r)) {
1688 $now = strtotime('now');
1690 foreach($r as $rr) {
1691 if(strlen($rr['name']))
1694 $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start'],'Y-m-d');
1695 if($strt === datetime_convert('UTC',$a->timezone,'now','Y-m-d'))
1698 $classtoday = (($istoday) ? 'event-today' : '');
1701 foreach($r as &$rr) {
1703 $md = datetime_convert('UTC',$a->timezone,$rr['start'],'Y/m');
1705 $md = datetime_convert('UTC','UTC',$rr['start'],'Y/m');
1706 $md .= "/#link-".$rr['id'];
1708 $title = substr(strip_tags(bbcode($rr['desc'])),0,32) . '... ';
1710 $title = t('[No description]');
1712 $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start']);
1713 $today = ((substr($strt,0,10) === datetime_convert('UTC',$a->timezone,'now','Y-m-d')) ? true : false);
1716 $rr['title'] = $title;
1717 $rr['date'] = day_translate(datetime_convert('UTC', $rr['adjust'] ? $a->timezone : 'UTC', $rr['start'], $bd_format)) . (($today) ? ' ' . t('[today]') : '');
1718 $rr['startime'] = $strt;
1719 $rr['today'] = $today;
1723 $tpl = get_markup_template("events_reminder.tpl");
1724 return replace_macros($tpl, array(
1725 '$baseurl' => $a->get_baseurl(),
1726 '$classtoday' => $classtoday,
1727 '$count' => count($r),
1728 '$event_reminders' => t('Event Reminders'),
1729 '$event_title' => t('Events this week:'),
1738 * Wrap calls to proc_close(proc_open()) and call hook
1739 * so plugins can take part in process :)
1742 * $cmd program to run
1743 * next args are passed as $cmd command line
1745 * e.g.: proc_run("ls","-la","/tmp");
1747 * $cmd and string args are surrounded with ""
1750 if(! function_exists('proc_run')) {
1751 function proc_run($cmd){
1755 $args = func_get_args();
1761 // expand any arrays
1763 foreach($args as $arg) {
1764 if(is_array($arg)) {
1765 foreach($arg as $n) {
1775 $arr = array('args' => $args, 'run_cmd' => true);
1777 call_hooks("proc_run", $arr);
1778 if(! $arr['run_cmd'])
1781 if(count($args) && $args[0] === 'php')
1782 $args[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
1784 // add baseurl to args. cli scripts can't construct it
1785 $args[] = $a->get_baseurl();
1787 for($x = 0; $x < count($args); $x ++)
1788 $args[$x] = escapeshellarg($args[$x]);
1792 $cmdline = implode($args," ");
1793 if(get_config('system','proc_windows'))
1794 proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
1796 proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
1800 if(! function_exists('current_theme')) {
1801 function current_theme(){
1802 $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
1806 // $mobile_detect = new Mobile_Detect();
1807 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1808 $is_mobile = $a->is_mobile || $a->is_tablet;
1811 if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
1816 $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : '');
1817 $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
1819 if($theme_name === '---') {
1820 // user has selected to have the mobile theme be the same as the normal one
1826 if(!$is_mobile || ($system_theme === '' && $theme_name === '')) {
1827 $system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1828 $theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $system_theme);
1832 (file_exists('view/theme/' . $theme_name . '/style.css') ||
1833 file_exists('view/theme/' . $theme_name . '/style.php')))
1834 return($theme_name);
1836 foreach($app_base_themes as $t) {
1837 if(file_exists('view/theme/' . $t . '/style.css')||
1838 file_exists('view/theme/' . $t . '/style.php'))
1842 $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
1843 if(count($fallback))
1844 return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
1850 * Return full URL to theme which is currently in effect.
1851 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1853 if(! function_exists('current_theme_url')) {
1854 function current_theme_url() {
1856 $t = current_theme();
1857 if (file_exists('view/theme/' . $t . '/style.php'))
1858 return($a->get_baseurl() . '/view/theme/' . $t . '/style.pcss');
1859 return($a->get_baseurl() . '/view/theme/' . $t . '/style.css');
1863 if(! function_exists('feed_birthday')) {
1864 function feed_birthday($uid,$tz) {
1868 * Determine the next birthday, but only if the birthday is published
1869 * in the default profile. We _could_ also look for a private profile that the
1870 * recipient can see, but somebody could get mad at us if they start getting
1871 * public birthday greetings when they haven't made this info public.
1873 * Assuming we are able to publish this info, we are then going to convert
1874 * the start time from the owner's timezone to UTC.
1876 * This will potentially solve the problem found with some social networks
1877 * where birthdays are converted to the viewer's timezone and salutations from
1878 * elsewhere in the world show up on the wrong day. We will convert it to the
1879 * viewer's timezone also, but first we are going to convert it from the birthday
1880 * person's timezone to GMT - so the viewer may find the birthday starting at
1881 * 6:00PM the day before, but that will correspond to midnight to the birthday person.
1891 $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
1895 if($p && count($p)) {
1896 $tmp_dob = substr($p[0]['dob'],5);
1897 if(intval($tmp_dob)) {
1898 $y = datetime_convert($tz,$tz,'now','Y');
1899 $bd = $y . '-' . $tmp_dob . ' 00:00';
1900 $t_dob = strtotime($bd);
1901 $now = strtotime(datetime_convert($tz,$tz,'now'));
1903 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
1904 $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
1912 if(! function_exists('is_site_admin')) {
1913 function is_site_admin() {
1916 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
1918 //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
1919 if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && in_array($a->user['email'], $adminlist))
1926 if(! function_exists('load_contact_links')) {
1927 function load_contact_links($uid) {
1933 if(! $uid || x($a->contacts,'empty'))
1936 $r = q("SELECT `id`,`network`,`url`,`thumb` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 ",
1941 $url = normalise_link($rr['url']);
1946 $ret['empty'] = true;
1947 $a->contacts = $ret;
1952 if(! function_exists('profile_tabs')){
1953 function profile_tabs($a, $is_owner=False, $nickname=Null){
1954 //echo "<pre>"; var_dump($a->user); killme();
1956 if (is_null($nickname))
1957 $nickname = $a->user['nickname'];
1960 $tab = notags(trim($_GET['tab']));
1962 $url = $a->get_baseurl() . '/profile/' . $nickname;
1966 'label'=>t('Status'),
1968 'sel' => ((!isset($tab)&&$a->argv[0]=='profile')?'active':''),
1969 'title' => t('Status Messages and Posts'),
1970 'id' => 'status-tab',
1973 'label' => t('Profile'),
1974 'url' => $url.'/?tab=profile',
1975 'sel' => ((isset($tab) && $tab=='profile')?'active':''),
1976 'title' => t('Profile Details'),
1977 'id' => 'profile-tab',
1980 'label' => t('Photos'),
1981 'url' => $a->get_baseurl() . '/photos/' . $nickname,
1982 'sel' => ((!isset($tab)&&$a->argv[0]=='photos')?'active':''),
1983 'title' => t('Photo Albums'),
1984 'id' => 'photo-tab',
1987 'label' => t('Videos'),
1988 'url' => $a->get_baseurl() . '/videos/' . $nickname,
1989 'sel' => ((!isset($tab)&&$a->argv[0]=='videos')?'active':''),
1990 'title' => t('Videos'),
1991 'id' => 'video-tab',
1997 'label' => t('Events'),
1998 'url' => $a->get_baseurl() . '/events',
1999 'sel' =>((!isset($tab)&&$a->argv[0]=='events')?'active':''),
2000 'title' => t('Events and Calendar'),
2001 'id' => 'events-tab',
2004 'label' => t('Personal Notes'),
2005 'url' => $a->get_baseurl() . '/notes',
2006 'sel' =>((!isset($tab)&&$a->argv[0]=='notes')?'active':''),
2007 'title' => t('Only You Can See This'),
2008 'id' => 'notes-tab',
2013 $arr = array('is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => (($tab) ? $tab : false), 'tabs' => $tabs);
2014 call_hooks('profile_tabs', $arr);
2016 $tpl = get_markup_template('common_tabs.tpl');
2018 return replace_macros($tpl,array('$tabs' => $arr['tabs']));
2022 function get_my_url() {
2023 if(x($_SESSION,'my_url'))
2024 return $_SESSION['my_url'];
2028 function zrl_init(&$a) {
2029 $tmp_str = get_my_url();
2030 if(validate_url($tmp_str)) {
2031 proc_run('php','include/gprobe.php',bin2hex($tmp_str));
2032 $arr = array('zrl' => $tmp_str, 'url' => $a->cmd);
2033 call_hooks('zrl_init',$arr);
2037 function zrl($s,$force = false) {
2040 if((! strpos($s,'/profile/')) && (! $force))
2042 if($force && substr($s,-1,1) !== '/')
2044 $achar = strpos($s,'?') ? '&' : '?';
2045 $mine = get_my_url();
2046 if($mine and ! link_compare($mine,$s))
2047 return $s . $achar . 'zrl=' . urlencode($mine);
2052 * returns querystring as string from a mapped array
2054 * @param params Array
2057 function build_querystring($params, $name=null) {
2059 foreach($params as $key=>$val) {
2060 if(is_array($val)) {
2062 $ret .= build_querystring($val, $key);
2064 $ret .= build_querystring($val, $name."[$key]");
2067 $val = urlencode($val);
2069 $ret.=$name."[$key]"."=$val&";
2071 $ret.= "$key=$val&";
2078 function explode_querystring($query) {
2079 $arg_st = strpos($query, '?');
2080 if($arg_st !== false) {
2081 $base = substr($query, 0, $arg_st);
2089 $args = explode('&', substr($query, $arg_st));
2090 foreach($args as $k=>$arg) {
2094 $args = array_values($args);
2099 $args = array_values($args);
2109 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
2111 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
2113 function curPageURL() {
2115 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
2117 if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
2118 $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
2120 $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
2125 function random_digits($digits) {
2127 for($i = 0; $i < $digits; $i++) {
2133 function get_cachefile($file, $writemode = true) {
2134 $cache = get_config("system","itemcache");
2136 if ((! $cache) || (! is_dir($cache)))
2139 $subfolder = $cache."/".substr($file, 0, 2);
2141 $cachepath = $subfolder."/".$file;
2144 if (!is_dir($subfolder)) {
2146 chmod($subfolder, 0777);
2153 function clear_cache($basepath = "", $path = "") {
2155 $basepath = get_config('system','itemcache');
2159 if (($path == "") OR (!is_dir($path)))
2162 if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
2165 $cachetime = (int)get_config('system','itemcache_duration');
2166 if ($cachetime == 0)
2169 if (is_writable($path)){
2170 if ($dh = opendir($path)) {
2171 while (($file = readdir($dh)) !== false) {
2172 $fullpath = $path."/".$file;
2173 if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
2174 clear_cache($basepath, $fullpath);
2175 if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
2183 function set_template_engine(&$a, $engine = 'internal') {
2184 // This function is no longer necessary, but keep it as a wrapper to the class method
2185 // to avoid breaking themes again unnecessarily
2187 $a->set_template_engine($engine);
2190 if(!function_exists('exif_imagetype')) {
2191 function exif_imagetype($file) {
2192 $size = getimagesize($file);