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