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