]> git.mxchange.org Git - friendica.git/blob - include/identity.php
Add Contact Object
[friendica.git] / include / identity.php
1 <?php
2 /**
3  * @file include/identity.php
4  */
5
6 use Friendica\App;
7 use Friendica\Core\Cache;
8 use Friendica\Core\Config;
9 use Friendica\Core\PConfig;
10 use Friendica\Core\System;
11 use Friendica\Core\Worker;
12 use Friendica\Database\DBM;
13 use Friendica\Object\Contact;
14
15 require_once 'include/ForumManager.php';
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`, `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`, `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 = account_type($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         if ($a->theme['template_engine'] === 'internal') {
447                 $location = template_escape($location);
448         }
449
450         $tpl = get_markup_template('profile_vcard.tpl');
451         $o .= replace_macros(
452                 $tpl,
453                 array(
454                 '$profile' => $p,
455                 '$xmpp' => $xmpp,
456                 '$connect'  => $connect,
457                 '$remoteconnect'  => $remoteconnect,
458                 '$subscribe_feed' => $subscribe_feed,
459                 '$wallmessage' => $wallmessage,
460                 '$wallmessage_link' => $wallmessage_link,
461                 '$account_type' => $account_type,
462                 '$location' => $location,
463                 '$gender'   => $gender,
464                 // '$pdesc'     => $pdesc,
465                 '$marital'  => $marital,
466                 '$homepage' => $homepage,
467                 '$about' => $about,
468                 '$network' =>  t('Network:'),
469                 '$contacts' => $contacts,
470                 '$updated' => $updated,
471                 '$diaspora' => $diaspora,
472                 '$contact_block' => $contact_block,
473                 )
474         );
475
476         $arr = array('profile' => &$profile, 'entry' => &$o);
477
478         call_hooks('profile_sidebar', $arr);
479
480         return $o;
481 }
482
483
484 function get_birthdays()
485 {
486         $a = get_app();
487         $o = '';
488
489         if (! local_user() || $a->is_mobile || $a->is_tablet) {
490                 return $o;
491         }
492
493         /*
494          * $mobile_detect = new Mobile_Detect();
495          * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
496          *              if ($is_mobile)
497          *                      return $o;
498          */
499
500         $bd_format = t('g A l F d'); // 8 AM Friday January 18
501         $bd_short = t('F d');
502
503         $cachekey = "get_birthdays:".local_user();
504         $r = Cache::get($cachekey);
505         if (is_null($r)) {
506                 $s = dba::p(
507                         "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
508                         INNER JOIN `contact` ON `contact`.`id` = `event`.`cid`
509                         WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
510                         ORDER BY `start` ASC ",
511                         local_user(),
512                         datetime_convert('UTC', 'UTC', 'now + 6 days'),
513                         datetime_convert('UTC', 'UTC', 'now')
514                 );
515                 if (DBM::is_result($s)) {
516                         $r = dba::inArray($s);
517                         Cache::set($cachekey, $r, CACHE_HOUR);
518                 }
519         }
520         if (DBM::is_result($r)) {
521                 $total = 0;
522                 $now = strtotime('now');
523                 $cids = array();
524
525                 $istoday = false;
526                 foreach ($r as $rr) {
527                         if (strlen($rr['name'])) {
528                                 $total ++;
529                         }
530                         if ((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) {
531                                 $istoday = true;
532                         }
533                 }
534                 $classtoday = $istoday ? ' birthday-today ' : '';
535                 if ($total) {
536                         foreach ($r as &$rr) {
537                                 if (! strlen($rr['name'])) {
538                                         continue;
539                                 }
540
541                                 // avoid duplicates
542
543                                 if (in_array($rr['cid'], $cids)) {
544                                         continue;
545                                 }
546                                 $cids[] = $rr['cid'];
547
548                                 $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
549                                 $sparkle = '';
550                                 $url = $rr['url'];
551                                 if ($rr['network'] === NETWORK_DFRN) {
552                                         $sparkle = " sparkle";
553                                         $url = System::baseUrl() . '/redir/'  . $rr['cid'];
554                                 }
555
556                                 $rr['link'] = $url;
557                                 $rr['title'] = $rr['name'];
558                                 $rr['date'] = day_translate(datetime_convert('UTC', $a->timezone, $rr['start'], $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ?  ' ' . t('[today]') : '');
559                                 $rr['startime'] = null;
560                                 $rr['today'] = $today;
561                         }
562                 }
563         }
564         $tpl = get_markup_template("birthdays_reminder.tpl");
565         return replace_macros(
566                 $tpl,
567                 array(
568                 '$baseurl' => System::baseUrl(),
569                 '$classtoday' => $classtoday,
570                 '$count' => $total,
571                 '$event_reminders' => t('Birthday Reminders'),
572                 '$event_title' => t('Birthdays this week:'),
573                 '$events' => $r,
574                 '$lbr' => '{',  // raw brackets mess up if/endif macro processing
575                 '$rbr' => '}'
576                 )
577         );
578 }
579
580
581 function get_events()
582 {
583         require_once 'include/bbcode.php';
584
585         $a = get_app();
586
587         if (! local_user() || $a->is_mobile || $a->is_tablet) {
588                 return $o;
589         }
590
591         /*
592          *      $mobile_detect = new Mobile_Detect();
593          *              $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
594          *              if ($is_mobile)
595          *                      return $o;
596          */
597
598         $bd_format = t('g A l F d'); // 8 AM Friday January 18
599         $bd_short = t('F d');
600
601         $s = dba::p(
602                 "SELECT `event`.* FROM `event`
603                 WHERE `event`.`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?
604                 ORDER BY `start` ASC ",
605                 local_user(),
606                 datetime_convert('UTC', 'UTC', 'now + 7 days'),
607                 datetime_convert('UTC', 'UTC', 'now - 1 days')
608         );
609
610         $r = array();
611
612         if (DBM::is_result($s)) {
613                 $now = strtotime('now');
614                 $istoday = false;
615
616                 while ($rr = dba::fetch($s)) {
617                         if (strlen($rr['name'])) {
618                                 $total ++;
619                         }
620
621                         $strt = datetime_convert('UTC', $rr['convert'] ? $a->timezone : 'UTC', $rr['start'], 'Y-m-d');
622                         if ($strt === datetime_convert('UTC', $a->timezone, 'now', 'Y-m-d')) {
623                                 $istoday = true;
624                         }
625
626                         $title = strip_tags(html_entity_decode(bbcode($rr['summary']), ENT_QUOTES, 'UTF-8'));
627
628                         if (strlen($title) > 35) {
629                                 $title = substr($title, 0, 32) . '... ';
630                         }
631
632                         $description = substr(strip_tags(bbcode($rr['desc'])), 0, 32) . '... ';
633                         if (! $description) {
634                                 $description = t('[No description]');
635                         }
636
637                         $strt = datetime_convert('UTC', $rr['convert'] ? $a->timezone : 'UTC', $rr['start']);
638
639                         if (substr($strt, 0, 10) < datetime_convert('UTC', $a->timezone, 'now', 'Y-m-d')) {
640                                 continue;
641                         }
642
643                         $today = ((substr($strt, 0, 10) === datetime_convert('UTC', $a->timezone, 'now', 'Y-m-d')) ? true : false);
644
645                         $rr['title'] = $title;
646                         $rr['description'] = $desciption;
647                         $rr['date'] = day_translate(datetime_convert('UTC', $rr['adjust'] ? $a->timezone : 'UTC', $rr['start'], $bd_format)) . (($today) ?  ' ' . t('[today]') : '');
648                         $rr['startime'] = $strt;
649                         $rr['today'] = $today;
650
651                         $r[] = $rr;
652                 }
653                 dba::close($s);
654                 $classtoday = (($istoday) ? 'event-today' : '');
655         }
656         $tpl = get_markup_template("events_reminder.tpl");
657         return replace_macros(
658                 $tpl,
659                 array(
660                 '$baseurl' => System::baseUrl(),
661                 '$classtoday' => $classtoday,
662                 '$count' => count($r),
663                 '$event_reminders' => t('Event Reminders'),
664                 '$event_title' => t('Events this week:'),
665                 '$events' => $r,
666                 )
667         );
668 }
669
670 function advanced_profile(App $a)
671 {
672         $o = '';
673         $uid = $a->profile['uid'];
674
675         $o .= replace_macros(
676                 get_markup_template('section_title.tpl'),
677                 array(
678                 '$title' => t('Profile')
679                 )
680         );
681
682         if ($a->profile['name']) {
683                 $tpl = get_markup_template('profile_advanced.tpl');
684
685                 $profile = array();
686
687                 $profile['fullname'] = array( t('Full Name:'), $a->profile['name'] ) ;
688
689                 if ($a->profile['gender']) {
690                         $profile['gender'] = array( t('Gender:'),  $a->profile['gender'] );
691                 }
692
693                 if (($a->profile['dob']) && ($a->profile['dob'] > '0001-01-01')) {
694                         $year_bd_format = t('j F, Y');
695                         $short_bd_format = t('j F');
696
697
698                         $val = ((intval($a->profile['dob']))
699                                 ? day_translate(datetime_convert('UTC', 'UTC', $a->profile['dob'] . ' 00:00 +00:00', $year_bd_format))
700                                 : day_translate(datetime_convert('UTC', 'UTC', '2001-' . substr($a->profile['dob'], 5) . ' 00:00 +00:00', $short_bd_format)));
701
702                         $profile['birthday'] = array( t('Birthday:'), $val);
703                 }
704                 if (!empty($a->profile['dob'])
705                         && $a->profile['dob'] > '0001-01-01'
706                         && $age = age($a->profile['dob'], $a->profile['timezone'], '')
707                 ) {
708                         $profile['age'] = array( t('Age:'), $age );
709                 }
710
711                 if ($a->profile['marital']) {
712                         $profile['marital'] = array( t('Status:'), $a->profile['marital']);
713                 }
714
715                 /// @TODO Maybe use x() here, plus below?
716                 if ($a->profile['with']) {
717                         $profile['marital']['with'] = $a->profile['with'];
718                 }
719
720                 if (strlen($a->profile['howlong']) && $a->profile['howlong'] >= NULL_DATE) {
721                         $profile['howlong'] = relative_date($a->profile['howlong'], t('for %1$d %2$s'));
722                 }
723
724                 if ($a->profile['sexual']) {
725                         $profile['sexual'] = array( t('Sexual Preference:'), $a->profile['sexual'] );
726                 }
727
728                 if ($a->profile['homepage']) {
729                         $profile['homepage'] = array( t('Homepage:'), linkify($a->profile['homepage']) );
730                 }
731
732                 if ($a->profile['hometown']) {
733                         $profile['hometown'] = array( t('Hometown:'), linkify($a->profile['hometown']) );
734                 }
735
736                 if ($a->profile['pub_keywords']) {
737                         $profile['pub_keywords'] = array( t('Tags:'), $a->profile['pub_keywords']);
738                 }
739
740                 if ($a->profile['politic']) {
741                         $profile['politic'] = array( t('Political Views:'), $a->profile['politic']);
742                 }
743
744                 if ($a->profile['religion']) {
745                         $profile['religion'] = array( t('Religion:'), $a->profile['religion']);
746                 }
747
748                 if ($txt = prepare_text($a->profile['about'])) {
749                         $profile['about'] = array( t('About:'), $txt );
750                 }
751
752                 if ($txt = prepare_text($a->profile['interest'])) {
753                         $profile['interest'] = array( t('Hobbies/Interests:'), $txt);
754                 }
755
756                 if ($txt = prepare_text($a->profile['likes'])) {
757                         $profile['likes'] = array( t('Likes:'), $txt);
758                 }
759
760                 if ($txt = prepare_text($a->profile['dislikes'])) {
761                         $profile['dislikes'] = array( t('Dislikes:'), $txt);
762                 }
763
764                 if ($txt = prepare_text($a->profile['contact'])) {
765                         $profile['contact'] = array( t('Contact information and Social Networks:'), $txt);
766                 }
767
768                 if ($txt = prepare_text($a->profile['music'])) {
769                         $profile['music'] = array( t('Musical interests:'), $txt);
770                 }
771
772                 if ($txt = prepare_text($a->profile['book'])) {
773                         $profile['book'] = array( t('Books, literature:'), $txt);
774                 }
775
776                 if ($txt = prepare_text($a->profile['tv'])) {
777                         $profile['tv'] = array( t('Television:'), $txt);
778                 }
779
780                 if ($txt = prepare_text($a->profile['film'])) {
781                         $profile['film'] = array( t('Film/dance/culture/entertainment:'), $txt);
782                 }
783
784                 if ($txt = prepare_text($a->profile['romance'])) {
785                         $profile['romance'] = array( t('Love/Romance:'), $txt);
786                 }
787
788                 if ($txt = prepare_text($a->profile['work'])) {
789                         $profile['work'] = array( t('Work/employment:'), $txt);
790                 }
791
792                 if ($txt = prepare_text($a->profile['education'])) {
793                         $profile['education'] = array( t('School/education:'), $txt );
794                 }
795
796                 //show subcribed forum if it is enabled in the usersettings
797                 if (feature_enabled($uid, 'forumlist_profile')) {
798                         $profile['forumlist'] = array( t('Forums:'), ForumManager::profile_advanced($uid));
799                 }
800
801                 if ($a->profile['uid'] == local_user()) {
802                         $profile['edit'] = array(System::baseUrl(). '/profiles/'.$a->profile['id'], t('Edit profile'),"", t('Edit profile'));
803                 }
804
805                 return replace_macros(
806                         $tpl,
807                         array(
808                         '$title' => t('Profile'),
809                         '$basic' => t('Basic'),
810                         '$advanced' => t('Advanced'),
811                         '$profile' => $profile
812                         )
813                 );
814         }
815
816         return '';
817 }
818
819 function profile_tabs($a, $is_owner = false, $nickname = null)
820 {
821         //echo "<pre>"; var_dump($a->user); killme();
822
823         if (is_null($nickname)) {
824                 $nickname  = $a->user['nickname'];
825         }
826
827         if (x($_GET, 'tab')) {
828                 $tab = notags(trim($_GET['tab']));
829         }
830
831         $url = System::baseUrl() . '/profile/' . $nickname;
832
833         $tabs = array(
834                 array(
835                         'label'=>t('Status'),
836                         'url' => $url,
837                         'sel' => ((!isset($tab) && $a->argv[0]=='profile') ? 'active' : ''),
838                         'title' => t('Status Messages and Posts'),
839                         'id' => 'status-tab',
840                         'accesskey' => 'm',
841                 ),
842                 array(
843                         'label' => t('Profile'),
844                         'url'   => $url.'/?tab=profile',
845                         'sel'   => ((isset($tab) && $tab=='profile') ? 'active' : ''),
846                         'title' => t('Profile Details'),
847                         'id' => 'profile-tab',
848                         'accesskey' => 'r',
849                 ),
850                 array(
851                         'label' => t('Photos'),
852                         'url'   => System::baseUrl() . '/photos/' . $nickname,
853                         'sel'   => ((!isset($tab) && $a->argv[0]=='photos') ? 'active' : ''),
854                         'title' => t('Photo Albums'),
855                         'id' => 'photo-tab',
856                         'accesskey' => 'h',
857                 ),
858                 array(
859                         'label' => t('Videos'),
860                         'url'   => System::baseUrl() . '/videos/' . $nickname,
861                         'sel'   => ((!isset($tab) && $a->argv[0]=='videos') ? 'active' : ''),
862                         'title' => t('Videos'),
863                         'id' => 'video-tab',
864                         'accesskey' => 'v',
865                 ),
866         );
867
868         // the calendar link for the full featured events calendar
869         if ($is_owner && $a->theme_events_in_profile) {
870                         $tabs[] = array(
871                                 'label' => t('Events'),
872                                 'url'   => System::baseUrl() . '/events',
873                                 'sel'   =>((!isset($tab) && $a->argv[0]=='events') ? 'active' : ''),
874                                 'title' => t('Events and Calendar'),
875                                 'id' => 'events-tab',
876                                 'accesskey' => 'e',
877                         );
878                 // if the user is not the owner of the calendar we only show a calendar
879                 // with the public events of the calendar owner
880         } elseif (! $is_owner) {
881                 $tabs[] = array(
882                                 'label' => t('Events'),
883                                 'url'   => System::baseUrl() . '/cal/' . $nickname,
884                                 'sel'   =>((!isset($tab) && $a->argv[0]=='cal') ? 'active' : ''),
885                                 'title' => t('Events and Calendar'),
886                                 'id' => 'events-tab',
887                                 'accesskey' => 'e',
888                         );
889         }
890
891         if ($is_owner) {
892                 $tabs[] = array(
893                         'label' => t('Personal Notes'),
894                         'url'   => System::baseUrl() . '/notes',
895                         'sel'   =>((!isset($tab) && $a->argv[0]=='notes') ? 'active' : ''),
896                         'title' => t('Only You Can See This'),
897                         'id' => 'notes-tab',
898                         'accesskey' => 't',
899                 );
900         }
901
902         if ((! $is_owner) && ((count($a->profile)) || (! $a->profile['hide-friends']))) {
903                 $tabs[] = array(
904                         'label' => t('Contacts'),
905                         'url'   => System::baseUrl() . '/viewcontacts/' . $nickname,
906                         'sel'   => ((!isset($tab) && $a->argv[0]=='viewcontacts') ? 'active' : ''),
907                         'title' => t('Contacts'),
908                         'id' => 'viewcontacts-tab',
909                         'accesskey' => 'k',
910                 );
911         }
912
913         $arr = array('is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => (($tab) ? $tab : false), 'tabs' => $tabs);
914         call_hooks('profile_tabs', $arr);
915
916         $tpl = get_markup_template('common_tabs.tpl');
917
918         return replace_macros($tpl, array('$tabs' => $arr['tabs']));
919 }
920
921 function get_my_url()
922 {
923         if (x($_SESSION, 'my_url')) {
924                 return $_SESSION['my_url'];
925         }
926         return false;
927 }
928
929 function zrl_init(App $a)
930 {
931         $tmp_str = get_my_url();
932         if (validate_url($tmp_str)) {
933                 // Is it a DDoS attempt?
934                 // The check fetches the cached value from gprobe to reduce the load for this system
935                 $urlparts = parse_url($tmp_str);
936
937                 $result = Cache::get("gprobe:" . $urlparts["host"]);
938                 if ((!is_null($result)) && (in_array($result["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
939                         logger("DDoS attempt detected for " . $urlparts["host"] . " by " . $_SERVER["REMOTE_ADDR"] . ". server data: " . print_r($_SERVER, true), LOGGER_DEBUG);
940                         return;
941                 }
942
943                 Worker::add(PRIORITY_LOW, 'GProbe', $tmp_str);
944                 $arr = array('zrl' => $tmp_str, 'url' => $a->cmd);
945                 call_hooks('zrl_init', $arr);
946         }
947 }
948
949 function zrl($s, $force = false)
950 {
951         if (! strlen($s)) {
952                 return $s;
953         }
954         if ((! strpos($s, '/profile/')) && (! $force)) {
955                 return $s;
956         }
957         if ($force && substr($s, -1, 1) !== '/') {
958                 $s = $s . '/';
959         }
960         $achar = strpos($s, '?') ? '&' : '?';
961         $mine = get_my_url();
962         if ($mine && ! link_compare($mine, $s)) {
963                 return $s . $achar . 'zrl=' . urlencode($mine);
964         }
965         return $s;
966 }
967
968 /**
969  * @brief Get the user ID of the page owner
970  *
971  * Used from within PCSS themes to set theme parameters. If there's a
972  * puid request variable, that is the "page owner" and normally their theme
973  * settings take precedence; unless a local user sets the "always_my_theme"
974  * system pconfig, which means they don't want to see anybody else's theme
975  * settings except their own while on this site.
976  *
977  * @return int user ID
978  *
979  * @note Returns local_user instead of user ID if "always_my_theme"
980  *      is set to true
981  */
982 function get_theme_uid()
983 {
984         $uid = ((!empty($_REQUEST['puid'])) ? intval($_REQUEST['puid']) : 0);
985         if ((local_user()) && ((PConfig::get(local_user(), 'system', 'always_my_theme')) || (! $uid))) {
986                 return local_user();
987         }
988
989         return $uid;
990 }