]> git.mxchange.org Git - friendica.git/blob - include/identity.php
3066b71130fca3b3746bfe53dbd870f989b4ec45
[friendica.git] / include / identity.php
1 <?php
2 /**
3  * @file include/identity.php
4  */
5
6 use Friendica\App;
7 use Friendica\Content\ForumManager;
8 use Friendica\Core\Cache;
9 use Friendica\Core\Config;
10 use Friendica\Core\PConfig;
11 use Friendica\Core\System;
12 use Friendica\Core\Worker;
13 use Friendica\Database\DBM;
14 use Friendica\Object\Contact;
15
16 require_once 'include/bbcode.php';
17 require_once 'mod/proxy.php';
18
19 /**
20  *
21  * @brief Loads a profile into the page sidebar.
22  *
23  * The function requires a writeable copy of the main App structure, and the nickname
24  * of a registered local account.
25  *
26  * If the viewer is an authenticated remote viewer, the profile displayed is the
27  * one that has been configured for his/her viewing in the Contact manager.
28  * Passing a non-zero profile ID can also allow a preview of a selected profile
29  * by the owner.
30  *
31  * Profile information is placed in the App structure for later retrieval.
32  * Honours the owner's chosen theme for display.
33  *
34  * @attention Should only be run in the _init() functions of a module. That ensures that
35  *      the theme is chosen before the _init() function of a theme is run, which will usually
36  *      load a lot of theme-specific content
37  *
38  * @param object $a           App
39  * @param string $nickname    string
40  * @param int    $profile     int
41  * @param array  $profiledata array
42  */
43 function profile_load(App $a, $nickname, $profile = 0, $profiledata = array())
44 {
45         $user = q(
46                 "SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1",
47                 dbesc($nickname)
48         );
49
50         if (!$user && count($user) && !count($profiledata)) {
51                 logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
52                 notice(t('Requested account is not available.') . EOL);
53                 $a->error = 404;
54                 return;
55         }
56
57         $pdata = get_profiledata_by_nick($nickname, $user[0]['uid'], $profile);
58
59         if (empty($pdata) && empty($profiledata)) {
60                 logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
61                 notice(t('Requested profile is not available.') . EOL);
62                 $a->error = 404;
63                 return;
64         }
65
66         // fetch user tags if this isn't the default profile
67
68         if (!$pdata['is-default']) {
69                 $x = q(
70                         "SELECT `pub_keywords` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
71                         intval($pdata['profile_uid'])
72                 );
73                 if ($x && count($x))
74                         $pdata['pub_keywords'] = $x[0]['pub_keywords'];
75         }
76
77         $a->profile = $pdata;
78         $a->profile_uid = $pdata['profile_uid'];
79
80         $a->profile['mobile-theme'] = PConfig::get($a->profile['profile_uid'], 'system', 'mobile_theme');
81         $a->profile['network'] = NETWORK_DFRN;
82
83         $a->page['title'] = $a->profile['name'] . " @ " . $a->config['sitename'];
84
85         if (!$profiledata  && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
86                 $_SESSION['theme'] = $a->profile['theme'];
87         }
88
89         $_SESSION['mobile-theme'] = $a->profile['mobile-theme'];
90
91         /*
92          * load/reload current theme info
93          */
94
95         $a->set_template_engine(); // reset the template engine to the default in case the user's theme doesn't specify one
96
97         $theme_info_file = "view/theme/" . current_theme() . "/theme.php";
98         if (file_exists($theme_info_file)) {
99                 require_once $theme_info_file;
100         }
101
102         if (! (x($a->page, 'aside'))) {
103                 $a->page['aside'] = '';
104         }
105
106         if (local_user() && local_user() == $a->profile['uid'] && $profiledata) {
107                 $a->page['aside'] .= replace_macros(
108                         get_markup_template('profile_edlink.tpl'),
109                         array(
110                                 '$editprofile' => t('Edit profile'),
111                                 '$profid' => $a->profile['id']
112                         )
113                 );
114         }
115
116         $block = (((Config::get('system', 'block_public')) && (! local_user()) && (! remote_user())) ? true : false);
117
118         /**
119          * @todo
120          * By now, the contact block isn't shown, when a different profile is given
121          * But: When this profile was on the same server, then we could display the contacts
122          */
123         if ($profiledata) {
124                 $a->page['aside'] .= profile_sidebar($profiledata, true);
125         } else {
126                 $a->page['aside'] .= profile_sidebar($a->profile, $block);
127         }
128
129         /*if (! $block)
130          $a->page['aside'] .= contact_block();*/
131
132         return;
133 }
134
135
136 /**
137  * @brief Get all profil data of a local user
138  *
139  * If the viewer is an authenticated remote viewer, the profile displayed is the
140  * one that has been configured for his/her viewing in the Contact manager.
141  * Passing a non-zero profile ID can also allow a preview of a selected profile
142  * by the owner
143  *
144  * @param string $nickname nick
145  * @param int    $uid      uid
146  * @param int    $profile  ID of the profile
147  * @returns array
148  *      Includes all available profile data
149  */
150 function get_profiledata_by_nick($nickname, $uid = 0, $profile = 0)
151 {
152         if (remote_user() && count($_SESSION['remote'])) {
153                 foreach ($_SESSION['remote'] as $visitor) {
154                         if ($visitor['uid'] == $uid) {
155                                 $r = dba::select('contact', array('profile-id'), array('id' => $visitor['cid']), array('limit' => 1));
156                                 if (DBM::is_result($r)) {
157                                         $profile = $r['profile-id'];
158                                 }
159                                 break;
160                         }
161                 }
162         }
163
164         $r = null;
165
166         if ($profile) {
167                 $profile_int = intval($profile);
168                 $r = dba::fetch_first(
169                         "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` AS `contact_photo`,
170                                 `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
171                                 `profile`.`uid` AS `profile_uid`, `profile`.*,
172                                 `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
173                         FROM `profile`
174                         INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
175                         INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
176                         WHERE `user`.`nickname` = ? AND `profile`.`id` = ? LIMIT 1",
177                         $nickname,
178                         $profile_int
179                 );
180         }
181         if (!DBM::is_result($r)) {
182                 $r = dba::fetch_first(
183                         "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` as `contact_photo`,
184                                 `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
185                                 `profile`.`uid` AS `profile_uid`, `profile`.*,
186                                 `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
187                         FROM `profile`
188                         INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
189                         INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
190                         WHERE `user`.`nickname` = ? AND `profile`.`is-default` LIMIT 1",
191                         $nickname
192                 );
193         }
194
195         return $r;
196 }
197
198
199 /**
200  * @brief Formats a profile for display in the sidebar.
201  *
202  * It is very difficult to templatise the HTML completely
203  * because of all the conditional logic.
204  *
205  * @param array $profile
206  * @param int $block
207  *
208  * @return HTML string stuitable for sidebar inclusion
209  *
210  * @note Returns empty string if passed $profile is wrong type or not populated
211  *
212  * @hooks 'profile_sidebar_enter'
213  *      array $profile - profile data
214  * @hooks 'profile_sidebar'
215  *      array $arr
216  */
217 function profile_sidebar($profile, $block = 0)
218 {
219         $a = get_app();
220
221         $o = '';
222         $location = false;
223         $address = false;
224         // $pdesc = true;
225
226         // This function can also use contact information in $profile
227         $is_contact = x($profile, 'cid');
228
229         if ((! is_array($profile)) && (! count($profile))) {
230                 return $o;
231         }
232
233         $profile['picdate'] = urlencode($profile['picdate']);
234
235         if (($profile['network'] != "") && ($profile['network'] != NETWORK_DFRN)) {
236                 $profile['network_name'] = format_network_name($profile['network'], $profile['url']);
237         } else {
238                 $profile['network_name'] = "";
239         }
240
241         call_hooks('profile_sidebar_enter', $profile);
242
243
244         // don't show connect link to yourself
245         $connect = (($profile['uid'] != local_user()) ? t('Connect')  : false);
246
247         // don't show connect link to authenticated visitors either
248         if (remote_user() && count($_SESSION['remote'])) {
249                 foreach ($_SESSION['remote'] as $visitor) {
250                         if ($visitor['uid'] == $profile['uid']) {
251                                 $connect = false;
252                                 break;
253                         }
254                 }
255         }
256
257         // Is the local user already connected to that user?
258         if ($connect && local_user()) {
259                 if (isset($profile["url"])) {
260                         $profile_url = normalise_link($profile["url"]);
261                 } else {
262                         $profile_url = normalise_link(System::baseUrl()."/profile/".$profile["nickname"]);
263                 }
264
265                 if (dba::exists('contact', array('pending' => false, 'uid' => local_user(), 'nurl' => $profile_url))) {
266                         $connect = false;
267                 }
268         }
269
270         if ($connect && ($profile['network'] != NETWORK_DFRN) && !isset($profile['remoteconnect']))
271                 $connect = false;
272
273         $remoteconnect = null;
274         if (isset($profile['remoteconnect']))
275                 $remoteconnect = $profile['remoteconnect'];
276
277         if ($connect && ($profile['network'] == NETWORK_DFRN) && !isset($remoteconnect))
278                 $subscribe_feed = t("Atom feed");
279         else
280                 $subscribe_feed = false;
281
282         if (remote_user() || (get_my_url() && $profile['unkmail'] && ($profile['uid'] != local_user()))) {
283                 $wallmessage = t('Message');
284                 $wallmessage_link = "wallmessage/".$profile["nickname"];
285
286                 if (remote_user()) {
287                         $r = q(
288                                 "SELECT `url` FROM `contact` WHERE `uid` = %d AND `id` = '%s' AND `rel` = %d",
289                                 intval($profile['uid']),
290                                 intval(remote_user()),
291                                 intval(CONTACT_IS_FRIEND)
292                         );
293                 } else {
294                         $r = q(
295                                 "SELECT `url` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `rel` = %d",
296                                 intval($profile['uid']),
297                                 dbesc(normalise_link(get_my_url())),
298                                 intval(CONTACT_IS_FRIEND)
299                         );
300                 }
301                 if ($r) {
302                         $remote_url = $r[0]["url"];
303                         $message_path = preg_replace("=(.*)/profile/(.*)=ism", "$1/message/new/", $remote_url);
304                         $wallmessage_link = $message_path.base64_encode($profile["addr"]);
305                 }
306         } else {
307                 $wallmessage = false;
308                 $wallmessage_link = false;
309         }
310
311         // show edit profile to yourself
312         if (!$is_contact && $profile['uid'] == local_user() && feature_enabled(local_user(), 'multi_profiles')) {
313                 $profile['edit'] = array(System::baseUrl(). '/profiles', t('Profiles'),"", t('Manage/edit profiles'));
314                 $r = q(
315                         "SELECT * FROM `profile` WHERE `uid` = %d",
316                         local_user()
317                 );
318
319                 $profile['menu'] = array(
320                         'chg_photo' => t('Change profile photo'),
321                         'cr_new' => t('Create New Profile'),
322                         'entries' => array(),
323                 );
324
325                 if (DBM::is_result($r)) {
326                         foreach ($r as $rr) {
327                                 $profile['menu']['entries'][] = array(
328                                         'photo' => $rr['thumb'],
329                                         'id' => $rr['id'],
330                                         'alt' => t('Profile Image'),
331                                         'profile_name' => $rr['profile-name'],
332                                         'isdefault' => $rr['is-default'],
333                                         'visibile_to_everybody' =>  t('visible to everybody'),
334                                         'edit_visibility' => t('Edit visibility'),
335                                 );
336                         }
337                 }
338         }
339         if (!$is_contact && $profile['uid'] == local_user() && !feature_enabled(local_user(), 'multi_profiles')) {
340                 $profile['edit'] = array(System::baseUrl(). '/profiles/'.$profile['id'], t('Edit profile'),"", t('Edit profile'));
341                 $profile['menu'] = array(
342                         'chg_photo' => t('Change profile photo'),
343                         'cr_new' => null,
344                         'entries' => array(),
345                 );
346         }
347
348         // Fetch the account type
349         $account_type = Contact::getAccountType($profile);
350
351         if ((x($profile, 'address') == 1)
352                 || (x($profile, 'location') == 1)
353                 || (x($profile, 'locality') == 1)
354                 || (x($profile, 'region') == 1)
355                 || (x($profile, 'postal-code') == 1)
356                 || (x($profile, 'country-name') == 1)
357         ) {
358                 $location = t('Location:');
359         }
360
361         $gender = ((x($profile, 'gender') == 1) ? t('Gender:') : false);
362
363
364         $marital = ((x($profile, 'marital') == 1) ?  t('Status:') : false);
365
366         $homepage = ((x($profile, 'homepage') == 1) ?  t('Homepage:') : false);
367
368         $about = ((x($profile, 'about') == 1) ?  t('About:') : false);
369
370         $xmpp = ((x($profile, 'xmpp') == 1) ?  t('XMPP:') : false);
371
372         if (($profile['hidewall'] || $block) && (! local_user()) && (! remote_user())) {
373                 $location = $pdesc = $gender = $marital = $homepage = $about = false;
374         }
375
376         $firstname = ((strpos($profile['name'], ' '))
377                         ? trim(substr($profile['name'], 0, strpos($profile['name'], ' '))) : $profile['name']);
378         $lastname = (($firstname === $profile['name']) ? '' : trim(substr($profile['name'], strlen($firstname))));
379
380         if ($profile['guid'] != "") {
381                 $diaspora = array(
382                         'guid' => $profile['guid'],
383                         'podloc' => System::baseUrl(),
384                         'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false' ),
385                         'nickname' => $profile['nickname'],
386                         'fullname' => $profile['name'],
387                         'firstname' => $firstname,
388                         'lastname' => $lastname,
389                         'photo300' => $profile['contact_photo'],
390                         'photo100' => $profile['contact_thumb'],
391                         'photo50' => $profile['contact_micro'],
392                 );
393         } else {
394                 $diaspora = false;
395         }
396
397         if (!$block) {
398                 $contact_block = contact_block();
399
400                 if (is_array($a->profile) && !$a->profile['hide-friends']) {
401                         $r = q(
402                                 "SELECT `gcontact`.`updated` FROM `contact` INNER JOIN `gcontact` WHERE `gcontact`.`nurl` = `contact`.`nurl` AND `self` AND `uid` = %d LIMIT 1",
403                                 intval($a->profile['uid'])
404                         );
405                         if (DBM::is_result($r)) {
406                                 $updated =  date("c", strtotime($r[0]['updated']));
407                         }
408
409                         $r = q(
410                                 "SELECT COUNT(*) AS `total` FROM `contact`
411                                 WHERE `uid` = %d
412                                         AND NOT `self` AND NOT `blocked` AND NOT `pending`
413                                         AND NOT `hidden` AND NOT `archive`
414                                         AND `network` IN ('%s', '%s', '%s', '')",
415                                 intval($profile['uid']),
416                                 dbesc(NETWORK_DFRN),
417                                 dbesc(NETWORK_DIASPORA),
418                                 dbesc(NETWORK_OSTATUS)
419                         );
420                         if (DBM::is_result($r)) {
421                                 $contacts = intval($r[0]['total']);
422                         }
423                 }
424         }
425
426         $p = array();
427         foreach ($profile as $k => $v) {
428                 $k = str_replace('-', '_', $k);
429                 $p[$k] = $v;
430         }
431
432         if (isset($p["about"])) {
433                 $p["about"] = bbcode($p["about"]);
434         }
435
436         if (isset($p["address"])) {
437                 $p["address"] = bbcode($p["address"]);
438         } else {
439                 $p["address"] = bbcode($p["location"]);
440         }
441
442         if (isset($p["photo"])) {
443                 $p["photo"] = proxy_url($p["photo"], false, PROXY_SIZE_SMALL);
444         }
445
446         $tpl = get_markup_template('profile_vcard.tpl');
447         $o .= replace_macros(
448                 $tpl,
449                 array(
450                 '$profile' => $p,
451                 '$xmpp' => $xmpp,
452                 '$connect'  => $connect,
453                 '$remoteconnect'  => $remoteconnect,
454                 '$subscribe_feed' => $subscribe_feed,
455                 '$wallmessage' => $wallmessage,
456                 '$wallmessage_link' => $wallmessage_link,
457                 '$account_type' => $account_type,
458                 '$location' => $location,
459                 '$gender'   => $gender,
460                 // '$pdesc'     => $pdesc,
461                 '$marital'  => $marital,
462                 '$homepage' => $homepage,
463                 '$about' => $about,
464                 '$network' =>  t('Network:'),
465                 '$contacts' => $contacts,
466                 '$updated' => $updated,
467                 '$diaspora' => $diaspora,
468                 '$contact_block' => $contact_block,
469                 )
470         );
471
472         $arr = array('profile' => &$profile, 'entry' => &$o);
473
474         call_hooks('profile_sidebar', $arr);
475
476         return $o;
477 }
478
479
480 function get_birthdays()
481 {
482         $a = get_app();
483         $o = '';
484
485         if (! local_user() || $a->is_mobile || $a->is_tablet) {
486                 return $o;
487         }
488
489         /*
490          * $mobile_detect = new Mobile_Detect();
491          * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
492          *              if ($is_mobile)
493          *                      return $o;
494          */
495
496         $bd_format = t('g A l F d'); // 8 AM Friday January 18
497         $bd_short = t('F d');
498
499         $cachekey = "get_birthdays:".local_user();
500         $r = Cache::get($cachekey);
501         if (is_null($r)) {
502                 $s = dba::p(
503                         "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
504                         INNER JOIN `contact` ON `contact`.`id` = `event`.`cid`
505                         WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
506                         ORDER BY `start` ASC ",
507                         local_user(),
508                         datetime_convert('UTC', 'UTC', 'now + 6 days'),
509                         datetime_convert('UTC', 'UTC', 'now')
510                 );
511                 if (DBM::is_result($s)) {
512                         $r = dba::inArray($s);
513                         Cache::set($cachekey, $r, CACHE_HOUR);
514                 }
515         }
516         if (DBM::is_result($r)) {
517                 $total = 0;
518                 $now = strtotime('now');
519                 $cids = array();
520
521                 $istoday = false;
522                 foreach ($r as $rr) {
523                         if (strlen($rr['name'])) {
524                                 $total ++;
525                         }
526                         if ((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) {
527                                 $istoday = true;
528                         }
529                 }
530                 $classtoday = $istoday ? ' birthday-today ' : '';
531                 if ($total) {
532                         foreach ($r as &$rr) {
533                                 if (! strlen($rr['name'])) {
534                                         continue;
535                                 }
536
537                                 // avoid duplicates
538
539                                 if (in_array($rr['cid'], $cids)) {
540                                         continue;
541                                 }
542                                 $cids[] = $rr['cid'];
543
544                                 $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
545                                 $sparkle = '';
546                                 $url = $rr['url'];
547                                 if ($rr['network'] === NETWORK_DFRN) {
548                                         $sparkle = " sparkle";
549                                         $url = System::baseUrl() . '/redir/'  . $rr['cid'];
550                                 }
551
552                                 $rr['link'] = $url;
553                                 $rr['title'] = $rr['name'];
554                                 $rr['date'] = day_translate(datetime_convert('UTC', $a->timezone, $rr['start'], $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ?  ' ' . t('[today]') : '');
555                                 $rr['startime'] = null;
556                                 $rr['today'] = $today;
557                         }
558                 }
559         }
560         $tpl = get_markup_template("birthdays_reminder.tpl");
561         return replace_macros(
562                 $tpl,
563                 array(
564                 '$baseurl' => System::baseUrl(),
565                 '$classtoday' => $classtoday,
566                 '$count' => $total,
567                 '$event_reminders' => t('Birthday Reminders'),
568                 '$event_title' => t('Birthdays this week:'),
569                 '$events' => $r,
570                 '$lbr' => '{',  // raw brackets mess up if/endif macro processing
571                 '$rbr' => '}'
572                 )
573         );
574 }
575
576
577 function get_events()
578 {
579         require_once 'include/bbcode.php';
580
581         $a = get_app();
582
583         if (! local_user() || $a->is_mobile || $a->is_tablet) {
584                 return $o;
585         }
586
587         /*
588          *      $mobile_detect = new Mobile_Detect();
589          *              $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
590          *              if ($is_mobile)
591          *                      return $o;
592          */
593
594         $bd_format = t('g A l F d'); // 8 AM Friday January 18
595         $bd_short = t('F d');
596
597         $s = dba::p(
598                 "SELECT `event`.* FROM `event`
599                 WHERE `event`.`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?
600                 ORDER BY `start` ASC ",
601                 local_user(),
602                 datetime_convert('UTC', 'UTC', 'now + 7 days'),
603                 datetime_convert('UTC', 'UTC', 'now - 1 days')
604         );
605
606         $r = array();
607
608         if (DBM::is_result($s)) {
609                 $now = strtotime('now');
610                 $istoday = false;
611
612                 while ($rr = dba::fetch($s)) {
613                         if (strlen($rr['name'])) {
614                                 $total ++;
615                         }
616
617                         $strt = datetime_convert('UTC', $rr['convert'] ? $a->timezone : 'UTC', $rr['start'], 'Y-m-d');
618                         if ($strt === datetime_convert('UTC', $a->timezone, 'now', 'Y-m-d')) {
619                                 $istoday = true;
620                         }
621
622                         $title = strip_tags(html_entity_decode(bbcode($rr['summary']), ENT_QUOTES, 'UTF-8'));
623
624                         if (strlen($title) > 35) {
625                                 $title = substr($title, 0, 32) . '... ';
626                         }
627
628                         $description = substr(strip_tags(bbcode($rr['desc'])), 0, 32) . '... ';
629                         if (! $description) {
630                                 $description = t('[No description]');
631                         }
632
633                         $strt = datetime_convert('UTC', $rr['convert'] ? $a->timezone : 'UTC', $rr['start']);
634
635                         if (substr($strt, 0, 10) < datetime_convert('UTC', $a->timezone, 'now', 'Y-m-d')) {
636                                 continue;
637                         }
638
639                         $today = ((substr($strt, 0, 10) === datetime_convert('UTC', $a->timezone, 'now', 'Y-m-d')) ? true : false);
640
641                         $rr['title'] = $title;
642                         $rr['description'] = $desciption;
643                         $rr['date'] = day_translate(datetime_convert('UTC', $rr['adjust'] ? $a->timezone : 'UTC', $rr['start'], $bd_format)) . (($today) ?  ' ' . t('[today]') : '');
644                         $rr['startime'] = $strt;
645                         $rr['today'] = $today;
646
647                         $r[] = $rr;
648                 }
649                 dba::close($s);
650                 $classtoday = (($istoday) ? 'event-today' : '');
651         }
652         $tpl = get_markup_template("events_reminder.tpl");
653         return replace_macros(
654                 $tpl,
655                 array(
656                 '$baseurl' => System::baseUrl(),
657                 '$classtoday' => $classtoday,
658                 '$count' => count($r),
659                 '$event_reminders' => t('Event Reminders'),
660                 '$event_title' => t('Events this week:'),
661                 '$events' => $r,
662                 )
663         );
664 }
665
666 function advanced_profile(App $a)
667 {
668         $o = '';
669         $uid = $a->profile['uid'];
670
671         $o .= replace_macros(
672                 get_markup_template('section_title.tpl'),
673                 array(
674                 '$title' => t('Profile')
675                 )
676         );
677
678         if ($a->profile['name']) {
679                 $tpl = get_markup_template('profile_advanced.tpl');
680
681                 $profile = array();
682
683                 $profile['fullname'] = array( t('Full Name:'), $a->profile['name'] ) ;
684
685                 if ($a->profile['gender']) {
686                         $profile['gender'] = array( t('Gender:'),  $a->profile['gender'] );
687                 }
688
689                 if (($a->profile['dob']) && ($a->profile['dob'] > '0001-01-01')) {
690                         $year_bd_format = t('j F, Y');
691                         $short_bd_format = t('j F');
692
693
694                         $val = ((intval($a->profile['dob']))
695                                 ? day_translate(datetime_convert('UTC', 'UTC', $a->profile['dob'] . ' 00:00 +00:00', $year_bd_format))
696                                 : day_translate(datetime_convert('UTC', 'UTC', '2001-' . substr($a->profile['dob'], 5) . ' 00:00 +00:00', $short_bd_format)));
697
698                         $profile['birthday'] = array( t('Birthday:'), $val);
699                 }
700                 if (!empty($a->profile['dob'])
701                         && $a->profile['dob'] > '0001-01-01'
702                         && $age = age($a->profile['dob'], $a->profile['timezone'], '')
703                 ) {
704                         $profile['age'] = array( t('Age:'), $age );
705                 }
706
707                 if ($a->profile['marital']) {
708                         $profile['marital'] = array( t('Status:'), $a->profile['marital']);
709                 }
710
711                 /// @TODO Maybe use x() here, plus below?
712                 if ($a->profile['with']) {
713                         $profile['marital']['with'] = $a->profile['with'];
714                 }
715
716                 if (strlen($a->profile['howlong']) && $a->profile['howlong'] >= NULL_DATE) {
717                         $profile['howlong'] = relative_date($a->profile['howlong'], t('for %1$d %2$s'));
718                 }
719
720                 if ($a->profile['sexual']) {
721                         $profile['sexual'] = array( t('Sexual Preference:'), $a->profile['sexual'] );
722                 }
723
724                 if ($a->profile['homepage']) {
725                         $profile['homepage'] = array( t('Homepage:'), linkify($a->profile['homepage']) );
726                 }
727
728                 if ($a->profile['hometown']) {
729                         $profile['hometown'] = array( t('Hometown:'), linkify($a->profile['hometown']) );
730                 }
731
732                 if ($a->profile['pub_keywords']) {
733                         $profile['pub_keywords'] = array( t('Tags:'), $a->profile['pub_keywords']);
734                 }
735
736                 if ($a->profile['politic']) {
737                         $profile['politic'] = array( t('Political Views:'), $a->profile['politic']);
738                 }
739
740                 if ($a->profile['religion']) {
741                         $profile['religion'] = array( t('Religion:'), $a->profile['religion']);
742                 }
743
744                 if ($txt = prepare_text($a->profile['about'])) {
745                         $profile['about'] = array( t('About:'), $txt );
746                 }
747
748                 if ($txt = prepare_text($a->profile['interest'])) {
749                         $profile['interest'] = array( t('Hobbies/Interests:'), $txt);
750                 }
751
752                 if ($txt = prepare_text($a->profile['likes'])) {
753                         $profile['likes'] = array( t('Likes:'), $txt);
754                 }
755
756                 if ($txt = prepare_text($a->profile['dislikes'])) {
757                         $profile['dislikes'] = array( t('Dislikes:'), $txt);
758                 }
759
760                 if ($txt = prepare_text($a->profile['contact'])) {
761                         $profile['contact'] = array( t('Contact information and Social Networks:'), $txt);
762                 }
763
764                 if ($txt = prepare_text($a->profile['music'])) {
765                         $profile['music'] = array( t('Musical interests:'), $txt);
766                 }
767
768                 if ($txt = prepare_text($a->profile['book'])) {
769                         $profile['book'] = array( t('Books, literature:'), $txt);
770                 }
771
772                 if ($txt = prepare_text($a->profile['tv'])) {
773                         $profile['tv'] = array( t('Television:'), $txt);
774                 }
775
776                 if ($txt = prepare_text($a->profile['film'])) {
777                         $profile['film'] = array( t('Film/dance/culture/entertainment:'), $txt);
778                 }
779
780                 if ($txt = prepare_text($a->profile['romance'])) {
781                         $profile['romance'] = array( t('Love/Romance:'), $txt);
782                 }
783
784                 if ($txt = prepare_text($a->profile['work'])) {
785                         $profile['work'] = array( t('Work/employment:'), $txt);
786                 }
787
788                 if ($txt = prepare_text($a->profile['education'])) {
789                         $profile['education'] = array( t('School/education:'), $txt );
790                 }
791
792                 //show subcribed forum if it is enabled in the usersettings
793                 if (feature_enabled($uid, 'forumlist_profile')) {
794                         $profile['forumlist'] = array( t('Forums:'), ForumManager::profileAdvanced($uid));
795                 }
796
797                 if ($a->profile['uid'] == local_user()) {
798                         $profile['edit'] = array(System::baseUrl(). '/profiles/'.$a->profile['id'], t('Edit profile'),"", t('Edit profile'));
799                 }
800
801                 return replace_macros(
802                         $tpl,
803                         array(
804                         '$title' => t('Profile'),
805                         '$basic' => t('Basic'),
806                         '$advanced' => t('Advanced'),
807                         '$profile' => $profile
808                         )
809                 );
810         }
811
812         return '';
813 }
814
815 function profile_tabs($a, $is_owner = false, $nickname = null)
816 {
817         //echo "<pre>"; var_dump($a->user); killme();
818
819         if (is_null($nickname)) {
820                 $nickname  = $a->user['nickname'];
821         }
822
823         if (x($_GET, 'tab')) {
824                 $tab = notags(trim($_GET['tab']));
825         }
826
827         $url = System::baseUrl() . '/profile/' . $nickname;
828
829         $tabs = array(
830                 array(
831                         'label'=>t('Status'),
832                         'url' => $url,
833                         'sel' => ((!isset($tab) && $a->argv[0]=='profile') ? 'active' : ''),
834                         'title' => t('Status Messages and Posts'),
835                         'id' => 'status-tab',
836                         'accesskey' => 'm',
837                 ),
838                 array(
839                         'label' => t('Profile'),
840                         'url'   => $url.'/?tab=profile',
841                         'sel'   => ((isset($tab) && $tab=='profile') ? 'active' : ''),
842                         'title' => t('Profile Details'),
843                         'id' => 'profile-tab',
844                         'accesskey' => 'r',
845                 ),
846                 array(
847                         'label' => t('Photos'),
848                         'url'   => System::baseUrl() . '/photos/' . $nickname,
849                         'sel'   => ((!isset($tab) && $a->argv[0]=='photos') ? 'active' : ''),
850                         'title' => t('Photo Albums'),
851                         'id' => 'photo-tab',
852                         'accesskey' => 'h',
853                 ),
854                 array(
855                         'label' => t('Videos'),
856                         'url'   => System::baseUrl() . '/videos/' . $nickname,
857                         'sel'   => ((!isset($tab) && $a->argv[0]=='videos') ? 'active' : ''),
858                         'title' => t('Videos'),
859                         'id' => 'video-tab',
860                         'accesskey' => 'v',
861                 ),
862         );
863
864         // the calendar link for the full featured events calendar
865         if ($is_owner && $a->theme_events_in_profile) {
866                         $tabs[] = array(
867                                 'label' => t('Events'),
868                                 'url'   => System::baseUrl() . '/events',
869                                 'sel'   =>((!isset($tab) && $a->argv[0]=='events') ? 'active' : ''),
870                                 'title' => t('Events and Calendar'),
871                                 'id' => 'events-tab',
872                                 'accesskey' => 'e',
873                         );
874                 // if the user is not the owner of the calendar we only show a calendar
875                 // with the public events of the calendar owner
876         } elseif (! $is_owner) {
877                 $tabs[] = array(
878                                 'label' => t('Events'),
879                                 'url'   => System::baseUrl() . '/cal/' . $nickname,
880                                 'sel'   =>((!isset($tab) && $a->argv[0]=='cal') ? 'active' : ''),
881                                 'title' => t('Events and Calendar'),
882                                 'id' => 'events-tab',
883                                 'accesskey' => 'e',
884                         );
885         }
886
887         if ($is_owner) {
888                 $tabs[] = array(
889                         'label' => t('Personal Notes'),
890                         'url'   => System::baseUrl() . '/notes',
891                         'sel'   =>((!isset($tab) && $a->argv[0]=='notes') ? 'active' : ''),
892                         'title' => t('Only You Can See This'),
893                         'id' => 'notes-tab',
894                         'accesskey' => 't',
895                 );
896         }
897
898         if ((! $is_owner) && ((count($a->profile)) || (! $a->profile['hide-friends']))) {
899                 $tabs[] = array(
900                         'label' => t('Contacts'),
901                         'url'   => System::baseUrl() . '/viewcontacts/' . $nickname,
902                         'sel'   => ((!isset($tab) && $a->argv[0]=='viewcontacts') ? 'active' : ''),
903                         'title' => t('Contacts'),
904                         'id' => 'viewcontacts-tab',
905                         'accesskey' => 'k',
906                 );
907         }
908
909         $arr = array('is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => (($tab) ? $tab : false), 'tabs' => $tabs);
910         call_hooks('profile_tabs', $arr);
911
912         $tpl = get_markup_template('common_tabs.tpl');
913
914         return replace_macros($tpl, array('$tabs' => $arr['tabs']));
915 }
916
917 function get_my_url()
918 {
919         if (x($_SESSION, 'my_url')) {
920                 return $_SESSION['my_url'];
921         }
922         return false;
923 }
924
925 function zrl_init(App $a)
926 {
927         $tmp_str = get_my_url();
928         if (validate_url($tmp_str)) {
929                 // Is it a DDoS attempt?
930                 // The check fetches the cached value from gprobe to reduce the load for this system
931                 $urlparts = parse_url($tmp_str);
932
933                 $result = Cache::get("gprobe:" . $urlparts["host"]);
934                 if ((!is_null($result)) && (in_array($result["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
935                         logger("DDoS attempt detected for " . $urlparts["host"] . " by " . $_SERVER["REMOTE_ADDR"] . ". server data: " . print_r($_SERVER, true), LOGGER_DEBUG);
936                         return;
937                 }
938
939                 Worker::add(PRIORITY_LOW, 'GProbe', $tmp_str);
940                 $arr = array('zrl' => $tmp_str, 'url' => $a->cmd);
941                 call_hooks('zrl_init', $arr);
942         }
943 }
944
945 function zrl($s, $force = false)
946 {
947         if (! strlen($s)) {
948                 return $s;
949         }
950         if ((! strpos($s, '/profile/')) && (! $force)) {
951                 return $s;
952         }
953         if ($force && substr($s, -1, 1) !== '/') {
954                 $s = $s . '/';
955         }
956         $achar = strpos($s, '?') ? '&' : '?';
957         $mine = get_my_url();
958         if ($mine && ! link_compare($mine, $s)) {
959                 return $s . $achar . 'zrl=' . urlencode($mine);
960         }
961         return $s;
962 }
963
964 /**
965  * @brief Get the user ID of the page owner
966  *
967  * Used from within PCSS themes to set theme parameters. If there's a
968  * puid request variable, that is the "page owner" and normally their theme
969  * settings take precedence; unless a local user sets the "always_my_theme"
970  * system pconfig, which means they don't want to see anybody else's theme
971  * settings except their own while on this site.
972  *
973  * @return int user ID
974  *
975  * @note Returns local_user instead of user ID if "always_my_theme"
976  *      is set to true
977  */
978 function get_theme_uid()
979 {
980         $uid = ((!empty($_REQUEST['puid'])) ? intval($_REQUEST['puid']) : 0);
981         if ((local_user()) && ((PConfig::get(local_user(), 'system', 'always_my_theme')) || (! $uid))) {
982                 return local_user();
983         }
984
985         return $uid;
986 }