]> git.mxchange.org Git - friendica.git/blob - src/Model/Profile.php
29bc7e680d1bbd3d7240c1af30de1997d6271575
[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\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\Protocol;
17 use Friendica\Core\System;
18 use Friendica\Core\Worker;
19 use Friendica\Database\DBA;
20 use Friendica\Model\Contact;
21 use Friendica\Protocol\Diaspora;
22 use Friendica\Util\DateTimeFormat;
23 use Friendica\Util\Network;
24 use Friendica\Util\Proxy as ProxyUtils;
25 use Friendica\Util\Temporal;
26
27 require_once 'include/dba.php';
28
29 class Profile
30 {
31         /**
32          * @brief Returns a formatted location string from the given profile array
33          *
34          * @param array $profile Profile array (Generated from the "profile" table)
35          *
36          * @return string Location string
37          */
38         public static function formatLocation(array $profile)
39         {
40                 $location = '';
41
42                 if (!empty($profile['locality'])) {
43                         $location .= $profile['locality'];
44                 }
45
46                 if (!empty($profile['region']) && (defaults($profile, 'locality', '') != $profile['region'])) {
47                         if ($location) {
48                                 $location .= ', ';
49                         }
50
51                         $location .= $profile['region'];
52                 }
53
54                 if (!empty($profile['country-name'])) {
55                         if ($location) {
56                                 $location .= ', ';
57                         }
58
59                         $location .= $profile['country-name'];
60                 }
61
62                 return $location;
63         }
64
65         /**
66          *
67          * Loads a profile into the page sidebar.
68          *
69          * The function requires a writeable copy of the main App structure, and the nickname
70          * of a registered local account.
71          *
72          * If the viewer is an authenticated remote viewer, the profile displayed is the
73          * one that has been configured for his/her viewing in the Contact manager.
74          * Passing a non-zero profile ID can also allow a preview of a selected profile
75          * by the owner.
76          *
77          * Profile information is placed in the App structure for later retrieval.
78          * Honours the owner's chosen theme for display.
79          *
80          * @attention Should only be run in the _init() functions of a module. That ensures that
81          *      the theme is chosen before the _init() function of a theme is run, which will usually
82          *      load a lot of theme-specific content
83          *
84          * @brief Loads a profile into the page sidebar.
85          * @param object  $a            App
86          * @param string  $nickname     string
87          * @param int     $profile      int
88          * @param array   $profiledata  array
89          * @param boolean $show_connect Show connect link
90          */
91         public static function load(App $a, $nickname, $profile = 0, array $profiledata = [], $show_connect = true)
92         {
93                 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nickname, 'account_removed' => false]);
94
95                 if (!DBA::isResult($user) && empty($profiledata)) {
96                         logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
97                         notice(L10n::t('Requested account is not available.') . EOL);
98                         $a->error = 404;
99                         return;
100                 }
101
102                 if (count($profiledata) > 0) {
103                         // Add profile data to sidebar
104                         $a->page['aside'] .= self::sidebar($profiledata, true, $show_connect);
105
106                         if (!DBA::isResult($user)) {
107                                 return;
108                         }
109                 }
110
111                 $pdata = self::getByNickname($nickname, $user['uid'], $profile);
112
113                 if (empty($pdata) && empty($profiledata)) {
114                         logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
115                         notice(L10n::t('Requested profile is not available.') . EOL);
116                         $a->error = 404;
117                         return;
118                 }
119
120                 if (empty($pdata)) {
121                         $pdata = ['uid' => 0, 'profile_uid' => 0, 'is-default' => false,'name' => $nickname];
122                 }
123
124                 // fetch user tags if this isn't the default profile
125
126                 if (!$pdata['is-default']) {
127                         $condition = ['uid' => $pdata['profile_uid'], 'is-default' => true];
128                         $profile = DBA::selectFirst('profile', ['pub_keywords'], $condition);
129                         if (DBA::isResult($profile)) {
130                                 $pdata['pub_keywords'] = $profile['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'] = Protocol::DFRN;
139
140                 $a->page['title'] = $a->profile['name'] . ' @ ' . Config::get('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/' . $a->getCurrentTheme() . '/theme.php';
155                 if (file_exists($theme_info_file)) {
156                         require_once $theme_info_file;
157                 }
158
159                 if (local_user() && local_user() == $a->profile['uid'] && $profiledata) {
160                         $a->page['aside'] .= replace_macros(
161                                 get_markup_template('profile_edlink.tpl'),
162                                 [
163                                         '$editprofile' => L10n::t('Edit profile'),
164                                         '$profid' => $a->profile['id']
165                                 ]
166                         );
167                 }
168
169                 $block = ((Config::get('system', 'block_public') && !local_user() && !remote_user()) ? true : false);
170
171                 /**
172                  * @todo
173                  * By now, the contact block isn't shown, when a different profile is given
174                  * But: When this profile was on the same server, then we could display the contacts
175                  */
176                 if (!$profiledata) {
177                         $a->page['aside'] .= self::sidebar($a->profile, $block, $show_connect);
178                 }
179
180                 return;
181         }
182
183         /**
184          * Get all profile data of a local user
185          *
186          * If the viewer is an authenticated remote viewer, the profile displayed is the
187          * one that has been configured for his/her viewing in the Contact manager.
188          * Passing a non-zero profile ID can also allow a preview of a selected profile
189          * by the owner
190          *
191          * Includes all available profile data
192          *
193          * @brief Get all profile data of a local user
194          * @param string $nickname nick
195          * @param int    $uid      uid
196          * @param int    $profile_id  ID of the profile
197          * @return array
198          */
199         public static function getByNickname($nickname, $uid = 0, $profile_id = 0)
200         {
201                 if (remote_user() && !empty($_SESSION['remote'])) {
202                         foreach ($_SESSION['remote'] as $visitor) {
203                                 if ($visitor['uid'] == $uid) {
204                                         $contact = DBA::selectFirst('contact', ['profile-id'], ['id' => $visitor['cid']]);
205                                         if (DBA::isResult($contact)) {
206                                                 $profile_id = $contact['profile-id'];
207                                         }
208                                         break;
209                                 }
210                         }
211                 }
212
213                 $profile = null;
214
215                 if ($profile_id) {
216                         $profile = DBA::fetchFirst(
217                                 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` AS `contact_photo`,
218                                         `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
219                                         `profile`.`uid` AS `profile_uid`, `profile`.*,
220                                         `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
221                                 FROM `profile`
222                                 INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
223                                 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
224                                 WHERE `user`.`nickname` = ? AND `profile`.`id` = ? LIMIT 1",
225                                 $nickname,
226                                 intval($profile_id)
227                         );
228                 }
229                 if (!DBA::isResult($profile)) {
230                         $profile = DBA::fetchFirst(
231                                 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` as `contact_photo`,
232                                         `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
233                                         `profile`.`uid` AS `profile_uid`, `profile`.*,
234                                         `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
235                                 FROM `profile`
236                                 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
237                                 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
238                                 WHERE `user`.`nickname` = ? AND `profile`.`is-default` LIMIT 1",
239                                 $nickname
240                         );
241                 }
242
243                 return $profile;
244         }
245
246         /**
247          * Formats a profile for display in the sidebar.
248          *
249          * It is very difficult to templatise the HTML completely
250          * because of all the conditional logic.
251          *
252          * @brief Formats a profile for display in the sidebar.
253          * @param array $profile
254          * @param int $block
255          * @param boolean $show_connect Show connect link
256          *
257          * @return string HTML sidebar module
258          *
259          * @note Returns empty string if passed $profile is wrong type or not populated
260          *
261          * @hooks 'profile_sidebar_enter'
262          *      array $profile - profile data
263          * @hooks 'profile_sidebar'
264          *      array $arr
265          */
266         private static function sidebar($profile, $block = 0, $show_connect = true)
267         {
268                 $a = get_app();
269
270                 $o = '';
271                 $location = false;
272
273                 // This function can also use contact information in $profile
274                 $is_contact = x($profile, 'cid');
275
276                 if (!is_array($profile) && !count($profile)) {
277                         return $o;
278                 }
279
280                 $profile['picdate'] = urlencode(defaults($profile, 'picdate', ''));
281
282                 if (($profile['network'] != '') && ($profile['network'] != Protocol::DFRN)) {
283                         $profile['network_name'] = format_network_name($profile['network'], $profile['url']);
284                 } else {
285                         $profile['network_name'] = '';
286                 }
287
288                 Addon::callHooks('profile_sidebar_enter', $profile);
289
290
291                 // don't show connect link to yourself
292                 $connect = $profile['uid'] != local_user() ? L10n::t('Connect') : false;
293
294                 // don't show connect link to authenticated visitors either
295                 if (remote_user() && !empty($_SESSION['remote'])) {
296                         foreach ($_SESSION['remote'] as $visitor) {
297                                 if ($visitor['uid'] == $profile['uid']) {
298                                         $connect = false;
299                                         break;
300                                 }
301                         }
302                 }
303
304                 if (!$show_connect) {
305                         $connect = false;
306                 }
307
308                 $profile_url = '';
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'] != Protocol::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'] == Protocol::DFRN) && !isset($remoteconnect)) {
333                         $subscribe_feed = L10n::t('Atom feed');
334                 } else {
335                         $subscribe_feed = false;
336                 }
337
338                 $wallmessage = false;
339                 $wallmessage_link = false;
340
341                 // See issue https://github.com/friendica/friendica/issues/3838
342                 // Either we remove the message link for remote users or we enable creating messages from remote users
343                 if (remote_user() || (self::getMyURL() && x($profile, 'unkmail') && ($profile['uid'] != local_user()))) {
344                         $wallmessage = L10n::t('Message');
345
346                         if (remote_user()) {
347                                 $r = q(
348                                         "SELECT `url` FROM `contact` WHERE `uid` = %d AND `id` = '%s' AND `rel` = %d",
349                                         intval($profile['uid']),
350                                         intval(remote_user()),
351                                         intval(Contact::FRIEND)
352                                 );
353                         } else {
354                                 $r = q(
355                                         "SELECT `url` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `rel` = %d",
356                                         intval($profile['uid']),
357                                         DBA::escape(normalise_link(self::getMyURL())),
358                                         intval(Contact::FRIEND)
359                                 );
360                         }
361                         if ($r) {
362                                 $remote_url = $r[0]['url'];
363                                 $message_path = preg_replace('=(.*)/profile/(.*)=ism', '$1/message/new/', $remote_url);
364                                 $wallmessage_link = $message_path . base64_encode($profile['addr']);
365                         } else if (!empty($profile['nickname'])) {
366                                 $wallmessage_link = 'wallmessage/' . $profile['nickname'];
367                         }
368                 }
369
370                 // show edit profile to yourself
371                 if (!$is_contact && $profile['uid'] == local_user() && Feature::isEnabled(local_user(), 'multi_profiles')) {
372                         $profile['edit'] = [System::baseUrl() . '/profiles', L10n::t('Profiles'), '', L10n::t('Manage/edit profiles')];
373                         $r = q(
374                                 "SELECT * FROM `profile` WHERE `uid` = %d",
375                                 local_user()
376                         );
377
378                         $profile['menu'] = [
379                                 'chg_photo' => L10n::t('Change profile photo'),
380                                 'cr_new' => L10n::t('Create New Profile'),
381                                 'entries' => [],
382                         ];
383
384                         if (DBA::isResult($r)) {
385                                 foreach ($r as $rr) {
386                                         $profile['menu']['entries'][] = [
387                                                 'photo' => $rr['thumb'],
388                                                 'id' => $rr['id'],
389                                                 'alt' => L10n::t('Profile Image'),
390                                                 'profile_name' => $rr['profile-name'],
391                                                 'isdefault' => $rr['is-default'],
392                                                 'visibile_to_everybody' => L10n::t('visible to everybody'),
393                                                 'edit_visibility' => L10n::t('Edit visibility'),
394                                         ];
395                                 }
396                         }
397                 }
398                 if (!$is_contact && $profile['uid'] == local_user() && !Feature::isEnabled(local_user(), 'multi_profiles')) {
399                         $profile['edit'] = [System::baseUrl() . '/profiles/' . $profile['id'], L10n::t('Edit profile'), '', L10n::t('Edit profile')];
400                         $profile['menu'] = [
401                                 'chg_photo' => L10n::t('Change profile photo'),
402                                 'cr_new' => null,
403                                 'entries' => [],
404                         ];
405                 }
406
407                 // Fetch the account type
408                 $account_type = Contact::getAccountType($profile);
409
410                 if (x($profile, 'address')
411                         || x($profile, 'location')
412                         || x($profile, 'locality')
413                         || x($profile, 'region')
414                         || x($profile, 'postal-code')
415                         || x($profile, 'country-name')
416                 ) {
417                         $location = L10n::t('Location:');
418                 }
419
420                 $gender   = x($profile, 'gender')   ? L10n::t('Gender:')   : false;
421                 $marital  = x($profile, 'marital')  ? L10n::t('Status:')   : false;
422                 $homepage = x($profile, 'homepage') ? L10n::t('Homepage:') : false;
423                 $about    = x($profile, 'about')    ? L10n::t('About:')    : false;
424                 $xmpp     = x($profile, 'xmpp')     ? L10n::t('XMPP:')     : false;
425
426                 if ((x($profile, 'hidewall') || $block) && !local_user() && !remote_user()) {
427                         $location = $gender = $marital = $homepage = $about = false;
428                 }
429
430                 $split_name = Diaspora::splitName($profile['name']);
431                 $firstname = $split_name['first'];
432                 $lastname = $split_name['last'];
433
434                 if (x($profile, 'guid')) {
435                         $diaspora = [
436                                 'guid' => $profile['guid'],
437                                 'podloc' => System::baseUrl(),
438                                 'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false' ),
439                                 'nickname' => $profile['nickname'],
440                                 'fullname' => $profile['name'],
441                                 'firstname' => $firstname,
442                                 'lastname' => $lastname,
443                                 'photo300' => defaults($profile, 'contact_photo', ''),
444                                 'photo100' => defaults($profile, 'contact_thumb', ''),
445                                 'photo50' => defaults($profile, 'contact_micro', ''),
446                         ];
447                 } else {
448                         $diaspora = false;
449                 }
450
451                 $contact_block = '';
452                 $updated = '';
453                 $contacts = 0;
454                 if (!$block) {
455                         $contact_block = contact_block();
456
457                         if (is_array($a->profile) && !$a->profile['hide-friends']) {
458                                 $r = q(
459                                         "SELECT `gcontact`.`updated` FROM `contact` INNER JOIN `gcontact` WHERE `gcontact`.`nurl` = `contact`.`nurl` AND `self` AND `uid` = %d LIMIT 1",
460                                         intval($a->profile['uid'])
461                                 );
462                                 if (DBA::isResult($r)) {
463                                         $updated = date('c', strtotime($r[0]['updated']));
464                                 }
465
466                                 $r = q(
467                                         "SELECT COUNT(*) AS `total` FROM `contact`
468                                         WHERE `uid` = %d
469                                                 AND NOT `self` AND NOT `blocked` AND NOT `pending`
470                                                 AND NOT `hidden` AND NOT `archive`
471                                                 AND `network` IN ('%s', '%s', '%s', '')",
472                                         intval($profile['uid']),
473                                         DBA::escape(Protocol::DFRN),
474                                         DBA::escape(Protocol::DIASPORA),
475                                         DBA::escape(Protocol::OSTATUS)
476                                 );
477                                 if (DBA::isResult($r)) {
478                                         $contacts = intval($r[0]['total']);
479                                 }
480                         }
481                 }
482
483                 $p = [];
484                 foreach ($profile as $k => $v) {
485                         $k = str_replace('-', '_', $k);
486                         $p[$k] = $v;
487                 }
488
489                 if (isset($p['about'])) {
490                         $p['about'] = BBCode::convert($p['about']);
491                 }
492
493                 if (isset($p['address'])) {
494                         $p['address'] = BBCode::convert($p['address']);
495                 } elseif (isset($p['location'])) {
496                         $p['address'] = BBCode::convert($p['location']);
497                 }
498
499                 if (isset($p['photo'])) {
500                         $p['photo'] = ProxyUtils::proxifyUrl($p['photo'], false, ProxyUtils::SIZE_SMALL);
501                 }
502
503                 $p['url'] = Contact::magicLink(defaults($p, 'url', $profile_url));
504
505                 $tpl = get_markup_template('profile_vcard.tpl');
506                 $o .= replace_macros($tpl, [
507                         '$profile' => $p,
508                         '$xmpp' => $xmpp,
509                         '$connect' => $connect,
510                         '$remoteconnect' => $remoteconnect,
511                         '$subscribe_feed' => $subscribe_feed,
512                         '$wallmessage' => $wallmessage,
513                         '$wallmessage_link' => $wallmessage_link,
514                         '$account_type' => $account_type,
515                         '$location' => $location,
516                         '$gender' => $gender,
517                         '$marital' => $marital,
518                         '$homepage' => $homepage,
519                         '$about' => $about,
520                         '$network' => L10n::t('Network:'),
521                         '$contacts' => $contacts,
522                         '$updated' => $updated,
523                         '$diaspora' => $diaspora,
524                         '$contact_block' => $contact_block,
525                 ]);
526
527                 $arr = ['profile' => &$profile, 'entry' => &$o];
528
529                 Addon::callHooks('profile_sidebar', $arr);
530
531                 return $o;
532         }
533
534         public static function getBirthdays()
535         {
536                 $a = get_app();
537                 $o = '';
538
539                 if (!local_user() || $a->is_mobile || $a->is_tablet) {
540                         return $o;
541                 }
542
543                 /*
544                 * $mobile_detect = new Mobile_Detect();
545                 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
546                 *               if ($is_mobile)
547                 *                       return $o;
548                 */
549
550                 $bd_format = L10n::t('g A l F d'); // 8 AM Friday January 18
551                 $bd_short = L10n::t('F d');
552
553                 $cachekey = 'get_birthdays:' . local_user();
554                 $r = Cache::get($cachekey);
555                 if (is_null($r)) {
556                         $s = DBA::p(
557                                 "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
558                                 INNER JOIN `contact` ON `contact`.`id` = `event`.`cid`
559                                 WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
560                                 ORDER BY `start` ASC ",
561                                 local_user(),
562                                 DateTimeFormat::utc('now + 6 days'),
563                                 DateTimeFormat::utcNow()
564                         );
565                         if (DBA::isResult($s)) {
566                                 $r = DBA::toArray($s);
567                                 Cache::set($cachekey, $r, CACHE_HOUR);
568                         }
569                 }
570
571                 $total = 0;
572                 $classtoday = '';
573                 if (DBA::isResult($r)) {
574                         $now = strtotime('now');
575                         $cids = [];
576
577                         $istoday = false;
578                         foreach ($r as $rr) {
579                                 if (strlen($rr['name'])) {
580                                         $total ++;
581                                 }
582                                 if ((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) {
583                                         $istoday = true;
584                                 }
585                         }
586                         $classtoday = $istoday ? ' birthday-today ' : '';
587                         if ($total) {
588                                 foreach ($r as &$rr) {
589                                         if (!strlen($rr['name'])) {
590                                                 continue;
591                                         }
592
593                                         // avoid duplicates
594
595                                         if (in_array($rr['cid'], $cids)) {
596                                                 continue;
597                                         }
598                                         $cids[] = $rr['cid'];
599
600                                         $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
601
602                                         $rr['link'] = Contact::magicLink($rr['url']);
603                                         $rr['title'] = $rr['name'];
604                                         $rr['date'] = day_translate(DateTimeFormat::convert($rr['start'], $a->timezone, 'UTC', $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . L10n::t('[today]') : '');
605                                         $rr['startime'] = null;
606                                         $rr['today'] = $today;
607                                 }
608                         }
609                 }
610                 $tpl = get_markup_template('birthdays_reminder.tpl');
611                 return replace_macros($tpl, [
612                         '$baseurl' => System::baseUrl(),
613                         '$classtoday' => $classtoday,
614                         '$count' => $total,
615                         '$event_reminders' => L10n::t('Birthday Reminders'),
616                         '$event_title' => L10n::t('Birthdays this week:'),
617                         '$events' => $r,
618                         '$lbr' => '{', // raw brackets mess up if/endif macro processing
619                         '$rbr' => '}'
620                 ]);
621         }
622
623         public static function getEventsReminderHTML()
624         {
625                 $a = get_app();
626                 $o = '';
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                 $condition = ["`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?",
643                         local_user(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utc('now - 1 days')];
644                 $s = DBA::select('event', [], $condition, ['order' => ['start']]);
645
646                 $r = [];
647
648                 if (DBA::isResult($s)) {
649                         $istoday = false;
650                         $total = 0;
651
652                         while ($rr = DBA::fetch($s)) {
653                                 $condition = ['parent-uri' => $rr['uri'], 'uid' => $rr['uid'], 'author-id' => public_contact(),
654                                         'activity' => [Item::activityToIndex(ACTIVITY_ATTEND), Item::activityToIndex(ACTIVITY_ATTENDMAYBE)],
655                                         'visible' => true, 'deleted' => false];
656                                 if (!Item::exists($condition)) {
657                                         continue;
658                                 }
659
660                                 if (strlen($rr['summary'])) {
661                                         $total++;
662                                 }
663
664                                 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', 'Y-m-d');
665                                 if ($strt === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
666                                         $istoday = true;
667                                 }
668
669                                 $title = strip_tags(html_entity_decode(BBCode::convert($rr['summary']), ENT_QUOTES, 'UTF-8'));
670
671                                 if (strlen($title) > 35) {
672                                         $title = substr($title, 0, 32) . '... ';
673                                 }
674
675                                 $description = substr(strip_tags(BBCode::convert($rr['desc'])), 0, 32) . '... ';
676                                 if (!$description) {
677                                         $description = L10n::t('[No description]');
678                                 }
679
680                                 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC');
681
682                                 if (substr($strt, 0, 10) < DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
683                                         continue;
684                                 }
685
686                                 $today = ((substr($strt, 0, 10) === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) ? true : false);
687
688                                 $rr['title'] = $title;
689                                 $rr['description'] = $description;
690                                 $rr['date'] = day_translate(DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', $bd_format)) . (($today) ? ' ' . L10n::t('[today]') : '');
691                                 $rr['startime'] = $strt;
692                                 $rr['today'] = $today;
693
694                                 $r[] = $rr;
695                         }
696                         DBA::close($s);
697                         $classtoday = (($istoday) ? 'event-today' : '');
698                 }
699                 $tpl = get_markup_template('events_reminder.tpl');
700                 return replace_macros($tpl, [
701                         '$baseurl' => System::baseUrl(),
702                         '$classtoday' => $classtoday,
703                         '$count' => count($r),
704                         '$event_reminders' => L10n::t('Event Reminders'),
705                         '$event_title' => L10n::t('Upcoming events the next 7 days:'),
706                         '$events' => $r,
707                 ]);
708         }
709
710         public static function getAdvanced(App $a)
711         {
712                 $o = '';
713                 $uid = $a->profile['uid'];
714
715                 $o .= replace_macros(
716                         get_markup_template('section_title.tpl'),
717                         ['$title' => L10n::t('Profile')]
718                 );
719
720                 if ($a->profile['name']) {
721                         $tpl = get_markup_template('profile_advanced.tpl');
722
723                         $profile = [];
724
725                         $profile['fullname'] = [L10n::t('Full Name:'), $a->profile['name']];
726
727                         if (Feature::isEnabled($uid, 'profile_membersince')) {
728                                 $profile['membersince'] = [L10n::t('Member since:'), DateTimeFormat::local($a->profile['register_date'])];
729                         }
730
731                         if ($a->profile['gender']) {
732                                 $profile['gender'] = [L10n::t('Gender:'), $a->profile['gender']];
733                         }
734
735                         if (($a->profile['dob']) && ($a->profile['dob'] > '0001-01-01')) {
736                                 $year_bd_format = L10n::t('j F, Y');
737                                 $short_bd_format = L10n::t('j F');
738
739                                 $val = day_translate(
740                                         intval($a->profile['dob']) ?
741                                                 DateTimeFormat::utc($a->profile['dob'] . ' 00:00 +00:00', $year_bd_format)
742                                                 : DateTimeFormat::utc('2001-' . substr($a->profile['dob'], 5) . ' 00:00 +00:00', $short_bd_format)
743                                 );
744
745                                 $profile['birthday'] = [L10n::t('Birthday:'), $val];
746                         }
747
748                         if (!empty($a->profile['dob'])
749                                 && $a->profile['dob'] > '0001-01-01'
750                                 && $age = Temporal::getAgeByTimezone($a->profile['dob'], $a->profile['timezone'], '')
751                         ) {
752                                 $profile['age'] = [L10n::t('Age:'), $age];
753                         }
754
755                         if ($a->profile['marital']) {
756                                 $profile['marital'] = [L10n::t('Status:'), $a->profile['marital']];
757                         }
758
759                         /// @TODO Maybe use x() here, plus below?
760                         if ($a->profile['with']) {
761                                 $profile['marital']['with'] = $a->profile['with'];
762                         }
763
764                         if (strlen($a->profile['howlong']) && $a->profile['howlong'] >= NULL_DATE) {
765                                 $profile['howlong'] = Temporal::getRelativeDate($a->profile['howlong'], L10n::t('for %1$d %2$s'));
766                         }
767
768                         if ($a->profile['sexual']) {
769                                 $profile['sexual'] = [L10n::t('Sexual Preference:'), $a->profile['sexual']];
770                         }
771
772                         if ($a->profile['homepage']) {
773                                 $profile['homepage'] = [L10n::t('Homepage:'), linkify($a->profile['homepage'])];
774                         }
775
776                         if ($a->profile['hometown']) {
777                                 $profile['hometown'] = [L10n::t('Hometown:'), linkify($a->profile['hometown'])];
778                         }
779
780                         if ($a->profile['pub_keywords']) {
781                                 $profile['pub_keywords'] = [L10n::t('Tags:'), $a->profile['pub_keywords']];
782                         }
783
784                         if ($a->profile['politic']) {
785                                 $profile['politic'] = [L10n::t('Political Views:'), $a->profile['politic']];
786                         }
787
788                         if ($a->profile['religion']) {
789                                 $profile['religion'] = [L10n::t('Religion:'), $a->profile['religion']];
790                         }
791
792                         if ($txt = prepare_text($a->profile['about'])) {
793                                 $profile['about'] = [L10n::t('About:'), $txt];
794                         }
795
796                         if ($txt = prepare_text($a->profile['interest'])) {
797                                 $profile['interest'] = [L10n::t('Hobbies/Interests:'), $txt];
798                         }
799
800                         if ($txt = prepare_text($a->profile['likes'])) {
801                                 $profile['likes'] = [L10n::t('Likes:'), $txt];
802                         }
803
804                         if ($txt = prepare_text($a->profile['dislikes'])) {
805                                 $profile['dislikes'] = [L10n::t('Dislikes:'), $txt];
806                         }
807
808                         if ($txt = prepare_text($a->profile['contact'])) {
809                                 $profile['contact'] = [L10n::t('Contact information and Social Networks:'), $txt];
810                         }
811
812                         if ($txt = prepare_text($a->profile['music'])) {
813                                 $profile['music'] = [L10n::t('Musical interests:'), $txt];
814                         }
815
816                         if ($txt = prepare_text($a->profile['book'])) {
817                                 $profile['book'] = [L10n::t('Books, literature:'), $txt];
818                         }
819
820                         if ($txt = prepare_text($a->profile['tv'])) {
821                                 $profile['tv'] = [L10n::t('Television:'), $txt];
822                         }
823
824                         if ($txt = prepare_text($a->profile['film'])) {
825                                 $profile['film'] = [L10n::t('Film/dance/culture/entertainment:'), $txt];
826                         }
827
828                         if ($txt = prepare_text($a->profile['romance'])) {
829                                 $profile['romance'] = [L10n::t('Love/Romance:'), $txt];
830                         }
831
832                         if ($txt = prepare_text($a->profile['work'])) {
833                                 $profile['work'] = [L10n::t('Work/employment:'), $txt];
834                         }
835
836                         if ($txt = prepare_text($a->profile['education'])) {
837                                 $profile['education'] = [L10n::t('School/education:'), $txt];
838                         }
839
840                         //show subcribed forum if it is enabled in the usersettings
841                         if (Feature::isEnabled($uid, 'forumlist_profile')) {
842                                 $profile['forumlist'] = [L10n::t('Forums:'), ForumManager::profileAdvanced($uid)];
843                         }
844
845                         if ($a->profile['uid'] == local_user()) {
846                                 $profile['edit'] = [System::baseUrl() . '/profiles/' . $a->profile['id'], L10n::t('Edit profile'), '', L10n::t('Edit profile')];
847                         }
848
849                         return replace_macros($tpl, [
850                                 '$title' => L10n::t('Profile'),
851                                 '$basic' => L10n::t('Basic'),
852                                 '$advanced' => L10n::t('Advanced'),
853                                 '$profile' => $profile
854                         ]);
855                 }
856
857                 return '';
858         }
859
860         public static function getTabs($a, $is_owner = false, $nickname = null)
861         {
862                 if (is_null($nickname)) {
863                         $nickname = $a->user['nickname'];
864                 }
865
866                 $tab = false;
867                 if (x($_GET, 'tab')) {
868                         $tab = notags(trim($_GET['tab']));
869                 }
870
871                 $url = System::baseUrl() . '/profile/' . $nickname;
872
873                 $tabs = [
874                         [
875                                 'label' => L10n::t('Status'),
876                                 'url'   => $url,
877                                 'sel'   => !$tab && $a->argv[0] == 'profile' ? 'active' : '',
878                                 'title' => L10n::t('Status Messages and Posts'),
879                                 'id'    => 'status-tab',
880                                 'accesskey' => 'm',
881                         ],
882                         [
883                                 'label' => L10n::t('Profile'),
884                                 'url'   => $url . '/?tab=profile',
885                                 'sel'   => $tab == 'profile' ? 'active' : '',
886                                 'title' => L10n::t('Profile Details'),
887                                 'id'    => 'profile-tab',
888                                 'accesskey' => 'r',
889                         ],
890                         [
891                                 'label' => L10n::t('Photos'),
892                                 'url'   => System::baseUrl() . '/photos/' . $nickname,
893                                 'sel'   => !$tab && $a->argv[0] == 'photos' ? 'active' : '',
894                                 'title' => L10n::t('Photo Albums'),
895                                 'id'    => 'photo-tab',
896                                 'accesskey' => 'h',
897                         ],
898                         [
899                                 'label' => L10n::t('Videos'),
900                                 'url'   => System::baseUrl() . '/videos/' . $nickname,
901                                 'sel'   => !$tab && $a->argv[0] == 'videos' ? 'active' : '',
902                                 'title' => L10n::t('Videos'),
903                                 'id'    => 'video-tab',
904                                 'accesskey' => 'v',
905                         ],
906                 ];
907
908                 // the calendar link for the full featured events calendar
909                 if ($is_owner && $a->theme_events_in_profile) {
910                         $tabs[] = [
911                                 'label' => L10n::t('Events'),
912                                 'url'   => System::baseUrl() . '/events',
913                                 'sel'   => !$tab && $a->argv[0] == 'events' ? 'active' : '',
914                                 'title' => L10n::t('Events and Calendar'),
915                                 'id'    => 'events-tab',
916                                 'accesskey' => 'e',
917                         ];
918                         // if the user is not the owner of the calendar we only show a calendar
919                         // with the public events of the calendar owner
920                 } elseif (!$is_owner) {
921                         $tabs[] = [
922                                 'label' => L10n::t('Events'),
923                                 'url'   => System::baseUrl() . '/cal/' . $nickname,
924                                 'sel'   => !$tab && $a->argv[0] == 'cal' ? 'active' : '',
925                                 'title' => L10n::t('Events and Calendar'),
926                                 'id'    => 'events-tab',
927                                 'accesskey' => 'e',
928                         ];
929                 }
930
931                 if ($is_owner) {
932                         $tabs[] = [
933                                 'label' => L10n::t('Personal Notes'),
934                                 'url'   => System::baseUrl() . '/notes',
935                                 'sel'   => !$tab && $a->argv[0] == 'notes' ? 'active' : '',
936                                 'title' => L10n::t('Only You Can See This'),
937                                 'id'    => 'notes-tab',
938                                 'accesskey' => 't',
939                         ];
940                 }
941
942                 if (!empty($_SESSION['new_member']) && $is_owner) {
943                         $tabs[] = [
944                                 'label' => L10n::t('Tips for New Members'),
945                                 'url'   => System::baseUrl() . '/newmember',
946                                 'sel'   => false,
947                                 'title' => L10n::t('Tips for New Members'),
948                                 'id'    => 'newmember-tab',
949                         ];
950                 }
951
952                 if (!$is_owner && empty($a->profile['hide-friends'])) {
953                         $tabs[] = [
954                                 'label' => L10n::t('Contacts'),
955                                 'url'   => System::baseUrl() . '/viewcontacts/' . $nickname,
956                                 'sel'   => !$tab && $a->argv[0] == 'viewcontacts' ? 'active' : '',
957                                 'title' => L10n::t('Contacts'),
958                                 'id'    => 'viewcontacts-tab',
959                                 'accesskey' => 'k',
960                         ];
961                 }
962
963                 $arr = ['is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => $tab, 'tabs' => $tabs];
964                 Addon::callHooks('profile_tabs', $arr);
965
966                 $tpl = get_markup_template('common_tabs.tpl');
967
968                 return replace_macros($tpl, ['$tabs' => $arr['tabs']]);
969         }
970
971         /**
972          * Retrieves the my_url session variable
973          *
974          * @return string
975          */
976         public static function getMyURL()
977         {
978                 if (x($_SESSION, 'my_url')) {
979                         return $_SESSION['my_url'];
980                 }
981                 return null;
982         }
983
984         /**
985          * Process the 'zrl' parameter and initiate the remote authentication.
986          *
987          * This method checks if the visitor has a public contact entry and
988          * redirects the visitor to his/her instance to start the magic auth (Authentication)
989          * process.
990          *
991          * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/channel.php
992          *
993          * @param App $a Application instance.
994          */
995         public static function zrlInit(App $a)
996         {
997                 $my_url = self::getMyURL();
998                 $my_url = Network::isUrlValid($my_url);
999
1000                 if ($my_url) {
1001                         if (!local_user()) {
1002                                 // Is it a DDoS attempt?
1003                                 // The check fetches the cached value from gprobe to reduce the load for this system
1004                                 $urlparts = parse_url($my_url);
1005
1006                                 $result = Cache::get('gprobe:' . $urlparts['host']);
1007                                 if ((!is_null($result)) && (in_array($result['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
1008                                         logger('DDoS attempt detected for ' . $urlparts['host'] . ' by ' . $_SERVER['REMOTE_ADDR'] . '. server data: ' . print_r($_SERVER, true), LOGGER_DEBUG);
1009                                         return;
1010                                 }
1011
1012                                 Worker::add(PRIORITY_LOW, 'GProbe', $my_url);
1013                                 $arr = ['zrl' => $my_url, 'url' => $a->cmd];
1014                                 Addon::callHooks('zrl_init', $arr);
1015
1016                                 // Try to find the public contact entry of the visitor.
1017                                 $cid = Contact::getIdForURL($my_url);
1018                                 if (!$cid) {
1019                                         logger('No contact record found for ' . $my_url, LOGGER_DEBUG);
1020                                         return;
1021                                 }
1022
1023                                 $contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]);
1024
1025                                 if (DBA::isResult($contact) && remote_user() && remote_user() == $contact['id']) {
1026                                         // The visitor is already authenticated.
1027                                         return;
1028                                 }
1029
1030                                 logger('Not authenticated. Invoking reverse magic-auth for ' . $my_url, LOGGER_DEBUG);
1031
1032                                 // Try to avoid recursion - but send them home to do a proper magic auth.
1033                                 $query = str_replace(array('?zrl=', '&zid='), array('?rzrl=', '&rzrl='), $a->query_string);
1034                                 // The other instance needs to know where to redirect.
1035                                 $dest = urlencode(System::baseUrl() . '/' . $query);
1036
1037                                 // We need to extract the basebath from the profile url
1038                                 // to redirect the visitors '/magic' module.
1039                                 // Note: We should have the basepath of a contact also in the contact table.
1040                                 $urlarr = explode('/profile/', $contact['url']);
1041                                 $basepath = $urlarr[0];
1042
1043                                 if ($basepath != System::baseUrl() && !strstr($dest, '/magic') && !strstr($dest, '/rmagic')) {
1044                                         $magic_path = $basepath . '/magic' . '?f=&owa=1&dest=' . $dest;
1045                                         $serverret = Network::curl($magic_path);
1046                                         if (!empty($serverret['success'])) {
1047                                                 goaway($magic_path);
1048                                         }
1049                                 }
1050                         }
1051                 }
1052         }
1053
1054         /**
1055          * OpenWebAuth authentication.
1056          *
1057          * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/zid.php
1058          *
1059          * @param string $token
1060          */
1061         public static function openWebAuthInit($token)
1062         {
1063                 $a = get_app();
1064
1065                 // Clean old OpenWebAuthToken entries.
1066                 OpenWebAuthToken::purge('owt', '3 MINUTE');
1067
1068                 // Check if the token we got is the same one
1069                 // we have stored in the database.
1070                 $visitor_handle = OpenWebAuthToken::getMeta('owt', 0, $token);
1071
1072                 if($visitor_handle === false) {
1073                         return;
1074                 }
1075
1076                 // Try to find the public contact entry of the visitor.
1077                 $cid = Contact::getIdForURL($visitor_handle);
1078                 if(!$cid) {
1079                         logger('owt: unable to finger ' . $visitor_handle, LOGGER_DEBUG);
1080                         return;
1081                 }
1082
1083                 $visitor = DBA::selectFirst('contact', [], ['id' => $cid]);
1084
1085                 // Authenticate the visitor.
1086                 $_SESSION['authenticated'] = 1;
1087                 $_SESSION['visitor_id'] = $visitor['id'];
1088                 $_SESSION['visitor_handle'] = $visitor['addr'];
1089                 $_SESSION['visitor_home'] = $visitor['url'];
1090                 $_SESSION['my_url'] = $visitor['url'];
1091
1092                 $arr = [
1093                         'visitor' => $visitor,
1094                         'url' => $a->query_string
1095                 ];
1096                 /**
1097                  * @hooks magic_auth_success
1098                  *   Called when a magic-auth was successful.
1099                  *   * \e array \b visitor
1100                  *   * \e string \b url
1101                  */
1102                 Addon::callHooks('magic_auth_success', $arr);
1103
1104                 $a->contact = $arr['visitor'];
1105
1106                 info(L10n::t('OpenWebAuth: %1$s welcomes %2$s', $a->get_hostname(), $visitor['name']));
1107
1108                 logger('OpenWebAuth: auth success from ' . $visitor['addr'], LOGGER_DEBUG);
1109         }
1110
1111         public static function zrl($s, $force = false)
1112         {
1113                 if (!strlen($s)) {
1114                         return $s;
1115                 }
1116                 if ((!strpos($s, '/profile/')) && (!$force)) {
1117                         return $s;
1118                 }
1119                 if ($force && substr($s, -1, 1) !== '/') {
1120                         $s = $s . '/';
1121                 }
1122                 $achar = strpos($s, '?') ? '&' : '?';
1123                 $mine = self::getMyURL();
1124                 if ($mine && !link_compare($mine, $s)) {
1125                         return $s . $achar . 'zrl=' . urlencode($mine);
1126                 }
1127                 return $s;
1128         }
1129
1130         /**
1131          * Get the user ID of the page owner.
1132          *
1133          * Used from within PCSS themes to set theme parameters. If there's a
1134          * puid request variable, that is the "page owner" and normally their theme
1135          * settings take precedence; unless a local user sets the "always_my_theme"
1136          * system pconfig, which means they don't want to see anybody else's theme
1137          * settings except their own while on this site.
1138          *
1139          * @brief Get the user ID of the page owner
1140          * @return int user ID
1141          *
1142          * @note Returns local_user instead of user ID if "always_my_theme"
1143          *      is set to true
1144          */
1145         public static function getThemeUid()
1146         {
1147                 $uid = ((!empty($_REQUEST['puid'])) ? intval($_REQUEST['puid']) : 0);
1148                 if ((local_user()) && ((PConfig::get(local_user(), 'system', 'always_my_theme')) || (!$uid))) {
1149                         return local_user();
1150                 }
1151
1152                 return $uid;
1153         }
1154
1155         /**
1156         * Stip zrl parameter from a string.
1157         *
1158         * @param string $s The input string.
1159         * @return string The zrl.
1160         */
1161         public static function stripZrls($s)
1162         {
1163                 return preg_replace('/[\?&]zrl=(.*?)([\?&]|$)/is', '', $s);
1164         }
1165
1166         /**
1167         * Stip query parameter from a string.
1168         *
1169         * @param string $s The input string.
1170         * @return string The query parameter.
1171         */
1172         public static function stripQueryParam($s, $param)
1173         {
1174                 return preg_replace('/[\?&]' . $param . '=(.*?)(&|$)/ism', '$2', $s);
1175         }
1176 }