]> git.mxchange.org Git - friendica.git/blob - src/Model/Profile.php
774f419ee78104c703b97256e26e205f7ae5e63c
[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\Text\BBCode;
9 use Friendica\Content\Widget\ContactBlock;
10 use Friendica\Core\Cache\Duration;
11 use Friendica\Core\Hook;
12 use Friendica\Core\Logger;
13 use Friendica\Core\Protocol;
14 use Friendica\Core\Renderer;
15 use Friendica\Core\Session;
16 use Friendica\Core\System;
17 use Friendica\Database\DBA;
18 use Friendica\DI;
19 use Friendica\Protocol\Activity;
20 use Friendica\Protocol\Diaspora;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Util\Network;
23 use Friendica\Util\Proxy as ProxyUtils;
24 use Friendica\Util\Strings;
25
26 class Profile
27 {
28         /**
29          * Returns default profile for a given user id
30          *
31          * @param integer User ID
32          *
33          * @return array Profile data
34          * @throws \Exception
35          */
36         public static function getByUID($uid)
37         {
38                 $profile = DBA::selectFirst('profile', [], ['uid' => $uid, 'is-default' => true]);
39                 return $profile;
40         }
41
42         /**
43          * Returns default profile for a given user ID and ID
44          *
45          * @param int $uid The contact ID
46          * @param int $id The contact owner ID
47          * @param array $fields The selected fields
48          *
49          * @return array Profile data for the ID
50          * @throws \Exception
51          */
52         public static function getById(int $uid, int $id, array $fields = [])
53         {
54                 return DBA::selectFirst('profile', $fields, ['uid' => $uid, 'id' => $id]);
55         }
56
57         /**
58          * Returns profile data for the contact owner
59          *
60          * @param int $uid The User ID
61          * @param array $fields The fields to retrieve
62          *
63          * @return array Array of profile data
64          * @throws \Exception
65          */
66         public static function getListByUser(int $uid, array $fields = [])
67         {
68                 return DBA::selectToArray('profile', $fields, ['uid' => $uid]);
69         }
70
71         /**
72          * Returns a formatted location string from the given profile array
73          *
74          * @param array $profile Profile array (Generated from the "profile" table)
75          *
76          * @return string Location string
77          */
78         public static function formatLocation(array $profile)
79         {
80                 $location = '';
81
82                 if (!empty($profile['locality'])) {
83                         $location .= $profile['locality'];
84                 }
85
86                 if (!empty($profile['region']) && (($profile['locality'] ?? '') != $profile['region'])) {
87                         if ($location) {
88                                 $location .= ', ';
89                         }
90
91                         $location .= $profile['region'];
92                 }
93
94                 if (!empty($profile['country-name'])) {
95                         if ($location) {
96                                 $location .= ', ';
97                         }
98
99                         $location .= $profile['country-name'];
100                 }
101
102                 return $location;
103         }
104
105         /**
106          * Loads a profile into the page sidebar.
107          *
108          * The function requires a writeable copy of the main App structure, and the nickname
109          * of a registered local account.
110          *
111          * If the viewer is an authenticated remote viewer, the profile displayed is the
112          * one that has been configured for his/her viewing in the Contact manager.
113          * Passing a non-zero profile ID can also allow a preview of a selected profile
114          * by the owner.
115          *
116          * Profile information is placed in the App structure for later retrieval.
117          * Honours the owner's chosen theme for display.
118          *
119          * @attention Should only be run in the _init() functions of a module. That ensures that
120          *      the theme is chosen before the _init() function of a theme is run, which will usually
121          *      load a lot of theme-specific content
122          *
123          * @param App     $a
124          * @param string  $nickname     string
125          * @param int     $profile_id   int
126          * @param array   $profiledata  array
127          * @param boolean $show_connect Show connect link
128          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
129          * @throws \ImagickException
130          */
131         public static function load(App $a, $nickname, $profile_id = 0, array $profiledata = [], $show_connect = true)
132         {
133                 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nickname, 'account_removed' => false]);
134
135                 if (!DBA::isResult($user) && empty($profiledata)) {
136                         Logger::log('profile error: ' . DI::args()->getQueryString(), Logger::DEBUG);
137                         return;
138                 }
139
140                 if (count($profiledata) > 0) {
141                         // Ensure to have a "nickname" field
142                         if (empty($profiledata['nickname']) && !empty($profiledata['nick'])) {
143                                 $profiledata['nickname'] = $profiledata['nick'];
144                         }
145
146                         // Add profile data to sidebar
147                         DI::page()['aside'] .= self::sidebar($a, $profiledata, true, $show_connect);
148
149                         if (!DBA::isResult($user)) {
150                                 return;
151                         }
152                 }
153
154                 $profile = self::getByNickname($nickname, $user['uid'], $profile_id);
155
156                 if (empty($profile) && empty($profiledata)) {
157                         Logger::log('profile error: ' . DI::args()->getQueryString(), Logger::DEBUG);
158                         return;
159                 }
160
161                 if (empty($profile)) {
162                         $profile = ['uid' => 0, 'is-default' => false,'name' => $nickname];
163                 }
164
165                 // fetch user tags if this isn't the default profile
166
167                 if (!$profile['is-default']) {
168                         $condition = ['uid' => $profile['uid'], 'is-default' => true];
169                         $profile_id = DBA::selectFirst('profile', ['pub_keywords'], $condition);
170                         if (DBA::isResult($profile_id)) {
171                                 $profile['pub_keywords'] = $profile_id['pub_keywords'];
172                         }
173                 }
174
175                 $a->profile = $profile;
176                 $a->profile_uid = $profile['uid'];
177
178                 $a->profile['mobile-theme'] = DI::pConfig()->get($a->profile['uid'], 'system', 'mobile_theme');
179                 $a->profile['network'] = Protocol::DFRN;
180
181                 DI::page()['title'] = $a->profile['name'] . ' @ ' . DI::config()->get('config', 'sitename');
182
183                 if (!$profiledata && !DI::pConfig()->get(local_user(), 'system', 'always_my_theme')) {
184                         $a->setCurrentTheme($a->profile['theme']);
185                         $a->setCurrentMobileTheme($a->profile['mobile-theme']);
186                 }
187
188                 /*
189                 * load/reload current theme info
190                 */
191
192                 Renderer::setActiveTemplateEngine(); // reset the template engine to the default in case the user's theme doesn't specify one
193
194                 $theme_info_file = 'view/theme/' . $a->getCurrentTheme() . '/theme.php';
195                 if (file_exists($theme_info_file)) {
196                         require_once $theme_info_file;
197                 }
198
199                 if (local_user() && local_user() == $a->profile['uid'] && $profiledata) {
200                         DI::page()['aside'] .= Renderer::replaceMacros(
201                                 Renderer::getMarkupTemplate('settings/profile/link.tpl'),
202                                 [
203                                         '$editprofile' => DI::l10n()->t('Edit profile'),
204                                         '$profid' => $a->profile['id']
205                                 ]
206                         );
207                 }
208
209                 $block = ((DI::config()->get('system', 'block_public') && !Session::isAuthenticated()) ? true : false);
210
211                 /**
212                  * @todo
213                  * By now, the contact block isn't shown, when a different profile is given
214                  * But: When this profile was on the same server, then we could display the contacts
215                  */
216                 if (!$profiledata) {
217                         DI::page()['aside'] .= self::sidebar($a, $a->profile, $block, $show_connect);
218                 }
219
220                 return;
221         }
222
223         /**
224          * Get all profile data of a local user
225          *
226          * If the viewer is an authenticated remote viewer, the profile displayed is the
227          * one that has been configured for his/her viewing in the Contact manager.
228          * Passing a non-zero profile ID can also allow a preview of a selected profile
229          * by the owner
230          *
231          * Includes all available profile data
232          *
233          * @param string $nickname   nick
234          * @param int    $uid        uid
235          * @param int    $profile_id ID of the profile
236          * @return array
237          * @throws \Exception
238          */
239         public static function getByNickname($nickname, $uid = 0)
240         {
241                 $profile = DBA::fetchFirst(
242                         "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` AS `contact_photo`,
243                                 `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
244                                 `profile`.*,
245                                 `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
246                         FROM `profile`
247                         INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
248                         INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
249                         WHERE `user`.`nickname` = ? AND `profile`.`uid` = ? LIMIT 1",
250                         $nickname,
251                         intval($uid)
252                 );
253
254                 return $profile;
255         }
256
257         /**
258          * Formats a profile for display in the sidebar.
259          *
260          * It is very difficult to templatise the HTML completely
261          * because of all the conditional logic.
262          *
263          * @param array   $profile
264          * @param int     $block
265          * @param boolean $show_connect Show connect link
266          *
267          * @return string HTML sidebar module
268          *
269          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
270          * @throws \ImagickException
271          * @note  Returns empty string if passed $profile is wrong type or not populated
272          *
273          * @hooks 'profile_sidebar_enter'
274          *      array $profile - profile data
275          * @hooks 'profile_sidebar'
276          *      array $arr
277          */
278         private static function sidebar(App $a, $profile, $block = 0, $show_connect = true)
279         {
280                 $o = '';
281                 $location = false;
282
283                 // This function can also use contact information in $profile
284                 $is_contact = !empty($profile['cid']);
285
286                 if (!is_array($profile) && !count($profile)) {
287                         return $o;
288                 }
289
290                 $profile['picdate'] = urlencode($profile['picdate'] ?? '');
291
292                 if (($profile['network'] != '') && ($profile['network'] != Protocol::DFRN)) {
293                         $profile['network_link'] = Strings::formatNetworkName($profile['network'], $profile['url']);
294                 } else {
295                         $profile['network_link'] = '';
296                 }
297
298                 Hook::callAll('profile_sidebar_enter', $profile);
299
300                 if (isset($profile['url'])) {
301                         $profile_url = $profile['url'];
302                 } else {
303                         $profile_url = DI::baseUrl()->get() . '/profile/' . $profile['nickname'];
304                 }
305
306                 $follow_link = null;
307                 $unfollow_link = null;
308                 $subscribe_feed_link = null;
309                 $wallmessage_link = null;
310
311
312
313                 $visitor_contact = [];
314                 if (!empty($profile['uid']) && self::getMyURL()) {
315                         $visitor_contact = Contact::selectFirst(['rel'], ['uid' => $profile['uid'], 'nurl' => Strings::normaliseLink(self::getMyURL())]);
316                 }
317
318                 $profile_contact = [];
319                 if (!empty($profile['cid']) && self::getMyURL()) {
320                         $profile_contact = Contact::selectFirst(['rel'], ['id' => $profile['cid']]);
321                 }
322
323                 $profile_is_dfrn = $profile['network'] == Protocol::DFRN;
324                 $profile_is_native = in_array($profile['network'], Protocol::NATIVE_SUPPORT);
325                 $local_user_is_self = local_user() && local_user() == ($profile['uid'] ?? 0);
326                 $visitor_is_authenticated = (bool)self::getMyURL();
327                 $visitor_is_following =
328                         in_array($visitor_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND])
329                         || in_array($profile_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND]);
330                 $visitor_is_followed =
331                         in_array($visitor_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND])
332                         || in_array($profile_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND]);
333                 $visitor_base_path = self::getMyURL() ? preg_replace('=/profile/(.*)=ism', '', self::getMyURL()) : '';
334
335                 if (!$local_user_is_self && $show_connect) {
336                         if (!$visitor_is_authenticated) {
337                                 if (!empty($profile['nickname'])) {
338                                         $follow_link = 'dfrn_request/' . $profile['nickname'];
339                                 }
340                         } elseif ($profile_is_native) {
341                                 if ($visitor_is_following) {
342                                         $unfollow_link = $visitor_base_path . '/unfollow?url=' . urlencode($profile_url);
343                                 } else {
344                                         $follow_link =  $visitor_base_path .'/follow?url=' . urlencode($profile_url);
345                                 }
346                         }
347
348                         if ($profile_is_dfrn) {
349                                 $subscribe_feed_link = 'dfrn_poll/' . $profile['nickname'];
350                         }
351
352                         if (Contact::canReceivePrivateMessages($profile)) {
353                                 if ($visitor_is_followed || $visitor_is_following) {
354                                         $wallmessage_link = $visitor_base_path . '/message/new/' . base64_encode($profile['addr'] ?? '');
355                                 } elseif ($visitor_is_authenticated && !empty($profile['unkmail'])) {
356                                         $wallmessage_link = 'wallmessage/' . $profile['nickname'];
357                                 }
358                         }
359                 }
360
361                 // show edit profile to yourself
362                 if (!$is_contact && $local_user_is_self) {
363                         $profile['edit'] = [DI::baseUrl() . '/settings/profile', DI::l10n()->t('Edit profile'), '', DI::l10n()->t('Edit profile')];
364                         $profile['menu'] = [
365                                 'chg_photo' => DI::l10n()->t('Change profile photo'),
366                                 'cr_new' => null,
367                                 'entries' => [],
368                         ];
369                 }
370
371                 // Fetch the account type
372                 $account_type = Contact::getAccountType($profile);
373
374                 if (!empty($profile['address'])
375                         || !empty($profile['location'])
376                         || !empty($profile['locality'])
377                         || !empty($profile['region'])
378                         || !empty($profile['postal-code'])
379                         || !empty($profile['country-name'])
380                 ) {
381                         $location = DI::l10n()->t('Location:');
382                 }
383
384                 $gender   = !empty($profile['gender'])   ? DI::l10n()->t('Gender:')   : false;
385                 $marital  = !empty($profile['marital'])  ? DI::l10n()->t('Status:')   : false;
386                 $homepage = !empty($profile['homepage']) ? DI::l10n()->t('Homepage:') : false;
387                 $about    = !empty($profile['about'])    ? DI::l10n()->t('About:')    : false;
388                 $xmpp     = !empty($profile['xmpp'])     ? DI::l10n()->t('XMPP:')     : false;
389
390                 if ((!empty($profile['hidewall']) || $block) && !Session::isAuthenticated()) {
391                         $location = $gender = $marital = $homepage = $about = false;
392                 }
393
394                 $split_name = Diaspora::splitName($profile['name']);
395                 $firstname = $split_name['first'];
396                 $lastname = $split_name['last'];
397
398                 if (!empty($profile['guid'])) {
399                         $diaspora = [
400                                 'guid' => $profile['guid'],
401                                 'podloc' => DI::baseUrl(),
402                                 'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false'),
403                                 'nickname' => $profile['nickname'],
404                                 'fullname' => $profile['name'],
405                                 'firstname' => $firstname,
406                                 'lastname' => $lastname,
407                                 'photo300' => $profile['contact_photo'] ?? '',
408                                 'photo100' => $profile['contact_thumb'] ?? '',
409                                 'photo50' => $profile['contact_micro'] ?? '',
410                         ];
411                 } else {
412                         $diaspora = false;
413                 }
414
415                 $contact_block = '';
416                 $updated = '';
417                 $contact_count = 0;
418                 if (!$block) {
419                         $contact_block = ContactBlock::getHTML($a->profile);
420
421                         if (is_array($a->profile) && !$a->profile['hide-friends']) {
422                                 $r = q(
423                                         "SELECT `gcontact`.`updated` FROM `contact` INNER JOIN `gcontact` WHERE `gcontact`.`nurl` = `contact`.`nurl` AND `self` AND `uid` = %d LIMIT 1",
424                                         intval($a->profile['uid'])
425                                 );
426                                 if (DBA::isResult($r)) {
427                                         $updated = date('c', strtotime($r[0]['updated']));
428                                 }
429
430                                 $contact_count = DBA::count('contact', [
431                                         'uid' => $profile['uid'],
432                                         'self' => false,
433                                         'blocked' => false,
434                                         'pending' => false,
435                                         'hidden' => false,
436                                         'archive' => false,
437                                         'network' => Protocol::FEDERATED,
438                                 ]);
439                         }
440                 }
441
442                 $p = [];
443                 foreach ($profile as $k => $v) {
444                         $k = str_replace('-', '_', $k);
445                         $p[$k] = $v;
446                 }
447
448                 if (isset($p['about'])) {
449                         $p['about'] = BBCode::convert($p['about']);
450                 }
451
452                 if (empty($p['address']) && !empty($p['location'])) {
453                         $p['address'] = $p['location'];
454                 }
455
456                 if (isset($p['address'])) {
457                         $p['address'] = BBCode::convert($p['address']);
458                 }
459
460                 if (isset($p['gender'])) {
461                         $p['gender'] = DI::l10n()->t($p['gender']);
462                 }
463
464                 if (isset($p['marital'])) {
465                         $p['marital'] = DI::l10n()->t($p['marital']);
466                 }
467
468                 if (isset($p['photo'])) {
469                         $p['photo'] = ProxyUtils::proxifyUrl($p['photo'], false, ProxyUtils::SIZE_SMALL);
470                 }
471
472                 $p['url'] = Contact::magicLink(($p['url'] ?? '') ?: $profile_url);
473
474                 $tpl = Renderer::getMarkupTemplate('profile/vcard.tpl');
475                 $o .= Renderer::replaceMacros($tpl, [
476                         '$profile' => $p,
477                         '$xmpp' => $xmpp,
478                         '$follow' => DI::l10n()->t('Follow'),
479                         '$follow_link' => $follow_link,
480                         '$unfollow' => DI::l10n()->t('Unfollow'),
481                         '$unfollow_link' => $unfollow_link,
482                         '$subscribe_feed' => DI::l10n()->t('Atom feed'),
483                         '$subscribe_feed_link' => $subscribe_feed_link,
484                         '$wallmessage' => DI::l10n()->t('Message'),
485                         '$wallmessage_link' => $wallmessage_link,
486                         '$account_type' => $account_type,
487                         '$location' => $location,
488                         '$gender' => $gender,
489                         '$marital' => $marital,
490                         '$homepage' => $homepage,
491                         '$about' => $about,
492                         '$network' => DI::l10n()->t('Network:'),
493                         '$contacts' => $contact_count,
494                         '$updated' => $updated,
495                         '$diaspora' => $diaspora,
496                         '$contact_block' => $contact_block,
497                 ]);
498
499                 $arr = ['profile' => &$profile, 'entry' => &$o];
500
501                 Hook::callAll('profile_sidebar', $arr);
502
503                 return $o;
504         }
505
506         public static function getBirthdays()
507         {
508                 $a = DI::app();
509                 $o = '';
510
511                 if (!local_user() || DI::mode()->isMobile() || DI::mode()->isMobile()) {
512                         return $o;
513                 }
514
515                 /*
516                 * $mobile_detect = new Mobile_Detect();
517                 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
518                 *               if ($is_mobile)
519                 *                       return $o;
520                 */
521
522                 $bd_format = DI::l10n()->t('g A l F d'); // 8 AM Friday January 18
523                 $bd_short = DI::l10n()->t('F d');
524
525                 $cachekey = 'get_birthdays:' . local_user();
526                 $r = DI::cache()->get($cachekey);
527                 if (is_null($r)) {
528                         $s = DBA::p(
529                                 "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
530                                 INNER JOIN `contact`
531                                         ON `contact`.`id` = `event`.`cid`
532                                         AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
533                                         AND NOT `contact`.`pending`
534                                         AND NOT `contact`.`hidden`
535                                         AND NOT `contact`.`blocked`
536                                         AND NOT `contact`.`archive`
537                                         AND NOT `contact`.`deleted`
538                                 WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
539                                 ORDER BY `start` ASC ",
540                                 Contact::SHARING,
541                                 Contact::FRIEND,
542                                 local_user(),
543                                 DateTimeFormat::utc('now + 6 days'),
544                                 DateTimeFormat::utcNow()
545                         );
546                         if (DBA::isResult($s)) {
547                                 $r = DBA::toArray($s);
548                                 DI::cache()->set($cachekey, $r, Duration::HOUR);
549                         }
550                 }
551
552                 $total = 0;
553                 $classtoday = '';
554                 if (DBA::isResult($r)) {
555                         $now = strtotime('now');
556                         $cids = [];
557
558                         $istoday = false;
559                         foreach ($r as $rr) {
560                                 if (strlen($rr['name'])) {
561                                         $total ++;
562                                 }
563                                 if ((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) {
564                                         $istoday = true;
565                                 }
566                         }
567                         $classtoday = $istoday ? ' birthday-today ' : '';
568                         if ($total) {
569                                 foreach ($r as &$rr) {
570                                         if (!strlen($rr['name'])) {
571                                                 continue;
572                                         }
573
574                                         // avoid duplicates
575
576                                         if (in_array($rr['cid'], $cids)) {
577                                                 continue;
578                                         }
579                                         $cids[] = $rr['cid'];
580
581                                         $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
582
583                                         $rr['link'] = Contact::magicLink($rr['url']);
584                                         $rr['title'] = $rr['name'];
585                                         $rr['date'] = DI::l10n()->getDay(DateTimeFormat::convert($rr['start'], $a->timezone, 'UTC', $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '');
586                                         $rr['startime'] = null;
587                                         $rr['today'] = $today;
588                                 }
589                         }
590                 }
591                 $tpl = Renderer::getMarkupTemplate('birthdays_reminder.tpl');
592                 return Renderer::replaceMacros($tpl, [
593                         '$classtoday' => $classtoday,
594                         '$count' => $total,
595                         '$event_reminders' => DI::l10n()->t('Birthday Reminders'),
596                         '$event_title' => DI::l10n()->t('Birthdays this week:'),
597                         '$events' => $r,
598                         '$lbr' => '{', // raw brackets mess up if/endif macro processing
599                         '$rbr' => '}'
600                 ]);
601         }
602
603         public static function getEventsReminderHTML()
604         {
605                 $a = DI::app();
606                 $o = '';
607
608                 if (!local_user() || DI::mode()->isMobile() || DI::mode()->isMobile()) {
609                         return $o;
610                 }
611
612                 /*
613                 *       $mobile_detect = new Mobile_Detect();
614                 *               $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
615                 *               if ($is_mobile)
616                 *                       return $o;
617                 */
618
619                 $bd_format = DI::l10n()->t('g A l F d'); // 8 AM Friday January 18
620                 $classtoday = '';
621
622                 $condition = ["`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?",
623                         local_user(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utc('now - 1 days')];
624                 $s = DBA::select('event', [], $condition, ['order' => ['start']]);
625
626                 $r = [];
627
628                 if (DBA::isResult($s)) {
629                         $istoday = false;
630                         $total = 0;
631
632                         while ($rr = DBA::fetch($s)) {
633                                 $condition = ['parent-uri' => $rr['uri'], 'uid' => $rr['uid'], 'author-id' => public_contact(),
634                                         'activity' => [Item::activityToIndex( Activity::ATTEND), Item::activityToIndex(Activity::ATTENDMAYBE)],
635                                         'visible' => true, 'deleted' => false];
636                                 if (!Item::exists($condition)) {
637                                         continue;
638                                 }
639
640                                 if (strlen($rr['summary'])) {
641                                         $total++;
642                                 }
643
644                                 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', 'Y-m-d');
645                                 if ($strt === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
646                                         $istoday = true;
647                                 }
648
649                                 $title = strip_tags(html_entity_decode(BBCode::convert($rr['summary']), ENT_QUOTES, 'UTF-8'));
650
651                                 if (strlen($title) > 35) {
652                                         $title = substr($title, 0, 32) . '... ';
653                                 }
654
655                                 $description = substr(strip_tags(BBCode::convert($rr['desc'])), 0, 32) . '... ';
656                                 if (!$description) {
657                                         $description = DI::l10n()->t('[No description]');
658                                 }
659
660                                 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC');
661
662                                 if (substr($strt, 0, 10) < DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
663                                         continue;
664                                 }
665
666                                 $today = ((substr($strt, 0, 10) === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) ? true : false);
667
668                                 $rr['title'] = $title;
669                                 $rr['description'] = $description;
670                                 $rr['date'] = DI::l10n()->getDay(DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', $bd_format)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '');
671                                 $rr['startime'] = $strt;
672                                 $rr['today'] = $today;
673
674                                 $r[] = $rr;
675                         }
676                         DBA::close($s);
677                         $classtoday = (($istoday) ? 'event-today' : '');
678                 }
679                 $tpl = Renderer::getMarkupTemplate('events_reminder.tpl');
680                 return Renderer::replaceMacros($tpl, [
681                         '$classtoday' => $classtoday,
682                         '$count' => count($r),
683                         '$event_reminders' => DI::l10n()->t('Event Reminders'),
684                         '$event_title' => DI::l10n()->t('Upcoming events the next 7 days:'),
685                         '$events' => $r,
686                 ]);
687         }
688
689     /**
690      * @param App    $a
691      * @param string $current
692      * @param bool   $is_owner
693      * @param string $nickname
694      * @return string
695      * @throws \Friendica\Network\HTTPException\InternalServerErrorException
696      */
697         public static function getTabs(App $a, string $current, bool $is_owner, string $nickname = null)
698         {
699                 if (is_null($nickname)) {
700                         $nickname = $a->user['nickname'];
701                 }
702
703                 $baseProfileUrl = DI::baseUrl() . '/profile/' . $nickname;
704
705                 $tabs = [
706                         [
707                                 'label' => DI::l10n()->t('Profile'),
708                                 'url'   => $baseProfileUrl,
709                                 'sel'   => $current == 'profile' ? 'active' : '',
710                                 'title' => DI::l10n()->t('Profile Details'),
711                                 'id'    => 'profile-tab',
712                                 'accesskey' => 'r',
713                         ],
714                         [
715                                 'label' => DI::l10n()->t('Status'),
716                                 'url'   => $baseProfileUrl . '/status',
717                                 'sel'   => $current == 'status' ? 'active' : '',
718                                 'title' => DI::l10n()->t('Status Messages and Posts'),
719                                 'id'    => 'status-tab',
720                                 'accesskey' => 'm',
721                         ],
722                         [
723                                 'label' => DI::l10n()->t('Photos'),
724                                 'url'   => DI::baseUrl() . '/photos/' . $nickname,
725                                 'sel'   => $current == 'photos' ? 'active' : '',
726                                 'title' => DI::l10n()->t('Photo Albums'),
727                                 'id'    => 'photo-tab',
728                                 'accesskey' => 'h',
729                         ],
730                         [
731                                 'label' => DI::l10n()->t('Videos'),
732                                 'url'   => DI::baseUrl() . '/videos/' . $nickname,
733                                 'sel'   => $current == 'videos' ? 'active' : '',
734                                 'title' => DI::l10n()->t('Videos'),
735                                 'id'    => 'video-tab',
736                                 'accesskey' => 'v',
737                         ],
738                 ];
739
740                 // the calendar link for the full featured events calendar
741                 if ($is_owner && $a->theme_events_in_profile) {
742                         $tabs[] = [
743                                 'label' => DI::l10n()->t('Events'),
744                                 'url'   => DI::baseUrl() . '/events',
745                                 'sel'   => $current == 'events' ? 'active' : '',
746                                 'title' => DI::l10n()->t('Events and Calendar'),
747                                 'id'    => 'events-tab',
748                                 'accesskey' => 'e',
749                         ];
750                         // if the user is not the owner of the calendar we only show a calendar
751                         // with the public events of the calendar owner
752                 } elseif (!$is_owner) {
753                         $tabs[] = [
754                                 'label' => DI::l10n()->t('Events'),
755                                 'url'   => DI::baseUrl() . '/cal/' . $nickname,
756                                 'sel'   => $current == 'cal' ? 'active' : '',
757                                 'title' => DI::l10n()->t('Events and Calendar'),
758                                 'id'    => 'events-tab',
759                                 'accesskey' => 'e',
760                         ];
761                 }
762
763                 if ($is_owner) {
764                         $tabs[] = [
765                                 'label' => DI::l10n()->t('Personal Notes'),
766                                 'url'   => DI::baseUrl() . '/notes',
767                                 'sel'   => $current == 'notes' ? 'active' : '',
768                                 'title' => DI::l10n()->t('Only You Can See This'),
769                                 'id'    => 'notes-tab',
770                                 'accesskey' => 't',
771                         ];
772                 }
773
774                 if (empty($a->profile['hide-friends'])) {
775                         $tabs[] = [
776                                 'label' => DI::l10n()->t('Contacts'),
777                                 'url'   => $baseProfileUrl . '/contacts',
778                                 'sel'   => $current == 'contacts' ? 'active' : '',
779                                 'title' => DI::l10n()->t('Contacts'),
780                                 'id'    => 'viewcontacts-tab',
781                                 'accesskey' => 'k',
782                         ];
783                 }
784
785                 if (!empty($_SESSION['new_member']) && $is_owner) {
786                         $tabs[] = [
787                                 'label' => DI::l10n()->t('Tips for New Members'),
788                                 'url'   => DI::baseUrl() . '/newmember',
789                                 'sel'   => false,
790                                 'title' => DI::l10n()->t('Tips for New Members'),
791                                 'id'    => 'newmember-tab',
792                         ];
793                 }
794
795                 $arr = ['is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => $current, 'tabs' => $tabs];
796
797                 Hook::callAll('profile_tabs', $arr);
798
799                 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
800
801                 return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
802         }
803
804         /**
805          * Retrieves the my_url session variable
806          *
807          * @return string
808          */
809         public static function getMyURL()
810         {
811                 return Session::get('my_url');
812         }
813
814         /**
815          * Process the 'zrl' parameter and initiate the remote authentication.
816          *
817          * This method checks if the visitor has a public contact entry and
818          * redirects the visitor to his/her instance to start the magic auth (Authentication)
819          * process.
820          *
821          * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/channel.php
822          *
823          * The implementation for Friendica sadly differs in some points from the one for Hubzilla:
824          * - Hubzilla uses the "zid" parameter, while for Friendica it had been replaced with "zrl"
825          * - There seem to be some reverse authentication (rmagic) that isn't implemented in Friendica at all
826          *
827          * It would be favourable to harmonize the two implementations.
828          *
829          * @param App $a Application instance.
830          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
831          * @throws \ImagickException
832          */
833         public static function zrlInit(App $a)
834         {
835                 $my_url = self::getMyURL();
836                 $my_url = Network::isUrlValid($my_url);
837
838                 if (empty($my_url) || local_user()) {
839                         return;
840                 }
841
842                 $addr = $_GET['addr'] ?? $my_url;
843
844                 $arr = ['zrl' => $my_url, 'url' => DI::args()->getCommand()];
845                 Hook::callAll('zrl_init', $arr);
846
847                 // Try to find the public contact entry of the visitor.
848                 $cid = Contact::getIdForURL($my_url);
849                 if (!$cid) {
850                         Logger::log('No contact record found for ' . $my_url, Logger::DEBUG);
851                         return;
852                 }
853
854                 $contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]);
855
856                 if (DBA::isResult($contact) && remote_user() && remote_user() == $contact['id']) {
857                         Logger::log('The visitor ' . $my_url . ' is already authenticated', Logger::DEBUG);
858                         return;
859                 }
860
861                 // Avoid endless loops
862                 $cachekey = 'zrlInit:' . $my_url;
863                 if (DI::cache()->get($cachekey)) {
864                         Logger::log('URL ' . $my_url . ' already tried to authenticate.', Logger::DEBUG);
865                         return;
866                 } else {
867                         DI::cache()->set($cachekey, true, Duration::MINUTE);
868                 }
869
870                 Logger::log('Not authenticated. Invoking reverse magic-auth for ' . $my_url, Logger::DEBUG);
871
872                 // Remove the "addr" parameter from the destination. It is later added as separate parameter again.
873                 $addr_request = 'addr=' . urlencode($addr);
874                 $query = rtrim(str_replace($addr_request, '', DI::args()->getQueryString()), '?&');
875
876                 // The other instance needs to know where to redirect.
877                 $dest = urlencode(DI::baseUrl()->get() . '/' . $query);
878
879                 // We need to extract the basebath from the profile url
880                 // to redirect the visitors '/magic' module.
881                 $basepath = Contact::getBasepath($contact['url']);
882
883                 if ($basepath != DI::baseUrl()->get() && !strstr($dest, '/magic')) {
884                         $magic_path = $basepath . '/magic' . '?owa=1&dest=' . $dest . '&' . $addr_request;
885
886                         // We have to check if the remote server does understand /magic without invoking something
887                         $serverret = Network::curl($basepath . '/magic');
888                         if ($serverret->isSuccess()) {
889                                 Logger::log('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path, Logger::DEBUG);
890                                 System::externalRedirect($magic_path);
891                         }
892                 }
893         }
894
895         /**
896          * Set the visitor cookies (see remote_user()) for the given handle
897          *
898          * @param string $handle Visitor handle
899          * @return array Visitor contact array
900          */
901         public static function addVisitorCookieForHandle($handle)
902         {
903                 $a = DI::app();
904
905                 // Try to find the public contact entry of the visitor.
906                 $cid = Contact::getIdForURL($handle);
907                 if (!$cid) {
908                         Logger::log('unable to finger ' . $handle, Logger::DEBUG);
909                         return [];
910                 }
911
912                 $visitor = DBA::selectFirst('contact', [], ['id' => $cid]);
913
914                 // Authenticate the visitor.
915                 $_SESSION['authenticated'] = 1;
916                 $_SESSION['visitor_id'] = $visitor['id'];
917                 $_SESSION['visitor_handle'] = $visitor['addr'];
918                 $_SESSION['visitor_home'] = $visitor['url'];
919                 $_SESSION['my_url'] = $visitor['url'];
920
921                 Session::setVisitorsContacts();
922
923                 $a->contact = $visitor;
924
925                 Logger::info('Authenticated visitor', ['url' => $visitor['url']]);
926
927                 return $visitor;
928         }
929
930         /**
931          * OpenWebAuth authentication.
932          *
933          * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/zid.php
934          *
935          * @param string $token
936          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
937          * @throws \ImagickException
938          */
939         public static function openWebAuthInit($token)
940         {
941                 $a = DI::app();
942
943                 // Clean old OpenWebAuthToken entries.
944                 OpenWebAuthToken::purge('owt', '3 MINUTE');
945
946                 // Check if the token we got is the same one
947                 // we have stored in the database.
948                 $visitor_handle = OpenWebAuthToken::getMeta('owt', 0, $token);
949
950                 if ($visitor_handle === false) {
951                         return;
952                 }
953
954                 $visitor = self::addVisitorCookieForHandle($visitor_handle);
955                 if (empty($visitor)) {
956                         return;
957                 }
958
959                 $arr = [
960                         'visitor' => $visitor,
961                         'url' => DI::args()->getQueryString()
962                 ];
963                 /**
964                  * @hooks magic_auth_success
965                  *   Called when a magic-auth was successful.
966                  *   * \e array \b visitor
967                  *   * \e string \b url
968                  */
969                 Hook::callAll('magic_auth_success', $arr);
970
971                 $a->contact = $arr['visitor'];
972
973                 info(DI::l10n()->t('OpenWebAuth: %1$s welcomes %2$s', DI::baseUrl()->getHostname(), $visitor['name']));
974
975                 Logger::log('OpenWebAuth: auth success from ' . $visitor['addr'], Logger::DEBUG);
976         }
977
978         public static function zrl($s, $force = false)
979         {
980                 if (!strlen($s)) {
981                         return $s;
982                 }
983                 if (!strpos($s, '/profile/') && !$force) {
984                         return $s;
985                 }
986                 if ($force && substr($s, -1, 1) !== '/') {
987                         $s = $s . '/';
988                 }
989                 $achar = strpos($s, '?') ? '&' : '?';
990                 $mine = self::getMyURL();
991                 if ($mine && !Strings::compareLink($mine, $s)) {
992                         return $s . $achar . 'zrl=' . urlencode($mine);
993                 }
994                 return $s;
995         }
996
997         /**
998          * Get the user ID of the page owner.
999          *
1000          * Used from within PCSS themes to set theme parameters. If there's a
1001          * profile_uid variable set in App, that is the "page owner" and normally their theme
1002          * settings take precedence; unless a local user sets the "always_my_theme"
1003          * system pconfig, which means they don't want to see anybody else's theme
1004          * settings except their own while on this site.
1005          *
1006          * @return int user ID
1007          *
1008          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1009          * @note Returns local_user instead of user ID if "always_my_theme" is set to true
1010          */
1011         public static function getThemeUid(App $a)
1012         {
1013                 $uid = !empty($a->profile_uid) ? intval($a->profile_uid) : 0;
1014                 if (local_user() && (DI::pConfig()->get(local_user(), 'system', 'always_my_theme') || !$uid)) {
1015                         return local_user();
1016                 }
1017
1018                 return $uid;
1019         }
1020
1021         /**
1022          * search for Profiles
1023          *
1024          * @param int  $start
1025          * @param int  $count
1026          * @param null $search
1027          *
1028          * @return array [ 'total' => 123, 'entries' => [...] ];
1029          *
1030          * @throws \Exception
1031          */
1032         public static function searchProfiles($start = 0, $count = 100, $search = null)
1033         {
1034                 $publish = (DI::config()->get('system', 'publish_all') ? '' : " AND `publish` = 1 ");
1035                 $total = 0;
1036
1037                 if (!empty($search)) {
1038                         $searchTerm = '%' . $search . '%';
1039                         $cnt = DBA::fetchFirst("SELECT COUNT(*) AS `total`
1040                                 FROM `profile`
1041                                 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1042                                 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed`
1043                                 AND ((`profile`.`name` LIKE ?) OR
1044                                 (`user`.`nickname` LIKE ?) OR
1045                                 (`profile`.`pdesc` LIKE ?) OR
1046                                 (`profile`.`locality` LIKE ?) OR
1047                                 (`profile`.`region` LIKE ?) OR
1048                                 (`profile`.`country-name` LIKE ?) OR
1049                                 (`profile`.`gender` LIKE ?) OR
1050                                 (`profile`.`marital` LIKE ?) OR
1051                                 (`profile`.`sexual` LIKE ?) OR
1052                                 (`profile`.`about` LIKE ?) OR
1053                                 (`profile`.`romance` LIKE ?) OR
1054                                 (`profile`.`work` LIKE ?) OR
1055                                 (`profile`.`education` LIKE ?) OR
1056                                 (`profile`.`pub_keywords` LIKE ?) OR
1057                                 (`profile`.`prv_keywords` LIKE ?))",
1058                                 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1059                                 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm);
1060                 } else {
1061                         $cnt = DBA::fetchFirst("SELECT COUNT(*) AS `total`
1062                                 FROM `profile`
1063                                 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1064                                 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed`");
1065                 }
1066
1067                 if (DBA::isResult($cnt)) {
1068                         $total = $cnt['total'];
1069                 }
1070
1071                 $order = " ORDER BY `name` ASC ";
1072                 $profiles = [];
1073
1074                 // If nothing found, don't try to select details
1075                 if ($total > 0) {
1076                         if (!empty($search)) {
1077                                 $searchTerm = '%' . $search . '%';
1078
1079                                 $profiles = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
1080                         `contact`.`addr`, `contact`.`url` AS `profile_url`
1081                         FROM `profile`
1082                         LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1083                         LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1084                         WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
1085                         AND ((`profile`.`name` LIKE ?) OR
1086                                 (`user`.`nickname` LIKE ?) OR
1087                                 (`profile`.`pdesc` LIKE ?) OR
1088                                 (`profile`.`locality` LIKE ?) OR
1089                                 (`profile`.`region` LIKE ?) OR
1090                                 (`profile`.`country-name` LIKE ?) OR
1091                                 (`profile`.`gender` LIKE ?) OR
1092                                 (`profile`.`marital` LIKE ?) OR
1093                                 (`profile`.`sexual` LIKE ?) OR
1094                                 (`profile`.`about` LIKE ?) OR
1095                                 (`profile`.`romance` LIKE ?) OR
1096                                 (`profile`.`work` LIKE ?) OR
1097                                 (`profile`.`education` LIKE ?) OR
1098                                 (`profile`.`pub_keywords` LIKE ?) OR
1099                                 (`profile`.`prv_keywords` LIKE ?))
1100                         $order LIMIT ?,?",
1101                                         $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1102                                         $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1103                                         $start, $count
1104                                 );
1105                         } else {
1106                                 $profiles = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
1107                         `contact`.`addr`, `contact`.`url` AS `profile_url`
1108                         FROM `profile`
1109                         LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1110                         LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1111                         WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
1112                         $order LIMIT ?,?",
1113                                         $start, $count
1114                                 );
1115                         }
1116                 }
1117
1118                 if (DBA::isResult($profiles) && $total > 0) {
1119                         return [
1120                                 'total'   => $total,
1121                                 'entries' => DBA::toArray($profiles),
1122                         ];
1123
1124                 } else {
1125                         return [
1126                                 'total'   => $total,
1127                                 'entries' => [],
1128                         ];
1129                 }
1130         }
1131 }