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