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