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.1751' );
16 define ( 'DFRN_PROTOCOL_VERSION', '2.23' );
17 define ( 'DB_UPDATE_VERSION', 1170 );
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
145 define ( 'NETWORK_STATUSNET', 'stac'); // Statusnet connector
146 define ( 'NETWORK_APPNET', 'apdn'); // app.net
148 define ( 'NETWORK_PHANTOM', 'unkn'); // Place holder
151 * These numbers are used in stored permissions
152 * and existing allocations MUST NEVER BE CHANGED
153 * OR RE-ASSIGNED! You may only add to them.
156 $netgroup_ids = array(
157 NETWORK_DFRN => (-1),
159 NETWORK_OSTATUS => (-3),
160 NETWORK_FEED => (-4),
161 NETWORK_DIASPORA => (-5),
162 NETWORK_MAIL => (-6),
163 NETWORK_MAIL2 => (-7),
164 NETWORK_FACEBOOK => (-8),
165 NETWORK_LINKEDIN => (-9),
166 NETWORK_XMPP => (-10),
167 NETWORK_MYSPACE => (-11),
168 NETWORK_GPLUS => (-12),
169 NETWORK_PUMPIO => (-13),
170 NETWORK_TWITTER => (-14),
171 NETWORK_DIASPORA2 => (-15),
172 NETWORK_STATUSNET => (-16),
173 NETWORK_APPNET => (-17),
175 NETWORK_PHANTOM => (-127),
180 * Maximum number of "people who like (or don't like) this" that we will list by name
183 define ( 'MAX_LIKERS', 75);
186 * Communication timeout
189 define ( 'ZCURL_TIMEOUT' , (-1));
193 * email notification options
196 define ( 'NOTIFY_INTRO', 0x0001 );
197 define ( 'NOTIFY_CONFIRM', 0x0002 );
198 define ( 'NOTIFY_WALL', 0x0004 );
199 define ( 'NOTIFY_COMMENT', 0x0008 );
200 define ( 'NOTIFY_MAIL', 0x0010 );
201 define ( 'NOTIFY_SUGGEST', 0x0020 );
202 define ( 'NOTIFY_PROFILE', 0x0040 );
203 define ( 'NOTIFY_TAGSELF', 0x0080 );
204 define ( 'NOTIFY_TAGSHARE', 0x0100 );
205 define ( 'NOTIFY_POKE', 0x0200 );
206 define ( 'NOTIFY_SHARE', 0x0400 );
208 define ( 'NOTIFY_SYSTEM', 0x8000 );
215 define ( 'TERM_UNKNOWN', 0 );
216 define ( 'TERM_HASHTAG', 1 );
217 define ( 'TERM_MENTION', 2 );
218 define ( 'TERM_CATEGORY', 3 );
219 define ( 'TERM_PCATEGORY', 4 );
220 define ( 'TERM_FILE', 5 );
221 define ( 'TERM_SAVEDSEARCH', 6 );
222 define ( 'TERM_CONVERSATION', 7 );
224 define ( 'TERM_OBJ_POST', 1 );
225 define ( 'TERM_OBJ_PHOTO', 2 );
230 * various namespaces we may need to parse
233 define ( 'NAMESPACE_ZOT', 'http://purl.org/zot' );
234 define ( 'NAMESPACE_DFRN' , 'http://purl.org/macgirvin/dfrn/1.0' );
235 define ( 'NAMESPACE_THREAD' , 'http://purl.org/syndication/thread/1.0' );
236 define ( 'NAMESPACE_TOMB' , 'http://purl.org/atompub/tombstones/1.0' );
237 define ( 'NAMESPACE_ACTIVITY', 'http://activitystrea.ms/spec/1.0/' );
238 define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/' );
239 define ( 'NAMESPACE_MEDIA', 'http://purl.org/syndication/atommedia' );
240 define ( 'NAMESPACE_SALMON_ME', 'http://salmon-protocol.org/ns/magic-env' );
241 define ( 'NAMESPACE_OSTATUSSUB', 'http://ostatus.org/schema/1.0/subscribe' );
242 define ( 'NAMESPACE_GEORSS', 'http://www.georss.org/georss' );
243 define ( 'NAMESPACE_POCO', 'http://portablecontacts.net/spec/1.0' );
244 define ( 'NAMESPACE_FEED', 'http://schemas.google.com/g/2010#updates-from' );
245 define ( 'NAMESPACE_OSTATUS', 'http://ostatus.org/schema/1.0' );
246 define ( 'NAMESPACE_STATUSNET', 'http://status.net/schema/api/1/' );
247 define ( 'NAMESPACE_ATOM1', 'http://www.w3.org/2005/Atom' );
249 * activity stream defines
252 define ( 'ACTIVITY_LIKE', NAMESPACE_ACTIVITY_SCHEMA . 'like' );
253 define ( 'ACTIVITY_DISLIKE', NAMESPACE_DFRN . '/dislike' );
254 define ( 'ACTIVITY_OBJ_HEART', NAMESPACE_DFRN . '/heart' );
256 define ( 'ACTIVITY_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
257 define ( 'ACTIVITY_REQ_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'request-friend' );
258 define ( 'ACTIVITY_UNFRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'remove-friend' );
259 define ( 'ACTIVITY_FOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'follow' );
260 define ( 'ACTIVITY_UNFOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'stop-following' );
261 define ( 'ACTIVITY_JOIN', NAMESPACE_ACTIVITY_SCHEMA . 'join' );
263 define ( 'ACTIVITY_POST', NAMESPACE_ACTIVITY_SCHEMA . 'post' );
264 define ( 'ACTIVITY_UPDATE', NAMESPACE_ACTIVITY_SCHEMA . 'update' );
265 define ( 'ACTIVITY_TAG', NAMESPACE_ACTIVITY_SCHEMA . 'tag' );
266 define ( 'ACTIVITY_FAVORITE', NAMESPACE_ACTIVITY_SCHEMA . 'favorite' );
268 define ( 'ACTIVITY_POKE', NAMESPACE_ZOT . '/activity/poke' );
269 define ( 'ACTIVITY_MOOD', NAMESPACE_ZOT . '/activity/mood' );
271 define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
272 define ( 'ACTIVITY_OBJ_NOTE', NAMESPACE_ACTIVITY_SCHEMA . 'note' );
273 define ( 'ACTIVITY_OBJ_PERSON', NAMESPACE_ACTIVITY_SCHEMA . 'person' );
274 define ( 'ACTIVITY_OBJ_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
275 define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
276 define ( 'ACTIVITY_OBJ_ALBUM', NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
277 define ( 'ACTIVITY_OBJ_EVENT', NAMESPACE_ACTIVITY_SCHEMA . 'event' );
278 define ( 'ACTIVITY_OBJ_GROUP', NAMESPACE_ACTIVITY_SCHEMA . 'group' );
279 define ( 'ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN . '/tagterm' );
280 define ( 'ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN . '/profile' );
283 * item weight for query ordering
286 define ( 'GRAVITY_PARENT', 0);
287 define ( 'GRAVITY_LIKE', 3);
288 define ( 'GRAVITY_COMMENT', 6);
292 * Reverse the effect of magic_quotes_gpc if it is enabled.
293 * Please disable magic_quotes_gpc so we don't have to do this.
294 * See http://php.net/manual/en/security.magicquotes.disabling.php
300 error_reporting(E_ERROR | E_WARNING | E_PARSE);
304 // This has to be quite large to deal with embedded private photos
305 ini_set('pcre.backtrack_limit', 500000);
308 if (get_magic_quotes_gpc()) {
309 $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
310 while (list($key, $val) = each($process)) {
311 foreach ($val as $k => $v) {
312 unset($process[$key][$k]);
314 $process[$key][stripslashes($k)] = $v;
315 $process[] = &$process[$key][stripslashes($k)];
317 $process[$key][stripslashes($k)] = stripslashes($v);
330 * Our main application structure for the life of this page
331 * Primarily deals with the URL that got us here
332 * and tries to make some sense of it, and
333 * stores our page contents and config storage
334 * and anything else that might need to be passed around
335 * before we spit the page out.
339 if(! class_exists('App')) {
342 public $module_loaded = false;
343 public $query_string;
351 public $page_contact;
353 public $data = array();
354 public $error = false;
364 public $interactive = true;
366 public $apps = array();
370 public $performance = array();
377 // Allow themes to control internal parameters
378 // by changing App values in theme.php
380 public $sourcename = '';
381 public $videowidth = 425;
382 public $videoheight = 350;
383 public $force_max_items = 0;
384 public $theme_thread_allow = true;
386 // An array for all theme-controllable parameters
387 // Mostly unimplemented yet. Only options 'stylesheet' and
390 public $theme = array(
393 'videoheight' => 350,
394 'force_max_items' => 0,
395 'thread_allow' => true,
397 'template_engine' => 'smarty3',
400 // array of registered template engines ('name'=>'class name')
401 public $template_engines = array();
402 // array of instanced template engines ('name'=>'instance')
403 public $template_engine_instance = array();
405 // Used for reducing load to the ostatus completion
406 public $last_ostatus_conversation_url;
408 private $ldelim = array(
412 private $rdelim = array(
423 private $curl_content_type;
424 private $curl_headers;
426 private $cached_profile_image;
427 private $cached_profile_picdate;
429 function __construct() {
431 global $default_timezone, $argv, $argc;
435 if (file_exists(".htpreconfig.php"))
436 @include(".htpreconfig.php");
438 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
440 date_default_timezone_set($this->timezone);
442 $this->performance["start"] = microtime(true);
443 $this->performance["database"] = 0;
444 $this->performance["network"] = 0;
445 $this->performance["file"] = 0;
446 $this->performance["rendering"] = 0;
447 $this->performance["parser"] = 0;
448 $this->performance["marktime"] = 0;
449 $this->performance["markstart"] = microtime(true);
451 $this->config = array();
452 $this->page = array();
453 $this->pager= array();
455 $this->query_string = '';
460 'include' . PATH_SEPARATOR
461 . 'library' . PATH_SEPARATOR
462 . 'library/phpsec' . PATH_SEPARATOR
463 . 'library/langdet' . PATH_SEPARATOR
467 $this->scheme = 'http';
468 if(x($_SERVER,'HTTPS') && $_SERVER['HTTPS'])
469 $this->scheme = 'https';
470 elseif(x($_SERVER,'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443))
471 $this->scheme = 'https';
473 if(x($_SERVER,'SERVER_NAME')) {
474 $this->hostname = $_SERVER['SERVER_NAME'];
476 // See bug 437 - this didn't work so disabling it
477 //if(stristr($this->hostname,'xn--')) {
478 // PHP or webserver may have converted idn to punycode, so
479 // convert punycode back to utf-8
480 // require_once('library/simplepie/idn/idna_convert.class.php');
481 // $x = new idna_convert();
482 // $this->hostname = $x->decode($_SERVER['SERVER_NAME']);
485 if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
486 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
488 * Figure out if we are running at the top of a domain
489 * or in a sub-directory and adjust accordingly
492 $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
493 if(isset($path) && strlen($path) && ($path != $this->path))
498 $this->hostname = $hostname;
500 if (is_array($argv) && $argc>1 && substr(end($argv), 0, 4)=="http" ) {
501 $this->set_baseurl(array_pop($argv) );
505 set_include_path("include/$this->hostname" . PATH_SEPARATOR . get_include_path());
507 if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
508 $this->query_string = substr($_SERVER['QUERY_STRING'],2);
509 // removing trailing / - maybe a nginx problem
510 if (substr($this->query_string, 0, 1) == "/")
511 $this->query_string = substr($this->query_string, 1);
514 $this->cmd = trim($_GET['q'],'/\\');
516 // unix style "homedir"
518 if(substr($this->cmd,0,1) === '~')
519 $this->cmd = 'profile/' . substr($this->cmd,1);
521 // Diaspora style profile url
523 if(substr($this->cmd,0,2) === 'u/')
524 $this->cmd = 'profile/' . substr($this->cmd,2);
528 * Break the URL path into C style argc/argv style arguments for our
529 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
530 * will be 3 (integer) and $this->argv will contain:
536 * There will always be one argument. If provided a naked domain
537 * URL, $this->argv[0] is set to "home".
541 $this->argv = explode('/',$this->cmd);
542 $this->argc = count($this->argv);
543 if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
544 $this->module = str_replace(".", "_", $this->argv[0]);
545 $this->module = str_replace("-", "_", $this->module);
549 $this->argv = array('home');
550 $this->module = 'home';
554 * See if there is any page number information, and initialise
558 $this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
559 $this->pager['itemspage'] = 50;
560 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
561 if($this->pager['start'] < 0)
562 $this->pager['start'] = 0;
563 $this->pager['total'] = 0;
566 * Detect mobile devices
569 $mobile_detect = new Mobile_Detect();
570 $this->is_mobile = $mobile_detect->isMobile();
571 $this->is_tablet = $mobile_detect->isTablet();
574 * register template engines
576 $dc = get_declared_classes();
577 foreach ($dc as $k) {
578 if (in_array("ITemplateEngine", class_implements($k))){
579 $this->register_template_engine($k);
585 function get_basepath() {
587 $basepath = get_config("system", "basepath");
590 $basepath = $_SERVER["DOCUMENT_ROOT"];
593 $basepath = $_SERVER["PWD"];
598 function get_baseurl($ssl = false) {
600 $scheme = $this->scheme;
602 if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
603 if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
606 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
607 // (and also the login link). Anything seen by an outsider will have it turned off.
609 if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
617 $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
618 return $this->baseurl;
621 function set_baseurl($url) {
622 $parsed = @parse_url($url);
624 $this->baseurl = $url;
627 $this->scheme = $parsed['scheme'];
629 $hostname = $parsed['host'];
630 if(x($parsed,'port'))
631 $hostname .= ':' . $parsed['port'];
632 if(x($parsed,'path'))
633 $this->path = trim($parsed['path'],'\\/');
635 if (file_exists(".htpreconfig.php"))
636 @include(".htpreconfig.php");
638 $this->hostname = $hostname;
643 function get_hostname() {
644 return $this->hostname;
647 function set_hostname($h) {
648 $this->hostname = $h;
651 function set_path($p) {
652 $this->path = trim(trim($p),'/');
655 function get_path() {
659 function set_pager_total($n) {
660 $this->pager['total'] = intval($n);
663 function set_pager_itemspage($n) {
664 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
665 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
668 function set_pager_page($n) {
669 $this->pager['page'] = $n;
670 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
673 function init_pagehead() {
674 $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
675 if($interval < 10000)
678 $this->page['title'] = $this->config['sitename'];
680 /* put the head template at the beginning of page['htmlhead']
681 * since the code added by the modules frequently depends on it
684 if(!isset($this->page['htmlhead']))
685 $this->page['htmlhead'] = '';
687 // If we're using Smarty, then doing replace_macros() will replace
688 // any unrecognized variables with a blank string. Since we delay
689 // replacing $stylesheet until later, we need to replace it now
690 // with another variable name
691 if($this->theme['template_engine'] === 'smarty3')
692 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
694 $stylesheet = '$stylesheet';
696 $shortcut_icon = get_config("system", "shortcut_icon");
697 if ($shortcut_icon == "")
698 $shortcut_icon = $this->get_baseurl()."/images/friendica-32.png";
700 $touch_icon = get_config("system", "touch_icon");
701 if ($touch_icon == "")
702 $touch_icon = $this->get_baseurl()."/images/friendica-128.png";
704 $tpl = get_markup_template('head.tpl');
705 $this->page['htmlhead'] = replace_macros($tpl,array(
706 '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
707 '$local_user' => local_user(),
708 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
709 '$delitem' => t('Delete this item?'),
710 '$comment' => t('Comment'),
711 '$showmore' => t('show more'),
712 '$showfewer' => t('show fewer'),
713 '$update_interval' => $interval,
714 '$shortcut_icon' => $shortcut_icon,
715 '$touch_icon' => $touch_icon,
716 '$stylesheet' => $stylesheet
717 )) . $this->page['htmlhead'];
720 function init_page_end() {
721 if(!isset($this->page['end']))
722 $this->page['end'] = '';
723 $tpl = get_markup_template('end.tpl');
724 $this->page['end'] = replace_macros($tpl,array(
725 '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
726 )) . $this->page['end'];
729 function set_curl_code($code) {
730 $this->curl_code = $code;
733 function get_curl_code() {
734 return $this->curl_code;
737 function set_curl_content_type($content_type) {
738 $this->curl_content_type = $content_type;
741 function get_curl_content_type() {
742 return $this->curl_content_type;
745 function set_curl_headers($headers) {
746 $this->curl_headers = $headers;
749 function get_curl_headers() {
750 return $this->curl_headers;
753 function get_cached_avatar_image($avatar_image){
754 if($this->cached_profile_image[$avatar_image])
755 return $this->cached_profile_image[$avatar_image];
757 $path_parts = explode("/",$avatar_image);
758 $common_filename = $path_parts[count($path_parts)-1];
760 if($this->cached_profile_picdate[$common_filename]){
761 $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
763 $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like '%%/%s'",
766 $this->cached_profile_image[$avatar_image] = $avatar_image;
768 $this->cached_profile_picdate[$common_filename] = "?rev=" . urlencode($r[0]['picdate']);
769 $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
772 return $this->cached_profile_image[$avatar_image];
777 * register template engine class
778 * if $name is "", is used class static property $class::$name
779 * @param string $class
780 * @param string $name
782 function register_template_engine($class, $name = '') {
784 $v = get_class_vars( $class );
785 if(x($v,"name")) $name = $v['name'];
788 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
791 $this->template_engines[$name] = $class;
795 * return template engine instance. If $name is not defined,
796 * return engine defined by theme, or default
798 * @param strin $name Template engine name
799 * @return object Template Engine instance
801 function template_engine($name = ''){
803 $template_engine = $name;
805 $template_engine = 'smarty3';
806 if (x($this->theme, 'template_engine')) {
807 $template_engine = $this->theme['template_engine'];
811 if (isset($this->template_engines[$template_engine])){
812 if(isset($this->template_engine_instance[$template_engine])){
813 return $this->template_engine_instance[$template_engine];
815 $class = $this->template_engines[$template_engine];
817 $this->template_engine_instance[$template_engine] = $obj;
822 echo "template engine <tt>$template_engine</tt> is not registered!\n"; killme();
825 function get_template_engine() {
826 return $this->theme['template_engine'];
829 function set_template_engine($engine = 'smarty3') {
830 $this->theme['template_engine'] = $engine;
832 $this->theme['template_engine'] = 'smarty3';
836 if(is_writable('view/smarty3/'))
837 $this->theme['template_engine'] = 'smarty3';
845 function get_template_ldelim($engine = 'smarty3') {
846 return $this->ldelim[$engine];
849 function get_template_rdelim($engine = 'smarty3') {
850 return $this->rdelim[$engine];
853 function save_timestamp($stamp, $value) {
854 $duration = (float)(microtime(true)-$stamp);
856 $this->performance[$value] += (float)$duration;
857 $this->performance["marktime"] += (float)$duration;
860 function mark_timestamp($mark) {
861 //$this->performance["markstart"] -= microtime(true) - $this->performance["marktime"];
862 $this->performance["markstart"] = microtime(true) - $this->performance["markstart"] - $this->performance["marktime"];
868 // retrieve the App structure
869 // useful in functions which require it but don't get it passed to them
871 if(! function_exists('get_app')) {
879 // Multi-purpose function to check variable state.
880 // Usage: x($var) or $x($array,'key')
881 // returns false if variable/key is not set
882 // if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
883 // e.g. x('') or x(0) returns 0;
885 if(! function_exists('x')) {
886 function x($s,$k = NULL) {
888 if((is_array($s)) && (array_key_exists($k,$s))) {
907 // called from db initialisation if db is dead.
909 if(! function_exists('system_unavailable')) {
910 function system_unavailable() {
911 include('system_unavailable.php');
919 function clean_urls() {
921 // if($a->config['system']['clean_urls'])
928 $base = $a->get_baseurl();
936 return $a->get_baseurl();
939 function absurl($path) {
940 if(strpos($path,'/') === 0)
941 return z_path() . $path;
946 return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
949 function check_db() {
951 $build = get_config('system','build');
953 set_config('system','build',DB_UPDATE_VERSION);
954 $build = DB_UPDATE_VERSION;
956 if($build != DB_UPDATE_VERSION)
957 proc_run('php', 'include/dbupdate.php');
964 // Sets the base url for use in cmdline programs which don't have
965 // $_SERVER variables
967 if(! function_exists('check_url')) {
968 function check_url(&$a) {
970 $url = get_config('system','url');
972 // if the url isn't set or the stored url is radically different
973 // than the currently visited url, store the current value accordingly.
974 // "Radically different" ignores common variations such as http vs https
975 // and www.example.com vs example.com.
976 // We will only change the url to an ip address if there is no existing setting
979 $url = set_config('system','url',$a->get_baseurl());
980 if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
981 $url = set_config('system','url',$a->get_baseurl());
988 // Automatic database updates
990 if(! function_exists('update_db')) {
991 function update_db(&$a) {
993 $build = get_config('system','build');
995 $build = set_config('system','build',DB_UPDATE_VERSION);
997 if($build != DB_UPDATE_VERSION) {
998 $stored = intval($build);
999 $current = intval(DB_UPDATE_VERSION);
1000 if(($stored < $current) && file_exists('update.php')) {
1002 load_config('database');
1004 // We're reporting a different version than what is currently installed.
1005 // Run any existing update scripts to bring the database up to current.
1007 require_once('update.php');
1009 // make sure that boot.php and update.php are the same release, we might be
1010 // updating right this very second and the correct version of the update.php
1011 // file may not be here yet. This can happen on a very busy site.
1013 if(DB_UPDATE_VERSION == UPDATE_VERSION) {
1015 // Compare the current structure with the defined structure
1016 require_once("include/dbstructure.php");
1017 update_structure(false, true);
1019 for($x = $stored; $x < $current; $x ++) {
1020 if(function_exists('update_' . $x)) {
1022 // There could be a lot of processes running or about to run.
1023 // We want exactly one process to run the update command.
1024 // So store the fact that we're taking responsibility
1025 // after first checking to see if somebody else already has.
1027 // If the update fails or times-out completely you may need to
1028 // delete the config entry to try again.
1030 $t = get_config('database','update_' . $x);
1033 set_config('database','update_' . $x, time());
1035 // call the specific update
1037 $func = 'update_' . $x;
1040 //send the administrator an e-mail
1041 $email_tpl = get_intltext_template("update_fail_eml.tpl");
1042 $email_msg = replace_macros($email_tpl, array(
1043 '$sitename' => $a->config['sitename'],
1044 '$siteurl' => $a->get_baseurl(),
1046 '$error' => sprintf( t('Update %s failed. See error logs.'), $x)
1048 $subject=sprintf(t('Update Error at %s'), $a->get_baseurl());
1049 require_once('include/email.php');
1050 $subject = email_header_encode($subject,'UTF-8');
1051 mail($a->config['admin_email'], $subject, $email_msg,
1052 'From: ' . 'Administrator' . '@' . $_SERVER['SERVER_NAME'] . "\n"
1053 . 'Content-type: text/plain; charset=UTF-8' . "\n"
1054 . 'Content-transfer-encoding: 8bit' );
1056 logger('CRITICAL: Update Failed: '. $x);
1060 set_config('database','update_' . $x, 'success');
1061 set_config('system','build', $x + 1);
1074 if(! function_exists('check_plugins')) {
1075 function check_plugins(&$a) {
1079 * Synchronise plugins:
1081 * $a->config['system']['addon'] contains a comma-separated list of names
1082 * of plugins/addons which are used on this system.
1083 * Go through the database list of already installed addons, and if we have
1084 * an entry, but it isn't in the config list, call the uninstall procedure
1085 * and mark it uninstalled in the database (for now we'll remove it).
1086 * Then go through the config list and if we have a plugin that isn't installed,
1087 * call the install procedure and add it to the database.
1091 $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
1095 $installed = array();
1097 $plugins = get_config('system','addon');
1098 $plugins_arr = array();
1101 $plugins_arr = explode(',',str_replace(' ', '',$plugins));
1103 $a->plugins = $plugins_arr;
1105 $installed_arr = array();
1107 if(count($installed)) {
1108 foreach($installed as $i) {
1109 if(! in_array($i['name'],$plugins_arr)) {
1110 uninstall_plugin($i['name']);
1113 $installed_arr[] = $i['name'];
1118 if(count($plugins_arr)) {
1119 foreach($plugins_arr as $p) {
1120 if(! in_array($p,$installed_arr)) {
1134 function get_guid($size=16) {
1135 $exists = true; // assume by default that we don't have a unique guid
1137 $s = random_string($size);
1138 $r = q("select id from guid where guid = '%s' limit 1", dbesc($s));
1142 q("insert into guid ( guid ) values ( '%s' ) ", dbesc($s));
1147 // wrapper for adding a login box. If $register == true provide a registration
1148 // link. This will most always depend on the value of $a->config['register_policy'].
1149 // returns the complete html for inserting into the page
1151 if(! function_exists('login')) {
1152 function login($register = false, $hiddens=false) {
1158 'title' => t('Create a New Account'),
1159 'desc' => t('Register')
1163 $noid = get_config('system','no_openid');
1165 $dest_url = $a->get_baseurl(true) . '/' . $a->query_string;
1168 $tpl = get_markup_template("logout.tpl");
1171 $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
1172 '$baseurl' => $a->get_baseurl(true)
1175 $tpl = get_markup_template("login.tpl");
1176 $_SESSION['return_url'] = $a->query_string;
1177 $a->module = 'login';
1180 $o .= replace_macros($tpl, array(
1182 '$dest_url' => $dest_url,
1183 '$logout' => t('Logout'),
1184 '$login' => t('Login'),
1186 '$lname' => array('username', t('Nickname or Email address: ') , '', ''),
1187 '$lpassword' => array('password', t('Password: '), '', ''),
1188 '$lremember' => array('remember', t('Remember me'), 0, ''),
1190 '$openid' => !$noid,
1191 '$lopenid' => array('openid_url', t('Or login using OpenID: '),'',''),
1193 '$hiddens' => $hiddens,
1195 '$register' => $reg,
1197 '$lostpass' => t('Forgot your password?'),
1198 '$lostlink' => t('Password Reset'),
1200 '$tostitle' => t('Website Terms of Service'),
1201 '$toslink' => t('terms of service'),
1203 '$privacytitle' => t('Website Privacy Policy'),
1204 '$privacylink' => t('privacy policy'),
1208 call_hooks('login_hook',$o);
1214 // Used to end the current process, after saving session state.
1216 if(! function_exists('killme')) {
1218 session_write_close();
1223 // redirect to another URL and terminate this process.
1225 if(! function_exists('goaway')) {
1226 function goaway($s) {
1227 header("Location: $s");
1233 // Returns the uid of locally logged in user or false.
1235 if(! function_exists('local_user')) {
1236 function local_user() {
1237 if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
1238 return intval($_SESSION['uid']);
1243 // Returns contact id of authenticated site visitor or false
1245 if(! function_exists('remote_user')) {
1246 function remote_user() {
1247 if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
1248 return intval($_SESSION['visitor_id']);
1253 // contents of $s are displayed prominently on the page the next time
1254 // a page is loaded. Usually used for errors or alerts.
1256 if(! function_exists('notice')) {
1258 * Show an error message to user.
1260 * This function save text in session, to be shown to the user at next page load
1262 * @param string $s - Text of notice
1264 function notice($s) {
1266 if(! x($_SESSION,'sysmsg')) $_SESSION['sysmsg'] = array();
1268 $_SESSION['sysmsg'][] = $s;
1271 if(! function_exists('info')) {
1273 * Show an info message to user.
1275 * This function save text in session, to be shown to the user at next page load
1277 * @param string $s - Text of notice
1282 if (local_user() AND get_pconfig(local_user(),'system','ignore_info'))
1285 if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
1287 $_SESSION['sysmsg_info'][] = $s;
1292 // wrapper around config to limit the text length of an incoming message
1294 if(! function_exists('get_max_import_size')) {
1295 function get_max_import_size() {
1297 return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
1305 * Function : profile_load
1307 * @parameter string $nickname
1308 * @parameter int $profile
1310 * Summary: Loads a profile into the page sidebar.
1311 * The function requires a writeable copy of the main App structure, and the nickname
1312 * of a registered local account.
1314 * If the viewer is an authenticated remote viewer, the profile displayed is the
1315 * one that has been configured for his/her viewing in the Contact manager.
1316 * Passing a non-zero profile ID can also allow a preview of a selected profile
1319 * Profile information is placed in the App structure for later retrieval.
1320 * Honours the owner's chosen theme for display.
1322 * IMPORTANT: Should only be run in the _init() functions of a module. That ensures that
1323 * the theme is chosen before the _init() function of a theme is run, which will usually
1324 * load a lot of theme-specific content
1328 if(! function_exists('profile_load')) {
1329 function profile_load(&$a, $nickname, $profile = 0) {
1331 $user = q("select uid from user where nickname = '%s' limit 1",
1335 if(! ($user && count($user))) {
1336 logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
1337 notice( t('Requested account is not available.') . EOL );
1342 if(remote_user() && count($_SESSION['remote'])) {
1343 foreach($_SESSION['remote'] as $visitor) {
1344 if($visitor['uid'] == $user[0]['uid']) {
1345 $r = q("SELECT `profile-id` FROM `contact` WHERE `id` = %d LIMIT 1",
1346 intval($visitor['cid'])
1349 $profile = $r[0]['profile-id'];
1358 $profile_int = intval($profile);
1359 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `contact`.`avatar-date` AS picdate, `user`.* FROM `profile`
1360 INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
1361 WHERE `user`.`nickname` = '%s' AND `profile`.`id` = %d and `contact`.`self` = 1 LIMIT 1",
1363 intval($profile_int)
1366 if((! $r) && (! count($r))) {
1367 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `contact`.`avatar-date` AS picdate, `user`.* FROM `profile`
1368 INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
1369 WHERE `user`.`nickname` = '%s' AND `profile`.`is-default` = 1 and `contact`.`self` = 1 LIMIT 1",
1374 if(($r === false) || (! count($r))) {
1375 logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
1376 notice( t('Requested profile is not available.') . EOL );
1381 // fetch user tags if this isn't the default profile
1383 if(! $r[0]['is-default']) {
1384 $x = q("select `pub_keywords` from `profile` where uid = %d and `is-default` = 1 limit 1",
1385 intval($r[0]['profile_uid'])
1388 $r[0]['pub_keywords'] = $x[0]['pub_keywords'];
1391 $a->profile = $r[0];
1393 $a->profile['mobile-theme'] = get_pconfig($a->profile['profile_uid'], 'system', 'mobile_theme');
1396 $a->page['title'] = $a->profile['name'] . " @ " . $a->config['sitename'];
1397 $_SESSION['theme'] = $a->profile['theme'];
1398 $_SESSION['mobile-theme'] = $a->profile['mobile-theme'];
1401 * load/reload current theme info
1404 $a->set_template_engine(); // reset the template engine to the default in case the user's theme doesn't specify one
1406 $theme_info_file = "view/theme/".current_theme()."/theme.php";
1407 if (file_exists($theme_info_file)){
1408 require_once($theme_info_file);
1411 if(! (x($a->page,'aside')))
1412 $a->page['aside'] = '';
1414 if(local_user() && local_user() == $a->profile['uid']) {
1415 $a->page['aside'] .= replace_macros(get_markup_template('profile_edlink.tpl'),array(
1416 '$editprofile' => t('Edit profile'),
1417 '$profid' => $a->profile['id']
1421 $block = (((get_config('system','block_public')) && (! local_user()) && (! remote_user())) ? true : false);
1423 $a->page['aside'] .= profile_sidebar($a->profile, $block);
1426 $a->page['aside'] .= contact_block();*/
1435 * Function: profile_sidebar
1437 * Formats a profile for display in the sidebar.
1438 * It is very difficult to templatise the HTML completely
1439 * because of all the conditional logic.
1441 * @parameter: array $profile
1443 * Returns HTML string stuitable for sidebar inclusion
1444 * Exceptions: Returns empty string if passed $profile is wrong type or not populated
1449 if(! function_exists('profile_sidebar')) {
1450 function profile_sidebar($profile, $block = 0) {
1459 if((! is_array($profile)) && (! count($profile)))
1462 $profile['picdate'] = urlencode($profile['picdate']);
1464 call_hooks('profile_sidebar_enter', $profile);
1467 // don't show connect link to yourself
1468 $connect = (($profile['uid'] != local_user()) ? t('Connect') : False);
1470 // don't show connect link to authenticated visitors either
1472 if(remote_user() && count($_SESSION['remote'])) {
1473 foreach($_SESSION['remote'] as $visitor) {
1474 if($visitor['uid'] == $profile['uid']) {
1481 if( get_my_url() && $profile['unkmail'] && ($profile['uid'] != local_user()) )
1482 $wallmessage = t('Message');
1484 $wallmessage = false;
1488 // show edit profile to yourself
1489 if ($profile['uid'] == local_user() && feature_enabled(local_user(),'multi_profiles')) {
1490 $profile['edit'] = array($a->get_baseurl(). '/profiles', t('Profiles'),"", t('Manage/edit profiles'));
1492 $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
1495 $profile['menu'] = array(
1496 'chg_photo' => t('Change profile photo'),
1497 'cr_new' => t('Create New Profile'),
1498 'entries' => array(),
1503 foreach($r as $rr) {
1504 $profile['menu']['entries'][] = array(
1505 'photo' => $rr['thumb'],
1507 'alt' => t('Profile Image'),
1508 'profile_name' => $rr['profile-name'],
1509 'isdefault' => $rr['is-default'],
1510 'visibile_to_everybody' => t('visible to everybody'),
1511 'edit_visibility' => t('Edit visibility'),
1519 if ($profile['uid'] == local_user() && !feature_enabled(local_user(),'multi_profiles')) {
1520 $profile['edit'] = array($a->get_baseurl(). '/profiles/'.$profile['id'], t('Edit profile'),"", t('Edit profile'));
1521 $profile['menu'] = array(
1522 'chg_photo' => t('Change profile photo'),
1524 'entries' => array(),
1531 if((x($profile,'address') == 1)
1532 || (x($profile,'locality') == 1)
1533 || (x($profile,'region') == 1)
1534 || (x($profile,'postal-code') == 1)
1535 || (x($profile,'country-name') == 1))
1536 $location = t('Location:');
1538 $gender = ((x($profile,'gender') == 1) ? t('Gender:') : False);
1541 $marital = ((x($profile,'marital') == 1) ? t('Status:') : False);
1543 $homepage = ((x($profile,'homepage') == 1) ? t('Homepage:') : False);
1545 if(($profile['hidewall'] || $block) && (! local_user()) && (! remote_user())) {
1546 $location = $pdesc = $gender = $marital = $homepage = False;
1549 $firstname = ((strpos($profile['name'],' '))
1550 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']);
1551 $lastname = (($firstname === $profile['name']) ? '' : trim(substr($profile['name'],strlen($firstname))));
1554 'podloc' => $a->get_baseurl(),
1555 'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false' ),
1556 'nickname' => $profile['nickname'],
1557 'fullname' => $profile['name'],
1558 'firstname' => $firstname,
1559 'lastname' => $lastname,
1560 'photo300' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/300/' . $profile['uid'] . '.jpg'),
1561 'photo100' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/100/' . $profile['uid'] . '.jpg'),
1562 'photo50' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/50/' . $profile['uid'] . '.jpg'),
1566 $contact_block = contact_block();
1571 foreach($profile as $k => $v) {
1572 $k = str_replace('-','_',$k);
1576 if($a->theme['template_engine'] === 'internal')
1577 $location = template_escape($location);
1580 $tpl = get_markup_template('profile_vcard.tpl');
1581 $o .= replace_macros($tpl, array(
1583 '$connect' => $connect,
1584 '$wallmessage' => $wallmessage,
1585 '$location' => $location,
1586 '$gender' => $gender,
1588 '$marital' => $marital,
1589 '$homepage' => $homepage,
1590 '$diaspora' => $diaspora,
1591 '$contact_block' => $contact_block,
1595 $arr = array('profile' => &$profile, 'entry' => &$o);
1597 call_hooks('profile_sidebar', $arr);
1604 if(! function_exists('get_birthdays')) {
1605 function get_birthdays() {
1610 if(! local_user() || $a->is_mobile || $a->is_tablet)
1613 // $mobile_detect = new Mobile_Detect();
1614 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1619 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
1620 $bd_short = t('F d');
1622 $r = q("SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
1623 INNER JOIN `contact` ON `contact`.`id` = `event`.`cid`
1624 WHERE `event`.`uid` = %d AND `type` = 'birthday' AND `start` < '%s' AND `finish` > '%s'
1625 ORDER BY `start` ASC ",
1626 intval(local_user()),
1627 dbesc(datetime_convert('UTC','UTC','now + 6 days')),
1628 dbesc(datetime_convert('UTC','UTC','now'))
1631 if($r && count($r)) {
1633 $now = strtotime('now');
1637 foreach($r as $rr) {
1638 if(strlen($rr['name']))
1640 if((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now))
1643 $classtoday = $istoday ? ' birthday-today ' : '';
1645 foreach($r as &$rr) {
1646 if(! strlen($rr['name']))
1651 if(in_array($rr['cid'],$cids))
1653 $cids[] = $rr['cid'];
1655 $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
1658 if($rr['network'] === NETWORK_DFRN) {
1659 $sparkle = " sparkle";
1660 $url = $a->get_baseurl() . '/redir/' . $rr['cid'];
1664 $rr['title'] = $rr['name'];
1665 $rr['date'] = day_translate(datetime_convert('UTC', $a->timezone, $rr['start'], $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . t('[today]') : '');
1666 $rr['startime'] = Null;
1667 $rr['today'] = $today;
1672 $tpl = get_markup_template("birthdays_reminder.tpl");
1673 return replace_macros($tpl, array(
1674 '$baseurl' => $a->get_baseurl(),
1675 '$classtoday' => $classtoday,
1677 '$event_reminders' => t('Birthday Reminders'),
1678 '$event_title' => t('Birthdays this week:'),
1680 '$lbr' => '{', // raw brackets mess up if/endif macro processing
1688 if(! function_exists('get_events')) {
1689 function get_events() {
1691 require_once('include/bbcode.php');
1695 if(! local_user() || $a->is_mobile || $a->is_tablet)
1699 // $mobile_detect = new Mobile_Detect();
1700 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1705 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
1706 $bd_short = t('F d');
1708 $r = q("SELECT `event`.* FROM `event`
1709 WHERE `event`.`uid` = %d AND `type` != 'birthday' AND `start` < '%s' AND `start` > '%s'
1710 ORDER BY `start` ASC ",
1711 intval(local_user()),
1712 dbesc(datetime_convert('UTC','UTC','now + 6 days')),
1713 dbesc(datetime_convert('UTC','UTC','now - 1 days'))
1716 if($r && count($r)) {
1717 $now = strtotime('now');
1719 foreach($r as $rr) {
1720 if(strlen($rr['name']))
1723 $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start'],'Y-m-d');
1724 if($strt === datetime_convert('UTC',$a->timezone,'now','Y-m-d'))
1727 $classtoday = (($istoday) ? 'event-today' : '');
1730 foreach($r as &$rr) {
1732 $md = datetime_convert('UTC',$a->timezone,$rr['start'],'Y/m');
1734 $md = datetime_convert('UTC','UTC',$rr['start'],'Y/m');
1735 $md .= "/#link-".$rr['id'];
1737 $title = substr(strip_tags(bbcode($rr['desc'])),0,32) . '... ';
1739 $title = t('[No description]');
1741 $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start']);
1742 $today = ((substr($strt,0,10) === datetime_convert('UTC',$a->timezone,'now','Y-m-d')) ? true : false);
1745 $rr['title'] = $title;
1746 $rr['date'] = day_translate(datetime_convert('UTC', $rr['adjust'] ? $a->timezone : 'UTC', $rr['start'], $bd_format)) . (($today) ? ' ' . t('[today]') : '');
1747 $rr['startime'] = $strt;
1748 $rr['today'] = $today;
1752 $tpl = get_markup_template("events_reminder.tpl");
1753 return replace_macros($tpl, array(
1754 '$baseurl' => $a->get_baseurl(),
1755 '$classtoday' => $classtoday,
1756 '$count' => count($r),
1757 '$event_reminders' => t('Event Reminders'),
1758 '$event_title' => t('Events this week:'),
1767 * Wrap calls to proc_close(proc_open()) and call hook
1768 * so plugins can take part in process :)
1771 * $cmd program to run
1772 * next args are passed as $cmd command line
1774 * e.g.: proc_run("ls","-la","/tmp");
1776 * $cmd and string args are surrounded with ""
1779 if(! function_exists('proc_run')) {
1780 function proc_run($cmd){
1784 $args = func_get_args();
1790 // expand any arrays
1792 foreach($args as $arg) {
1793 if(is_array($arg)) {
1794 foreach($arg as $n) {
1804 $arr = array('args' => $args, 'run_cmd' => true);
1806 call_hooks("proc_run", $arr);
1807 if(! $arr['run_cmd'])
1810 if(count($args) && $args[0] === 'php')
1811 $args[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
1813 // add baseurl to args. cli scripts can't construct it
1814 $args[] = $a->get_baseurl();
1816 for($x = 0; $x < count($args); $x ++)
1817 $args[$x] = escapeshellarg($args[$x]);
1821 $cmdline = implode($args," ");
1822 if(get_config('system','proc_windows'))
1823 proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
1825 proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
1829 if(! function_exists('current_theme')) {
1830 function current_theme(){
1831 $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
1835 // $mobile_detect = new Mobile_Detect();
1836 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1837 $is_mobile = $a->is_mobile || $a->is_tablet;
1840 if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
1845 $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : '');
1846 $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
1848 if($theme_name === '---') {
1849 // user has selected to have the mobile theme be the same as the normal one
1855 if(!$is_mobile || ($system_theme === '' && $theme_name === '')) {
1856 $system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1857 $theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $system_theme);
1861 (file_exists('view/theme/' . $theme_name . '/style.css') ||
1862 file_exists('view/theme/' . $theme_name . '/style.php')))
1863 return($theme_name);
1865 foreach($app_base_themes as $t) {
1866 if(file_exists('view/theme/' . $t . '/style.css')||
1867 file_exists('view/theme/' . $t . '/style.php'))
1871 $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
1872 if(count($fallback))
1873 return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
1879 * Return full URL to theme which is currently in effect.
1880 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1882 if(! function_exists('current_theme_url')) {
1883 function current_theme_url() {
1885 $t = current_theme();
1886 if (file_exists('view/theme/' . $t . '/style.php'))
1887 return($a->get_baseurl() . '/view/theme/' . $t . '/style.pcss');
1888 return($a->get_baseurl() . '/view/theme/' . $t . '/style.css');
1892 if(! function_exists('feed_birthday')) {
1893 function feed_birthday($uid,$tz) {
1897 * Determine the next birthday, but only if the birthday is published
1898 * in the default profile. We _could_ also look for a private profile that the
1899 * recipient can see, but somebody could get mad at us if they start getting
1900 * public birthday greetings when they haven't made this info public.
1902 * Assuming we are able to publish this info, we are then going to convert
1903 * the start time from the owner's timezone to UTC.
1905 * This will potentially solve the problem found with some social networks
1906 * where birthdays are converted to the viewer's timezone and salutations from
1907 * elsewhere in the world show up on the wrong day. We will convert it to the
1908 * viewer's timezone also, but first we are going to convert it from the birthday
1909 * person's timezone to GMT - so the viewer may find the birthday starting at
1910 * 6:00PM the day before, but that will correspond to midnight to the birthday person.
1920 $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
1924 if($p && count($p)) {
1925 $tmp_dob = substr($p[0]['dob'],5);
1926 if(intval($tmp_dob)) {
1927 $y = datetime_convert($tz,$tz,'now','Y');
1928 $bd = $y . '-' . $tmp_dob . ' 00:00';
1929 $t_dob = strtotime($bd);
1930 $now = strtotime(datetime_convert($tz,$tz,'now'));
1932 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
1933 $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
1941 if(! function_exists('is_site_admin')) {
1942 function is_site_admin() {
1945 $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
1947 //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
1948 if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && in_array($a->user['email'], $adminlist))
1955 if(! function_exists('load_contact_links')) {
1956 function load_contact_links($uid) {
1962 if(! $uid || x($a->contacts,'empty'))
1965 $r = q("SELECT `id`,`network`,`url`,`thumb` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 ",
1970 $url = normalise_link($rr['url']);
1975 $ret['empty'] = true;
1976 $a->contacts = $ret;
1981 if(! function_exists('profile_tabs')){
1982 function profile_tabs($a, $is_owner=False, $nickname=Null){
1983 //echo "<pre>"; var_dump($a->user); killme();
1985 if (is_null($nickname))
1986 $nickname = $a->user['nickname'];
1989 $tab = notags(trim($_GET['tab']));
1991 $url = $a->get_baseurl() . '/profile/' . $nickname;
1995 'label'=>t('Status'),
1997 'sel' => ((!isset($tab)&&$a->argv[0]=='profile')?'active':''),
1998 'title' => t('Status Messages and Posts'),
1999 'id' => 'status-tab',
2002 'label' => t('Profile'),
2003 'url' => $url.'/?tab=profile',
2004 'sel' => ((isset($tab) && $tab=='profile')?'active':''),
2005 'title' => t('Profile Details'),
2006 'id' => 'profile-tab',
2009 'label' => t('Photos'),
2010 'url' => $a->get_baseurl() . '/photos/' . $nickname,
2011 'sel' => ((!isset($tab)&&$a->argv[0]=='photos')?'active':''),
2012 'title' => t('Photo Albums'),
2013 'id' => 'photo-tab',
2016 'label' => t('Videos'),
2017 'url' => $a->get_baseurl() . '/videos/' . $nickname,
2018 'sel' => ((!isset($tab)&&$a->argv[0]=='videos')?'active':''),
2019 'title' => t('Videos'),
2020 'id' => 'video-tab',
2026 'label' => t('Events'),
2027 'url' => $a->get_baseurl() . '/events',
2028 'sel' =>((!isset($tab)&&$a->argv[0]=='events')?'active':''),
2029 'title' => t('Events and Calendar'),
2030 'id' => 'events-tab',
2033 'label' => t('Personal Notes'),
2034 'url' => $a->get_baseurl() . '/notes',
2035 'sel' =>((!isset($tab)&&$a->argv[0]=='notes')?'active':''),
2036 'title' => t('Only You Can See This'),
2037 'id' => 'notes-tab',
2042 $arr = array('is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => (($tab) ? $tab : false), 'tabs' => $tabs);
2043 call_hooks('profile_tabs', $arr);
2045 $tpl = get_markup_template('common_tabs.tpl');
2047 return replace_macros($tpl,array('$tabs' => $arr['tabs']));
2051 function get_my_url() {
2052 if(x($_SESSION,'my_url'))
2053 return $_SESSION['my_url'];
2057 function zrl_init(&$a) {
2058 $tmp_str = get_my_url();
2059 if(validate_url($tmp_str)) {
2060 proc_run('php','include/gprobe.php',bin2hex($tmp_str));
2061 $arr = array('zrl' => $tmp_str, 'url' => $a->cmd);
2062 call_hooks('zrl_init',$arr);
2066 function zrl($s,$force = false) {
2069 if((! strpos($s,'/profile/')) && (! $force))
2071 if($force && substr($s,-1,1) !== '/')
2073 $achar = strpos($s,'?') ? '&' : '?';
2074 $mine = get_my_url();
2075 if($mine and ! link_compare($mine,$s))
2076 return $s . $achar . 'zrl=' . urlencode($mine);
2081 * returns querystring as string from a mapped array
2083 * @param params Array
2086 function build_querystring($params, $name=null) {
2088 foreach($params as $key=>$val) {
2089 if(is_array($val)) {
2091 $ret .= build_querystring($val, $key);
2093 $ret .= build_querystring($val, $name."[$key]");
2096 $val = urlencode($val);
2098 $ret.=$name."[$key]"."=$val&";
2100 $ret.= "$key=$val&";
2107 function explode_querystring($query) {
2108 $arg_st = strpos($query, '?');
2109 if($arg_st !== false) {
2110 $base = substr($query, 0, $arg_st);
2118 $args = explode('&', substr($query, $arg_st));
2119 foreach($args as $k=>$arg) {
2123 $args = array_values($args);
2128 $args = array_values($args);
2138 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
2140 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
2142 function curPageURL() {
2144 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
2146 if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
2147 $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
2149 $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
2154 function random_digits($digits) {
2156 for($i = 0; $i < $digits; $i++) {
2162 function get_cachefile($file, $writemode = true) {
2163 $cache = get_itemcachepath();
2165 if ((! $cache) || (! is_dir($cache)))
2168 $subfolder = $cache."/".substr($file, 0, 2);
2170 $cachepath = $subfolder."/".$file;
2173 if (!is_dir($subfolder)) {
2175 chmod($subfolder, 0777);
2182 function clear_cache($basepath = "", $path = "") {
2184 $basepath = get_itemcachepath();
2188 if (($path == "") OR (!is_dir($path)))
2191 if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
2194 $cachetime = (int)get_config('system','itemcache_duration');
2195 if ($cachetime == 0)
2198 if (is_writable($path)){
2199 if ($dh = opendir($path)) {
2200 while (($file = readdir($dh)) !== false) {
2201 $fullpath = $path."/".$file;
2202 if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
2203 clear_cache($basepath, $fullpath);
2204 if ((filetype($fullpath) == "file") and (filectime($fullpath) < (time() - $cachetime)))
2212 function get_itemcachepath() {
2213 // Checking, if the cache is deactivated
2214 $cachetime = (int)get_config('system','itemcache_duration');
2218 $itemcache = get_config('system','itemcache');
2219 if (($itemcache != "") AND is_dir($itemcache) AND is_writable($itemcache))
2222 $temppath = get_temppath();
2224 if ($temppath != "") {
2225 $itemcache = $temppath."/itemcache";
2228 if (is_dir($itemcache) AND is_writable($itemcache)) {
2229 set_config("system", "itemcache", $itemcache);
2236 function get_lockpath() {
2237 $lockpath = get_config('system','lockpath');
2238 if (($lockpath != "") AND is_dir($lockpath) AND is_writable($lockpath))
2241 $temppath = get_temppath();
2243 if ($temppath != "") {
2244 $lockpath = $temppath."/lock";
2247 if (is_dir($lockpath) AND is_writable($lockpath)) {
2248 set_config("system", "lockpath", $lockpath);
2255 function get_temppath() {
2256 $temppath = get_config("system","temppath");
2257 if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath))
2260 $temppath = sys_get_temp_dir();
2261 if (($temppath != "") AND is_dir($temppath) AND is_writable($temppath)) {
2262 set_config("system", "temppath", $temppath);
2269 function set_template_engine(&$a, $engine = 'internal') {
2270 // This function is no longer necessary, but keep it as a wrapper to the class method
2271 // to avoid breaking themes again unnecessarily
2273 $a->set_template_engine($engine);
2276 if(!function_exists('exif_imagetype')) {
2277 function exif_imagetype($file) {
2278 $size = getimagesize($file);