]> git.mxchange.org Git - friendica.git/blob - src/Model/Profile.php
Shorten "Configuration" to "Config" again, since the Wrapper is gone
[friendica.git] / src / Model / Profile.php
1 <?php
2 /**
3  * @file src/Model/Profile.php
4  */
5 namespace Friendica\Model;
6
7 use Friendica\App;
8 use Friendica\Content\Feature;
9 use Friendica\Content\ForumManager;
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Content\Text\HTML;
12 use Friendica\Content\Widget\ContactBlock;
13 use Friendica\Core\Cache\Duration;
14 use Friendica\Core\Config;
15 use Friendica\Core\Hook;
16 use Friendica\Core\Logger;
17 use Friendica\Core\Protocol;
18 use Friendica\Core\Renderer;
19 use Friendica\Core\Session;
20 use Friendica\Core\System;
21 use Friendica\Database\DBA;
22 use Friendica\DI;
23 use Friendica\Protocol\Activity;
24 use Friendica\Protocol\Diaspora;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\Network;
27 use Friendica\Util\Proxy as ProxyUtils;
28 use Friendica\Util\Strings;
29 use Friendica\Util\Temporal;
30
31 class Profile
32 {
33         /**
34          * Returns default profile for a given user id
35          *
36          * @param integer User ID
37          *
38          * @return array Profile data
39          * @throws \Exception
40          */
41         public static function getByUID($uid)
42         {
43                 $profile = DBA::selectFirst('profile', [], ['uid' => $uid, 'is-default' => true]);
44                 return $profile;
45         }
46
47         /**
48          * Returns default profile for a given user ID and ID
49          *
50          * @param int $uid The contact ID
51          * @param int $id The contact owner ID
52          * @param array $fields The selected fields
53          *
54          * @return array Profile data for the ID
55          * @throws \Exception
56          */
57         public static function getById(int $uid, int $id, array $fields = [])
58         {
59                 return DBA::selectFirst('profile', $fields, ['uid' => $uid, 'id' => $id]);
60         }
61
62         /**
63          * Returns profile data for the contact owner
64          *
65          * @param int $uid The User ID
66          * @param array $fields The fields to retrieve
67          *
68          * @return array Array of profile data
69          * @throws \Exception
70          */
71         public static function getListByUser(int $uid, array $fields = [])
72         {
73                 return DBA::selectToArray('profile', $fields, ['uid' => $uid]);
74         }
75
76         /**
77          * Returns a formatted location string from the given profile array
78          *
79          * @param array $profile Profile array (Generated from the "profile" table)
80          *
81          * @return string Location string
82          */
83         public static function formatLocation(array $profile)
84         {
85                 $location = '';
86
87                 if (!empty($profile['locality'])) {
88                         $location .= $profile['locality'];
89                 }
90
91                 if (!empty($profile['region']) && (($profile['locality'] ?? '') != $profile['region'])) {
92                         if ($location) {
93                                 $location .= ', ';
94                         }
95
96                         $location .= $profile['region'];
97                 }
98
99                 if (!empty($profile['country-name'])) {
100                         if ($location) {
101                                 $location .= ', ';
102                         }
103
104                         $location .= $profile['country-name'];
105                 }
106
107                 return $location;
108         }
109
110         /**
111          * Loads a profile into the page sidebar.
112          *
113          * The function requires a writeable copy of the main App structure, and the nickname
114          * of a registered local account.
115          *
116          * If the viewer is an authenticated remote viewer, the profile displayed is the
117          * one that has been configured for his/her viewing in the Contact manager.
118          * Passing a non-zero profile ID can also allow a preview of a selected profile
119          * by the owner.
120          *
121          * Profile information is placed in the App structure for later retrieval.
122          * Honours the owner's chosen theme for display.
123          *
124          * @attention Should only be run in the _init() functions of a module. That ensures that
125          *      the theme is chosen before the _init() function of a theme is run, which will usually
126          *      load a lot of theme-specific content
127          *
128          * @param App     $a
129          * @param string  $nickname     string
130          * @param int     $profile      int
131          * @param array   $profiledata  array
132          * @param boolean $show_connect Show connect link
133          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
134          * @throws \ImagickException
135          */
136         public static function load(App $a, $nickname, $profile = 0, array $profiledata = [], $show_connect = true)
137         {
138                 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nickname, 'account_removed' => false]);
139
140                 if (!DBA::isResult($user) && empty($profiledata)) {
141                         Logger::log('profile error: ' . DI::args()->getQueryString(), Logger::DEBUG);
142                         return;
143                 }
144
145                 if (count($profiledata) > 0) {
146                         // Ensure to have a "nickname" field
147                         if (empty($profiledata['nickname']) && !empty($profiledata['nick'])) {
148                                 $profiledata['nickname'] = $profiledata['nick'];
149                         }
150
151                         // Add profile data to sidebar
152                         DI::page()['aside'] .= self::sidebar($a, $profiledata, true, $show_connect);
153
154                         if (!DBA::isResult($user)) {
155                                 return;
156                         }
157                 }
158
159                 $pdata = self::getByNickname($nickname, $user['uid'], $profile);
160
161                 if (empty($pdata) && empty($profiledata)) {
162                         Logger::log('profile error: ' . DI::args()->getQueryString(), Logger::DEBUG);
163                         return;
164                 }
165
166                 if (empty($pdata)) {
167                         $pdata = ['uid' => 0, 'profile_uid' => 0, 'is-default' => false,'name' => $nickname];
168                 }
169
170                 // fetch user tags if this isn't the default profile
171
172                 if (!$pdata['is-default']) {
173                         $condition = ['uid' => $pdata['profile_uid'], 'is-default' => true];
174                         $profile = DBA::selectFirst('profile', ['pub_keywords'], $condition);
175                         if (DBA::isResult($profile)) {
176                                 $pdata['pub_keywords'] = $profile['pub_keywords'];
177                         }
178                 }
179
180                 $a->profile = $pdata;
181                 $a->profile_uid = $pdata['profile_uid'];
182
183                 $a->profile['mobile-theme'] = DI::pConfig()->get($a->profile['profile_uid'], 'system', 'mobile_theme');
184                 $a->profile['network'] = Protocol::DFRN;
185
186                 DI::page()['title'] = $a->profile['name'] . ' @ ' . DI::config()->get('config', 'sitename');
187
188                 if (!$profiledata && !DI::pConfig()->get(local_user(), 'system', 'always_my_theme')) {
189                         $a->setCurrentTheme($a->profile['theme']);
190                         $a->setCurrentMobileTheme($a->profile['mobile-theme']);
191                 }
192
193                 /*
194                 * load/reload current theme info
195                 */
196
197                 Renderer::setActiveTemplateEngine(); // reset the template engine to the default in case the user's theme doesn't specify one
198
199                 $theme_info_file = 'view/theme/' . $a->getCurrentTheme() . '/theme.php';
200                 if (file_exists($theme_info_file)) {
201                         require_once $theme_info_file;
202                 }
203
204                 if (local_user() && local_user() == $a->profile['uid'] && $profiledata) {
205                         DI::page()['aside'] .= Renderer::replaceMacros(
206                                 Renderer::getMarkupTemplate('profile_edlink.tpl'),
207                                 [
208                                         '$editprofile' => DI::l10n()->t('Edit profile'),
209                                         '$profid' => $a->profile['id']
210                                 ]
211                         );
212                 }
213
214                 $block = ((DI::config()->get('system', 'block_public') && !Session::isAuthenticated()) ? true : false);
215
216                 /**
217                  * @todo
218                  * By now, the contact block isn't shown, when a different profile is given
219                  * But: When this profile was on the same server, then we could display the contacts
220                  */
221                 if (!$profiledata) {
222                         DI::page()['aside'] .= self::sidebar($a, $a->profile, $block, $show_connect);
223                 }
224
225                 return;
226         }
227
228         /**
229          * Get all profile data of a local user
230          *
231          * If the viewer is an authenticated remote viewer, the profile displayed is the
232          * one that has been configured for his/her viewing in the Contact manager.
233          * Passing a non-zero profile ID can also allow a preview of a selected profile
234          * by the owner
235          *
236          * Includes all available profile data
237          *
238          * @param string $nickname   nick
239          * @param int    $uid        uid
240          * @param int    $profile_id ID of the profile
241          * @return array
242          * @throws \Exception
243          */
244         public static function getByNickname($nickname, $uid = 0, $profile_id = 0)
245         {
246                 if (!empty(Session::getRemoteContactID($uid))) {
247                         $contact = DBA::selectFirst('contact', ['profile-id'], ['id' => Session::getRemoteContactID($uid)]);
248                         if (DBA::isResult($contact)) {
249                                 $profile_id = $contact['profile-id'];
250                         }
251                 }
252
253                 $profile = null;
254
255                 if ($profile_id) {
256                         $profile = DBA::fetchFirst(
257                                 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` AS `contact_photo`,
258                                         `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
259                                         `profile`.`uid` AS `profile_uid`, `profile`.*,
260                                         `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
261                                 FROM `profile`
262                                 INNER JOIN `contact` on `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
263                                 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
264                                 WHERE `user`.`nickname` = ? AND `profile`.`id` = ? LIMIT 1",
265                                 $nickname,
266                                 intval($profile_id)
267                         );
268                 }
269                 if (!DBA::isResult($profile)) {
270                         $profile = DBA::fetchFirst(
271                                 "SELECT `contact`.`id` AS `contact_id`, `contact`.`photo` as `contact_photo`,
272                                         `contact`.`thumb` AS `contact_thumb`, `contact`.`micro` AS `contact_micro`,
273                                         `profile`.`uid` AS `profile_uid`, `profile`.*,
274                                         `contact`.`avatar-date` AS picdate, `contact`.`addr`, `contact`.`url`, `user`.*
275                                 FROM `profile`
276                                 INNER JOIN `contact` ON `contact`.`uid` = `profile`.`uid` AND `contact`.`self`
277                                 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
278                                 WHERE `user`.`nickname` = ? AND `profile`.`is-default` LIMIT 1",
279                                 $nickname
280                         );
281                 }
282
283                 return $profile;
284         }
285
286         /**
287          * Formats a profile for display in the sidebar.
288          *
289          * It is very difficult to templatise the HTML completely
290          * because of all the conditional logic.
291          *
292          * @param array   $profile
293          * @param int     $block
294          * @param boolean $show_connect Show connect link
295          *
296          * @return string HTML sidebar module
297          *
298          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
299          * @throws \ImagickException
300          * @note  Returns empty string if passed $profile is wrong type or not populated
301          *
302          * @hooks 'profile_sidebar_enter'
303          *      array $profile - profile data
304          * @hooks 'profile_sidebar'
305          *      array $arr
306          */
307         private static function sidebar(App $a, $profile, $block = 0, $show_connect = true)
308         {
309                 $o = '';
310                 $location = false;
311
312                 // This function can also use contact information in $profile
313                 $is_contact = !empty($profile['cid']);
314
315                 if (!is_array($profile) && !count($profile)) {
316                         return $o;
317                 }
318
319                 $profile['picdate'] = urlencode($profile['picdate'] ?? '');
320
321                 if (($profile['network'] != '') && ($profile['network'] != Protocol::DFRN)) {
322                         $profile['network_link'] = Strings::formatNetworkName($profile['network'], $profile['url']);
323                 } else {
324                         $profile['network_link'] = '';
325                 }
326
327                 Hook::callAll('profile_sidebar_enter', $profile);
328
329                 if (isset($profile['url'])) {
330                         $profile_url = $profile['url'];
331                 } else {
332                         $profile_url = DI::baseUrl()->get() . '/profile/' . $profile['nickname'];
333                 }
334
335                 $follow_link = null;
336                 $unfollow_link = null;
337                 $subscribe_feed_link = null;
338                 $wallmessage_link = null;
339
340
341
342                 $visitor_contact = [];
343                 if (!empty($profile['uid']) && self::getMyURL()) {
344                         $visitor_contact = Contact::selectFirst(['rel'], ['uid' => $profile['uid'], 'nurl' => Strings::normaliseLink(self::getMyURL())]);
345                 }
346
347                 $profile_contact = [];
348                 if (!empty($profile['cid']) && self::getMyURL()) {
349                         $profile_contact = Contact::selectFirst(['rel'], ['id' => $profile['cid']]);
350                 }
351
352                 $profile_is_dfrn = $profile['network'] == Protocol::DFRN;
353                 $profile_is_native = in_array($profile['network'], Protocol::NATIVE_SUPPORT);
354                 $local_user_is_self = local_user() && local_user() == ($profile['profile_uid'] ?? 0);
355                 $visitor_is_authenticated = (bool)self::getMyURL();
356                 $visitor_is_following =
357                         in_array($visitor_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND])
358                         || in_array($profile_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND]);
359                 $visitor_is_followed =
360                         in_array($visitor_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND])
361                         || in_array($profile_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND]);
362                 $visitor_base_path = self::getMyURL() ? preg_replace('=/profile/(.*)=ism', '', self::getMyURL()) : '';
363
364                 if (!$local_user_is_self && $show_connect) {
365                         if (!$visitor_is_authenticated) {
366                                 if (!empty($profile['nickname'])) {
367                                         $follow_link = 'dfrn_request/' . $profile['nickname'];
368                                 }
369                         } elseif ($profile_is_native) {
370                                 if ($visitor_is_following) {
371                                         $unfollow_link = $visitor_base_path . '/unfollow?url=' . urlencode($profile_url);
372                                 } else {
373                                         $follow_link =  $visitor_base_path .'/follow?url=' . urlencode($profile_url);
374                                 }
375                         }
376
377                         if ($profile_is_dfrn) {
378                                 $subscribe_feed_link = 'dfrn_poll/' . $profile['nickname'];
379                         }
380
381                         if (Contact::canReceivePrivateMessages($profile)) {
382                                 if ($visitor_is_followed || $visitor_is_following) {
383                                         $wallmessage_link = $visitor_base_path . '/message/new/' . base64_encode($profile['addr'] ?? '');
384                                 } elseif ($visitor_is_authenticated && !empty($profile['unkmail'])) {
385                                         $wallmessage_link = 'wallmessage/' . $profile['nickname'];
386                                 }
387                         }
388                 }
389
390                 // show edit profile to yourself
391                 if (!$is_contact && $local_user_is_self) {
392                         if (Feature::isEnabled(local_user(), 'multi_profiles')) {
393                                 $profile['edit'] = [DI::baseUrl() . '/profiles', DI::l10n()->t('Profiles'), '', DI::l10n()->t('Manage/edit profiles')];
394                                 $r = q(
395                                         "SELECT * FROM `profile` WHERE `uid` = %d",
396                                         local_user()
397                                 );
398
399                                 $profile['menu'] = [
400                                         'chg_photo' => DI::l10n()->t('Change profile photo'),
401                                         'cr_new' => DI::l10n()->t('Create New Profile'),
402                                         'entries' => [],
403                                 ];
404
405                                 if (DBA::isResult($r)) {
406                                         foreach ($r as $rr) {
407                                                 $profile['menu']['entries'][] = [
408                                                         'photo' => $rr['thumb'],
409                                                         'id' => $rr['id'],
410                                                         'alt' => DI::l10n()->t('Profile Image'),
411                                                         'profile_name' => $rr['profile-name'],
412                                                         'isdefault' => $rr['is-default'],
413                                                         'visibile_to_everybody' => DI::l10n()->t('visible to everybody'),
414                                                         'edit_visibility' => DI::l10n()->t('Edit visibility'),
415                                                 ];
416                                         }
417                                 }
418                         } else {
419                                 $profile['edit'] = [DI::baseUrl() . '/profiles/' . $profile['id'], DI::l10n()->t('Edit profile'), '', DI::l10n()->t('Edit profile')];
420                                 $profile['menu'] = [
421                                         'chg_photo' => DI::l10n()->t('Change profile photo'),
422                                         'cr_new' => null,
423                                         'entries' => [],
424                                 ];
425                         }
426                 }
427
428                 // Fetch the account type
429                 $account_type = Contact::getAccountType($profile);
430
431                 if (!empty($profile['address'])
432                         || !empty($profile['location'])
433                         || !empty($profile['locality'])
434                         || !empty($profile['region'])
435                         || !empty($profile['postal-code'])
436                         || !empty($profile['country-name'])
437                 ) {
438                         $location = DI::l10n()->t('Location:');
439                 }
440
441                 $gender   = !empty($profile['gender'])   ? DI::l10n()->t('Gender:')   : false;
442                 $marital  = !empty($profile['marital'])  ? DI::l10n()->t('Status:')   : false;
443                 $homepage = !empty($profile['homepage']) ? DI::l10n()->t('Homepage:') : false;
444                 $about    = !empty($profile['about'])    ? DI::l10n()->t('About:')    : false;
445                 $xmpp     = !empty($profile['xmpp'])     ? DI::l10n()->t('XMPP:')     : false;
446
447                 if ((!empty($profile['hidewall']) || $block) && !Session::isAuthenticated()) {
448                         $location = $gender = $marital = $homepage = $about = false;
449                 }
450
451                 $split_name = Diaspora::splitName($profile['name']);
452                 $firstname = $split_name['first'];
453                 $lastname = $split_name['last'];
454
455                 if (!empty($profile['guid'])) {
456                         $diaspora = [
457                                 'guid' => $profile['guid'],
458                                 'podloc' => DI::baseUrl(),
459                                 'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false'),
460                                 'nickname' => $profile['nickname'],
461                                 'fullname' => $profile['name'],
462                                 'firstname' => $firstname,
463                                 'lastname' => $lastname,
464                                 'photo300' => $profile['contact_photo'] ?? '',
465                                 'photo100' => $profile['contact_thumb'] ?? '',
466                                 'photo50' => $profile['contact_micro'] ?? '',
467                         ];
468                 } else {
469                         $diaspora = false;
470                 }
471
472                 $contact_block = '';
473                 $updated = '';
474                 $contact_count = 0;
475                 if (!$block) {
476                         $contact_block = ContactBlock::getHTML($a->profile);
477
478                         if (is_array($a->profile) && !$a->profile['hide-friends']) {
479                                 $r = q(
480                                         "SELECT `gcontact`.`updated` FROM `contact` INNER JOIN `gcontact` WHERE `gcontact`.`nurl` = `contact`.`nurl` AND `self` AND `uid` = %d LIMIT 1",
481                                         intval($a->profile['uid'])
482                                 );
483                                 if (DBA::isResult($r)) {
484                                         $updated = date('c', strtotime($r[0]['updated']));
485                                 }
486
487                                 $contact_count = DBA::count('contact', [
488                                         'uid' => $profile['uid'],
489                                         'self' => false,
490                                         'blocked' => false,
491                                         'pending' => false,
492                                         'hidden' => false,
493                                         'archive' => false,
494                                         'network' => Protocol::FEDERATED,
495                                 ]);
496                         }
497                 }
498
499                 $p = [];
500                 foreach ($profile as $k => $v) {
501                         $k = str_replace('-', '_', $k);
502                         $p[$k] = $v;
503                 }
504
505                 if (isset($p['about'])) {
506                         $p['about'] = BBCode::convert($p['about']);
507                 }
508
509                 if (empty($p['address']) && !empty($p['location'])) {
510                         $p['address'] = $p['location'];
511                 }
512
513                 if (isset($p['address'])) {
514                         $p['address'] = BBCode::convert($p['address']);
515                 }
516
517                 if (isset($p['gender'])) {
518                         $p['gender'] = DI::l10n()->t($p['gender']);
519                 }
520
521                 if (isset($p['marital'])) {
522                         $p['marital'] = DI::l10n()->t($p['marital']);
523                 }
524
525                 if (isset($p['photo'])) {
526                         $p['photo'] = ProxyUtils::proxifyUrl($p['photo'], false, ProxyUtils::SIZE_SMALL);
527                 }
528
529                 $p['url'] = Contact::magicLink(($p['url'] ?? '') ?: $profile_url);
530
531                 $tpl = Renderer::getMarkupTemplate('profile_vcard.tpl');
532                 $o .= Renderer::replaceMacros($tpl, [
533                         '$profile' => $p,
534                         '$xmpp' => $xmpp,
535                         '$follow' => DI::l10n()->t('Follow'),
536                         '$follow_link' => $follow_link,
537                         '$unfollow' => DI::l10n()->t('Unfollow'),
538                         '$unfollow_link' => $unfollow_link,
539                         '$subscribe_feed' => DI::l10n()->t('Atom feed'),
540                         '$subscribe_feed_link' => $subscribe_feed_link,
541                         '$wallmessage' => DI::l10n()->t('Message'),
542                         '$wallmessage_link' => $wallmessage_link,
543                         '$account_type' => $account_type,
544                         '$location' => $location,
545                         '$gender' => $gender,
546                         '$marital' => $marital,
547                         '$homepage' => $homepage,
548                         '$about' => $about,
549                         '$network' => DI::l10n()->t('Network:'),
550                         '$contacts' => $contact_count,
551                         '$updated' => $updated,
552                         '$diaspora' => $diaspora,
553                         '$contact_block' => $contact_block,
554                 ]);
555
556                 $arr = ['profile' => &$profile, 'entry' => &$o];
557
558                 Hook::callAll('profile_sidebar', $arr);
559
560                 return $o;
561         }
562
563         public static function getBirthdays()
564         {
565                 $a = DI::app();
566                 $o = '';
567
568                 if (!local_user() || DI::mode()->isMobile() || DI::mode()->isMobile()) {
569                         return $o;
570                 }
571
572                 /*
573                 * $mobile_detect = new Mobile_Detect();
574                 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
575                 *               if ($is_mobile)
576                 *                       return $o;
577                 */
578
579                 $bd_format = DI::l10n()->t('g A l F d'); // 8 AM Friday January 18
580                 $bd_short = DI::l10n()->t('F d');
581
582                 $cachekey = 'get_birthdays:' . local_user();
583                 $r = DI::cache()->get($cachekey);
584                 if (is_null($r)) {
585                         $s = DBA::p(
586                                 "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
587                                 INNER JOIN `contact`
588                                         ON `contact`.`id` = `event`.`cid`
589                                         AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
590                                         AND NOT `contact`.`pending`
591                                         AND NOT `contact`.`hidden`
592                                         AND NOT `contact`.`blocked`
593                                         AND NOT `contact`.`archive`
594                                         AND NOT `contact`.`deleted`
595                                 WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
596                                 ORDER BY `start` ASC ",
597                                 Contact::SHARING,
598                                 Contact::FRIEND,
599                                 local_user(),
600                                 DateTimeFormat::utc('now + 6 days'),
601                                 DateTimeFormat::utcNow()
602                         );
603                         if (DBA::isResult($s)) {
604                                 $r = DBA::toArray($s);
605                                 DI::cache()->set($cachekey, $r, Duration::HOUR);
606                         }
607                 }
608
609                 $total = 0;
610                 $classtoday = '';
611                 if (DBA::isResult($r)) {
612                         $now = strtotime('now');
613                         $cids = [];
614
615                         $istoday = false;
616                         foreach ($r as $rr) {
617                                 if (strlen($rr['name'])) {
618                                         $total ++;
619                                 }
620                                 if ((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) {
621                                         $istoday = true;
622                                 }
623                         }
624                         $classtoday = $istoday ? ' birthday-today ' : '';
625                         if ($total) {
626                                 foreach ($r as &$rr) {
627                                         if (!strlen($rr['name'])) {
628                                                 continue;
629                                         }
630
631                                         // avoid duplicates
632
633                                         if (in_array($rr['cid'], $cids)) {
634                                                 continue;
635                                         }
636                                         $cids[] = $rr['cid'];
637
638                                         $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
639
640                                         $rr['link'] = Contact::magicLink($rr['url']);
641                                         $rr['title'] = $rr['name'];
642                                         $rr['date'] = DI::l10n()->getDay(DateTimeFormat::convert($rr['start'], $a->timezone, 'UTC', $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '');
643                                         $rr['startime'] = null;
644                                         $rr['today'] = $today;
645                                 }
646                         }
647                 }
648                 $tpl = Renderer::getMarkupTemplate('birthdays_reminder.tpl');
649                 return Renderer::replaceMacros($tpl, [
650                         '$classtoday' => $classtoday,
651                         '$count' => $total,
652                         '$event_reminders' => DI::l10n()->t('Birthday Reminders'),
653                         '$event_title' => DI::l10n()->t('Birthdays this week:'),
654                         '$events' => $r,
655                         '$lbr' => '{', // raw brackets mess up if/endif macro processing
656                         '$rbr' => '}'
657                 ]);
658         }
659
660         public static function getEventsReminderHTML()
661         {
662                 $a = DI::app();
663                 $o = '';
664
665                 if (!local_user() || DI::mode()->isMobile() || DI::mode()->isMobile()) {
666                         return $o;
667                 }
668
669                 /*
670                 *       $mobile_detect = new Mobile_Detect();
671                 *               $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
672                 *               if ($is_mobile)
673                 *                       return $o;
674                 */
675
676                 $bd_format = DI::l10n()->t('g A l F d'); // 8 AM Friday January 18
677                 $classtoday = '';
678
679                 $condition = ["`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?",
680                         local_user(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utc('now - 1 days')];
681                 $s = DBA::select('event', [], $condition, ['order' => ['start']]);
682
683                 $r = [];
684
685                 if (DBA::isResult($s)) {
686                         $istoday = false;
687                         $total = 0;
688
689                         while ($rr = DBA::fetch($s)) {
690                                 $condition = ['parent-uri' => $rr['uri'], 'uid' => $rr['uid'], 'author-id' => public_contact(),
691                                         'activity' => [Item::activityToIndex( Activity::ATTEND), Item::activityToIndex(Activity::ATTENDMAYBE)],
692                                         'visible' => true, 'deleted' => false];
693                                 if (!Item::exists($condition)) {
694                                         continue;
695                                 }
696
697                                 if (strlen($rr['summary'])) {
698                                         $total++;
699                                 }
700
701                                 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', 'Y-m-d');
702                                 if ($strt === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
703                                         $istoday = true;
704                                 }
705
706                                 $title = strip_tags(html_entity_decode(BBCode::convert($rr['summary']), ENT_QUOTES, 'UTF-8'));
707
708                                 if (strlen($title) > 35) {
709                                         $title = substr($title, 0, 32) . '... ';
710                                 }
711
712                                 $description = substr(strip_tags(BBCode::convert($rr['desc'])), 0, 32) . '... ';
713                                 if (!$description) {
714                                         $description = DI::l10n()->t('[No description]');
715                                 }
716
717                                 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC');
718
719                                 if (substr($strt, 0, 10) < DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
720                                         continue;
721                                 }
722
723                                 $today = ((substr($strt, 0, 10) === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) ? true : false);
724
725                                 $rr['title'] = $title;
726                                 $rr['description'] = $description;
727                                 $rr['date'] = DI::l10n()->getDay(DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', $bd_format)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '');
728                                 $rr['startime'] = $strt;
729                                 $rr['today'] = $today;
730
731                                 $r[] = $rr;
732                         }
733                         DBA::close($s);
734                         $classtoday = (($istoday) ? 'event-today' : '');
735                 }
736                 $tpl = Renderer::getMarkupTemplate('events_reminder.tpl');
737                 return Renderer::replaceMacros($tpl, [
738                         '$classtoday' => $classtoday,
739                         '$count' => count($r),
740                         '$event_reminders' => DI::l10n()->t('Event Reminders'),
741                         '$event_title' => DI::l10n()->t('Upcoming events the next 7 days:'),
742                         '$events' => $r,
743                 ]);
744         }
745
746         public static function getAdvanced(App $a)
747         {
748                 $uid = intval($a->profile['uid']);
749
750                 if ($a->profile['name']) {
751                         $tpl = Renderer::getMarkupTemplate('profile_advanced.tpl');
752
753                         $profile = [];
754
755                         $profile['fullname'] = [DI::l10n()->t('Full Name:'), $a->profile['name']];
756
757                         if (Feature::isEnabled($uid, 'profile_membersince')) {
758                                 $profile['membersince'] = [DI::l10n()->t('Member since:'), DateTimeFormat::local($a->profile['register_date'])];
759                         }
760
761                         if ($a->profile['gender']) {
762                                 $profile['gender'] = [DI::l10n()->t('Gender:'), DI::l10n()->t($a->profile['gender'])];
763                         }
764
765                         if (!empty($a->profile['dob']) && $a->profile['dob'] > DBA::NULL_DATE) {
766                                 $year_bd_format = DI::l10n()->t('j F, Y');
767                                 $short_bd_format = DI::l10n()->t('j F');
768
769                                 $val = DI::l10n()->getDay(
770                                         intval($a->profile['dob']) ?
771                                                 DateTimeFormat::utc($a->profile['dob'] . ' 00:00 +00:00', $year_bd_format)
772                                                 : DateTimeFormat::utc('2001-' . substr($a->profile['dob'], 5) . ' 00:00 +00:00', $short_bd_format)
773                                 );
774
775                                 $profile['birthday'] = [DI::l10n()->t('Birthday:'), $val];
776                         }
777
778                         if (!empty($a->profile['dob'])
779                                 && $a->profile['dob'] > DBA::NULL_DATE
780                                 && $age = Temporal::getAgeByTimezone($a->profile['dob'], $a->profile['timezone'], '')
781                         ) {
782                                 $profile['age'] = [DI::l10n()->t('Age:'), $age];
783                         }
784
785                         if ($a->profile['marital']) {
786                                 $profile['marital'] = [DI::l10n()->t('Status:'), DI::l10n()->t($a->profile['marital'])];
787                         }
788
789                         /// @TODO Maybe use x() here, plus below?
790                         if ($a->profile['with']) {
791                                 $profile['marital']['with'] = $a->profile['with'];
792                         }
793
794                         if (strlen($a->profile['howlong']) && $a->profile['howlong'] > DBA::NULL_DATETIME) {
795                                 $profile['howlong'] = Temporal::getRelativeDate($a->profile['howlong'], DI::l10n()->t('for %1$d %2$s'));
796                         }
797
798                         if ($a->profile['sexual']) {
799                                 $profile['sexual'] = [DI::l10n()->t('Sexual Preference:'), DI::l10n()->t($a->profile['sexual'])];
800                         }
801
802                         if ($a->profile['homepage']) {
803                                 $profile['homepage'] = [DI::l10n()->t('Homepage:'), HTML::toLink($a->profile['homepage'])];
804                         }
805
806                         if ($a->profile['hometown']) {
807                                 $profile['hometown'] = [DI::l10n()->t('Hometown:'), HTML::toLink($a->profile['hometown'])];
808                         }
809
810                         if ($a->profile['pub_keywords']) {
811                                 $profile['pub_keywords'] = [DI::l10n()->t('Tags:'), $a->profile['pub_keywords']];
812                         }
813
814                         if ($a->profile['politic']) {
815                                 $profile['politic'] = [DI::l10n()->t('Political Views:'), $a->profile['politic']];
816                         }
817
818                         if ($a->profile['religion']) {
819                                 $profile['religion'] = [DI::l10n()->t('Religion:'), $a->profile['religion']];
820                         }
821
822                         if ($txt = BBCode::convert($a->profile['about'])) {
823                                 $profile['about'] = [DI::l10n()->t('About:'), $txt];
824                         }
825
826                         if ($txt = BBCode::convert($a->profile['interest'])) {
827                                 $profile['interest'] = [DI::l10n()->t('Hobbies/Interests:'), $txt];
828                         }
829
830                         if ($txt = BBCode::convert($a->profile['likes'])) {
831                                 $profile['likes'] = [DI::l10n()->t('Likes:'), $txt];
832                         }
833
834                         if ($txt = BBCode::convert($a->profile['dislikes'])) {
835                                 $profile['dislikes'] = [DI::l10n()->t('Dislikes:'), $txt];
836                         }
837
838                         if ($txt = BBCode::convert($a->profile['contact'])) {
839                                 $profile['contact'] = [DI::l10n()->t('Contact information and Social Networks:'), $txt];
840                         }
841
842                         if ($txt = BBCode::convert($a->profile['music'])) {
843                                 $profile['music'] = [DI::l10n()->t('Musical interests:'), $txt];
844                         }
845
846                         if ($txt = BBCode::convert($a->profile['book'])) {
847                                 $profile['book'] = [DI::l10n()->t('Books, literature:'), $txt];
848                         }
849
850                         if ($txt = BBCode::convert($a->profile['tv'])) {
851                                 $profile['tv'] = [DI::l10n()->t('Television:'), $txt];
852                         }
853
854                         if ($txt = BBCode::convert($a->profile['film'])) {
855                                 $profile['film'] = [DI::l10n()->t('Film/dance/culture/entertainment:'), $txt];
856                         }
857
858                         if ($txt = BBCode::convert($a->profile['romance'])) {
859                                 $profile['romance'] = [DI::l10n()->t('Love/Romance:'), $txt];
860                         }
861
862                         if ($txt = BBCode::convert($a->profile['work'])) {
863                                 $profile['work'] = [DI::l10n()->t('Work/employment:'), $txt];
864                         }
865
866                         if ($txt = BBCode::convert($a->profile['education'])) {
867                                 $profile['education'] = [DI::l10n()->t('School/education:'), $txt];
868                         }
869
870                         //show subcribed forum if it is enabled in the usersettings
871                         if (Feature::isEnabled($uid, 'forumlist_profile')) {
872                                 $profile['forumlist'] = [DI::l10n()->t('Forums:'), ForumManager::profileAdvanced($uid)];
873                         }
874
875                         if ($a->profile['uid'] == local_user()) {
876                                 $profile['edit'] = [DI::baseUrl() . '/profiles/' . $a->profile['id'], DI::l10n()->t('Edit profile'), '', DI::l10n()->t('Edit profile')];
877                         }
878
879                         return Renderer::replaceMacros($tpl, [
880                                 '$title' => DI::l10n()->t('Profile'),
881                                 '$basic' => DI::l10n()->t('Basic'),
882                                 '$advanced' => DI::l10n()->t('Advanced'),
883                                 '$profile' => $profile
884                         ]);
885                 }
886
887                 return '';
888         }
889
890     /**
891      * @param App    $a
892      * @param string $current
893      * @param bool   $is_owner
894      * @param string $nickname
895      * @return string
896      * @throws \Friendica\Network\HTTPException\InternalServerErrorException
897      */
898         public static function getTabs(App $a, string $current, bool $is_owner, string $nickname = null)
899         {
900                 if (is_null($nickname)) {
901                         $nickname = $a->user['nickname'];
902                 }
903
904                 $baseProfileUrl = DI::baseUrl() . '/profile/' . $nickname;
905
906                 $tabs = [
907                         [
908                                 'label' => DI::l10n()->t('Status'),
909                                 'url'   => $baseProfileUrl,
910                                 'sel'   => !$current ? 'active' : '',
911                                 'title' => DI::l10n()->t('Status Messages and Posts'),
912                                 'id'    => 'status-tab',
913                                 'accesskey' => 'm',
914                         ],
915                         [
916                                 'label' => DI::l10n()->t('Profile'),
917                                 'url'   => $baseProfileUrl . '/?tab=profile',
918                                 'sel'   => $current == 'profile' ? 'active' : '',
919                                 'title' => DI::l10n()->t('Profile Details'),
920                                 'id'    => 'profile-tab',
921                                 'accesskey' => 'r',
922                         ],
923                         [
924                                 'label' => DI::l10n()->t('Photos'),
925                                 'url'   => DI::baseUrl() . '/photos/' . $nickname,
926                                 'sel'   => $current == 'photos' ? 'active' : '',
927                                 'title' => DI::l10n()->t('Photo Albums'),
928                                 'id'    => 'photo-tab',
929                                 'accesskey' => 'h',
930                         ],
931                         [
932                                 'label' => DI::l10n()->t('Videos'),
933                                 'url'   => DI::baseUrl() . '/videos/' . $nickname,
934                                 'sel'   => $current == 'videos' ? 'active' : '',
935                                 'title' => DI::l10n()->t('Videos'),
936                                 'id'    => 'video-tab',
937                                 'accesskey' => 'v',
938                         ],
939                 ];
940
941                 // the calendar link for the full featured events calendar
942                 if ($is_owner && $a->theme_events_in_profile) {
943                         $tabs[] = [
944                                 'label' => DI::l10n()->t('Events'),
945                                 'url'   => DI::baseUrl() . '/events',
946                                 'sel'   => $current == 'events' ? 'active' : '',
947                                 'title' => DI::l10n()->t('Events and Calendar'),
948                                 'id'    => 'events-tab',
949                                 'accesskey' => 'e',
950                         ];
951                         // if the user is not the owner of the calendar we only show a calendar
952                         // with the public events of the calendar owner
953                 } elseif (!$is_owner) {
954                         $tabs[] = [
955                                 'label' => DI::l10n()->t('Events'),
956                                 'url'   => DI::baseUrl() . '/cal/' . $nickname,
957                                 'sel'   => $current == 'cal' ? 'active' : '',
958                                 'title' => DI::l10n()->t('Events and Calendar'),
959                                 'id'    => 'events-tab',
960                                 'accesskey' => 'e',
961                         ];
962                 }
963
964                 if ($is_owner) {
965                         $tabs[] = [
966                                 'label' => DI::l10n()->t('Personal Notes'),
967                                 'url'   => DI::baseUrl() . '/notes',
968                                 'sel'   => $current == 'notes' ? 'active' : '',
969                                 'title' => DI::l10n()->t('Only You Can See This'),
970                                 'id'    => 'notes-tab',
971                                 'accesskey' => 't',
972                         ];
973                 }
974
975                 if (!empty($_SESSION['new_member']) && $is_owner) {
976                         $tabs[] = [
977                                 'label' => DI::l10n()->t('Tips for New Members'),
978                                 'url'   => DI::baseUrl() . '/newmember',
979                                 'sel'   => false,
980                                 'title' => DI::l10n()->t('Tips for New Members'),
981                                 'id'    => 'newmember-tab',
982                         ];
983                 }
984
985                 if ($is_owner || empty($a->profile['hide-friends'])) {
986                         $tabs[] = [
987                                 'label' => DI::l10n()->t('Contacts'),
988                                 'url'   => $baseProfileUrl . '/contacts',
989                                 'sel'   => $current == 'contacts' ? 'active' : '',
990                                 'title' => DI::l10n()->t('Contacts'),
991                                 'id'    => 'viewcontacts-tab',
992                                 'accesskey' => 'k',
993                         ];
994                 }
995
996                 $arr = ['is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => $current, 'tabs' => $tabs];
997                 Hook::callAll('profile_tabs', $arr);
998
999                 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
1000
1001                 return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
1002         }
1003
1004         /**
1005          * Retrieves the my_url session variable
1006          *
1007          * @return string
1008          */
1009         public static function getMyURL()
1010         {
1011                 return Session::get('my_url');
1012         }
1013
1014         /**
1015          * Process the 'zrl' parameter and initiate the remote authentication.
1016          *
1017          * This method checks if the visitor has a public contact entry and
1018          * redirects the visitor to his/her instance to start the magic auth (Authentication)
1019          * process.
1020          *
1021          * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/channel.php
1022          *
1023          * The implementation for Friendica sadly differs in some points from the one for Hubzilla:
1024          * - Hubzilla uses the "zid" parameter, while for Friendica it had been replaced with "zrl"
1025          * - There seem to be some reverse authentication (rmagic) that isn't implemented in Friendica at all
1026          *
1027          * It would be favourable to harmonize the two implementations.
1028          *
1029          * @param App $a Application instance.
1030          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1031          * @throws \ImagickException
1032          */
1033         public static function zrlInit(App $a)
1034         {
1035                 $my_url = self::getMyURL();
1036                 $my_url = Network::isUrlValid($my_url);
1037
1038                 if (empty($my_url) || local_user()) {
1039                         return;
1040                 }
1041
1042                 $addr = $_GET['addr'] ?? $my_url;
1043
1044                 $arr = ['zrl' => $my_url, 'url' => DI::args()->getCommand()];
1045                 Hook::callAll('zrl_init', $arr);
1046
1047                 // Try to find the public contact entry of the visitor.
1048                 $cid = Contact::getIdForURL($my_url);
1049                 if (!$cid) {
1050                         Logger::log('No contact record found for ' . $my_url, Logger::DEBUG);
1051                         return;
1052                 }
1053
1054                 $contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]);
1055
1056                 if (DBA::isResult($contact) && remote_user() && remote_user() == $contact['id']) {
1057                         Logger::log('The visitor ' . $my_url . ' is already authenticated', Logger::DEBUG);
1058                         return;
1059                 }
1060
1061                 // Avoid endless loops
1062                 $cachekey = 'zrlInit:' . $my_url;
1063                 if (DI::cache()->get($cachekey)) {
1064                         Logger::log('URL ' . $my_url . ' already tried to authenticate.', Logger::DEBUG);
1065                         return;
1066                 } else {
1067                         DI::cache()->set($cachekey, true, Duration::MINUTE);
1068                 }
1069
1070                 Logger::log('Not authenticated. Invoking reverse magic-auth for ' . $my_url, Logger::DEBUG);
1071
1072                 // Remove the "addr" parameter from the destination. It is later added as separate parameter again.
1073                 $addr_request = 'addr=' . urlencode($addr);
1074                 $query = rtrim(str_replace($addr_request, '', DI::args()->getQueryString()), '?&');
1075
1076                 // The other instance needs to know where to redirect.
1077                 $dest = urlencode(DI::baseUrl()->get() . '/' . $query);
1078
1079                 // We need to extract the basebath from the profile url
1080                 // to redirect the visitors '/magic' module.
1081                 $basepath = Contact::getBasepath($contact['url']);
1082
1083                 if ($basepath != DI::baseUrl()->get() && !strstr($dest, '/magic')) {
1084                         $magic_path = $basepath . '/magic' . '?owa=1&dest=' . $dest . '&' . $addr_request;
1085
1086                         // We have to check if the remote server does understand /magic without invoking something
1087                         $serverret = Network::curl($basepath . '/magic');
1088                         if ($serverret->isSuccess()) {
1089                                 Logger::log('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path, Logger::DEBUG);
1090                                 System::externalRedirect($magic_path);
1091                         }
1092                 }
1093         }
1094
1095         /**
1096          * Set the visitor cookies (see remote_user()) for the given handle
1097          *
1098          * @param string $handle Visitor handle
1099          * @return array Visitor contact array
1100          */
1101         public static function addVisitorCookieForHandle($handle)
1102         {
1103                 $a = DI::app();
1104
1105                 // Try to find the public contact entry of the visitor.
1106                 $cid = Contact::getIdForURL($handle);
1107                 if (!$cid) {
1108                         Logger::log('unable to finger ' . $handle, Logger::DEBUG);
1109                         return [];
1110                 }
1111
1112                 $visitor = DBA::selectFirst('contact', [], ['id' => $cid]);
1113
1114                 // Authenticate the visitor.
1115                 $_SESSION['authenticated'] = 1;
1116                 $_SESSION['visitor_id'] = $visitor['id'];
1117                 $_SESSION['visitor_handle'] = $visitor['addr'];
1118                 $_SESSION['visitor_home'] = $visitor['url'];
1119                 $_SESSION['my_url'] = $visitor['url'];
1120
1121                 Session::setVisitorsContacts();
1122
1123                 $a->contact = $visitor;
1124
1125                 Logger::info('Authenticated visitor', ['url' => $visitor['url']]);
1126
1127                 return $visitor;
1128         }
1129
1130         /**
1131          * OpenWebAuth authentication.
1132          *
1133          * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/zid.php
1134          *
1135          * @param string $token
1136          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1137          * @throws \ImagickException
1138          */
1139         public static function openWebAuthInit($token)
1140         {
1141                 $a = DI::app();
1142
1143                 // Clean old OpenWebAuthToken entries.
1144                 OpenWebAuthToken::purge('owt', '3 MINUTE');
1145
1146                 // Check if the token we got is the same one
1147                 // we have stored in the database.
1148                 $visitor_handle = OpenWebAuthToken::getMeta('owt', 0, $token);
1149
1150                 if ($visitor_handle === false) {
1151                         return;
1152                 }
1153
1154                 $visitor = self::addVisitorCookieForHandle($visitor_handle);
1155                 if (empty($visitor)) {
1156                         return;
1157                 }
1158
1159                 $arr = [
1160                         'visitor' => $visitor,
1161                         'url' => DI::args()->getQueryString()
1162                 ];
1163                 /**
1164                  * @hooks magic_auth_success
1165                  *   Called when a magic-auth was successful.
1166                  *   * \e array \b visitor
1167                  *   * \e string \b url
1168                  */
1169                 Hook::callAll('magic_auth_success', $arr);
1170
1171                 $a->contact = $arr['visitor'];
1172
1173                 info(DI::l10n()->t('OpenWebAuth: %1$s welcomes %2$s', DI::baseUrl()->getHostname(), $visitor['name']));
1174
1175                 Logger::log('OpenWebAuth: auth success from ' . $visitor['addr'], Logger::DEBUG);
1176         }
1177
1178         public static function zrl($s, $force = false)
1179         {
1180                 if (!strlen($s)) {
1181                         return $s;
1182                 }
1183                 if (!strpos($s, '/profile/') && !$force) {
1184                         return $s;
1185                 }
1186                 if ($force && substr($s, -1, 1) !== '/') {
1187                         $s = $s . '/';
1188                 }
1189                 $achar = strpos($s, '?') ? '&' : '?';
1190                 $mine = self::getMyURL();
1191                 if ($mine && !Strings::compareLink($mine, $s)) {
1192                         return $s . $achar . 'zrl=' . urlencode($mine);
1193                 }
1194                 return $s;
1195         }
1196
1197         /**
1198          * Get the user ID of the page owner.
1199          *
1200          * Used from within PCSS themes to set theme parameters. If there's a
1201          * profile_uid variable set in App, that is the "page owner" and normally their theme
1202          * settings take precedence; unless a local user sets the "always_my_theme"
1203          * system pconfig, which means they don't want to see anybody else's theme
1204          * settings except their own while on this site.
1205          *
1206          * @return int user ID
1207          *
1208          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1209          * @note Returns local_user instead of user ID if "always_my_theme" is set to true
1210          */
1211         public static function getThemeUid(App $a)
1212         {
1213                 $uid = !empty($a->profile_uid) ? intval($a->profile_uid) : 0;
1214                 if (local_user() && (DI::pConfig()->get(local_user(), 'system', 'always_my_theme') || !$uid)) {
1215                         return local_user();
1216                 }
1217
1218                 return $uid;
1219         }
1220
1221         /**
1222          * search for Profiles
1223          *
1224          * @param int  $start
1225          * @param int  $count
1226          * @param null $search
1227          *
1228          * @return array [ 'total' => 123, 'entries' => [...] ];
1229          *
1230          * @throws \Exception
1231          */
1232         public static function searchProfiles($start = 0, $count = 100, $search = null)
1233         {
1234                 $publish = (DI::config()->get('system', 'publish_all') ? '' : " AND `publish` = 1 ");
1235                 $total = 0;
1236
1237                 if (!empty($search)) {
1238                         $searchTerm = '%' . $search . '%';
1239                         $cnt = DBA::fetchFirst("SELECT COUNT(*) AS `total`
1240                                 FROM `profile`
1241                                 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1242                                 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed`
1243                                 AND ((`profile`.`name` LIKE ?) OR
1244                                 (`user`.`nickname` LIKE ?) OR
1245                                 (`profile`.`pdesc` LIKE ?) OR
1246                                 (`profile`.`locality` LIKE ?) OR
1247                                 (`profile`.`region` LIKE ?) OR
1248                                 (`profile`.`country-name` LIKE ?) OR
1249                                 (`profile`.`gender` LIKE ?) OR
1250                                 (`profile`.`marital` LIKE ?) OR
1251                                 (`profile`.`sexual` LIKE ?) OR
1252                                 (`profile`.`about` LIKE ?) OR
1253                                 (`profile`.`romance` LIKE ?) OR
1254                                 (`profile`.`work` LIKE ?) OR
1255                                 (`profile`.`education` LIKE ?) OR
1256                                 (`profile`.`pub_keywords` LIKE ?) OR
1257                                 (`profile`.`prv_keywords` LIKE ?))",
1258                                 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1259                                 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm);
1260                 } else {
1261                         $cnt = DBA::fetchFirst("SELECT COUNT(*) AS `total`
1262                                 FROM `profile`
1263                                 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1264                                 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed`");
1265                 }
1266
1267                 if (DBA::isResult($cnt)) {
1268                         $total = $cnt['total'];
1269                 }
1270
1271                 $order = " ORDER BY `name` ASC ";
1272                 $profiles = [];
1273
1274                 // If nothing found, don't try to select details
1275                 if ($total > 0) {
1276                         if (!empty($search)) {
1277                                 $searchTerm = '%' . $search . '%';
1278
1279                                 $profiles = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
1280                         `contact`.`addr`, `contact`.`url` AS `profile_url`
1281                         FROM `profile`
1282                         LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1283                         LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1284                         WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
1285                         AND ((`profile`.`name` LIKE ?) OR
1286                                 (`user`.`nickname` LIKE ?) OR
1287                                 (`profile`.`pdesc` LIKE ?) OR
1288                                 (`profile`.`locality` LIKE ?) OR
1289                                 (`profile`.`region` LIKE ?) OR
1290                                 (`profile`.`country-name` LIKE ?) OR
1291                                 (`profile`.`gender` LIKE ?) OR
1292                                 (`profile`.`marital` LIKE ?) OR
1293                                 (`profile`.`sexual` LIKE ?) OR
1294                                 (`profile`.`about` LIKE ?) OR
1295                                 (`profile`.`romance` LIKE ?) OR
1296                                 (`profile`.`work` LIKE ?) OR
1297                                 (`profile`.`education` LIKE ?) OR
1298                                 (`profile`.`pub_keywords` LIKE ?) OR
1299                                 (`profile`.`prv_keywords` LIKE ?))
1300                         $order LIMIT ?,?",
1301                                         $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1302                                         $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1303                                         $start, $count
1304                                 );
1305                         } else {
1306                                 $profiles = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
1307                         `contact`.`addr`, `contact`.`url` AS `profile_url`
1308                         FROM `profile`
1309                         LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1310                         LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1311                         WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
1312                         $order LIMIT ?,?",
1313                                         $start, $count
1314                                 );
1315                         }
1316                 }
1317
1318                 if (DBA::isResult($profiles) && $total > 0) {
1319                         return [
1320                                 'total'   => $total,
1321                                 'entries' => DBA::toArray($profiles),
1322                         ];
1323
1324                 } else {
1325                         return [
1326                                 'total'   => $total,
1327                                 'entries' => [],
1328                         ];
1329                 }
1330         }
1331 }