]> git.mxchange.org Git - friendica.git/blob - src/Model/Profile.php
Merge pull request #10406 from annando/profile-publish
[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 all profile data of a local user
287          *
288          * If the viewer is an authenticated remote viewer, the profile displayed is the
289          * one that has been configured for his/her viewing in the Contact manager.
290          * Passing a non-zero profile ID can also allow a preview of a selected profile
291          * by the owner
292          *
293          * Includes all available profile data
294          *
295          * @param string $nickname   nick
296          * @param int    $uid        uid
297          * @param int    $profile_id ID of the profile
298          * @return array
299          * @throws \Exception
300          */
301         public static function getByNickname($nickname, $uid = 0)
302         {
303                 $profile = DBA::selectFirst('owner-view', [], ['nickname' => $nickname, 'uid' => $uid]);
304                 return $profile;
305         }
306
307         /**
308          * Formats a profile for display in the sidebar.
309          *
310          * It is very difficult to templatise the HTML completely
311          * because of all the conditional logic.
312          *
313          * @param array   $profile
314          * @param int     $block
315          * @param boolean $show_connect Show connect link
316          *
317          * @return string HTML sidebar module
318          *
319          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
320          * @throws \ImagickException
321          * @note  Returns empty string if passed $profile is wrong type or not populated
322          *
323          * @hooks 'profile_sidebar_enter'
324          *      array $profile - profile data
325          * @hooks 'profile_sidebar'
326          *      array $arr
327          */
328         private static function sidebar(App $a, array $profile, $block = 0, $show_connect = true)
329         {
330                 $o = '';
331                 $location = false;
332
333                 // This function can also use contact information in $profile, but the 'cid'
334                 // value is going to be coming from 'owner-view', which means it's the wrong
335                 // contact ID for the user viewing this page. Use 'nurl' to look up the
336                 // correct contact table entry for the logged-in user.
337                 $profile_contact = [];
338
339                 if (!empty($profile['nurl'] ?? '')) {
340                         if (local_user() && ($profile['uid'] ?? '') != local_user()) {
341                                 $profile_contact = Contact::getById(Contact::getIdForURL($profile['nurl'], local_user()));
342                         }
343                         if (!empty($profile['cid']) && self::getMyURL()) {
344                                 $profile_contact = Contact::selectFirst(['rel'], ['id' => $profile['cid']]);
345                         }
346                 }
347
348                 if (empty($profile['nickname'])) {
349                         Logger::warning('Received profile with no nickname', ['profile' => $profile, 'callstack' => System::callstack(10)]);
350                         return $o;
351                 }
352
353                 $profile['picdate'] = urlencode($profile['picdate'] ?? '');
354
355                 if (($profile['network'] != '') && ($profile['network'] != Protocol::DFRN)) {
356                         $profile['network_link'] = Strings::formatNetworkName($profile['network'], $profile['url']);
357                 } else {
358                         $profile['network_link'] = '';
359                 }
360
361                 Hook::callAll('profile_sidebar_enter', $profile);
362
363                 if (isset($profile['url'])) {
364                         $profile_url = $profile['url'];
365                 } else {
366                         $profile_url = DI::baseUrl()->get() . '/profile/' . $profile['nickname'];
367                 }
368
369                 $follow_link = null;
370                 $unfollow_link = null;
371                 $subscribe_feed_link = null;
372                 $wallmessage_link = null;
373
374                 // Who is the logged-in user to this profile?
375                 $visitor_contact = [];
376                 if (!empty($profile['uid']) && self::getMyURL()) {
377                         $visitor_contact = Contact::selectFirst(['rel'], ['uid' => $profile['uid'], 'nurl' => Strings::normaliseLink(self::getMyURL())]);
378                 }
379
380                 $profile_is_dfrn = $profile['network'] == Protocol::DFRN;
381                 $profile_is_native = in_array($profile['network'], Protocol::NATIVE_SUPPORT);
382                 $local_user_is_self = self::getMyURL() && ($profile['url'] == self::getMyURL());
383                 $visitor_is_authenticated = (bool)self::getMyURL();
384                 $visitor_is_following =
385                         in_array($visitor_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND])
386                         || in_array($profile_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND]);
387                 $visitor_is_followed =
388                         in_array($visitor_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND])
389                         || in_array($profile_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND]);
390                 $visitor_base_path = self::getMyURL() ? preg_replace('=/profile/(.*)=ism', '', self::getMyURL()) : '';
391
392                 if (!$local_user_is_self && $show_connect) {
393                         if (!$visitor_is_authenticated) {
394                                 // Remote follow is only available for local profiles
395                                 if (!empty($profile['nickname']) && strpos($profile_url, DI::baseUrl()->get()) === 0) {
396                                         $follow_link = 'remote_follow/' . $profile['nickname'];
397                                 }
398                         } elseif ($profile_is_native) {
399                                 if ($visitor_is_following) {
400                                         $unfollow_link = $visitor_base_path . '/unfollow?url=' . urlencode($profile_url) . '&auto=1';
401                                 } else {
402                                         $follow_link =  $visitor_base_path .'/follow?url=' . urlencode($profile_url) . '&auto=1';
403                                 }
404                         }
405
406                         if ($profile_is_dfrn) {
407                                 $subscribe_feed_link = 'dfrn_poll/' . $profile['nickname'];
408                         }
409
410                         if (Contact::canReceivePrivateMessages($profile_contact)) {
411                                 if ($visitor_is_followed || $visitor_is_following) {
412                                         $wallmessage_link = $visitor_base_path . '/message/new/' . $profile_contact['id'];
413                                 } elseif ($visitor_is_authenticated && !empty($profile['unkmail'])) {
414                                         $wallmessage_link = 'wallmessage/' . $profile['nickname'];
415                                 }
416                         }
417                 }
418
419                 // show edit profile to yourself, but only if this is not meant to be
420                 // rendered as a "contact". i.e., if 'self' (a "contact" table column) isn't
421                 // set in $profile.
422                 if (!isset($profile['self']) && $local_user_is_self) {
423                         $profile['edit'] = [DI::baseUrl() . '/settings/profile', DI::l10n()->t('Edit profile'), '', DI::l10n()->t('Edit profile')];
424                         $profile['menu'] = [
425                                 'chg_photo' => DI::l10n()->t('Change profile photo'),
426                                 'cr_new' => null,
427                                 'entries' => [],
428                         ];
429                 }
430
431                 // Fetch the account type
432                 $account_type = Contact::getAccountType($profile);
433
434                 if (!empty($profile['address']) || !empty($profile['location'])) {
435                         $location = DI::l10n()->t('Location:');
436                 }
437
438                 $homepage = !empty($profile['homepage']) ? DI::l10n()->t('Homepage:') : false;
439                 $about    = !empty($profile['about'])    ? DI::l10n()->t('About:')    : false;
440                 $xmpp     = !empty($profile['xmpp'])     ? DI::l10n()->t('XMPP:')     : false;
441
442                 if ((!empty($profile['hidewall']) || $block) && !Session::isAuthenticated()) {
443                         $location = $homepage = $about = false;
444                 }
445
446                 $split_name = Diaspora::splitName($profile['name']);
447                 $firstname = $split_name['first'];
448                 $lastname = $split_name['last'];
449
450                 if (!empty($profile['guid'])) {
451                         $diaspora = [
452                                 'guid' => $profile['guid'],
453                                 'podloc' => DI::baseUrl(),
454                                 'searchable' => ($profile['net-publish'] ? 'true' : 'false'),
455                                 'nickname' => $profile['nickname'],
456                                 'fullname' => $profile['name'],
457                                 'firstname' => $firstname,
458                                 'lastname' => $lastname,
459                                 'photo300' => $profile['photo'] ?? '',
460                                 'photo100' => $profile['thumb'] ?? '',
461                                 'photo50' => $profile['micro'] ?? '',
462                         ];
463                 } else {
464                         $diaspora = false;
465                 }
466
467                 $contact_block = '';
468                 $updated = '';
469                 $contact_count = 0;
470
471                 if (!empty($profile['last-item'])) {
472                         $updated = date('c', strtotime($profile['last-item']));
473                 }
474
475                 if (!$block) {
476                         $contact_block = ContactBlock::getHTML($a->profile);
477
478                         if (is_array($a->profile) && !$a->profile['hide-friends']) {
479                                 $contact_count = DBA::count('contact', [
480                                         'uid' => $profile['uid'],
481                                         'self' => false,
482                                         'blocked' => false,
483                                         'pending' => false,
484                                         'hidden' => false,
485                                         'archive' => false,
486                                         'failed' => false,
487                                         'network' => Protocol::FEDERATED,
488                                 ]);
489                         }
490                 }
491
492                 // Expected profile/vcard.tpl profile.* template variables
493                 $p = [
494                         'address' => null,
495                         'edit' => null,
496                         'upubkey' => null,
497                 ];
498                 foreach ($profile as $k => $v) {
499                         $k = str_replace('-', '_', $k);
500                         $p[$k] = $v;
501                 }
502
503                 if (isset($p['about'])) {
504                         $p['about'] = BBCode::convert($p['about']);
505                 }
506
507                 if (isset($p['address'])) {
508                         $p['address'] = BBCode::convert($p['address']);
509                 }
510
511                 if (isset($p['photo'])) {
512                         $p['photo'] = ProxyUtils::proxifyUrl($p['photo'], false, ProxyUtils::SIZE_SMALL);
513                 }
514
515                 $p['url'] = Contact::magicLink(($p['url'] ?? '') ?: $profile_url);
516
517                 $tpl = Renderer::getMarkupTemplate('profile/vcard.tpl');
518                 $o .= Renderer::replaceMacros($tpl, [
519                         '$profile' => $p,
520                         '$xmpp' => $xmpp,
521                         '$follow' => DI::l10n()->t('Follow'),
522                         '$follow_link' => $follow_link,
523                         '$unfollow' => DI::l10n()->t('Unfollow'),
524                         '$unfollow_link' => $unfollow_link,
525                         '$subscribe_feed' => DI::l10n()->t('Atom feed'),
526                         '$subscribe_feed_link' => $subscribe_feed_link,
527                         '$wallmessage' => DI::l10n()->t('Message'),
528                         '$wallmessage_link' => $wallmessage_link,
529                         '$account_type' => $account_type,
530                         '$location' => $location,
531                         '$homepage' => $homepage,
532                         '$about' => $about,
533                         '$network' => DI::l10n()->t('Network:'),
534                         '$contacts' => $contact_count,
535                         '$updated' => $updated,
536                         '$diaspora' => $diaspora,
537                         '$contact_block' => $contact_block,
538                 ]);
539
540                 $arr = ['profile' => &$profile, 'entry' => &$o];
541
542                 Hook::callAll('profile_sidebar', $arr);
543
544                 return $o;
545         }
546
547         public static function getBirthdays()
548         {
549                 $a = DI::app();
550                 $o = '';
551
552                 if (!local_user() || DI::mode()->isMobile() || DI::mode()->isMobile()) {
553                         return $o;
554                 }
555
556                 /*
557                 * $mobile_detect = new Mobile_Detect();
558                 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
559                 *               if ($is_mobile)
560                 *                       return $o;
561                 */
562
563                 $bd_format = DI::l10n()->t('g A l F d'); // 8 AM Friday January 18
564                 $bd_short = DI::l10n()->t('F d');
565
566                 $cachekey = 'get_birthdays:' . local_user();
567                 $r = DI::cache()->get($cachekey);
568                 if (is_null($r)) {
569                         $s = DBA::p(
570                                 "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
571                                 INNER JOIN `contact`
572                                         ON `contact`.`id` = `event`.`cid`
573                                         AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
574                                         AND NOT `contact`.`pending`
575                                         AND NOT `contact`.`hidden`
576                                         AND NOT `contact`.`blocked`
577                                         AND NOT `contact`.`archive`
578                                         AND NOT `contact`.`deleted`
579                                 WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
580                                 ORDER BY `start` ASC ",
581                                 Contact::SHARING,
582                                 Contact::FRIEND,
583                                 local_user(),
584                                 DateTimeFormat::utc('now + 6 days'),
585                                 DateTimeFormat::utcNow()
586                         );
587                         if (DBA::isResult($s)) {
588                                 $r = DBA::toArray($s);
589                                 DI::cache()->set($cachekey, $r, Duration::HOUR);
590                         }
591                 }
592
593                 $total = 0;
594                 $classtoday = '';
595                 if (DBA::isResult($r)) {
596                         $now = strtotime('now');
597                         $cids = [];
598
599                         $istoday = false;
600                         foreach ($r as $rr) {
601                                 if (strlen($rr['name'])) {
602                                         $total ++;
603                                 }
604                                 if ((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) {
605                                         $istoday = true;
606                                 }
607                         }
608                         $classtoday = $istoday ? ' birthday-today ' : '';
609                         if ($total) {
610                                 foreach ($r as &$rr) {
611                                         if (!strlen($rr['name'])) {
612                                                 continue;
613                                         }
614
615                                         // avoid duplicates
616
617                                         if (in_array($rr['cid'], $cids)) {
618                                                 continue;
619                                         }
620                                         $cids[] = $rr['cid'];
621
622                                         $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
623
624                                         $rr['link'] = Contact::magicLinkById($rr['cid']);
625                                         $rr['title'] = $rr['name'];
626                                         $rr['date'] = DI::l10n()->getDay(DateTimeFormat::convert($rr['start'], $a->timezone, 'UTC', $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '');
627                                         $rr['startime'] = null;
628                                         $rr['today'] = $today;
629                                 }
630                         }
631                 }
632                 $tpl = Renderer::getMarkupTemplate('birthdays_reminder.tpl');
633                 return Renderer::replaceMacros($tpl, [
634                         '$classtoday' => $classtoday,
635                         '$count' => $total,
636                         '$event_reminders' => DI::l10n()->t('Birthday Reminders'),
637                         '$event_title' => DI::l10n()->t('Birthdays this week:'),
638                         '$events' => $r,
639                         '$lbr' => '{', // raw brackets mess up if/endif macro processing
640                         '$rbr' => '}'
641                 ]);
642         }
643
644         public static function getEventsReminderHTML()
645         {
646                 $a = DI::app();
647                 $o = '';
648
649                 if (!local_user() || DI::mode()->isMobile() || DI::mode()->isMobile()) {
650                         return $o;
651                 }
652
653                 /*
654                 *       $mobile_detect = new Mobile_Detect();
655                 *               $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
656                 *               if ($is_mobile)
657                 *                       return $o;
658                 */
659
660                 $bd_format = DI::l10n()->t('g A l F d'); // 8 AM Friday January 18
661                 $classtoday = '';
662
663                 $condition = ["`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?",
664                         local_user(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utc('now - 1 days')];
665                 $s = DBA::select('event', [], $condition, ['order' => ['start']]);
666
667                 $r = [];
668
669                 if (DBA::isResult($s)) {
670                         $istoday = false;
671                         $total = 0;
672
673                         while ($rr = DBA::fetch($s)) {
674                                 $condition = ['parent-uri' => $rr['uri'], 'uid' => $rr['uid'], 'author-id' => public_contact(),
675                                         'vid' => [Verb::getID(Activity::ATTEND), Verb::getID(Activity::ATTENDMAYBE)],
676                                         'visible' => true, 'deleted' => false];
677                                 if (!Post::exists($condition)) {
678                                         continue;
679                                 }
680
681                                 if (strlen($rr['summary'])) {
682                                         $total++;
683                                 }
684
685                                 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', 'Y-m-d');
686                                 if ($strt === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
687                                         $istoday = true;
688                                 }
689
690                                 $title = strip_tags(html_entity_decode(BBCode::convert($rr['summary']), ENT_QUOTES, 'UTF-8'));
691
692                                 if (strlen($title) > 35) {
693                                         $title = substr($title, 0, 32) . '... ';
694                                 }
695
696                                 $description = substr(strip_tags(BBCode::convert($rr['desc'])), 0, 32) . '... ';
697                                 if (!$description) {
698                                         $description = DI::l10n()->t('[No description]');
699                                 }
700
701                                 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC');
702
703                                 if (substr($strt, 0, 10) < DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
704                                         continue;
705                                 }
706
707                                 $today = ((substr($strt, 0, 10) === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) ? true : false);
708
709                                 $rr['title'] = $title;
710                                 $rr['description'] = $description;
711                                 $rr['date'] = DI::l10n()->getDay(DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', $bd_format)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '');
712                                 $rr['startime'] = $strt;
713                                 $rr['today'] = $today;
714
715                                 $r[] = $rr;
716                         }
717                         DBA::close($s);
718                         $classtoday = (($istoday) ? 'event-today' : '');
719                 }
720                 $tpl = Renderer::getMarkupTemplate('events_reminder.tpl');
721                 return Renderer::replaceMacros($tpl, [
722                         '$classtoday' => $classtoday,
723                         '$count' => count($r),
724                         '$event_reminders' => DI::l10n()->t('Event Reminders'),
725                         '$event_title' => DI::l10n()->t('Upcoming events the next 7 days:'),
726                         '$events' => $r,
727                 ]);
728         }
729
730         /**
731          * Retrieves the my_url session variable
732          *
733          * @return string
734          */
735         public static function getMyURL()
736         {
737                 return Session::get('my_url');
738         }
739
740         /**
741          * Process the 'zrl' parameter and initiate the remote authentication.
742          *
743          * This method checks if the visitor has a public contact entry and
744          * redirects the visitor to his/her instance to start the magic auth (Authentication)
745          * process.
746          *
747          * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/channel.php
748          *
749          * The implementation for Friendica sadly differs in some points from the one for Hubzilla:
750          * - Hubzilla uses the "zid" parameter, while for Friendica it had been replaced with "zrl"
751          * - There seem to be some reverse authentication (rmagic) that isn't implemented in Friendica at all
752          *
753          * It would be favourable to harmonize the two implementations.
754          *
755          * @param App $a Application instance.
756          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
757          * @throws \ImagickException
758          */
759         public static function zrlInit(App $a)
760         {
761                 $my_url = self::getMyURL();
762                 $my_url = Network::isUrlValid($my_url);
763
764                 if (empty($my_url) || local_user()) {
765                         return;
766                 }
767
768                 $addr = $_GET['addr'] ?? $my_url;
769
770                 $arr = ['zrl' => $my_url, 'url' => DI::args()->getCommand()];
771                 Hook::callAll('zrl_init', $arr);
772
773                 // Try to find the public contact entry of the visitor.
774                 $cid = Contact::getIdForURL($my_url);
775                 if (!$cid) {
776                         Logger::log('No contact record found for ' . $my_url, Logger::DEBUG);
777                         return;
778                 }
779
780                 $contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]);
781
782                 if (DBA::isResult($contact) && remote_user() && remote_user() == $contact['id']) {
783                         Logger::log('The visitor ' . $my_url . ' is already authenticated', Logger::DEBUG);
784                         return;
785                 }
786
787                 // Avoid endless loops
788                 $cachekey = 'zrlInit:' . $my_url;
789                 if (DI::cache()->get($cachekey)) {
790                         Logger::log('URL ' . $my_url . ' already tried to authenticate.', Logger::DEBUG);
791                         return;
792                 } else {
793                         DI::cache()->set($cachekey, true, Duration::MINUTE);
794                 }
795
796                 Logger::log('Not authenticated. Invoking reverse magic-auth for ' . $my_url, Logger::DEBUG);
797
798                 // Remove the "addr" parameter from the destination. It is later added as separate parameter again.
799                 $addr_request = 'addr=' . urlencode($addr);
800                 $query = rtrim(str_replace($addr_request, '', DI::args()->getQueryString()), '?&');
801
802                 // The other instance needs to know where to redirect.
803                 $dest = urlencode(DI::baseUrl()->get() . '/' . $query);
804
805                 // We need to extract the basebath from the profile url
806                 // to redirect the visitors '/magic' module.
807                 $basepath = Contact::getBasepath($contact['url']);
808
809                 if ($basepath != DI::baseUrl()->get() && !strstr($dest, '/magic')) {
810                         $magic_path = $basepath . '/magic' . '?owa=1&dest=' . $dest . '&' . $addr_request;
811
812                         // We have to check if the remote server does understand /magic without invoking something
813                         $serverret = DI::httpRequest()->get($basepath . '/magic');
814                         if ($serverret->isSuccess()) {
815                                 Logger::log('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path, Logger::DEBUG);
816                                 System::externalRedirect($magic_path);
817                         }
818                 }
819         }
820
821         /**
822          * Set the visitor cookies (see remote_user()) for the given handle
823          *
824          * @param string $handle Visitor handle
825          * @return array Visitor contact array
826          */
827         public static function addVisitorCookieForHandle($handle)
828         {
829                 $a = DI::app();
830
831                 // Try to find the public contact entry of the visitor.
832                 $cid = Contact::getIdForURL($handle);
833                 if (!$cid) {
834                         Logger::log('unable to finger ' . $handle, Logger::DEBUG);
835                         return [];
836                 }
837
838                 $visitor = DBA::selectFirst('contact', [], ['id' => $cid]);
839
840                 // Authenticate the visitor.
841                 $_SESSION['authenticated'] = 1;
842                 $_SESSION['visitor_id'] = $visitor['id'];
843                 $_SESSION['visitor_handle'] = $visitor['addr'];
844                 $_SESSION['visitor_home'] = $visitor['url'];
845                 $_SESSION['my_url'] = $visitor['url'];
846                 $_SESSION['remote_comment'] = $visitor['subscribe'];
847
848                 Session::setVisitorsContacts();
849
850                 $a->contact = $visitor;
851
852                 Logger::info('Authenticated visitor', ['url' => $visitor['url']]);
853
854                 return $visitor;
855         }
856
857         /**
858          * OpenWebAuth authentication.
859          *
860          * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/zid.php
861          *
862          * @param string $token
863          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
864          * @throws \ImagickException
865          */
866         public static function openWebAuthInit($token)
867         {
868                 $a = DI::app();
869
870                 // Clean old OpenWebAuthToken entries.
871                 OpenWebAuthToken::purge('owt', '3 MINUTE');
872
873                 // Check if the token we got is the same one
874                 // we have stored in the database.
875                 $visitor_handle = OpenWebAuthToken::getMeta('owt', 0, $token);
876
877                 if ($visitor_handle === false) {
878                         return;
879                 }
880
881                 $visitor = self::addVisitorCookieForHandle($visitor_handle);
882                 if (empty($visitor)) {
883                         return;
884                 }
885
886                 $arr = [
887                         'visitor' => $visitor,
888                         'url' => DI::args()->getQueryString()
889                 ];
890                 /**
891                  * @hooks magic_auth_success
892                  *   Called when a magic-auth was successful.
893                  *   * \e array \b visitor
894                  *   * \e string \b url
895                  */
896                 Hook::callAll('magic_auth_success', $arr);
897
898                 $a->contact = $arr['visitor'];
899
900                 info(DI::l10n()->t('OpenWebAuth: %1$s welcomes %2$s', DI::baseUrl()->getHostname(), $visitor['name']));
901
902                 Logger::log('OpenWebAuth: auth success from ' . $visitor['addr'], Logger::DEBUG);
903         }
904
905         public static function zrl($s, $force = false)
906         {
907                 if (!strlen($s)) {
908                         return $s;
909                 }
910                 if (!strpos($s, '/profile/') && !$force) {
911                         return $s;
912                 }
913                 if ($force && substr($s, -1, 1) !== '/') {
914                         $s = $s . '/';
915                 }
916                 $achar = strpos($s, '?') ? '&' : '?';
917                 $mine = self::getMyURL();
918                 if ($mine && !Strings::compareLink($mine, $s)) {
919                         return $s . $achar . 'zrl=' . urlencode($mine);
920                 }
921                 return $s;
922         }
923
924         /**
925          * Get the user ID of the page owner.
926          *
927          * Used from within PCSS themes to set theme parameters. If there's a
928          * profile_uid variable set in App, that is the "page owner" and normally their theme
929          * settings take precedence; unless a local user sets the "always_my_theme"
930          * system pconfig, which means they don't want to see anybody else's theme
931          * settings except their own while on this site.
932          *
933          * @return int user ID
934          *
935          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
936          * @note Returns local_user instead of user ID if "always_my_theme" is set to true
937          */
938         public static function getThemeUid(App $a)
939         {
940                 $uid = !empty($a->profile_uid) ? intval($a->profile_uid) : 0;
941                 if (local_user() && (DI::pConfig()->get(local_user(), 'system', 'always_my_theme') || !$uid)) {
942                         return local_user();
943                 }
944
945                 return $uid;
946         }
947
948         /**
949          * search for Profiles
950          *
951          * @param int  $start
952          * @param int  $count
953          * @param null $search
954          *
955          * @return array [ 'total' => 123, 'entries' => [...] ];
956          *
957          * @throws \Exception
958          */
959         public static function searchProfiles($start = 0, $count = 100, $search = null)
960         {
961                 if (!empty($search)) {
962                         $publish = (DI::config()->get('system', 'publish_all') ? '' : "AND `publish` ");
963                         $searchTerm = '%' . $search . '%';
964                         $condition = ["NOT `blocked` AND NOT `account_removed`
965                                 $publish
966                                 AND ((`name` LIKE ?) OR
967                                 (`nickname` LIKE ?) OR
968                                 (`about` LIKE ?) OR
969                                 (`locality` LIKE ?) OR
970                                 (`region` LIKE ?) OR
971                                 (`country-name` LIKE ?) OR
972                                 (`pub_keywords` LIKE ?) OR
973                                 (`prv_keywords` LIKE ?))",
974                                 $searchTerm, $searchTerm, $searchTerm, $searchTerm,
975                                 $searchTerm, $searchTerm, $searchTerm, $searchTerm];
976                 } else {
977                         $condition = ['blocked' => false, 'account_removed' => false];
978                         if (!DI::config()->get('system', 'publish_all')) {
979                                 $condition['publish'] = true;
980                         }
981                 }
982
983                 $total = DBA::count('owner-view', $condition);
984
985                 // If nothing found, don't try to select details
986                 if ($total > 0) {
987                         $profiles = DBA::selectToArray('owner-view', [], $condition, ['order' => ['name'], 'limit' => [$start, $count]]);
988                 } else {
989                         $profiles = [];
990                 }
991
992                 return ['total' => $total, 'entries' => $profiles];
993         }
994 }