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