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