Merge branch 'develop' of https://github.com/friendica/friendica into develop
[friendica.git/.git] / src / Model / Profile.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2024, 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\App\Mode;
26 use Friendica\Content\Text\BBCode;
27 use Friendica\Content\Widget\ContactBlock;
28 use Friendica\Core\Cache\Enum\Duration;
29 use Friendica\Core\Hook;
30 use Friendica\Core\Logger;
31 use Friendica\Core\Protocol;
32 use Friendica\Core\Renderer;
33 use Friendica\Core\Search;
34 use Friendica\Core\Worker;
35 use Friendica\Database\DBA;
36 use Friendica\DI;
37 use Friendica\Network\HTTPException;
38 use Friendica\Protocol\Activity;
39 use Friendica\Protocol\Diaspora;
40 use Friendica\Security\PermissionSet\Entity\PermissionSet;
41 use Friendica\Util\DateTimeFormat;
42 use Friendica\Util\Proxy;
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|bool Profile data or false on error
53          * @throws \Exception
54          */
55         public static function getByUID(int $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|bool Profile data for the ID or false on error
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|bool $fields The fields to retrieve or false on error
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 Profile fields to update
93          * @param integer $uid    User id
94          *
95          * @return boolean Whether update was successful
96          * @throws \Exception
97          */
98         public static function update(array $fields, int $uid): bool
99         {
100                 $old_owner = User::getOwnerDataById($uid);
101                 if (empty($old_owner)) {
102                         return false;
103                 }
104
105                 if (!DBA::update('profile', $fields, ['uid' => $uid])) {
106                         return false;
107                 }
108
109                 $update = Contact::updateSelfFromUserID($uid);
110
111                 $owner = User::getOwnerDataById($uid);
112                 if (empty($owner)) {
113                         return false;
114                 }
115
116                 $profile_fields = ['postal-code', 'dob', 'prv_keywords', 'homepage'];
117                 foreach ($profile_fields as $field) {
118                         if ($old_owner[$field] != $owner[$field]) {
119                                 $update = true;
120                         }
121                 }
122
123                 if ($update) {
124                         self::publishUpdate($uid, ($old_owner['net-publish'] != $owner['net-publish']));
125                 }
126
127                 return true;
128         }
129
130         /**
131          * Publish a changed profile
132          *
133          * @param int  $uid User id
134          * @param bool $force Force publishing to the directory
135          *
136          * @return void
137          */
138         public static function publishUpdate(int $uid, bool $force = false)
139         {
140                 $owner = User::getOwnerDataById($uid);
141                 if (empty($owner)) {
142                         return;
143                 }
144
145                 if ($owner['net-publish'] || $force) {
146                         // Update global directory in background
147                         if (Search::getGlobalDirectory()) {
148                                 Worker::add(Worker::PRIORITY_LOW, 'Directory', $owner['url']);
149                         }
150                 }
151
152                 Worker::add(Worker::PRIORITY_LOW, 'ProfileUpdate', $uid);
153         }
154
155         /**
156          * Returns a formatted location string from the given profile array
157          *
158          * @param array $profile Profile array (Generated from the "profile" table)
159          *
160          * @return string Location string
161          */
162         public static function formatLocation(array $profile): string
163         {
164                 $location = '';
165
166                 if (!empty($profile['locality'])) {
167                         $location .= $profile['locality'];
168                 }
169
170                 if (!empty($profile['region']) && (($profile['locality'] ?? '') != $profile['region'])) {
171                         if ($location) {
172                                 $location .= ', ';
173                         }
174
175                         $location .= $profile['region'];
176                 }
177
178                 if (!empty($profile['country-name'])) {
179                         if ($location) {
180                                 $location .= ', ';
181                         }
182
183                         $location .= $profile['country-name'];
184                 }
185
186                 return $location;
187         }
188
189         /**
190          * Loads a profile into the page sidebar.
191          *
192          * The function requires a writeable copy of the main App structure, and the nickname
193          * of a registered local account.
194          *
195          * If the viewer is an authenticated remote viewer, the profile displayed is the
196          * one that has been configured for his/her viewing in the Contact manager.
197          * Passing a non-zero profile ID can also allow a preview of a selected profile
198          * by the owner.
199          *
200          * Profile information is placed in the App structure for later retrieval.
201          * Honours the owner's chosen theme for display.
202          *
203          * @attention Should only be run in the _init() functions of a module. That ensures that
204          *      the theme is chosen before the _init() function of a theme is run, which will usually
205          *      load a lot of theme-specific content
206          *
207          * @param App    $a
208          * @param string $nickname string
209          * @param bool   $show_contacts
210          *
211          * @return array Profile
212          * @throws HTTPException\NotFoundException
213          * @throws HTTPException\InternalServerErrorException
214          * @throws \ImagickException
215          */
216         public static function load(App $a, string $nickname, bool $show_contacts = true): array
217         {
218                 $profile = User::getOwnerDataByNick($nickname);
219                 if (!isset($profile['account_removed']) || $profile['account_removed']) {
220                         Logger::info('profile error: ' . DI::args()->getQueryString());
221                         return [];
222                 }
223
224                 // System user, aborting
225                 if ($profile['uid'] === 0) {
226                         DI::logger()->warning('System user found in Profile::load', ['nickname' => $nickname]);
227                         throw new HTTPException\NotFoundException(DI::l10n()->t('User not found.'));
228                 }
229
230                 $a->setProfileOwner($profile['uid']);
231
232                 DI::page()['title'] = $profile['name'] . ' @ ' . DI::config()->get('config', 'sitename');
233
234                 if (!DI::userSession()->getLocalUserId()) {
235                         $a->setCurrentTheme($profile['theme']);
236                         $a->setCurrentMobileTheme(DI::pConfig()->get($a->getProfileOwner(), 'system', 'mobile_theme') ?? '');
237                 }
238
239                 /*
240                 * load/reload current theme info
241                 */
242
243                 Renderer::setActiveTemplateEngine(); // reset the template engine to the default in case the user's theme doesn't specify one
244
245                 $theme_info_file = 'view/theme/' . $a->getCurrentTheme() . '/theme.php';
246                 if (file_exists($theme_info_file)) {
247                         require_once $theme_info_file;
248                 }
249
250                 $block = (DI::config()->get('system', 'block_public') && !DI::userSession()->isAuthenticated());
251
252                 /**
253                  * @todo
254                  * By now, the contact block isn't shown, when a different profile is given
255                  * But: When this profile was on the same server, then we could display the contacts
256                  */
257                 DI::page()['aside'] .= self::getVCardHtml($profile, $block, $show_contacts);
258
259                 return $profile;
260         }
261
262         /**
263          * Formats a profile for display in the sidebar.
264          *
265          * It is very difficult to templatise the HTML completely
266          * because of all the conditional logic.
267          *
268          * @param array $profile       Profile array
269          * @param bool  $block         Block personal details
270          * @param bool  $show_contacts Show contact block
271          *
272          * @return string HTML sidebar module
273          *
274          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
275          * @throws \ImagickException
276          * @note  Returns empty string if passed $profile is wrong type or not populated
277          *
278          * @hooks 'profile_sidebar_enter'
279          *      array $profile - profile data
280          * @hooks 'profile_sidebar'
281          *      array $arr
282          */
283         public static function getVCardHtml(array $profile, bool $block, bool $show_contacts): string
284         {
285                 $o = '';
286                 $location = false;
287
288                 $profile_contact = [];
289
290                 if (DI::userSession()->getLocalUserId() && ($profile['uid'] ?? 0) != DI::userSession()->getLocalUserId()) {
291                         $profile_contact = Contact::getByURL($profile['nurl'], null, [], DI::userSession()->getLocalUserId());
292                 }
293                 if (!empty($profile['cid']) && DI::userSession()->getMyUrl()) {
294                         $profile_contact = Contact::selectFirst([], ['id' => $profile['cid']]);
295                 }
296
297                 $profile['picdate'] = urlencode($profile['picdate']);
298
299                 $profile['network_link'] = '';
300
301                 Hook::callAll('profile_sidebar_enter', $profile);
302
303                 $profile_url = $profile['url'];
304
305                 $contact = Contact::selectFirst(['id'], ['uri-id' => $profile['uri-id'], 'uid' => 0]);
306                 if (!$contact) {
307                         return $o;
308                 }
309
310                 $cid = $contact['id'];
311
312                 $follow_link = null;
313                 $unfollow_link = null;
314                 $wallmessage_link = null;
315
316                 // Who is the logged-in user to this profile?
317                 $visitor_contact = [];
318                 if (!empty($profile['uid']) && DI::userSession()->getMyUrl()) {
319                         $visitor_contact = Contact::selectFirst(['rel'], ['uid' => $profile['uid'], 'nurl' => Strings::normaliseLink(DI::userSession()->getMyUrl())]);
320                 }
321
322                 $local_user_is_self = DI::userSession()->getMyUrl() && ($profile['url'] == DI::userSession()->getMyUrl());
323                 $visitor_is_authenticated = (bool)DI::userSession()->getMyUrl();
324                 $visitor_is_following =
325                         in_array($visitor_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND])
326                         || in_array($profile_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND]);
327                 $visitor_is_followed =
328                         in_array($visitor_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND])
329                         || in_array($profile_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND]);
330                 $visitor_base_path = DI::userSession()->getMyUrl() ? preg_replace('=/profile/(.*)=ism', '', DI::userSession()->getMyUrl()) : '';
331
332                 if (!$local_user_is_self) {
333                         if (!$visitor_is_authenticated) {
334                                 // Remote follow is only available for local profiles
335                                 if (!empty($profile['nickname']) && strpos($profile_url, (string)DI::baseUrl()) === 0) {
336                                         $follow_link = 'profile/' . $profile['nickname'] . '/remote_follow';
337                                 }
338                         } else {
339                                 if ($visitor_is_following) {
340                                         $unfollow_link = $visitor_base_path . '/contact/unfollow?url=' . urlencode($profile_url) . '&auto=1';
341                                 } else {
342                                         $follow_link = $visitor_base_path . '/contact/follow?url=' . urlencode($profile_url) . '&auto=1';
343                                 }
344                         }
345
346                         if (Contact::canReceivePrivateMessages($profile_contact)) {
347                                 if ($visitor_is_followed || $visitor_is_following) {
348                                         $wallmessage_link = $visitor_base_path . '/message/new/' . $profile_contact['id'];
349                                 }
350                         }
351                 }
352
353                 // show edit profile to yourself, but only if this is not meant to be
354                 // rendered as a "contact". i.e., if 'self' (a "contact" table column) isn't
355                 // set in $profile.
356                 if (!isset($profile['self']) && $local_user_is_self) {
357                         $profile['edit'] = [DI::baseUrl() . '/settings/profile', DI::l10n()->t('Edit profile'), '', DI::l10n()->t('Edit profile')];
358                         $profile['menu'] = [
359                                 'chg_photo' => DI::l10n()->t('Change profile photo'),
360                                 'cr_new' => null,
361                                 'entries' => [],
362                         ];
363                 }
364
365                 // Fetch the account type
366                 $account_type = Contact::getAccountType($profile['account-type']);
367
368                 if (!empty($profile['address']) || !empty($profile['location'])) {
369                         $location = DI::l10n()->t('Location:');
370                 }
371
372                 $homepage = !empty($profile['homepage']) ? DI::l10n()->t('Homepage:') : false;
373                 $about    = !empty($profile['about'])    ? DI::l10n()->t('About:')    : false;
374                 $xmpp     = !empty($profile['xmpp'])     ? DI::l10n()->t('XMPP:')     : false;
375                 $matrix   = !empty($profile['matrix'])   ? DI::l10n()->t('Matrix:')   : false;
376
377                 if ((!empty($profile['hidewall']) || $block) && !DI::userSession()->isAuthenticated()) {
378                         $location = $homepage = $about = false;
379                 }
380
381                 $split_name = Diaspora::splitName($profile['name']);
382                 $firstname = $split_name['first'];
383                 $lastname = $split_name['last'];
384
385                 if (!empty($profile['guid'])) {
386                         $diaspora = [
387                                 'guid'       => $profile['guid'],
388                                 'podloc'     => DI::baseUrl(),
389                                 'searchable' => ($profile['net-publish'] ? 'true' : 'false'),
390                                 'nickname'   => $profile['nickname'],
391                                 'fullname'   => $profile['name'],
392                                 'firstname'  => $firstname,
393                                 'lastname'   => $lastname,
394                                 'photo300'   => $profile['photo'] ?? '',
395                                 'photo100'   => $profile['thumb'] ?? '',
396                                 'photo50'    => $profile['micro'] ?? '',
397                         ];
398                 } else {
399                         $diaspora = false;
400                 }
401
402                 $contact_block = '';
403                 $updated = '';
404                 $contact_count = 0;
405
406                 if (!empty($profile['last-item'])) {
407                         $updated = date('c', strtotime($profile['last-item']));
408                 }
409
410                 if (!$block && $show_contacts) {
411                         $contact_block = ContactBlock::getHTML($profile, DI::userSession()->getLocalUserId());
412
413                         if (is_array($profile) && !$profile['hide-friends']) {
414                                 $contact_count = DBA::count('contact', [
415                                         'uid'     => $profile['uid'],
416                                         'self'    => false,
417                                         'blocked' => false,
418                                         'pending' => false,
419                                         'hidden'  => false,
420                                         'archive' => false,
421                                         'failed'  => false,
422                                         'network' => Protocol::FEDERATED,
423                                 ]);
424                         }
425                 }
426
427                 // Expected profile/vcard.tpl profile.* template variables
428                 $p = [
429                         'address' => null,
430                         'edit'    => null,
431                         'upubkey' => null,
432                 ];
433                 foreach ($profile as $k => $v) {
434                         $k = str_replace('-', '_', $k);
435                         $p[$k] = $v;
436                 }
437
438                 if (isset($p['about'])) {
439                         $p['about'] = BBCode::convertForUriId($profile['uri-id'] ?? 0, $p['about']);
440                 }
441
442                 if (isset($p['address'])) {
443                         $p['address'] = BBCode::convertForUriId($profile['uri-id'] ?? 0, $p['address']);
444                 }
445
446                 $p['photo'] = Contact::getAvatarUrlForId($cid, Proxy::SIZE_SMALL);
447
448                 $p['url'] = Contact::magicLinkById($cid, $profile['url']);
449
450                 if (!isset($profile['hidewall'])) {
451                         Logger::warning('Missing hidewall key in profile array', ['profile' => $profile]);
452                 }
453
454                 if ($profile['account-type'] == Contact::TYPE_COMMUNITY) {
455                         $mention_label = DI::l10n()->t('Post to group');
456                         $mention_url   = 'compose/0?body=!' . $profile['addr'];
457                         $network_label = DI::l10n()->t('View group');
458                 } else {
459                         $mention_label = DI::l10n()->t('Mention');
460                         $mention_url   = 'compose/0?body=@' . $profile['addr'];
461                         $network_label = DI::l10n()->t('Network Posts');
462                 }
463                 $network_url   = 'contact/' . $cid . '/conversations';
464
465                 $tpl = Renderer::getMarkupTemplate('profile/vcard.tpl');
466                 $o .= Renderer::replaceMacros($tpl, [
467                         '$profile' => $p,
468                         '$xmpp' => $xmpp,
469                         '$matrix' => $matrix,
470                         '$follow' => DI::l10n()->t('Follow'),
471                         '$follow_link' => $follow_link,
472                         '$unfollow' => DI::l10n()->t('Unfollow'),
473                         '$unfollow_link' => $unfollow_link,
474                         '$subscribe_feed' => DI::l10n()->t('Atom feed'),
475                         '$subscribe_feed_link' => $profile['hidewall'] ?? 0 ? '' : $profile['poll'],
476                         '$wallmessage' => DI::l10n()->t('Message'),
477                         '$wallmessage_link' => $wallmessage_link,
478                         '$account_type' => $account_type,
479                         '$location' => $location,
480                         '$homepage' => $homepage,
481                         '$homepage_verified' => DI::l10n()->t('This website has been verified to belong to the same person.'),
482                         '$about' => $about,
483                         '$network' => DI::l10n()->t('Network:'),
484                         '$contacts' => $contact_count,
485                         '$updated' => $updated,
486                         '$diaspora' => $diaspora,
487                         '$contact_block' => $contact_block,
488                         '$mention_label' => $mention_label,
489                         '$mention_url' => $mention_url,
490                         '$network_label' => $network_label,
491                         '$network_url' => $network_url,
492                 ]);
493
494                 $arr = ['profile' => &$profile, 'entry' => &$o];
495
496                 Hook::callAll('profile_sidebar', $arr);
497
498                 return $o;
499         }
500
501         /**
502          * Check if the event list should be displayed
503          *
504          * @param integer $uid
505          * @param Mode $mode
506          * @return boolean
507          */
508         public static function shouldDisplayEventList(int $uid, Mode $mode): bool
509         {
510                 if (empty($uid) || $mode->isMobile()) {
511                         return false;
512                 }
513
514                 if (!DI::pConfig()->get($uid, 'system', 'display_eventlist', true)) {
515                         return false;
516                 }
517
518                 return !DI::config()->get('theme', 'hide_eventlist');
519         }
520
521         /**
522          * Returns the upcoming birthdays of contacts of the current user as HTML content
523          * @param int $uid  User Id
524          *
525          * @return string The upcoming birthdays (HTML)
526          * @throws HTTPException\InternalServerErrorException
527          * @throws HTTPException\ServiceUnavailableException
528          * @throws \ImagickException
529          */
530         public static function getBirthdays(int $uid): string
531         {
532                 $bd_short = DI::l10n()->t('F d');
533
534                 $cacheKey = 'get_birthdays:' . $uid;
535                 $events   = DI::cache()->get($cacheKey);
536                 if (is_null($events)) {
537                         $result = DBA::p(
538                                 "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
539                                 INNER JOIN `contact`
540                                         ON `contact`.`id` = `event`.`cid`
541                                         AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
542                                         AND NOT `contact`.`pending`
543                                         AND NOT `contact`.`hidden`
544                                         AND NOT `contact`.`blocked`
545                                         AND NOT `contact`.`archive`
546                                         AND NOT `contact`.`deleted`
547                                 WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
548                                 ORDER BY `start`",
549                                 Contact::SHARING,
550                                 Contact::FRIEND,
551                                 $uid,
552                                 DateTimeFormat::utc('now + 6 days'),
553                                 DateTimeFormat::utcNow()
554                         );
555                         if (DBA::isResult($result)) {
556                                 $events = DBA::toArray($result);
557                                 DI::cache()->set($cacheKey, $events, Duration::HOUR);
558                         }
559                 }
560
561                 $total      = 0;
562                 $classToday = '';
563                 $tpl_events = [];
564                 if (DBA::isResult($events)) {
565                         $now  = strtotime('now');
566                         $cids = [];
567
568                         $isToday = false;
569                         foreach ($events as $event) {
570                                 if (strlen($event['name'])) {
571                                         $total++;
572                                 }
573                                 if ((strtotime($event['start'] . ' +00:00') < $now) && (strtotime($event['finish'] . ' +00:00') > $now)) {
574                                         $isToday = true;
575                                 }
576                         }
577                         $classToday = $isToday ? ' birthday-today ' : '';
578                         if ($total) {
579                                 foreach ($events as $event) {
580                                         if (!strlen($event['name'])) {
581                                                 continue;
582                                         }
583
584                                         // avoid duplicates
585                                         if (in_array($event['cid'], $cids)) {
586                                                 continue;
587                                         }
588                                         $cids[] = $event['cid'];
589
590                                         $today = (strtotime($event['start'] . ' +00:00') < $now) && (strtotime($event['finish'] . ' +00:00') > $now);
591
592                                         $tpl_events[] = [
593                                                 'id'    => $event['id'],
594                                                 'link'  => Contact::magicLinkById($event['cid']),
595                                                 'title' => $event['name'],
596                                                 'date'  => DI::l10n()->getDay(DateTimeFormat::local($event['start'], $bd_short)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '')
597                                         ];
598                                 }
599                         }
600                 }
601                 $tpl = Renderer::getMarkupTemplate('birthdays_reminder.tpl');
602                 return Renderer::replaceMacros($tpl, [
603                         '$classtoday'      => $classToday,
604                         '$count'           => $total,
605                         '$event_reminders' => DI::l10n()->t('Birthday Reminders'),
606                         '$event_title'     => DI::l10n()->t('Birthdays this week:'),
607                         '$events'          => $tpl_events,
608                         '$lbr'             => '{', // raw brackets mess up if/endif macro processing
609                         '$rbr'             => '}'
610                 ]);
611         }
612
613         /**
614          * Renders HTML for event reminder (e.g. contact birthdays
615          * @param int $uid  User Id
616          * @param int $pcid Public Contact Id
617          *
618          * @return string Rendered HTML
619          */
620         public static function getEventsReminderHTML(int $uid, int $pcid): string
621         {
622                 $bd_format = DI::l10n()->t('g A l F d'); // 8 AM Friday January 18
623                 $classtoday = '';
624
625                 $condition = ["`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?",
626                         $uid, DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utc('now - 1 days')];
627                 $s = DBA::select('event', [], $condition, ['order' => ['start']]);
628
629                 $r = [];
630
631                 if (DBA::isResult($s)) {
632                         $istoday = false;
633                         $total = 0;
634
635                         while ($rr = DBA::fetch($s)) {
636                                 $condition = ['parent-uri' => $rr['uri'], 'uid' => $rr['uid'], 'author-id' => $pcid,
637                                         'vid' => [Verb::getID(Activity::ATTEND), Verb::getID(Activity::ATTENDMAYBE)],
638                                         'visible' => true, 'deleted' => false];
639                                 if (!Post::exists($condition)) {
640                                         continue;
641                                 }
642
643                                 if (strlen($rr['summary'])) {
644                                         $total++;
645                                 }
646
647                                 $strt = DateTimeFormat::local($rr['start'], 'Y-m-d');
648                                 if ($strt === DateTimeFormat::localNow('Y-m-d')) {
649                                         $istoday = true;
650                                 }
651
652                                 $title = BBCode::toPlaintext($rr['summary'], false);
653
654                                 if (strlen($title) > 35) {
655                                         $title = substr($title, 0, 32) . '... ';
656                                 }
657
658                                 $description = BBCode::toPlaintext($rr['desc'], false) . '... ';
659                                 if (!$description) {
660                                         $description = DI::l10n()->t('[No description]');
661                                 }
662
663                                 $strt = DateTimeFormat::local($rr['start']);
664
665                                 if (substr($strt, 0, 10) < DateTimeFormat::localNow('Y-m-d')) {
666                                         continue;
667                                 }
668
669                                 $today = substr($strt, 0, 10) === DateTimeFormat::localNow('Y-m-d');
670
671                                 $rr['title'] = $title;
672                                 $rr['description'] = $description;
673                                 $rr['date'] = DI::l10n()->getDay(DateTimeFormat::local($rr['start'], $bd_format)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '');
674                                 $rr['startime'] = $strt;
675                                 $rr['today'] = $today;
676
677                                 $r[] = $rr;
678                         }
679                         DBA::close($s);
680                         $classtoday = (($istoday) ? 'event-today' : '');
681                 }
682                 $tpl = Renderer::getMarkupTemplate('events_reminder.tpl');
683                 return Renderer::replaceMacros($tpl, [
684                         '$classtoday' => $classtoday,
685                         '$count' => count($r),
686                         '$event_reminders' => DI::l10n()->t('Event Reminders'),
687                         '$event_title' => DI::l10n()->t('Upcoming events the next 7 days:'),
688                         '$events' => $r,
689                 ]);
690         }
691
692         /**
693          * Get the user ID of the page owner.
694          *
695          * Used from within PCSS themes to set theme parameters. If there's a
696          * profile_uid variable set in App, that is the "page owner" and normally their theme
697          * settings take precedence; unless a local user is logged in which means they don't
698          * want to see anybody else's theme settings except their own while on this site.
699          *
700          * @param App $a
701          *
702          * @return int user ID
703          *
704          * @note Returns local_user instead of user ID if "always_my_theme" is set to true
705          */
706         public static function getThemeUid(App $a): int
707         {
708                 return DI::userSession()->getLocalUserId() ?: $a->getProfileOwner();
709         }
710
711         /**
712          * search for Profiles
713          *
714          * @param int  $start Starting record (see LIMIT start,count)
715          * @param int  $count Maximum records (see LIMIT start,count)
716          * @param string $search Optional search word (see LIKE %s?%s)
717          *
718          * @return array [ 'total' => 123, 'entries' => [...] ];
719          *
720          * @throws \Exception
721          */
722         public static function searchProfiles(int $start = 0, int $count = 100, string $search = null): array
723         {
724                 if (!empty($search)) {
725                         $publish = (DI::config()->get('system', 'publish_all') ? '' : "AND `publish` ");
726                         $searchTerm = '%' . $search . '%';
727                         $condition = ["`verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired`
728                                 $publish
729                                 AND ((`name` LIKE ?) OR
730                                 (`nickname` LIKE ?) OR
731                                 (`about` LIKE ?) OR
732                                 (`locality` LIKE ?) OR
733                                 (`region` LIKE ?) OR
734                                 (`country-name` LIKE ?) OR
735                                 (`pub_keywords` LIKE ?) OR
736                                 (`prv_keywords` LIKE ?))",
737                                 $searchTerm, $searchTerm, $searchTerm, $searchTerm,
738                                 $searchTerm, $searchTerm, $searchTerm, $searchTerm];
739                 } else {
740                         $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
741                         if (!DI::config()->get('system', 'publish_all')) {
742                                 $condition['publish'] = true;
743                         }
744                 }
745
746                 $total = DBA::count('owner-view', $condition);
747
748                 // If nothing found, don't try to select details
749                 if ($total > 0) {
750                         $profiles = DBA::selectToArray('owner-view', [], $condition, ['order' => ['name'], 'limit' => [$start, $count]]);
751                 } else {
752                         $profiles = [];
753                 }
754
755                 return ['total' => $total, 'entries' => $profiles];
756         }
757
758         /**
759          * Migrates a legacy profile to the new slimmer profile with extra custom fields.
760          * Multi profiles are converted to ACl-protected custom fields and deleted.
761          *
762          * @param array $profile One profile array
763          *
764          * @return void
765          * @throws \Exception
766          */
767         public static function migrate(array $profile)
768         {
769                 // Already processed, aborting
770                 if ($profile['is-default'] === null) {
771                         return;
772                 }
773
774                 $contacts = [];
775
776                 if (!$profile['is-default']) {
777                         $contacts = Contact::selectToArray(['id'], [
778                                 'uid'        => $profile['uid'],
779                                 'profile-id' => $profile['id']
780                         ]);
781                         if (!count($contacts)) {
782                                 // No contact visibility selected defaults to user-only permission
783                                 $contacts = Contact::selectToArray(['id'], ['uid' => $profile['uid'], 'self' => true]);
784                         }
785                 }
786
787                 $permissionSet = DI::permissionSet()->selectOrCreate(
788                         new PermissionSet(
789                                 $profile['uid'],
790                                 array_column($contacts, 'id') ?? []
791                         )
792                 );
793
794                 $order = 1;
795
796                 $custom_fields = [
797                         'hometown'  => DI::l10n()->t('Hometown:'),
798                         'marital'   => DI::l10n()->t('Marital Status:'),
799                         'with'      => DI::l10n()->t('With:'),
800                         'howlong'   => DI::l10n()->t('Since:'),
801                         'sexual'    => DI::l10n()->t('Sexual Preference:'),
802                         'politic'   => DI::l10n()->t('Political Views:'),
803                         'religion'  => DI::l10n()->t('Religious Views:'),
804                         'likes'     => DI::l10n()->t('Likes:'),
805                         'dislikes'  => DI::l10n()->t('Dislikes:'),
806                         'pdesc'     => DI::l10n()->t('Title/Description:'),
807                         'summary'   => DI::l10n()->t('Summary'),
808                         'music'     => DI::l10n()->t('Musical interests'),
809                         'book'      => DI::l10n()->t('Books, literature'),
810                         'tv'        => DI::l10n()->t('Television'),
811                         'film'      => DI::l10n()->t('Film/dance/culture/entertainment'),
812                         'interest'  => DI::l10n()->t('Hobbies/Interests'),
813                         'romance'   => DI::l10n()->t('Love/romance'),
814                         'work'      => DI::l10n()->t('Work/employment'),
815                         'education' => DI::l10n()->t('School/education'),
816                         'contact'   => DI::l10n()->t('Contact information and Social Networks'),
817                 ];
818
819                 foreach ($custom_fields as $field => $label) {
820                         if (!empty($profile[$field]) && $profile[$field] > DBA::NULL_DATE && $profile[$field] > DBA::NULL_DATETIME) {
821                                 DI::profileField()->save(DI::profileFieldFactory()->createFromValues(
822                                         $profile['uid'],
823                                         $order,
824                                         trim($label, ':'),
825                                         $profile[$field],
826                                         $permissionSet
827                                 ));
828                         }
829
830                         $profile[$field] = null;
831                 }
832
833                 if ($profile['is-default']) {
834                         $profile['profile-name'] = null;
835                         $profile['is-default']   = null;
836                         DBA::update('profile', $profile, ['id' => $profile['id']]);
837                 } else if (!empty($profile['id'])) {
838                         DBA::delete('profile', ['id' => $profile['id']]);
839                 }
840         }
841 }