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