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.1.1556' );
16 define ( 'DFRN_PROTOCOL_VERSION', '2.23' );
17 define ( 'DB_UPDATE_VERSION', 1157 );
19 define ( 'EOL', "<br />\r\n" );
20 define ( 'ATOM_TIME', 'Y-m-d\TH:i:s\Z' );
25 * Image storage quality. Lower numbers save space at cost of image detail.
26 * For ease of upgrade, please do not change here. Change jpeg quality with
27 * $a->config['system']['jpeg_quality'] = n;
28 * in .htconfig.php, where n is netween 1 and 100, and with very poor results
33 define ( 'JPEG_QUALITY', 100 );
35 * $a->config['system']['png_quality'] from 0 (uncompressed) to 9
37 define ( 'PNG_QUALITY', 8 );
41 * An alternate way of limiting picture upload sizes. Specify the maximum pixel
42 * length that pictures are allowed to be (for non-square pictures, it will apply
43 * to the longest side). Pictures longer than this length will be resized to be
44 * this length (on the longest side, the other side will be scaled appropriately).
45 * Modify this value using
47 * $a->config['system']['max_image_length'] = n;
51 * If you don't want to set a maximum length, set to -1. The default value is
52 * defined by 'MAX_IMAGE_LENGTH' below.
55 define ( 'MAX_IMAGE_LENGTH', -1 );
62 define ( 'DEFAULT_DB_ENGINE', 'MyISAM' );
65 * SSL redirection policies
68 define ( 'SSL_POLICY_NONE', 0 );
69 define ( 'SSL_POLICY_FULL', 1 );
70 define ( 'SSL_POLICY_SELFSIGN', 2 );
77 define ( 'LOGGER_NORMAL', 0 );
78 define ( 'LOGGER_TRACE', 1 );
79 define ( 'LOGGER_DEBUG', 2 );
80 define ( 'LOGGER_DATA', 3 );
81 define ( 'LOGGER_ALL', 4 );
84 * registration policies
87 define ( 'REGISTER_CLOSED', 0 );
88 define ( 'REGISTER_APPROVE', 1 );
89 define ( 'REGISTER_OPEN', 2 );
95 define ( 'CONTACT_IS_FOLLOWER', 1);
96 define ( 'CONTACT_IS_SHARING', 2);
97 define ( 'CONTACT_IS_FRIEND', 3);
101 * DB update return values
104 define ( 'UPDATE_SUCCESS', 0);
105 define ( 'UPDATE_FAILED', 1);
112 * PAGE_NORMAL is a typical personal profile account
113 * PAGE_SOAPBOX automatically approves all friend requests as CONTACT_IS_SHARING, (readonly)
114 * PAGE_COMMUNITY automatically approves all friend requests as CONTACT_IS_SHARING, but with
115 * write access to wall and comments (no email and not included in page owner's ACL lists)
116 * PAGE_FREELOVE automatically approves all friend requests as full friends (CONTACT_IS_FRIEND).
120 define ( 'PAGE_NORMAL', 0 );
121 define ( 'PAGE_SOAPBOX', 1 );
122 define ( 'PAGE_COMMUNITY', 2 );
123 define ( 'PAGE_FREELOVE', 3 );
124 define ( 'PAGE_BLOG', 4 );
125 define ( 'PAGE_PRVGROUP', 5 );
128 * Network and protocol family types
131 define ( 'NETWORK_DFRN', 'dfrn'); // Friendica, Mistpark, other DFRN implementations
132 define ( 'NETWORK_ZOT', 'zot!'); // Zot!
133 define ( 'NETWORK_OSTATUS', 'stat'); // status.net, identi.ca, GNU-social, other OStatus implementations
134 define ( 'NETWORK_FEED', 'feed'); // RSS/Atom feeds with no known "post/notify" protocol
135 define ( 'NETWORK_DIASPORA', 'dspr'); // Diaspora
136 define ( 'NETWORK_MAIL', 'mail'); // IMAP/POP
137 define ( 'NETWORK_MAIL2', 'mai2'); // extended IMAP/POP
138 define ( 'NETWORK_FACEBOOK', 'face'); // Facebook API
139 define ( 'NETWORK_LINKEDIN', 'lnkd'); // LinkedIn
140 define ( 'NETWORK_XMPP', 'xmpp'); // XMPP
141 define ( 'NETWORK_MYSPACE', 'mysp'); // MySpace
142 define ( 'NETWORK_GPLUS', 'goog'); // Google+
144 define ( 'NETWORK_PHANTOM', 'unkn'); // Place holder
147 * These numbers are used in stored permissions
148 * and existing allocations MUST NEVER BE CHANGED
149 * OR RE-ASSIGNED! You may only add to them.
152 $netgroup_ids = array(
153 NETWORK_DFRN => (-1),
155 NETWORK_OSTATUS => (-3),
156 NETWORK_FEED => (-4),
157 NETWORK_DIASPORA => (-5),
158 NETWORK_MAIL => (-6),
159 NETWORK_MAIL2 => (-7),
160 NETWORK_FACEBOOK => (-8),
161 NETWORK_LINKEDIN => (-9),
162 NETWORK_XMPP => (-10),
163 NETWORK_MYSPACE => (-11),
164 NETWORK_GPLUS => (-12),
166 NETWORK_PHANTOM => (-127),
171 * Maximum number of "people who like (or don't like) this" that we will list by name
174 define ( 'MAX_LIKERS', 75);
177 * Communication timeout
180 define ( 'ZCURL_TIMEOUT' , (-1));
184 * email notification options
187 define ( 'NOTIFY_INTRO', 0x0001 );
188 define ( 'NOTIFY_CONFIRM', 0x0002 );
189 define ( 'NOTIFY_WALL', 0x0004 );
190 define ( 'NOTIFY_COMMENT', 0x0008 );
191 define ( 'NOTIFY_MAIL', 0x0010 );
192 define ( 'NOTIFY_SUGGEST', 0x0020 );
193 define ( 'NOTIFY_PROFILE', 0x0040 );
194 define ( 'NOTIFY_TAGSELF', 0x0080 );
195 define ( 'NOTIFY_TAGSHARE', 0x0100 );
196 define ( 'NOTIFY_POKE', 0x0200 );
198 define ( 'NOTIFY_SYSTEM', 0x8000 );
205 define ( 'TERM_UNKNOWN', 0 );
206 define ( 'TERM_HASHTAG', 1 );
207 define ( 'TERM_MENTION', 2 );
208 define ( 'TERM_CATEGORY', 3 );
209 define ( 'TERM_PCATEGORY', 4 );
210 define ( 'TERM_FILE', 5 );
212 define ( 'TERM_OBJ_POST', 1 );
213 define ( 'TERM_OBJ_PHOTO', 2 );
218 * various namespaces we may need to parse
221 define ( 'NAMESPACE_ZOT', 'http://purl.org/zot' );
222 define ( 'NAMESPACE_DFRN' , 'http://purl.org/macgirvin/dfrn/1.0' );
223 define ( 'NAMESPACE_THREAD' , 'http://purl.org/syndication/thread/1.0' );
224 define ( 'NAMESPACE_TOMB' , 'http://purl.org/atompub/tombstones/1.0' );
225 define ( 'NAMESPACE_ACTIVITY', 'http://activitystrea.ms/spec/1.0/' );
226 define ( 'NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/' );
227 define ( 'NAMESPACE_MEDIA', 'http://purl.org/syndication/atommedia' );
228 define ( 'NAMESPACE_SALMON_ME', 'http://salmon-protocol.org/ns/magic-env' );
229 define ( 'NAMESPACE_OSTATUSSUB', 'http://ostatus.org/schema/1.0/subscribe' );
230 define ( 'NAMESPACE_GEORSS', 'http://www.georss.org/georss' );
231 define ( 'NAMESPACE_POCO', 'http://portablecontacts.net/spec/1.0' );
232 define ( 'NAMESPACE_FEED', 'http://schemas.google.com/g/2010#updates-from' );
233 define ( 'NAMESPACE_OSTATUS', 'http://ostatus.org/schema/1.0' );
234 define ( 'NAMESPACE_STATUSNET', 'http://status.net/schema/api/1/' );
235 define ( 'NAMESPACE_ATOM1', 'http://www.w3.org/2005/Atom' );
237 * activity stream defines
240 define ( 'ACTIVITY_LIKE', NAMESPACE_ACTIVITY_SCHEMA . 'like' );
241 define ( 'ACTIVITY_DISLIKE', NAMESPACE_DFRN . '/dislike' );
242 define ( 'ACTIVITY_OBJ_HEART', NAMESPACE_DFRN . '/heart' );
244 define ( 'ACTIVITY_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'make-friend' );
245 define ( 'ACTIVITY_REQ_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'request-friend' );
246 define ( 'ACTIVITY_UNFRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'remove-friend' );
247 define ( 'ACTIVITY_FOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'follow' );
248 define ( 'ACTIVITY_UNFOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'stop-following' );
249 define ( 'ACTIVITY_JOIN', NAMESPACE_ACTIVITY_SCHEMA . 'join' );
251 define ( 'ACTIVITY_POST', NAMESPACE_ACTIVITY_SCHEMA . 'post' );
252 define ( 'ACTIVITY_UPDATE', NAMESPACE_ACTIVITY_SCHEMA . 'update' );
253 define ( 'ACTIVITY_TAG', NAMESPACE_ACTIVITY_SCHEMA . 'tag' );
254 define ( 'ACTIVITY_FAVORITE', NAMESPACE_ACTIVITY_SCHEMA . 'favorite' );
256 define ( 'ACTIVITY_POKE', NAMESPACE_ZOT . '/activity/poke' );
257 define ( 'ACTIVITY_MOOD', NAMESPACE_ZOT . '/activity/mood' );
259 define ( 'ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment' );
260 define ( 'ACTIVITY_OBJ_NOTE', NAMESPACE_ACTIVITY_SCHEMA . 'note' );
261 define ( 'ACTIVITY_OBJ_PERSON', NAMESPACE_ACTIVITY_SCHEMA . 'person' );
262 define ( 'ACTIVITY_OBJ_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'photo' );
263 define ( 'ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo' );
264 define ( 'ACTIVITY_OBJ_ALBUM', NAMESPACE_ACTIVITY_SCHEMA . 'photo-album' );
265 define ( 'ACTIVITY_OBJ_EVENT', NAMESPACE_ACTIVITY_SCHEMA . 'event' );
266 define ( 'ACTIVITY_OBJ_GROUP', NAMESPACE_ACTIVITY_SCHEMA . 'group' );
267 define ( 'ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN . '/tagterm' );
268 define ( 'ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN . '/profile' );
271 * item weight for query ordering
274 define ( 'GRAVITY_PARENT', 0);
275 define ( 'GRAVITY_LIKE', 3);
276 define ( 'GRAVITY_COMMENT', 6);
280 * Reverse the effect of magic_quotes_gpc if it is enabled.
281 * Please disable magic_quotes_gpc so we don't have to do this.
282 * See http://php.net/manual/en/security.magicquotes.disabling.php
288 error_reporting(E_ERROR | E_WARNING | E_PARSE);
292 // This has to be quite large to deal with embedded private photos
293 ini_set('pcre.backtrack_limit', 500000);
296 if (get_magic_quotes_gpc()) {
297 $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
298 while (list($key, $val) = each($process)) {
299 foreach ($val as $k => $v) {
300 unset($process[$key][$k]);
302 $process[$key][stripslashes($k)] = $v;
303 $process[] = &$process[$key][stripslashes($k)];
305 $process[$key][stripslashes($k)] = stripslashes($v);
318 * Our main application structure for the life of this page
319 * Primarily deals with the URL that got us here
320 * and tries to make some sense of it, and
321 * stores our page contents and config storage
322 * and anything else that might need to be passed around
323 * before we spit the page out.
327 if(! class_exists('App')) {
330 public $module_loaded = false;
331 public $query_string;
339 public $page_contact;
341 public $data = array();
342 public $error = false;
352 public $interactive = true;
354 public $apps = array();
364 // Allow themes to control internal parameters
365 // by changing App values in theme.php
367 public $sourcename = '';
368 public $videowidth = 425;
369 public $videoheight = 350;
370 public $force_max_items = 0;
371 public $theme_thread_allow = true;
373 // An array for all theme-controllable parameters
374 // Mostly unimplemented yet. Only options 'stylesheet' and
377 public $theme = array(
380 'videoheight' => 350,
381 'force_max_items' => 0,
382 'thread_allow' => true,
392 private $curl_headers;
394 private $cached_profile_image;
395 private $cached_profile_picdate;
397 function __construct() {
399 global $default_timezone, $argv, $argc;
401 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
403 date_default_timezone_set($this->timezone);
405 $this->config = array();
406 $this->page = array();
407 $this->pager= array();
409 $this->query_string = '';
413 $this->scheme = 'http';
414 if(x($_SERVER,'HTTPS') && $_SERVER['HTTPS'])
415 $this->scheme = 'https';
416 elseif(x($_SERVER,'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443))
417 $this->scheme = 'https';
419 if(x($_SERVER,'SERVER_NAME')) {
420 $this->hostname = $_SERVER['SERVER_NAME'];
422 // See bug 437 - this didn't work so disabling it
423 //if(stristr($this->hostname,'xn--')) {
424 // PHP or webserver may have converted idn to punycode, so
425 // convert punycode back to utf-8
426 // require_once('library/simplepie/idn/idna_convert.class.php');
427 // $x = new idna_convert();
428 // $this->hostname = $x->decode($_SERVER['SERVER_NAME']);
431 if(x($_SERVER,'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443)
432 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
434 * Figure out if we are running at the top of a domain
435 * or in a sub-directory and adjust accordingly
438 $path = trim(dirname($_SERVER['SCRIPT_NAME']),'/\\');
439 if(isset($path) && strlen($path) && ($path != $this->path))
442 if (is_array($argv) && $argc>1 && substr(end($argv), 0, 4)=="http" ) {
443 $this->set_baseurl(array_pop($argv) );
448 "include/$this->hostname" . PATH_SEPARATOR
449 . 'include' . PATH_SEPARATOR
450 . 'library' . PATH_SEPARATOR
451 . 'library/phpsec' . PATH_SEPARATOR
452 . 'library/langdet' . PATH_SEPARATOR
456 if((x($_SERVER,'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'],0,2) === "q=") {
457 $this->query_string = substr($_SERVER['QUERY_STRING'],2);
458 // removing trailing / - maybe a nginx problem
459 if (substr($this->query_string, 0, 1) == "/")
460 $this->query_string = substr($this->query_string, 1);
463 $this->cmd = trim($_GET['q'],'/\\');
465 // unix style "homedir"
467 if(substr($this->cmd,0,1) === '~')
468 $this->cmd = 'profile/' . substr($this->cmd,1);
470 // Diaspora style profile url
472 if(substr($this->cmd,0,2) === 'u/')
473 $this->cmd = 'profile/' . substr($this->cmd,2);
477 * Break the URL path into C style argc/argv style arguments for our
478 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
479 * will be 3 (integer) and $this->argv will contain:
485 * There will always be one argument. If provided a naked domain
486 * URL, $this->argv[0] is set to "home".
490 $this->argv = explode('/',$this->cmd);
491 $this->argc = count($this->argv);
492 if((array_key_exists('0',$this->argv)) && strlen($this->argv[0])) {
493 $this->module = str_replace(".", "_", $this->argv[0]);
494 $this->module = str_replace("-", "_", $this->module);
498 $this->argv = array('home');
499 $this->module = 'home';
503 * See if there is any page number information, and initialise
507 $this->pager['page'] = ((x($_GET,'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
508 $this->pager['itemspage'] = 50;
509 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
510 if($this->pager['start'] < 0)
511 $this->pager['start'] = 0;
512 $this->pager['total'] = 0;
515 * Detect mobile devices
518 $mobile_detect = new Mobile_Detect();
519 $this->is_mobile = $mobile_detect->isMobile();
520 $this->is_tablet = $mobile_detect->isTablet();
523 function get_baseurl($ssl = false) {
525 $scheme = $this->scheme;
527 if((x($this->config,'system')) && (x($this->config['system'],'ssl_policy'))) {
528 if(intval($this->config['system']['ssl_policy']) === intval(SSL_POLICY_FULL))
531 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
532 // (and also the login link). Anything seen by an outsider will have it turned off.
534 if($this->config['system']['ssl_policy'] == SSL_POLICY_SELFSIGN) {
542 $this->baseurl = $scheme . "://" . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
543 return $this->baseurl;
546 function set_baseurl($url) {
547 $parsed = @parse_url($url);
549 $this->baseurl = $url;
552 $this->scheme = $parsed['scheme'];
554 $this->hostname = $parsed['host'];
555 if(x($parsed,'port'))
556 $this->hostname .= ':' . $parsed['port'];
557 if(x($parsed,'path'))
558 $this->path = trim($parsed['path'],'\\/');
563 function get_hostname() {
564 return $this->hostname;
567 function set_hostname($h) {
568 $this->hostname = $h;
571 function set_path($p) {
572 $this->path = trim(trim($p),'/');
575 function get_path() {
579 function set_pager_total($n) {
580 $this->pager['total'] = intval($n);
583 function set_pager_itemspage($n) {
584 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
585 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
589 function init_pagehead() {
590 $interval = ((local_user()) ? get_pconfig(local_user(),'system','update_interval') : 40000);
591 if($interval < 10000)
594 $this->page['title'] = $this->config['sitename'];
596 /* put the head template at the beginning of page['htmlhead']
597 * since the code added by the modules frequently depends on it
600 if(!isset($this->page['htmlhead']))
601 $this->page['htmlhead'] = '';
602 $tpl = get_markup_template('head.tpl');
603 $this->page['htmlhead'] = replace_macros($tpl,array(
604 '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
605 '$local_user' => local_user(),
606 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
607 '$delitem' => t('Delete this item?'),
608 '$comment' => t('Comment'),
609 '$showmore' => t('show more'),
610 '$showfewer' => t('show fewer'),
611 '$update_interval' => $interval
612 )) . $this->page['htmlhead'];
615 function init_page_end() {
616 if(!isset($this->page['end']))
617 $this->page['end'] = '';
618 $tpl = get_markup_template('end.tpl');
619 $this->page['end'] = replace_macros($tpl,array(
620 '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
621 )) . $this->page['end'];
624 function set_curl_code($code) {
625 $this->curl_code = $code;
628 function get_curl_code() {
629 return $this->curl_code;
632 function set_curl_headers($headers) {
633 $this->curl_headers = $headers;
636 function get_curl_headers() {
637 return $this->curl_headers;
640 function get_cached_avatar_image($avatar_image){
641 if($this->cached_profile_image[$avatar_image])
642 return $this->cached_profile_image[$avatar_image];
644 $path_parts = explode("/",$avatar_image);
645 $common_filename = $path_parts[count($path_parts)-1];
647 if($this->cached_profile_picdate[$common_filename]){
648 $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
650 $r = q("SELECT `contact`.`avatar-date` AS picdate FROM `contact` WHERE `contact`.`thumb` like \"%%/%s\"",
653 $this->cached_profile_image[$avatar_image] = $avatar_image;
655 $this->cached_profile_picdate[$common_filename] = "?rev=" . urlencode($r[0]['picdate']);
656 $this->cached_profile_image[$avatar_image] = $avatar_image . $this->cached_profile_picdate[$common_filename];
659 return $this->cached_profile_image[$avatar_image];
666 // retrieve the App structure
667 // useful in functions which require it but don't get it passed to them
669 if(! function_exists('get_app')) {
677 // Multi-purpose function to check variable state.
678 // Usage: x($var) or $x($array,'key')
679 // returns false if variable/key is not set
680 // if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
681 // e.g. x('') or x(0) returns 0;
683 if(! function_exists('x')) {
684 function x($s,$k = NULL) {
686 if((is_array($s)) && (array_key_exists($k,$s))) {
705 // called from db initialisation if db is dead.
707 if(! function_exists('system_unavailable')) {
708 function system_unavailable() {
709 include('system_unavailable.php');
717 function clean_urls() {
719 // if($a->config['system']['clean_urls'])
726 $base = $a->get_baseurl();
734 return $a->get_baseurl();
737 function absurl($path) {
738 if(strpos($path,'/') === 0)
739 return z_path() . $path;
744 return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
748 // Primarily involved with database upgrade, but also sets the
749 // base url for use in cmdline programs which don't have
750 // $_SERVER variables, and synchronising the state of installed plugins.
753 if(! function_exists('check_config')) {
754 function check_config(&$a) {
756 $build = get_config('system','build');
758 $build = set_config('system','build',DB_UPDATE_VERSION);
760 $url = get_config('system','url');
762 // if the url isn't set or the stored url is radically different
763 // than the currently visited url, store the current value accordingly.
764 // "Radically different" ignores common variations such as http vs https
765 // and www.example.com vs example.com.
766 // We will only change the url to an ip address if there is no existing setting
769 $url = set_config('system','url',$a->get_baseurl());
770 if((! link_compare($url,$a->get_baseurl())) && (! preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$a->get_hostname)))
771 $url = set_config('system','url',$a->get_baseurl());
774 if($build != DB_UPDATE_VERSION) {
775 $stored = intval($build);
776 $current = intval(DB_UPDATE_VERSION);
777 if(($stored < $current) && file_exists('update.php')) {
779 load_config('database');
781 // We're reporting a different version than what is currently installed.
782 // Run any existing update scripts to bring the database up to current.
784 require_once('update.php');
786 // make sure that boot.php and update.php are the same release, we might be
787 // updating right this very second and the correct version of the update.php
788 // file may not be here yet. This can happen on a very busy site.
790 if(DB_UPDATE_VERSION == UPDATE_VERSION) {
792 for($x = $stored; $x < $current; $x ++) {
793 if(function_exists('update_' . $x)) {
795 // There could be a lot of processes running or about to run.
796 // We want exactly one process to run the update command.
797 // So store the fact that we're taking responsibility
798 // after first checking to see if somebody else already has.
800 // If the update fails or times-out completely you may need to
801 // delete the config entry to try again.
803 $t = get_config('database','update_' . $x);
806 set_config('database','update_' . $x, time());
808 // call the specific update
810 $func = 'update_' . $x;
813 //send the administrator an e-mail
814 $email_tpl = get_intltext_template("update_fail_eml.tpl");
815 $email_msg = replace_macros($email_tpl, array(
816 '$sitename' => $a->config['sitename'],
817 '$siteurl' => $a->get_baseurl(),
819 '$error' => sprintf( t('Update %s failed. See error logs.'), $x)
821 $subject=sprintf(t('Update Error at %s'), $a->get_baseurl());
823 mail($a->config['admin_email'], $subject, $email_msg,
824 'From: ' . t('Administrator') . '@' . $_SERVER['SERVER_NAME'] . "\n"
825 . 'Content-type: text/plain; charset=UTF-8' . "\n"
826 . 'Content-transfer-encoding: 8bit' );
828 logger('CRITICAL: Update Failed: '. $x);
832 set_config('database','update_' . $x, 'success');
833 set_config('system','build', $x + 1);
843 * Synchronise plugins:
845 * $a->config['system']['addon'] contains a comma-separated list of names
846 * of plugins/addons which are used on this system.
847 * Go through the database list of already installed addons, and if we have
848 * an entry, but it isn't in the config list, call the uninstall procedure
849 * and mark it uninstalled in the database (for now we'll remove it).
850 * Then go through the config list and if we have a plugin that isn't installed,
851 * call the install procedure and add it to the database.
855 $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
859 $installed = array();
861 $plugins = get_config('system','addon');
862 $plugins_arr = array();
865 $plugins_arr = explode(',',str_replace(' ', '',$plugins));
867 $a->plugins = $plugins_arr;
869 $installed_arr = array();
871 if(count($installed)) {
872 foreach($installed as $i) {
873 if(! in_array($i['name'],$plugins_arr)) {
874 uninstall_plugin($i['name']);
877 $installed_arr[] = $i['name'];
882 if(count($plugins_arr)) {
883 foreach($plugins_arr as $p) {
884 if(! in_array($p,$installed_arr)) {
898 function get_guid($size=16) {
899 $exists = true; // assume by default that we don't have a unique guid
901 $s = random_string($size);
902 $r = q("select id from guid where guid = '%s' limit 1", dbesc($s));
906 q("insert into guid ( guid ) values ( '%s' ) ", dbesc($s));
911 // wrapper for adding a login box. If $register == true provide a registration
912 // link. This will most always depend on the value of $a->config['register_policy'].
913 // returns the complete html for inserting into the page
915 if(! function_exists('login')) {
916 function login($register = false, $hiddens=false) {
922 'title' => t('Create a New Account'),
923 'desc' => t('Register')
927 $noid = get_config('system','no_openid');
929 $dest_url = $a->get_baseurl(true) . '/' . $a->query_string;
932 $tpl = get_markup_template("logout.tpl");
935 $a->page['htmlhead'] .= replace_macros(get_markup_template("login_head.tpl"),array(
936 '$baseurl' => $a->get_baseurl(true)
939 $tpl = get_markup_template("login.tpl");
940 $_SESSION['return_url'] = $a->query_string;
941 $a->module = 'login';
945 $o .= replace_macros($tpl,array(
947 '$dest_url' => $dest_url,
948 '$logout' => t('Logout'),
949 '$login' => t('Login'),
951 '$lname' => array('username', t('Nickname or Email address: ') , '', ''),
952 '$lpassword' => array('password', t('Password: '), '', ''),
953 '$lremember' => array('remember', t('Remember me'), 0, ''),
956 '$lopenid' => array('openid_url', t('Or login using OpenID: '),'',''),
958 '$hiddens' => $hiddens,
962 '$lostpass' => t('Forgot your password?'),
963 '$lostlink' => t('Password Reset'),
966 call_hooks('login_hook',$o);
972 // Used to end the current process, after saving session state.
974 if(! function_exists('killme')) {
976 session_write_close();
981 // redirect to another URL and terminate this process.
983 if(! function_exists('goaway')) {
984 function goaway($s) {
985 header("Location: $s");
991 // Returns the uid of locally logged in user or false.
993 if(! function_exists('local_user')) {
994 function local_user() {
995 if((x($_SESSION,'authenticated')) && (x($_SESSION,'uid')))
996 return intval($_SESSION['uid']);
1001 // Returns contact id of authenticated site visitor or false
1003 if(! function_exists('remote_user')) {
1004 function remote_user() {
1005 if((x($_SESSION,'authenticated')) && (x($_SESSION,'visitor_id')))
1006 return intval($_SESSION['visitor_id']);
1011 // contents of $s are displayed prominently on the page the next time
1012 // a page is loaded. Usually used for errors or alerts.
1014 if(! function_exists('notice')) {
1016 * Show an error message to user.
1018 * This function save text in session, to be shown to the user at next page load
1020 * @param string $s - Text of notice
1022 function notice($s) {
1024 if(! x($_SESSION,'sysmsg')) $_SESSION['sysmsg'] = array();
1026 $_SESSION['sysmsg'][] = $s;
1029 if(! function_exists('info')) {
1031 * Show an info message to user.
1033 * This function save text in session, to be shown to the user at next page load
1035 * @param string $s - Text of notice
1039 if(! x($_SESSION,'sysmsg_info')) $_SESSION['sysmsg_info'] = array();
1041 $_SESSION['sysmsg_info'][] = $s;
1046 // wrapper around config to limit the text length of an incoming message
1048 if(! function_exists('get_max_import_size')) {
1049 function get_max_import_size() {
1051 return ((x($a->config,'max_import_size')) ? $a->config['max_import_size'] : 0 );
1059 * Function : profile_load
1061 * @parameter string $nickname
1062 * @parameter int $profile
1064 * Summary: Loads a profile into the page sidebar.
1065 * The function requires a writeable copy of the main App structure, and the nickname
1066 * of a registered local account.
1068 * If the viewer is an authenticated remote viewer, the profile displayed is the
1069 * one that has been configured for his/her viewing in the Contact manager.
1070 * Passing a non-zero profile ID can also allow a preview of a selected profile
1073 * Profile information is placed in the App structure for later retrieval.
1074 * Honours the owner's chosen theme for display.
1078 if(! function_exists('profile_load')) {
1079 function profile_load(&$a, $nickname, $profile = 0) {
1081 $user = q("select uid from user where nickname = '%s' limit 1",
1085 if(! ($user && count($user))) {
1086 logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
1087 notice( t('Requested account is not available.') . EOL );
1092 if(remote_user() && count($_SESSION['remote'])) {
1093 foreach($_SESSION['remote'] as $visitor) {
1094 if($visitor['uid'] == $user[0]['uid']) {
1095 $r = q("SELECT `profile-id` FROM `contact` WHERE `id` = %d LIMIT 1",
1096 intval($visitor['cid'])
1099 $profile = $r[0]['profile-id'];
1108 $profile_int = intval($profile);
1109 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `contact`.`avatar-date` AS picdate, `user`.* FROM `profile`
1110 left join `contact` on `contact`.`uid` = `profile`.`uid` LEFT JOIN `user` ON `profile`.`uid` = `user`.`uid`
1111 WHERE `user`.`nickname` = '%s' AND `profile`.`id` = %d and `contact`.`self` = 1 LIMIT 1",
1113 intval($profile_int)
1116 if((! $r) && (! count($r))) {
1117 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `contact`.`avatar-date` AS picdate, `user`.* FROM `profile`
1118 left join `contact` on `contact`.`uid` = `profile`.`uid` LEFT JOIN `user` ON `profile`.`uid` = `user`.`uid`
1119 WHERE `user`.`nickname` = '%s' AND `profile`.`is-default` = 1 and `contact`.`self` = 1 LIMIT 1",
1124 if(($r === false) || (! count($r))) {
1125 logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
1126 notice( t('Requested profile is not available.') . EOL );
1131 // fetch user tags if this isn't the default profile
1133 if(! $r[0]['is-default']) {
1134 $x = q("select `pub_keywords` from `profile` where uid = %d and `is-default` = 1 limit 1",
1135 intval($profile_uid)
1138 $r[0]['pub_keywords'] = $x[0]['pub_keywords'];
1141 $a->profile = $r[0];
1143 $a->profile['mobile-theme'] = get_pconfig($profile_uid, 'system', 'mobile_theme');
1146 $a->page['title'] = $a->profile['name'] . " @ " . $a->config['sitename'];
1147 $_SESSION['theme'] = $a->profile['theme'];
1148 $_SESSION['mobile-theme'] = $a->profile['mobile-theme'];
1151 * load/reload current theme info
1154 $theme_info_file = "view/theme/".current_theme()."/theme.php";
1155 if (file_exists($theme_info_file)){
1156 require_once($theme_info_file);
1159 if(! (x($a->page,'aside')))
1160 $a->page['aside'] = '';
1162 if(local_user() && local_user() == $a->profile['uid']) {
1163 $a->page['aside'] .= replace_macros(get_markup_template('profile_edlink.tpl'),array(
1164 '$editprofile' => t('Edit profile'),
1165 '$profid' => $a->profile['id']
1169 $block = (((get_config('system','block_public')) && (! local_user()) && (! remote_user())) ? true : false);
1171 $a->page['aside'] .= profile_sidebar($a->profile, $block);
1174 $a->page['aside'] .= contact_block();*/
1183 * Function: profile_sidebar
1185 * Formats a profile for display in the sidebar.
1186 * It is very difficult to templatise the HTML completely
1187 * because of all the conditional logic.
1189 * @parameter: array $profile
1191 * Returns HTML string stuitable for sidebar inclusion
1192 * Exceptions: Returns empty string if passed $profile is wrong type or not populated
1197 if(! function_exists('profile_sidebar')) {
1198 function profile_sidebar($profile, $block = 0) {
1207 if((! is_array($profile)) && (! count($profile)))
1210 $profile['picdate'] = urlencode($profile['picdate']);
1212 call_hooks('profile_sidebar_enter', $profile);
1215 // don't show connect link to yourself
1216 $connect = (($profile['uid'] != local_user()) ? t('Connect') : False);
1218 // don't show connect link to authenticated visitors either
1220 if(remote_user() && count($_SESSION['remote'])) {
1221 foreach($_SESSION['remote'] as $visitor) {
1222 if($visitor['uid'] == $profile['uid']) {
1229 if(get_my_url() && $profile['unkmail'])
1230 $wallmessage = t('Message');
1232 $wallmessage = false;
1236 // show edit profile to yourself
1237 if ($profile['uid'] == local_user() && feature_enabled(local_user(),'multi_profiles')) {
1238 $profile['edit'] = array($a->get_baseurl(). '/profiles', t('Profiles'),"", t('Manage/edit profiles'));
1240 $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
1243 $profile['menu'] = array(
1244 'chg_photo' => t('Change profile photo'),
1245 'cr_new' => t('Create New Profile'),
1246 'entries' => array(),
1251 foreach($r as $rr) {
1252 $profile['menu']['entries'][] = array(
1253 'photo' => $rr['thumb'],
1255 'alt' => t('Profile Image'),
1256 'profile_name' => $rr['profile-name'],
1257 'isdefault' => $rr['is-default'],
1258 'visibile_to_everybody' => t('visible to everybody'),
1259 'edit_visibility' => t('Edit visibility'),
1273 if((x($profile,'address') == 1)
1274 || (x($profile,'locality') == 1)
1275 || (x($profile,'region') == 1)
1276 || (x($profile,'postal-code') == 1)
1277 || (x($profile,'country-name') == 1))
1278 $location = t('Location:');
1280 $gender = ((x($profile,'gender') == 1) ? t('Gender:') : False);
1283 $marital = ((x($profile,'marital') == 1) ? t('Status:') : False);
1285 $homepage = ((x($profile,'homepage') == 1) ? t('Homepage:') : False);
1287 if(($profile['hidewall'] || $block) && (! local_user()) && (! remote_user())) {
1288 $location = $pdesc = $gender = $marital = $homepage = False;
1291 $firstname = ((strpos($profile['name'],' '))
1292 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']);
1293 $lastname = (($firstname === $profile['name']) ? '' : trim(substr($profile['name'],strlen($firstname))));
1296 'podloc' => $a->get_baseurl(),
1297 'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false' ),
1298 'nickname' => $profile['nickname'],
1299 'fullname' => $profile['name'],
1300 'firstname' => $firstname,
1301 'lastname' => $lastname,
1302 'photo300' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/300/' . $profile['uid'] . '.jpg'),
1303 'photo100' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/100/' . $profile['uid'] . '.jpg'),
1304 'photo50' => $a->get_cached_avatar_image($a->get_baseurl() . '/photo/custom/50/' . $profile['uid'] . '.jpg'),
1308 $contact_block = contact_block();
1312 $tpl = get_markup_template('profile_vcard.tpl');
1314 $o .= replace_macros($tpl, array(
1315 '$profile' => $profile,
1316 '$connect' => $connect,
1317 '$wallmessage' => $wallmessage,
1318 '$location' => template_escape($location),
1319 '$gender' => $gender,
1321 '$marital' => $marital,
1322 '$homepage' => $homepage,
1323 '$diaspora' => $diaspora,
1324 '$contact_block' => $contact_block,
1328 $arr = array('profile' => &$profile, 'entry' => &$o);
1330 call_hooks('profile_sidebar', $arr);
1337 if(! function_exists('get_birthdays')) {
1338 function get_birthdays() {
1343 if(! local_user() || $a->is_mobile || $a->is_tablet)
1346 // $mobile_detect = new Mobile_Detect();
1347 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1352 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
1353 $bd_short = t('F d');
1355 $r = q("SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
1356 LEFT JOIN `contact` ON `contact`.`id` = `event`.`cid`
1357 WHERE `event`.`uid` = %d AND `type` = 'birthday' AND `start` < '%s' AND `finish` > '%s'
1358 ORDER BY `start` ASC ",
1359 intval(local_user()),
1360 dbesc(datetime_convert('UTC','UTC','now + 6 days')),
1361 dbesc(datetime_convert('UTC','UTC','now'))
1364 if($r && count($r)) {
1366 $now = strtotime('now');
1370 foreach($r as $rr) {
1371 if(strlen($rr['name']))
1373 if((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now))
1376 $classtoday = $istoday ? ' birthday-today ' : '';
1378 foreach($r as &$rr) {
1379 if(! strlen($rr['name']))
1384 if(in_array($rr['cid'],$cids))
1386 $cids[] = $rr['cid'];
1388 $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
1391 if($rr['network'] === NETWORK_DFRN) {
1392 $sparkle = " sparkle";
1393 $url = $a->get_baseurl() . '/redir/' . $rr['cid'];
1397 $rr['title'] = $rr['name'];
1398 $rr['date'] = day_translate(datetime_convert('UTC', $a->timezone, $rr['start'], $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . t('[today]') : '');
1399 $rr['startime'] = Null;
1400 $rr['today'] = $today;
1405 $tpl = get_markup_template("birthdays_reminder.tpl");
1406 return replace_macros($tpl, array(
1407 '$baseurl' => $a->get_baseurl(),
1408 '$classtoday' => $classtoday,
1410 '$event_reminders' => t('Birthday Reminders'),
1411 '$event_title' => t('Birthdays this week:'),
1413 '$lbr' => '{', // raw brackets mess up if/endif macro processing
1421 if(! function_exists('get_events')) {
1422 function get_events() {
1424 require_once('include/bbcode.php');
1428 if(! local_user() || $a->is_mobile || $a->is_tablet)
1432 // $mobile_detect = new Mobile_Detect();
1433 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1438 $bd_format = t('g A l F d') ; // 8 AM Friday January 18
1439 $bd_short = t('F d');
1441 $r = q("SELECT `event`.* FROM `event`
1442 WHERE `event`.`uid` = %d AND `type` != 'birthday' AND `start` < '%s' AND `start` > '%s'
1443 ORDER BY `start` ASC ",
1444 intval(local_user()),
1445 dbesc(datetime_convert('UTC','UTC','now + 6 days')),
1446 dbesc(datetime_convert('UTC','UTC','now - 1 days'))
1449 if($r && count($r)) {
1450 $now = strtotime('now');
1452 foreach($r as $rr) {
1453 if(strlen($rr['name']))
1456 $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start'],'Y-m-d');
1457 if($strt === datetime_convert('UTC',$a->timezone,'now','Y-m-d'))
1460 $classtoday = (($istoday) ? 'event-today' : '');
1463 foreach($r as &$rr) {
1465 $md = datetime_convert('UTC',$a->timezone,$rr['start'],'Y/m');
1467 $md = datetime_convert('UTC','UTC',$rr['start'],'Y/m');
1468 $md .= "/#link-".$rr['id'];
1470 $title = substr(strip_tags(bbcode($rr['desc'])),0,32) . '... ';
1472 $title = t('[No description]');
1474 $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start']);
1475 $today = ((substr($strt,0,10) === datetime_convert('UTC',$a->timezone,'now','Y-m-d')) ? true : false);
1478 $rr['title'] = $title;
1479 $rr['date'] = day_translate(datetime_convert('UTC', $rr['adjust'] ? $a->timezone : 'UTC', $rr['start'], $bd_format)) . (($today) ? ' ' . t('[today]') : '');
1480 $rr['startime'] = $strt;
1481 $rr['today'] = $today;
1485 $tpl = get_markup_template("events_reminder.tpl");
1486 return replace_macros($tpl, array(
1487 '$baseurl' => $a->get_baseurl(),
1488 '$classtoday' => $classtoday,
1489 '$count' => count($r),
1490 '$event_reminders' => t('Event Reminders'),
1491 '$event_title' => t('Events this week:'),
1500 * Wrap calls to proc_close(proc_open()) and call hook
1501 * so plugins can take part in process :)
1504 * $cmd program to run
1505 * next args are passed as $cmd command line
1507 * e.g.: proc_run("ls","-la","/tmp");
1509 * $cmd and string args are surrounded with ""
1512 if(! function_exists('proc_run')) {
1513 function proc_run($cmd){
1517 $args = func_get_args();
1523 // expand any arrays
1525 foreach($args as $arg) {
1526 if(is_array($arg)) {
1527 foreach($arg as $n) {
1537 $arr = array('args' => $args, 'run_cmd' => true);
1539 call_hooks("proc_run", $arr);
1540 if(! $arr['run_cmd'])
1543 if(count($args) && $args[0] === 'php')
1544 $args[0] = ((x($a->config,'php_path')) && (strlen($a->config['php_path'])) ? $a->config['php_path'] : 'php');
1546 // add baseurl to args. cli scripts can't construct it
1547 $args[] = $a->get_baseurl();
1549 for($x = 0; $x < count($args); $x ++)
1550 $args[$x] = escapeshellarg($args[$x]);
1554 $cmdline = implode($args," ");
1555 if(get_config('system','proc_windows'))
1556 proc_close(proc_open('cmd /c start /b ' . $cmdline,array(),$foo,dirname(__FILE__)));
1558 proc_close(proc_open($cmdline." &",array(),$foo,dirname(__FILE__)));
1562 if(! function_exists('current_theme')) {
1563 function current_theme(){
1564 $app_base_themes = array('duepuntozero', 'dispy', 'quattro');
1568 // $mobile_detect = new Mobile_Detect();
1569 // $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1570 $is_mobile = $a->is_mobile || $a->is_tablet;
1573 if(isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
1578 $system_theme = ((isset($a->config['system']['mobile-theme'])) ? $a->config['system']['mobile-theme'] : '');
1579 $theme_name = ((isset($_SESSION) && x($_SESSION,'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
1581 if($theme_name === '---') {
1582 // user has selected to have the mobile theme be the same as the normal one
1588 if(!$is_mobile || ($system_theme === '' && $theme_name === '')) {
1589 $system_theme = ((isset($a->config['system']['theme'])) ? $a->config['system']['theme'] : '');
1590 $theme_name = ((isset($_SESSION) && x($_SESSION,'theme')) ? $_SESSION['theme'] : $system_theme);
1594 (file_exists('view/theme/' . $theme_name . '/style.css') ||
1595 file_exists('view/theme/' . $theme_name . '/style.php')))
1596 return($theme_name);
1598 foreach($app_base_themes as $t) {
1599 if(file_exists('view/theme/' . $t . '/style.css')||
1600 file_exists('view/theme/' . $t . '/style.php'))
1604 $fallback = array_merge(glob('view/theme/*/style.css'),glob('view/theme/*/style.php'));
1605 if(count($fallback))
1606 return (str_replace('view/theme/','', substr($fallback[0],0,-10)));
1612 * Return full URL to theme which is currently in effect.
1613 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1615 if(! function_exists('current_theme_url')) {
1616 function current_theme_url() {
1618 $t = current_theme();
1619 if (file_exists('view/theme/' . $t . '/style.php'))
1620 return($a->get_baseurl() . '/view/theme/' . $t . '/style.pcss');
1621 return($a->get_baseurl() . '/view/theme/' . $t . '/style.css');
1625 if(! function_exists('feed_birthday')) {
1626 function feed_birthday($uid,$tz) {
1630 * Determine the next birthday, but only if the birthday is published
1631 * in the default profile. We _could_ also look for a private profile that the
1632 * recipient can see, but somebody could get mad at us if they start getting
1633 * public birthday greetings when they haven't made this info public.
1635 * Assuming we are able to publish this info, we are then going to convert
1636 * the start time from the owner's timezone to UTC.
1638 * This will potentially solve the problem found with some social networks
1639 * where birthdays are converted to the viewer's timezone and salutations from
1640 * elsewhere in the world show up on the wrong day. We will convert it to the
1641 * viewer's timezone also, but first we are going to convert it from the birthday
1642 * person's timezone to GMT - so the viewer may find the birthday starting at
1643 * 6:00PM the day before, but that will correspond to midnight to the birthday person.
1653 $p = q("SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
1657 if($p && count($p)) {
1658 $tmp_dob = substr($p[0]['dob'],5);
1659 if(intval($tmp_dob)) {
1660 $y = datetime_convert($tz,$tz,'now','Y');
1661 $bd = $y . '-' . $tmp_dob . ' 00:00';
1662 $t_dob = strtotime($bd);
1663 $now = strtotime(datetime_convert($tz,$tz,'now'));
1665 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
1666 $birthday = datetime_convert($tz,'UTC',$bd,ATOM_TIME);
1674 if(! function_exists('is_site_admin')) {
1675 function is_site_admin() {
1677 if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
1684 if(! function_exists('load_contact_links')) {
1685 function load_contact_links($uid) {
1691 if(! $uid || x($a->contacts,'empty'))
1694 $r = q("SELECT `id`,`network`,`url`,`thumb` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 ",
1699 $url = normalise_link($rr['url']);
1704 $ret['empty'] = true;
1705 $a->contacts = $ret;
1710 if(! function_exists('profile_tabs')){
1711 function profile_tabs($a, $is_owner=False, $nickname=Null){
1712 //echo "<pre>"; var_dump($a->user); killme();
1714 if (is_null($nickname))
1715 $nickname = $a->user['nickname'];
1718 $tab = notags(trim($_GET['tab']));
1720 $url = $a->get_baseurl() . '/profile/' . $nickname;
1724 'label'=>t('Status'),
1726 'sel' => ((!isset($tab)&&$a->argv[0]=='profile')?'active':''),
1727 'title' => t('Status Messages and Posts'),
1728 'id' => 'status-tab',
1731 'label' => t('Profile'),
1732 'url' => $url.'/?tab=profile',
1733 'sel' => ((isset($tab) && $tab=='profile')?'active':''),
1734 'title' => t('Profile Details'),
1735 'id' => 'profile-tab',
1738 'label' => t('Photos'),
1739 'url' => $a->get_baseurl() . '/photos/' . $nickname,
1740 'sel' => ((!isset($tab)&&$a->argv[0]=='photos')?'active':''),
1741 'title' => t('Photo Albums'),
1742 'id' => 'photo-tab',
1748 'label' => t('Events'),
1749 'url' => $a->get_baseurl() . '/events',
1750 'sel' =>((!isset($tab)&&$a->argv[0]=='events')?'active':''),
1751 'title' => t('Events and Calendar'),
1752 'id' => 'events-tab',
1755 'label' => t('Personal Notes'),
1756 'url' => $a->get_baseurl() . '/notes',
1757 'sel' =>((!isset($tab)&&$a->argv[0]=='notes')?'active':''),
1758 'title' => t('Only You Can See This'),
1759 'id' => 'notes-tab',
1764 $arr = array('is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => (($tab) ? $tab : false), 'tabs' => $tabs);
1765 call_hooks('profile_tabs', $arr);
1767 $tpl = get_markup_template('common_tabs.tpl');
1769 return replace_macros($tpl,array('$tabs' => $arr['tabs']));
1773 function get_my_url() {
1774 if(x($_SESSION,'my_url'))
1775 return $_SESSION['my_url'];
1779 function zrl_init(&$a) {
1780 $tmp_str = get_my_url();
1781 if(validate_url($tmp_str)) {
1782 proc_run('php','include/gprobe.php',bin2hex($tmp_str));
1783 $arr = array('zrl' => $tmp_str, 'url' => $a->cmd);
1784 call_hooks('zrl_init',$arr);
1788 function zrl($s,$force = false) {
1791 if((! strpos($s,'/profile/')) && (! $force))
1793 if($force && substr($s,-1,1) !== '/')
1795 $achar = strpos($s,'?') ? '&' : '?';
1796 $mine = get_my_url();
1797 if($mine and ! link_compare($mine,$s))
1798 return $s . $achar . 'zrl=' . urlencode($mine);
1803 * returns querystring as string from a mapped array
1805 * @param params Array
1808 function build_querystring($params, $name=null) {
1810 foreach($params as $key=>$val) {
1811 if(is_array($val)) {
1813 $ret .= build_querystring($val, $key);
1815 $ret .= build_querystring($val, $name."[$key]");
1818 $val = urlencode($val);
1820 $ret.=$name."[$key]"."=$val&";
1822 $ret.= "$key=$val&";
1830 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
1832 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
1834 function curPageURL() {
1836 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
1838 if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
1839 $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
1841 $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
1846 function random_digits($digits) {
1848 for($i = 0; $i < $digits; $i++) {
1854 function get_cachefile($file, $writemode = true) {
1855 $cache = get_config("system","itemcache");
1860 if (!is_dir($cache))
1863 $subfolder = $cache."/".substr($file, 0, 2);
1865 $cachepath = $subfolder."/".$file;
1868 if (!is_dir($subfolder)) {
1870 chmod($subfolder, 0777);
1877 function clear_cache($basepath = "", $path = "") {
1879 $basepath = get_config('system','itemcache');
1883 if (($path == "") OR (!is_dir($path)))
1886 if (substr(realpath($path), 0, strlen($basepath)) != $basepath)
1889 $cachetime = (int)get_config('system','itemcache_duration');
1890 if ($cachetime == 0)
1893 if ($dh = opendir($path)) {
1894 while (($file = readdir($dh)) !== false) {
1895 $fullpath = $path."/".$file;
1896 if ((filetype($fullpath) == "dir") and ($file != ".") and ($file != ".."))
1897 clear_cache($basepath, $fullpath);
1898 if ((filetype($fullpath) == "file") and filectime($fullpath) < (time() - $cachetime))