]> git.mxchange.org Git - friendica.git/blob - include/identity.php
Restructured "dba::exists" function
[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                 $connect = !dba::exists('contact', array('pending' => false, 'uid' => local_user(), 'nurl' => $profile_url));
249         }
250
251         if ($connect && ($profile['network'] != NETWORK_DFRN) && !isset($profile['remoteconnect']))
252                 $connect = false;
253
254         $remoteconnect = NULL;
255         if (isset($profile['remoteconnect']))
256                 $remoteconnect = $profile['remoteconnect'];
257
258         if ($connect && ($profile['network'] == NETWORK_DFRN) && !isset($remoteconnect))
259                 $subscribe_feed = t("Atom feed");
260         else
261                 $subscribe_feed = false;
262
263         if (remote_user() || (get_my_url() && $profile['unkmail'] && ($profile['uid'] != local_user()))) {
264                 $wallmessage = t('Message');
265                 $wallmessage_link = "wallmessage/".$profile["nickname"];
266
267                 if (remote_user()) {
268                         $r = q("SELECT `url` FROM `contact` WHERE `uid` = %d AND `id` = '%s' AND `rel` = %d",
269                                 intval($profile['uid']),
270                                 intval(remote_user()),
271                                 intval(CONTACT_IS_FRIEND));
272                 } else {
273                         $r = q("SELECT `url` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `rel` = %d",
274                                 intval($profile['uid']),
275                                 dbesc(normalise_link(get_my_url())),
276                                 intval(CONTACT_IS_FRIEND));
277                 }
278                 if ($r) {
279                         $remote_url = $r[0]["url"];
280                         $message_path = preg_replace("=(.*)/profile/(.*)=ism", "$1/message/new/", $remote_url);
281                         $wallmessage_link = $message_path.base64_encode($profile["addr"]);
282                 }
283         } else {
284                 $wallmessage = false;
285                 $wallmessage_link = false;
286         }
287
288         // show edit profile to yourself
289         if (!$is_contact && $profile['uid'] == local_user() && feature_enabled(local_user(),'multi_profiles')) {
290                 $profile['edit'] = array(App::get_baseurl(). '/profiles', t('Profiles'),"", t('Manage/edit profiles'));
291                 $r = q("SELECT * FROM `profile` WHERE `uid` = %d",
292                                 local_user());
293
294                 $profile['menu'] = array(
295                         'chg_photo' => t('Change profile photo'),
296                         'cr_new' => t('Create New Profile'),
297                         'entries' => array(),
298                 );
299
300                 if (dbm::is_result($r)) {
301
302                         foreach ($r as $rr) {
303                                 $profile['menu']['entries'][] = array(
304                                         'photo' => $rr['thumb'],
305                                         'id' => $rr['id'],
306                                         'alt' => t('Profile Image'),
307                                         'profile_name' => $rr['profile-name'],
308                                         'isdefault' => $rr['is-default'],
309                                         'visibile_to_everybody' =>  t('visible to everybody'),
310                                         'edit_visibility' => t('Edit visibility'),
311
312                                 );
313                         }
314
315
316                 }
317         }
318         if (!$is_contact && $profile['uid'] == local_user() && !feature_enabled(local_user(),'multi_profiles')) {
319                 $profile['edit'] = array(App::get_baseurl(). '/profiles/'.$profile['id'], t('Edit profile'),"", t('Edit profile'));
320                 $profile['menu'] = array(
321                         'chg_photo' => t('Change profile photo'),
322                         'cr_new' => null,
323                         'entries' => array(),
324                 );
325         }
326
327         // Fetch the account type
328         $account_type = account_type($profile);
329
330         if ((x($profile,'address') == 1)
331                         || (x($profile,'location') == 1)
332                         || (x($profile,'locality') == 1)
333                         || (x($profile,'region') == 1)
334                         || (x($profile,'postal-code') == 1)
335                         || (x($profile,'country-name') == 1))
336                 $location = t('Location:');
337
338         $gender = ((x($profile,'gender') == 1) ? t('Gender:') : False);
339
340
341         $marital = ((x($profile,'marital') == 1) ?  t('Status:') : False);
342
343         $homepage = ((x($profile,'homepage') == 1) ?  t('Homepage:') : False);
344
345         $about = ((x($profile,'about') == 1) ?  t('About:') : False);
346
347         $xmpp = ((x($profile,'xmpp') == 1) ?  t('XMPP:') : False);
348
349         if (($profile['hidewall'] || $block) && (! local_user()) && (! remote_user())) {
350                 $location = $pdesc = $gender = $marital = $homepage = $about = False;
351         }
352
353         $firstname = ((strpos($profile['name'],' '))
354                         ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']);
355         $lastname = (($firstname === $profile['name']) ? '' : trim(substr($profile['name'],strlen($firstname))));
356
357         if ($profile['guid'] != "")
358                 $diaspora = array(
359                         'guid' => $profile['guid'],
360                         'podloc' => App::get_baseurl(),
361                         'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false' ),
362                         'nickname' => $profile['nickname'],
363                         'fullname' => $profile['name'],
364                         'firstname' => $firstname,
365                         'lastname' => $lastname,
366                         'photo300' => $profile['contact_photo'],
367                         'photo100' => $profile['contact_thumb'],
368                         'photo50' => $profile['contact_micro'],
369                 );
370         else
371                 $diaspora = false;
372
373         if (!$block) {
374                 $contact_block = contact_block();
375
376                 if (is_array($a->profile) && !$a->profile['hide-friends']) {
377                         $r = q("SELECT `gcontact`.`updated` FROM `contact` INNER JOIN `gcontact` WHERE `gcontact`.`nurl` = `contact`.`nurl` AND `self` AND `uid` = %d LIMIT 1",
378                                 intval($a->profile['uid']));
379                         if (dbm::is_result($r))
380                                 $updated =  date("c", strtotime($r[0]['updated']));
381
382                         $r = q("SELECT COUNT(*) AS `total` FROM `contact`
383                                 WHERE `uid` = %d
384                                         AND NOT `self` AND NOT `blocked` AND NOT `pending`
385                                         AND NOT `hidden` AND NOT `archive`
386                                         AND `network` IN ('%s', '%s', '%s', '')",
387                                 intval($profile['uid']),
388                                 dbesc(NETWORK_DFRN),
389                                 dbesc(NETWORK_DIASPORA),
390                                 dbesc(NETWORK_OSTATUS)
391                         );
392                         if (dbm::is_result($r))
393                                 $contacts = intval($r[0]['total']);
394                 }
395         }
396
397         $p = array();
398         foreach ($profile as $k => $v) {
399                 $k = str_replace('-','_',$k);
400                 $p[$k] = $v;
401         }
402
403         if (isset($p["about"]))
404                 $p["about"] = bbcode($p["about"]);
405
406         if (isset($p["address"]))
407                 $p["address"] = bbcode($p["address"]);
408         else
409                 $p["address"] = bbcode($p["location"]);
410
411         if (isset($p["photo"])) {
412                 $p["photo"] = proxy_url($p["photo"], false, PROXY_SIZE_SMALL);
413         }
414         if ($a->theme['template_engine'] === 'internal')
415                 $location = template_escape($location);
416
417         $tpl = get_markup_template('profile_vcard.tpl');
418         $o .= replace_macros($tpl, array(
419                 '$profile' => $p,
420                 '$xmpp' => $xmpp,
421                 '$connect'  => $connect,
422                 '$remoteconnect'  => $remoteconnect,
423                 '$subscribe_feed' => $subscribe_feed,
424                 '$wallmessage' => $wallmessage,
425                 '$wallmessage_link' => $wallmessage_link,
426                 '$account_type' => $account_type,
427                 '$location' => $location,
428                 '$gender'   => $gender,
429 //                      '$pdesc'        => $pdesc,
430                 '$marital'  => $marital,
431                 '$homepage' => $homepage,
432                 '$about' => $about,
433                 '$network' =>  t('Network:'),
434                 '$contacts' => $contacts,
435                 '$updated' => $updated,
436                 '$diaspora' => $diaspora,
437                 '$contact_block' => $contact_block,
438         ));
439
440         $arr = array('profile' => &$profile, 'entry' => &$o);
441
442         call_hooks('profile_sidebar', $arr);
443
444         return $o;
445 }
446
447
448 function get_birthdays() {
449
450         $a = get_app();
451         $o = '';
452
453         if (! local_user() || $a->is_mobile || $a->is_tablet)
454                 return $o;
455
456 //              $mobile_detect = new Mobile_Detect();
457 //              $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
458
459 //              if ($is_mobile)
460 //                      return $o;
461
462         $bd_format = t('g A l F d') ; // 8 AM Friday January 18
463         $bd_short = t('F d');
464
465         $cachekey = "get_birthdays:".local_user();
466         $r = Cache::get($cachekey);
467         if (is_null($r)) {
468                 $s = dba::p("SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
469                                 INNER JOIN `contact` ON `contact`.`id` = `event`.`cid`
470                                 WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
471                                 ORDER BY `start` ASC ",
472                                 local_user(),
473                                 datetime_convert('UTC','UTC','now + 6 days'),
474                                 datetime_convert('UTC','UTC','now')
475                 );
476                 if (dbm::is_result($s)) {
477                         $r = dba::inArray($s);
478                         Cache::set($cachekey, $r, CACHE_HOUR);
479                 }
480         }
481         if (dbm::is_result($r)) {
482                 $total = 0;
483                 $now = strtotime('now');
484                 $cids = array();
485
486                 $istoday = false;
487                 foreach ($r as $rr) {
488                         if (strlen($rr['name']))
489                                 $total ++;
490                         if ((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now))
491                                 $istoday = true;
492                 }
493                 $classtoday = $istoday ? ' birthday-today ' : '';
494                 if ($total) {
495                         foreach ($r as &$rr) {
496                                 if (! strlen($rr['name']))
497                                         continue;
498
499                                 // avoid duplicates
500
501                                 if (in_array($rr['cid'],$cids))
502                                         continue;
503                                 $cids[] = $rr['cid'];
504
505                                 $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
506                                 $sparkle = '';
507                                 $url = $rr['url'];
508                                 if ($rr['network'] === NETWORK_DFRN) {
509                                         $sparkle = " sparkle";
510                                         $url = App::get_baseurl() . '/redir/'  . $rr['cid'];
511                                 }
512
513                                 $rr['link'] = $url;
514                                 $rr['title'] = $rr['name'];
515                                 $rr['date'] = day_translate(datetime_convert('UTC', $a->timezone, $rr['start'], $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ?  ' ' . t('[today]') : '');
516                                 $rr['startime'] = Null;
517                                 $rr['today'] = $today;
518
519                         }
520                 }
521         }
522         $tpl = get_markup_template("birthdays_reminder.tpl");
523         return replace_macros($tpl, array(
524                 '$baseurl' => App::get_baseurl(),
525                 '$classtoday' => $classtoday,
526                 '$count' => $total,
527                 '$event_reminders' => t('Birthday Reminders'),
528                 '$event_title' => t('Birthdays this week:'),
529                 '$events' => $r,
530                 '$lbr' => '{',  // raw brackets mess up if/endif macro processing
531                 '$rbr' => '}'
532
533         ));
534 }
535
536
537 function get_events() {
538
539         require_once 'include/bbcode.php';
540
541         $a = get_app();
542
543         if (! local_user() || $a->is_mobile || $a->is_tablet) {
544                 return $o;
545         }
546
547 //              $mobile_detect = new Mobile_Detect();
548 //              $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
549
550 //              if ($is_mobile)
551 //                      return $o;
552
553         $bd_format = t('g A l F d') ; // 8 AM Friday January 18
554         $bd_short = t('F d');
555
556         $r = dba::p("SELECT `event`.* FROM `event`
557                         WHERE `event`.`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?
558                         ORDER BY `start` ASC ",
559                         local_user(),
560                         datetime_convert('UTC','UTC','now + 7 days'),
561                         datetime_convert('UTC','UTC','now - 1 days')
562         );
563
564         if (dbm::is_result($r)) {
565                 $now = strtotime('now');
566                 $istoday = false;
567                 $skip = 0;
568
569                 while ($rr = dba::fetch($r)) {
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                         $title = strip_tags(html_entity_decode(bbcode($rr['summary']),ENT_QUOTES,'UTF-8'));
580
581                         if (strlen($title) > 35) {
582                                 $title = substr($title,0,32) . '... ';
583                         }
584
585                         $description = substr(strip_tags(bbcode($rr['desc'])),0,32) . '... ';
586                         if (! $description) {
587                                 $description = t('[No description]');
588                         }
589
590                         $strt = datetime_convert('UTC',$rr['convert'] ? $a->timezone : 'UTC',$rr['start']);
591
592                         if (substr($strt,0,10) < datetime_convert('UTC',$a->timezone,'now','Y-m-d')) {
593                                 $skip++;
594                                 continue;
595                         }
596
597                         $today = ((substr($strt,0,10) === datetime_convert('UTC',$a->timezone,'now','Y-m-d')) ? true : false);
598
599                         $rr['title'] = $title;
600                         $rr['description'] = $desciption;
601                         $rr['date'] = day_translate(datetime_convert('UTC', $rr['adjust'] ? $a->timezone : 'UTC', $rr['start'], $bd_format)) . (($today) ?  ' ' . t('[today]') : '');
602                         $rr['startime'] = $strt;
603                         $rr['today'] = $today;
604                 }
605                 dba::close($r);
606                 $classtoday = (($istoday) ? 'event-today' : '');
607         }
608
609         $tpl = get_markup_template("events_reminder.tpl");
610         return replace_macros($tpl, array(
611                 '$baseurl' => App::get_baseurl(),
612                 '$classtoday' => $classtoday,
613                 '$count' => count($r) - $skip,
614                 '$event_reminders' => t('Event Reminders'),
615                 '$event_title' => t('Events this week:'),
616                 '$events' => $r,
617         ));
618 }
619
620 function advanced_profile(App $a) {
621
622         $o = '';
623         $uid = $a->profile['uid'];
624
625         $o .= replace_macros(get_markup_template('section_title.tpl'),array(
626                 '$title' => t('Profile')
627         ));
628
629         if ($a->profile['name']) {
630
631                 $tpl = get_markup_template('profile_advanced.tpl');
632
633                 $profile = array();
634
635                 $profile['fullname'] = array( t('Full Name:'), $a->profile['name'] ) ;
636
637                 if ($a->profile['gender']) {
638                         $profile['gender'] = array( t('Gender:'),  $a->profile['gender'] );
639                 }
640
641                 if (($a->profile['dob']) && ($a->profile['dob'] > '0001-01-01')) {
642                         $year_bd_format = t('j F, Y');
643                         $short_bd_format = t('j F');
644
645
646                         $val = ((intval($a->profile['dob']))
647                                 ? day_translate(datetime_convert('UTC','UTC',$a->profile['dob'] . ' 00:00 +00:00',$year_bd_format))
648                                 : day_translate(datetime_convert('UTC','UTC','2001-' . substr($a->profile['dob'],5) . ' 00:00 +00:00',$short_bd_format)));
649
650                         $profile['birthday'] = array( t('Birthday:'), $val);
651
652                 }
653                 if (!empty($a->profile['dob'])
654                         && $a->profile['dob'] > '0001-01-01'
655                         && $age = age($a->profile['dob'], $a->profile['timezone'], '')
656                 ) {
657                         $profile['age'] = array( t('Age:'), $age );
658                 }
659
660                 if ($a->profile['marital']) {
661                         $profile['marital'] = array( t('Status:'), $a->profile['marital']);
662                 }
663
664                 /// @TODO Maybe use x() here, plus below?
665                 if ($a->profile['with']) {
666                         $profile['marital']['with'] = $a->profile['with'];
667                 }
668
669                 if (strlen($a->profile['howlong']) && $a->profile['howlong'] >= NULL_DATE) {
670                         $profile['howlong'] = relative_date($a->profile['howlong'], t('for %1$d %2$s'));
671                 }
672
673                 if ($a->profile['sexual']) {
674                         $profile['sexual'] = array( t('Sexual Preference:'), $a->profile['sexual'] );
675                 }
676
677                 if ($a->profile['homepage']) {
678                         $profile['homepage'] = array( t('Homepage:'), linkify($a->profile['homepage']) );
679                 }
680
681                 if ($a->profile['hometown']) {
682                         $profile['hometown'] = array( t('Hometown:'), linkify($a->profile['hometown']) );
683                 }
684
685                 if ($a->profile['pub_keywords']) {
686                         $profile['pub_keywords'] = array( t('Tags:'), $a->profile['pub_keywords']);
687                 }
688
689                 if ($a->profile['politic']) {
690                         $profile['politic'] = array( t('Political Views:'), $a->profile['politic']);
691                 }
692
693                 if ($a->profile['religion']) {
694                         $profile['religion'] = array( t('Religion:'), $a->profile['religion']);
695                 }
696
697                 if ($txt = prepare_text($a->profile['about'])) {
698                         $profile['about'] = array( t('About:'), $txt );
699                 }
700
701                 if ($txt = prepare_text($a->profile['interest'])) {
702                         $profile['interest'] = array( t('Hobbies/Interests:'), $txt);
703                 }
704
705                 if ($txt = prepare_text($a->profile['likes'])) {
706                         $profile['likes'] = array( t('Likes:'), $txt);
707                 }
708
709                 if ($txt = prepare_text($a->profile['dislikes'])) {
710                         $profile['dislikes'] = array( t('Dislikes:'), $txt);
711                 }
712
713                 if ($txt = prepare_text($a->profile['contact'])) {
714                         $profile['contact'] = array( t('Contact information and Social Networks:'), $txt);
715                 }
716
717                 if ($txt = prepare_text($a->profile['music'])) {
718                         $profile['music'] = array( t('Musical interests:'), $txt);
719                 }
720
721                 if ($txt = prepare_text($a->profile['book'])) {
722                         $profile['book'] = array( t('Books, literature:'), $txt);
723                 }
724
725                 if ($txt = prepare_text($a->profile['tv'])) {
726                         $profile['tv'] = array( t('Television:'), $txt);
727                 }
728
729                 if ($txt = prepare_text($a->profile['film'])) {
730                         $profile['film'] = array( t('Film/dance/culture/entertainment:'), $txt);
731                 }
732
733                 if ($txt = prepare_text($a->profile['romance'])) {
734                         $profile['romance'] = array( t('Love/Romance:'), $txt);
735                 }
736
737                 if ($txt = prepare_text($a->profile['work'])) {
738                         $profile['work'] = array( t('Work/employment:'), $txt);
739                 }
740
741                 if ($txt = prepare_text($a->profile['education'])) {
742                         $profile['education'] = array( t('School/education:'), $txt );
743                 }
744
745                 //show subcribed forum if it is enabled in the usersettings
746                 if (feature_enabled($uid,'forumlist_profile')) {
747                         $profile['forumlist'] = array( t('Forums:'), ForumManager::profile_advanced($uid));
748                 }
749
750                 if ($a->profile['uid'] == local_user()) {
751                         $profile['edit'] = array(App::get_baseurl(). '/profiles/'.$a->profile['id'], t('Edit profile'),"", t('Edit profile'));
752                 }
753
754                 return replace_macros($tpl, array(
755                         '$title' => t('Profile'),
756                         '$basic' => t('Basic'),
757                         '$advanced' => t('Advanced'),
758                         '$profile' => $profile
759                 ));
760         }
761
762         return '';
763 }
764
765 function profile_tabs($a, $is_owner=False, $nickname=Null) {
766         //echo "<pre>"; var_dump($a->user); killme();
767
768         if (is_null($nickname)) {
769                 $nickname  = $a->user['nickname'];
770         }
771
772         if (x($_GET,'tab')) {
773                 $tab = notags(trim($_GET['tab']));
774         }
775
776         $url = App::get_baseurl() . '/profile/' . $nickname;
777
778         $tabs = array(
779                 array(
780                         'label'=>t('Status'),
781                         'url' => $url,
782                         'sel' => ((!isset($tab) && $a->argv[0]=='profile') ? 'active' : ''),
783                         'title' => t('Status Messages and Posts'),
784                         'id' => 'status-tab',
785                         'accesskey' => 'm',
786                 ),
787                 array(
788                         'label' => t('Profile'),
789                         'url'   => $url.'/?tab=profile',
790                         'sel'   => ((isset($tab) && $tab=='profile') ? 'active' : ''),
791                         'title' => t('Profile Details'),
792                         'id' => 'profile-tab',
793                         'accesskey' => 'r',
794                 ),
795                 array(
796                         'label' => t('Photos'),
797                         'url'   => App::get_baseurl() . '/photos/' . $nickname,
798                         'sel'   => ((!isset($tab) && $a->argv[0]=='photos') ? 'active' : ''),
799                         'title' => t('Photo Albums'),
800                         'id' => 'photo-tab',
801                         'accesskey' => 'h',
802                 ),
803                 array(
804                         'label' => t('Videos'),
805                         'url'   => App::get_baseurl() . '/videos/' . $nickname,
806                         'sel'   => ((!isset($tab) && $a->argv[0]=='videos') ? 'active' : ''),
807                         'title' => t('Videos'),
808                         'id' => 'video-tab',
809                         'accesskey' => 'v',
810                 ),
811         );
812
813         // the calendar link for the full featured events calendar
814         if ($is_owner && $a->theme_events_in_profile) {
815                         $tabs[] = array(
816                                 'label' => t('Events'),
817                                 'url'   => App::get_baseurl() . '/events',
818                                 'sel'   =>((!isset($tab) && $a->argv[0]=='events') ? 'active' : ''),
819                                 'title' => t('Events and Calendar'),
820                                 'id' => 'events-tab',
821                                 'accesskey' => 'e',
822                         );
823         // if the user is not the owner of the calendar we only show a calendar
824         // with the public events of the calendar owner
825         } elseif (! $is_owner) {
826                 $tabs[] = array(
827                                 'label' => t('Events'),
828                                 'url'   => App::get_baseurl() . '/cal/' . $nickname,
829                                 'sel'   =>((!isset($tab) && $a->argv[0]=='cal') ? 'active' : ''),
830                                 'title' => t('Events and Calendar'),
831                                 'id' => 'events-tab',
832                                 'accesskey' => 'e',
833                         );
834         }
835
836         if ($is_owner) {
837                 $tabs[] = array(
838                         'label' => t('Personal Notes'),
839                         'url'   => App::get_baseurl() . '/notes',
840                         'sel'   =>((!isset($tab) && $a->argv[0]=='notes') ? 'active' : ''),
841                         'title' => t('Only You Can See This'),
842                         'id' => 'notes-tab',
843                         'accesskey' => 't',
844                 );
845         }
846
847         if ((! $is_owner) && ((count($a->profile)) || (! $a->profile['hide-friends']))) {
848                 $tabs[] = array(
849                         'label' => t('Contacts'),
850                         'url'   => App::get_baseurl() . '/viewcontacts/' . $nickname,
851                         'sel'   => ((!isset($tab) && $a->argv[0]=='viewcontacts') ? 'active' : ''),
852                         'title' => t('Contacts'),
853                         'id' => 'viewcontacts-tab',
854                         'accesskey' => 'k',
855                 );
856         }
857
858         $arr = array('is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => (($tab) ? $tab : false), 'tabs' => $tabs);
859         call_hooks('profile_tabs', $arr);
860
861         $tpl = get_markup_template('common_tabs.tpl');
862
863         return replace_macros($tpl,array('$tabs' => $arr['tabs']));
864 }
865
866 function get_my_url() {
867         if (x($_SESSION, 'my_url')) {
868                 return $_SESSION['my_url'];
869         }
870         return false;
871 }
872
873 function zrl_init(App $a) {
874         $tmp_str = get_my_url();
875         if (validate_url($tmp_str)) {
876
877                 // Is it a DDoS attempt?
878                 // The check fetches the cached value from gprobe to reduce the load for this system
879                 $urlparts = parse_url($tmp_str);
880
881                 $result = Cache::get("gprobe:" . $urlparts["host"]);
882                 if ((!is_null($result)) && (in_array($result["network"], array(NETWORK_FEED, NETWORK_PHANTOM)))) {
883                         logger("DDoS attempt detected for " . $urlparts["host"] . " by " . $_SERVER["REMOTE_ADDR"] . ". server data: " . print_r($_SERVER, true), LOGGER_DEBUG);
884                         return;
885                 }
886
887                 proc_run(PRIORITY_LOW, 'include/gprobe.php', $tmp_str);
888                 $arr = array('zrl' => $tmp_str, 'url' => $a->cmd);
889                 call_hooks('zrl_init', $arr);
890         }
891 }
892
893 function zrl($s, $force = false) {
894         if (! strlen($s)) {
895                 return $s;
896         }
897         if ((! strpos($s, '/profile/')) && (! $force)) {
898                 return $s;
899         }
900         if ($force && substr($s, -1, 1) !== '/') {
901                 $s = $s . '/';
902         }
903         $achar = strpos($s, '?') ? '&' : '?';
904         $mine = get_my_url();
905         if ($mine && ! link_compare($mine, $s)) {
906                 return $s . $achar . 'zrl=' . urlencode($mine);
907         }
908         return $s;
909 }
910
911 /**
912  * @brief Get the user ID of the page owner
913  *
914  * Used from within PCSS themes to set theme parameters. If there's a
915  * puid request variable, that is the "page owner" and normally their theme
916  * settings take precedence; unless a local user sets the "always_my_theme"
917  * system pconfig, which means they don't want to see anybody else's theme
918  * settings except their own while on this site.
919  *
920  * @return int user ID
921  *
922  * @note Returns local_user instead of user ID if "always_my_theme"
923  *      is set to true
924  */
925 function get_theme_uid() {
926         $uid = ((!empty($_REQUEST['puid'])) ? intval($_REQUEST['puid']) : 0);
927         if ((local_user()) && ((get_pconfig(local_user(), 'system', 'always_my_theme')) || (! $uid))) {
928                 return local_user();
929         }
930
931         return $uid;
932 }