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