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