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