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