31d9fe846f27a623879cb769028f3a16d1cb0b50
[friendica.git/.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\Content\Text\BBCode;
11 use Friendica\Core\Addon;
12 use Friendica\Core\Cache;
13 use Friendica\Core\Config;
14 use Friendica\Core\L10n;
15 use Friendica\Core\PConfig;
16 use Friendica\Core\System;
17 use Friendica\Core\Worker;
18 use Friendica\Database\DBM;
19 use Friendica\Model\Contact;
20 use Friendica\Model\OpenWebAuthToken;
21 use Friendica\Protocol\Diaspora;
22 use Friendica\Util\DateTimeFormat;
23 use Friendica\Util\Network;
24 use Friendica\Util\Temporal;
25 use dba;
26
27 require_once 'include/dba.php';
28 require_once 'mod/proxy.php';
29
30 class Profile
31 {
32         /**
33          * @brief Returns a formatted location string from the given profile array
34          *
35          * @param array $profile Profile array (Generated from the "profile" table)
36          *
37          * @return string Location string
38          */
39         public static function formatLocation(array $profile)
40         {
41                 $location = '';
42
43                 if ($profile['locality']) {
44                         $location .= $profile['locality'];
45                 }
46
47                 if ($profile['region'] && ($profile['locality'] != $profile['region'])) {
48                         if ($location) {
49                                 $location .= ', ';
50                         }
51
52                         $location .= $profile['region'];
53                 }
54
55                 if ($profile['country-name']) {
56                         if ($location) {
57                                 $location .= ', ';
58                         }
59
60                         $location .= $profile['country-name'];
61                 }
62
63                 return $location;
64         }
65
66         /**
67          *
68          * Loads a profile into the page sidebar.
69          *
70          * The function requires a writeable copy of the main App structure, and the nickname
71          * of a registered local account.
72          *
73          * If the viewer is an authenticated remote viewer, the profile displayed is the
74          * one that has been configured for his/her viewing in the Contact manager.
75          * Passing a non-zero profile ID can also allow a preview of a selected profile
76          * by the owner.
77          *
78          * Profile information is placed in the App structure for later retrieval.
79          * Honours the owner's chosen theme for display.
80          *
81          * @attention Should only be run in the _init() functions of a module. That ensures that
82          *      the theme is chosen before the _init() function of a theme is run, which will usually
83          *      load a lot of theme-specific content
84          *
85          * @brief Loads a profile into the page sidebar.
86          * @param object  $a            App
87          * @param string  $nickname     string
88          * @param int     $profile      int
89          * @param array   $profiledata  array
90          * @param boolean $show_connect Show connect link
91          */
92         public static function load(App $a, $nickname, $profile = 0, $profiledata = [], $show_connect = true)
93         {
94                 $user = dba::selectFirst('user', ['uid'], ['nickname' => $nickname, 'account_removed' => false]);
95
96                 if (!DBM::is_result($user) && empty($profiledata)) {
97                         logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
98                         notice(L10n::t('Requested account is not available.') . EOL);
99                         $a->error = 404;
100                         return;
101                 }
102
103                 if (empty($a->page['aside'])) {
104                         $a->page['aside'] = '';
105                 }
106
107                 if ($profiledata) {
108                         $a->page['aside'] .= self::sidebar($profiledata, true, $show_connect);
109
110                         if (!DBM::is_result($user)) {
111                                 return;
112                         }
113                 }
114
115                 $pdata = self::getByNickname($nickname, $user[0]['uid'], $profile);
116
117                 if (empty($pdata) && empty($profiledata)) {
118                         logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
119                         notice(L10n::t('Requested profile is not available.') . EOL);
120                         $a->error = 404;
121                         return;
122                 }
123
124                 // fetch user tags if this isn't the default profile
125
126                 if (!$pdata['is-default']) {
127                         $x = q(
128                                 "SELECT `pub_keywords` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
129                                 intval($pdata['profile_uid'])
130                         );
131                         if ($x && count($x)) {
132                                 $pdata['pub_keywords'] = $x[0]['pub_keywords'];
133                         }
134                 }
135
136                 $a->profile = $pdata;
137                 $a->profile_uid = $pdata['profile_uid'];
138
139                 $a->profile['mobile-theme'] = PConfig::get($a->profile['profile_uid'], 'system', 'mobile_theme');
140                 $a->profile['network'] = NETWORK_DFRN;
141
142                 $a->page['title'] = $a->profile['name'] . ' @ ' . $a->config['sitename'];
143
144                 if (!$profiledata && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
145                         $_SESSION['theme'] = $a->profile['theme'];
146                 }
147
148                 $_SESSION['mobile-theme'] = $a->profile['mobile-theme'];
149
150                 /*
151                 * load/reload current theme info
152                 */
153
154                 $a->set_template_engine(); // reset the template engine to the default in case the user's theme doesn't specify one
155
156                 $theme_info_file = 'view/theme/' . $a->getCurrentTheme() . '/theme.php';
157                 if (file_exists($theme_info_file)) {
158                         require_once $theme_info_file;
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' => L10n::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 string HTML sidebar module
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() ? L10n::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 = L10n::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 = L10n::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', L10n::t('Profiles'), '', L10n::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' => L10n::t('Change profile photo'),
377                                 'cr_new' => L10n::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' => L10n::t('Profile Image'),
387                                                 'profile_name' => $rr['profile-name'],
388                                                 'isdefault' => $rr['is-default'],
389                                                 'visibile_to_everybody' => L10n::t('visible to everybody'),
390                                                 'edit_visibility' => L10n::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'], L10n::t('Edit profile'), '', L10n::t('Edit profile')];
397                         $profile['menu'] = [
398                                 'chg_photo' => L10n::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 = L10n::t('Location:');
415                 }
416
417                 $gender   = x($profile, 'gender')   ? L10n::t('Gender:')   : false;
418                 $marital  = x($profile, 'marital')  ? L10n::t('Status:')   : false;
419                 $homepage = x($profile, 'homepage') ? L10n::t('Homepage:') : false;
420                 $about    = x($profile, 'about')    ? L10n::t('About:')    : false;
421                 $xmpp     = x($profile, 'xmpp')     ? L10n::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::convert($p['about']);
488                 }
489
490                 if (isset($p['address'])) {
491                         $p['address'] = BBCode::convert($p['address']);
492                 } else {
493                         $p['address'] = BBCode::convert($p['location']);
494                 }
495
496                 if (isset($p['photo'])) {
497                         $p['photo'] = proxy_url($p['photo'], false, PROXY_SIZE_SMALL);
498                 }
499
500                 $p['url'] = Contact::magicLink($p['url']);
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                                 DateTimeFormat::utc('now + 6 days'),
560                                 DateTimeFormat::utcNow()
561                         );
562                         if (DBM::is_result($s)) {
563                                 $r = dba::inArray($s);
564                                 Cache::set($cachekey, $r, CACHE_HOUR);
565                         }
566                 }
567
568                 $total = 0;
569                 $classtoday = '';
570                 if (DBM::is_result($r)) {
571                         $now = strtotime('now');
572                         $cids = [];
573
574                         $istoday = false;
575                         foreach ($r as $rr) {
576                                 if (strlen($rr['name'])) {
577                                         $total ++;
578                                 }
579                                 if ((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) {
580                                         $istoday = true;
581                                 }
582                         }
583                         $classtoday = $istoday ? ' birthday-today ' : '';
584                         if ($total) {
585                                 foreach ($r as &$rr) {
586                                         if (!strlen($rr['name'])) {
587                                                 continue;
588                                         }
589
590                                         // avoid duplicates
591
592                                         if (in_array($rr['cid'], $cids)) {
593                                                 continue;
594                                         }
595                                         $cids[] = $rr['cid'];
596
597                                         $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
598
599                                         $rr['link'] = Contact::magicLink($rr['url']);
600                                         $rr['title'] = $rr['name'];
601                                         $rr['date'] = day_translate(DateTimeFormat::convert($rr['start'], $a->timezone, 'UTC', $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . L10n::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' => L10n::t('Birthday Reminders'),
613                         '$event_title' => L10n::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 getEventsReminderHTML()
621         {
622                 $a = get_app();
623                 $o = '';
624
625                 if (!local_user() || $a->is_mobile || $a->is_tablet) {
626                         return $o;
627                 }
628
629                 /*
630                 *       $mobile_detect = new Mobile_Detect();
631                 *               $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
632                 *               if ($is_mobile)
633                 *                       return $o;
634                 */
635
636                 $bd_format = L10n::t('g A l F d'); // 8 AM Friday January 18
637                 $classtoday = '';
638
639                 $s = dba::p(
640                         "SELECT `event`.*
641                         FROM `event`
642                         INNER JOIN `item`
643                                 ON `item`.`uid` = `event`.`uid`
644                                 AND `item`.`parent-uri` = `event`.`uri`
645                         WHERE `event`.`uid` = ?
646                         AND `event`.`type` != 'birthday'
647                         AND `event`.`start` < ?
648                         AND `event`.`start` >= ?
649                         AND `item`.`author-id` = ?
650                         AND (`item`.`verb` = ? OR `item`.`verb` = ?)
651                         AND `item`.`visible`
652                         AND NOT `item`.`deleted`
653                         ORDER BY  `event`.`start` ASC",
654                         local_user(),
655                         DateTimeFormat::utc('now + 7 days'),
656                         DateTimeFormat::utc('now - 1 days'),
657                         public_contact(),
658                         ACTIVITY_ATTEND,
659                         ACTIVITY_ATTENDMAYBE
660                 );
661
662                 $r = [];
663
664                 if (DBM::is_result($s)) {
665                         $istoday = false;
666
667                         while ($rr = dba::fetch($s)) {
668                                 if (strlen($rr['name'])) {
669                                         $total ++;
670                                 }
671
672                                 $strt = DateTimeFormat::convert($rr['start'], $rr['convert'] ? $a->timezone : 'UTC', 'UTC', 'Y-m-d');
673                                 if ($strt === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
674                                         $istoday = true;
675                                 }
676
677                                 $title = strip_tags(html_entity_decode(BBCode::convert($rr['summary']), ENT_QUOTES, 'UTF-8'));
678
679                                 if (strlen($title) > 35) {
680                                         $title = substr($title, 0, 32) . '... ';
681                                 }
682
683                                 $description = substr(strip_tags(BBCode::convert($rr['desc'])), 0, 32) . '... ';
684                                 if (!$description) {
685                                         $description = L10n::t('[No description]');
686                                 }
687
688                                 $strt = DateTimeFormat::convert($rr['start'], $rr['convert'] ? $a->timezone : 'UTC');
689
690                                 if (substr($strt, 0, 10) < DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
691                                         continue;
692                                 }
693
694                                 $today = ((substr($strt, 0, 10) === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) ? true : false);
695
696                                 $rr['title'] = $title;
697                                 $rr['description'] = $description;
698                                 $rr['date'] = day_translate(DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', $bd_format)) . (($today) ? ' ' . L10n::t('[today]') : '');
699                                 $rr['startime'] = $strt;
700                                 $rr['today'] = $today;
701
702                                 $r[] = $rr;
703                         }
704                         dba::close($s);
705                         $classtoday = (($istoday) ? 'event-today' : '');
706                 }
707                 $tpl = get_markup_template('events_reminder.tpl');
708                 return replace_macros($tpl, [
709                         '$baseurl' => System::baseUrl(),
710                         '$classtoday' => $classtoday,
711                         '$count' => count($r),
712                         '$event_reminders' => L10n::t('Event Reminders'),
713                         '$event_title' => L10n::t('Events this week:'),
714                         '$events' => $r,
715                 ]);
716         }
717
718         public static function getAdvanced(App $a)
719         {
720                 $o = '';
721                 $uid = $a->profile['uid'];
722
723                 $o .= replace_macros(
724                         get_markup_template('section_title.tpl'),
725                         ['$title' => L10n::t('Profile')]
726                 );
727
728                 if ($a->profile['name']) {
729                         $tpl = get_markup_template('profile_advanced.tpl');
730
731                         $profile = [];
732
733                         $profile['fullname'] = [L10n::t('Full Name:'), $a->profile['name']];
734
735                         if (Feature::isEnabled($uid, 'profile_membersince')) {
736                                 $profile['membersince'] = [L10n::t('Member since:'), DateTimeFormat::local($a->profile['register_date'])];
737                         }
738
739                         if ($a->profile['gender']) {
740                                 $profile['gender'] = [L10n::t('Gender:'), $a->profile['gender']];
741                         }
742
743                         if (($a->profile['dob']) && ($a->profile['dob'] > '0001-01-01')) {
744                                 $year_bd_format = L10n::t('j F, Y');
745                                 $short_bd_format = L10n::t('j F');
746
747                                 $val = day_translate(
748                                         intval($a->profile['dob']) ?
749                                                 DateTimeFormat::utc($a->profile['dob'] . ' 00:00 +00:00', $year_bd_format)
750                                                 : DateTimeFormat::utc('2001-' . substr($a->profile['dob'], 5) . ' 00:00 +00:00', $short_bd_format)
751                                 );
752
753                                 $profile['birthday'] = [L10n::t('Birthday:'), $val];
754                         }
755
756                         if (!empty($a->profile['dob'])
757                                 && $a->profile['dob'] > '0001-01-01'
758                                 && $age = Temporal::getAgeByTimezone($a->profile['dob'], $a->profile['timezone'], '')
759                         ) {
760                                 $profile['age'] = [L10n::t('Age:'), $age];
761                         }
762
763                         if ($a->profile['marital']) {
764                                 $profile['marital'] = [L10n::t('Status:'), $a->profile['marital']];
765                         }
766
767                         /// @TODO Maybe use x() here, plus below?
768                         if ($a->profile['with']) {
769                                 $profile['marital']['with'] = $a->profile['with'];
770                         }
771
772                         if (strlen($a->profile['howlong']) && $a->profile['howlong'] >= NULL_DATE) {
773                                 $profile['howlong'] = Temporal::getRelativeDate($a->profile['howlong'], L10n::t('for %1$d %2$s'));
774                         }
775
776                         if ($a->profile['sexual']) {
777                                 $profile['sexual'] = [L10n::t('Sexual Preference:'), $a->profile['sexual']];
778                         }
779
780                         if ($a->profile['homepage']) {
781                                 $profile['homepage'] = [L10n::t('Homepage:'), linkify($a->profile['homepage'])];
782                         }
783
784                         if ($a->profile['hometown']) {
785                                 $profile['hometown'] = [L10n::t('Hometown:'), linkify($a->profile['hometown'])];
786                         }
787
788                         if ($a->profile['pub_keywords']) {
789                                 $profile['pub_keywords'] = [L10n::t('Tags:'), $a->profile['pub_keywords']];
790                         }
791
792                         if ($a->profile['politic']) {
793                                 $profile['politic'] = [L10n::t('Political Views:'), $a->profile['politic']];
794                         }
795
796                         if ($a->profile['religion']) {
797                                 $profile['religion'] = [L10n::t('Religion:'), $a->profile['religion']];
798                         }
799
800                         if ($txt = prepare_text($a->profile['about'])) {
801                                 $profile['about'] = [L10n::t('About:'), $txt];
802                         }
803
804                         if ($txt = prepare_text($a->profile['interest'])) {
805                                 $profile['interest'] = [L10n::t('Hobbies/Interests:'), $txt];
806                         }
807
808                         if ($txt = prepare_text($a->profile['likes'])) {
809                                 $profile['likes'] = [L10n::t('Likes:'), $txt];
810                         }
811
812                         if ($txt = prepare_text($a->profile['dislikes'])) {
813                                 $profile['dislikes'] = [L10n::t('Dislikes:'), $txt];
814                         }
815
816                         if ($txt = prepare_text($a->profile['contact'])) {
817                                 $profile['contact'] = [L10n::t('Contact information and Social Networks:'), $txt];
818                         }
819
820                         if ($txt = prepare_text($a->profile['music'])) {
821                                 $profile['music'] = [L10n::t('Musical interests:'), $txt];
822                         }
823
824                         if ($txt = prepare_text($a->profile['book'])) {
825                                 $profile['book'] = [L10n::t('Books, literature:'), $txt];
826                         }
827
828                         if ($txt = prepare_text($a->profile['tv'])) {
829                                 $profile['tv'] = [L10n::t('Television:'), $txt];
830                         }
831
832                         if ($txt = prepare_text($a->profile['film'])) {
833                                 $profile['film'] = [L10n::t('Film/dance/culture/entertainment:'), $txt];
834                         }
835
836                         if ($txt = prepare_text($a->profile['romance'])) {
837                                 $profile['romance'] = [L10n::t('Love/Romance:'), $txt];
838                         }
839
840                         if ($txt = prepare_text($a->profile['work'])) {
841                                 $profile['work'] = [L10n::t('Work/employment:'), $txt];
842                         }
843
844                         if ($txt = prepare_text($a->profile['education'])) {
845                                 $profile['education'] = [L10n::t('School/education:'), $txt];
846                         }
847
848                         //show subcribed forum if it is enabled in the usersettings
849                         if (Feature::isEnabled($uid, 'forumlist_profile')) {
850                                 $profile['forumlist'] = [L10n::t('Forums:'), ForumManager::profileAdvanced($uid)];
851                         }
852
853                         if ($a->profile['uid'] == local_user()) {
854                                 $profile['edit'] = [System::baseUrl() . '/profiles/' . $a->profile['id'], L10n::t('Edit profile'), '', L10n::t('Edit profile')];
855                         }
856
857                         return replace_macros($tpl, [
858                                 '$title' => L10n::t('Profile'),
859                                 '$basic' => L10n::t('Basic'),
860                                 '$advanced' => L10n::t('Advanced'),
861                                 '$profile' => $profile
862                         ]);
863                 }
864
865                 return '';
866         }
867
868         public static function getTabs($a, $is_owner = false, $nickname = null)
869         {
870                 if (is_null($nickname)) {
871                         $nickname = $a->user['nickname'];
872                 }
873
874                 $tab = false;
875                 if (x($_GET, 'tab')) {
876                         $tab = notags(trim($_GET['tab']));
877                 }
878
879                 $url = System::baseUrl() . '/profile/' . $nickname;
880
881                 $tabs = [
882                         [
883                                 'label' => L10n::t('Status'),
884                                 'url'   => $url,
885                                 'sel'   => !$tab && $a->argv[0] == 'profile' ? 'active' : '',
886                                 'title' => L10n::t('Status Messages and Posts'),
887                                 'id'    => 'status-tab',
888                                 'accesskey' => 'm',
889                         ],
890                         [
891                                 'label' => L10n::t('Profile'),
892                                 'url'   => $url . '/?tab=profile',
893                                 'sel'   => $tab == 'profile' ? 'active' : '',
894                                 'title' => L10n::t('Profile Details'),
895                                 'id'    => 'profile-tab',
896                                 'accesskey' => 'r',
897                         ],
898                         [
899                                 'label' => L10n::t('Photos'),
900                                 'url'   => System::baseUrl() . '/photos/' . $nickname,
901                                 'sel'   => !$tab && $a->argv[0] == 'photos' ? 'active' : '',
902                                 'title' => L10n::t('Photo Albums'),
903                                 'id'    => 'photo-tab',
904                                 'accesskey' => 'h',
905                         ],
906                         [
907                                 'label' => L10n::t('Videos'),
908                                 'url'   => System::baseUrl() . '/videos/' . $nickname,
909                                 'sel'   => !$tab && $a->argv[0] == 'videos' ? 'active' : '',
910                                 'title' => L10n::t('Videos'),
911                                 'id'    => 'video-tab',
912                                 'accesskey' => 'v',
913                         ],
914                 ];
915
916                 // the calendar link for the full featured events calendar
917                 if ($is_owner && $a->theme_events_in_profile) {
918                         $tabs[] = [
919                                 'label' => L10n::t('Events'),
920                                 'url'   => System::baseUrl() . '/events',
921                                 'sel'   => !$tab && $a->argv[0] == 'events' ? 'active' : '',
922                                 'title' => L10n::t('Events and Calendar'),
923                                 'id'    => 'events-tab',
924                                 'accesskey' => 'e',
925                         ];
926                         // if the user is not the owner of the calendar we only show a calendar
927                         // with the public events of the calendar owner
928                 } elseif (!$is_owner) {
929                         $tabs[] = [
930                                 'label' => L10n::t('Events'),
931                                 'url'   => System::baseUrl() . '/cal/' . $nickname,
932                                 'sel'   => !$tab && $a->argv[0] == 'cal' ? 'active' : '',
933                                 'title' => L10n::t('Events and Calendar'),
934                                 'id'    => 'events-tab',
935                                 'accesskey' => 'e',
936                         ];
937                 }
938
939                 if ($is_owner) {
940                         $tabs[] = [
941                                 'label' => L10n::t('Personal Notes'),
942                                 'url'   => System::baseUrl() . '/notes',
943                                 'sel'   => !$tab && $a->argv[0] == 'notes' ? 'active' : '',
944                                 'title' => L10n::t('Only You Can See This'),
945                                 'id'    => 'notes-tab',
946                                 'accesskey' => 't',
947                         ];
948                 }
949
950                 if (!$is_owner && empty($a->profile['hide-friends'])) {
951                         $tabs[] = [
952                                 'label' => L10n::t('Contacts'),
953                                 'url'   => System::baseUrl() . '/viewcontacts/' . $nickname,
954                                 'sel'   => !$tab && $a->argv[0] == 'viewcontacts' ? 'active' : '',
955                                 'title' => L10n::t('Contacts'),
956                                 'id'    => 'viewcontacts-tab',
957                                 'accesskey' => 'k',
958                         ];
959                 }
960
961                 $arr = ['is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => $tab, 'tabs' => $tabs];
962                 Addon::callHooks('profile_tabs', $arr);
963
964                 $tpl = get_markup_template('common_tabs.tpl');
965
966                 return replace_macros($tpl, ['$tabs' => $arr['tabs']]);
967         }
968
969         /**
970          * Retrieves the my_url session variable
971          *
972          * @return string
973          */
974         public static function getMyURL()
975         {
976                 if (x($_SESSION, 'my_url')) {
977                         return $_SESSION['my_url'];
978                 }
979                 return null;
980         }
981
982         /**
983          * Process the 'zrl' parameter and initiate the remote authentication.
984          * 
985          * This method checks if the visitor has a public contact entry and
986          * redirects the visitor to his/her instance to start the magic auth (Authentication)
987          * process.
988          * 
989          * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/channel.php
990          * 
991          * @param App $a Application instance.
992          */
993         public static function zrlInit(App $a)
994         {
995                 $my_url = self::getMyURL();
996                 $my_url = Network::isUrlValid($my_url);
997
998                 if ($my_url) {
999                         if (!local_user()) {
1000                                 // Is it a DDoS attempt?
1001                                 // The check fetches the cached value from gprobe to reduce the load for this system
1002                                 $urlparts = parse_url($my_url);
1003
1004                                 $result = Cache::get('gprobe:' . $urlparts['host']);
1005                                 if ((!is_null($result)) && (in_array($result['network'], [NETWORK_FEED, NETWORK_PHANTOM]))) {
1006                                         logger('DDoS attempt detected for ' . $urlparts['host'] . ' by ' . $_SERVER['REMOTE_ADDR'] . '. server data: ' . print_r($_SERVER, true), LOGGER_DEBUG);
1007                                         return;
1008                                 }
1009
1010                                 Worker::add(PRIORITY_LOW, 'GProbe', $my_url);
1011                                 $arr = ['zrl' => $my_url, 'url' => $a->cmd];
1012                                 Addon::callHooks('zrl_init', $arr);
1013
1014                                 // Try to find the public contact entry of the visitor.
1015                                 $cid = Contact::getIdForURL($my_url);
1016                                 if (!$cid) {
1017                                         logger('No contact record found for ' . $my_url, LOGGER_DEBUG);
1018                                         return;
1019                                 }
1020
1021                                 $contact = dba::selectFirst('contact',['id', 'url'], ['id' => $cid]);
1022
1023                                 if (DBM::is_result($contact) && remote_user() && remote_user() == $contact['id']) {
1024                                         // The visitor is already authenticated.
1025                                         return;
1026                                 }
1027
1028                                 logger('Not authenticated. Invoking reverse magic-auth for ' . $my_url, LOGGER_DEBUG);
1029
1030                                 // Try to avoid recursion - but send them home to do a proper magic auth.
1031                                 $query = str_replace(array('?zrl=', '&zid='), array('?rzrl=', '&rzrl='), $a->query_string);
1032                                 // The other instance needs to know where to redirect.
1033                                 $dest = urlencode(System::baseUrl() . '/' . $query);
1034
1035                                 // We need to extract the basebath from the profile url
1036                                 // to redirect the visitors '/magic' module.
1037                                 // Note: We should have the basepath of a contact also in the contact table.
1038                                 $urlarr = explode('/profile/', $contact['url']);
1039                                 $basepath = $urlarr[0];
1040
1041                                 if ($basepath != System::baseUrl() && !strstr($dest, '/magic') && !strstr($dest, '/rmagic')) {
1042                                         goaway($basepath . '/magic' . '?f=&owa=1&dest=' . $dest);
1043                                 }
1044                         }
1045                 }
1046         }
1047
1048         /**
1049          * OpenWebAuth authentication.
1050          *
1051          * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/zid.php
1052          * 
1053          * @param string $token
1054          */
1055         public static function openWebAuthInit($token)
1056         {
1057                 $a = get_app();
1058
1059                 // Clean old OpenWebAuthToken entries.
1060                 OpenWebAuthToken::purge('owt', '3 MINUTE');
1061
1062                 // Check if the token we got is the same one
1063                 // we have stored in the database.
1064                 $visitor_handle = OpenWebAuthToken::getMeta('owt', 0, $token);
1065
1066                 if($visitor_handle === false) {
1067                         return;
1068                 }
1069
1070                 // Try to find the public contact entry of the visitor.
1071                 $cid = Contact::getIdForURL($visitor_handle);
1072                 if(!$cid) {
1073                         logger('owt: unable to finger ' . $visitor_handle, LOGGER_DEBUG);
1074                         return;
1075                 }
1076
1077                 $visitor = dba::selectFirst('contact', [], ['id' => $cid]);
1078
1079                 // Authenticate the visitor.
1080                 $_SESSION['authenticated'] = 1;
1081                 $_SESSION['visitor_id'] = $visitor['id'];
1082                 $_SESSION['visitor_handle'] = $visitor['addr'];
1083                 $_SESSION['visitor_home'] = $visitor['url'];
1084
1085                 $arr = [
1086                         'visitor' => $visitor,
1087                         'url' => $a->query_string
1088                 ];
1089                 /**
1090                  * @hooks magic_auth_success
1091                  *   Called when a magic-auth was successful.
1092                  *   * \e array \b visitor
1093                  *   * \e string \b url
1094                  */
1095                 Addon::callHooks('magic_auth_success', $arr);
1096
1097                 $a->contact = $arr['visitor'];
1098
1099                 info(L10n::t('OpenWebAuth: %1$s welcomes %2$s', $a->get_hostname(), $visitor['name']));
1100
1101                 logger('OpenWebAuth: auth success from ' . $visitor['addr'], LOGGER_DEBUG);
1102         }
1103
1104         public static function zrl($s, $force = false)
1105         {
1106                 if (!strlen($s)) {
1107                         return $s;
1108                 }
1109                 if ((!strpos($s, '/profile/')) && (!$force)) {
1110                         return $s;
1111                 }
1112                 if ($force && substr($s, -1, 1) !== '/') {
1113                         $s = $s . '/';
1114                 }
1115                 $achar = strpos($s, '?') ? '&' : '?';
1116                 $mine = self::getMyURL();
1117                 if ($mine && !link_compare($mine, $s)) {
1118                         return $s . $achar . 'zrl=' . urlencode($mine);
1119                 }
1120                 return $s;
1121         }
1122
1123         /**
1124          * Get the user ID of the page owner.
1125          *
1126          * Used from within PCSS themes to set theme parameters. If there's a
1127          * puid request variable, that is the "page owner" and normally their theme
1128          * settings take precedence; unless a local user sets the "always_my_theme"
1129          * system pconfig, which means they don't want to see anybody else's theme
1130          * settings except their own while on this site.
1131          *
1132          * @brief Get the user ID of the page owner
1133          * @return int user ID
1134          *
1135          * @note Returns local_user instead of user ID if "always_my_theme"
1136          *      is set to true
1137          */
1138         public static function getThemeUid()
1139         {
1140                 $uid = ((!empty($_REQUEST['puid'])) ? intval($_REQUEST['puid']) : 0);
1141                 if ((local_user()) && ((PConfig::get(local_user(), 'system', 'always_my_theme')) || (!$uid))) {
1142                         return local_user();
1143                 }
1144
1145                 return $uid;
1146         }
1147
1148         /**
1149         * Stip zrl parameter from a string.
1150         * 
1151         * @param string $s The input string.
1152         * @return string The zrl.
1153         */
1154         public static function stripZrls($s)
1155         {
1156                 return preg_replace('/[\?&]zrl=(.*?)([\?&]|$)/is', '', $s);
1157         }
1158
1159         /**
1160         * Stip query parameter from a string.
1161         * 
1162         * @param string $s The input string.
1163         * @return string The query parameter.
1164         */
1165         public static function stripQueryParam($s, $param)
1166         {
1167                 return preg_replace('/[\?&]' . $param . '=(.*?)(&|$)/ism', '$2', $s);
1168         }
1169 }