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