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