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