]> git.mxchange.org Git - friendica.git/blob - src/Model/Profile.php
b77bfa8e1dfc423133a6fb19e25c259dfb4cbb56
[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_id   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_id = 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                 $profile = self::getByNickname($nickname, $user['uid'], $profile_id);
159
160                 if (empty($profile) && empty($profiledata)) {
161                         Logger::log('profile error: ' . DI::args()->getQueryString(), Logger::DEBUG);
162                         return;
163                 }
164
165                 if (empty($profile)) {
166                         $profile = ['uid' => 0, 'is-default' => false,'name' => $nickname];
167                 }
168
169                 // fetch user tags if this isn't the default profile
170
171                 if (!$profile['is-default']) {
172                         $condition = ['uid' => $profile['uid'], 'is-default' => true];
173                         $profile_id = DBA::selectFirst('profile', ['pub_keywords'], $condition);
174                         if (DBA::isResult($profile_id)) {
175                                 $profile['pub_keywords'] = $profile_id['pub_keywords'];
176                         }
177                 }
178
179                 $a->profile = $profile;
180                 $a->profile_uid = $profile['uid'];
181
182                 $a->profile['mobile-theme'] = DI::pConfig()->get($a->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('settings/profile/link.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`.*,
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`.*,
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['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                         $profile['edit'] = [DI::baseUrl() . '/settings/profile', DI::l10n()->t('Edit profile'), '', DI::l10n()->t('Edit profile')];
392                         $profile['menu'] = [
393                                 'chg_photo' => DI::l10n()->t('Change profile photo'),
394                                 'cr_new' => null,
395                                 'entries' => [],
396                         ];
397                 }
398
399                 // Fetch the account type
400                 $account_type = Contact::getAccountType($profile);
401
402                 if (!empty($profile['address'])
403                         || !empty($profile['location'])
404                         || !empty($profile['locality'])
405                         || !empty($profile['region'])
406                         || !empty($profile['postal-code'])
407                         || !empty($profile['country-name'])
408                 ) {
409                         $location = DI::l10n()->t('Location:');
410                 }
411
412                 $gender   = !empty($profile['gender'])   ? DI::l10n()->t('Gender:')   : false;
413                 $marital  = !empty($profile['marital'])  ? DI::l10n()->t('Status:')   : false;
414                 $homepage = !empty($profile['homepage']) ? DI::l10n()->t('Homepage:') : false;
415                 $about    = !empty($profile['about'])    ? DI::l10n()->t('About:')    : false;
416                 $xmpp     = !empty($profile['xmpp'])     ? DI::l10n()->t('XMPP:')     : false;
417
418                 if ((!empty($profile['hidewall']) || $block) && !Session::isAuthenticated()) {
419                         $location = $gender = $marital = $homepage = $about = false;
420                 }
421
422                 $split_name = Diaspora::splitName($profile['name']);
423                 $firstname = $split_name['first'];
424                 $lastname = $split_name['last'];
425
426                 if (!empty($profile['guid'])) {
427                         $diaspora = [
428                                 'guid' => $profile['guid'],
429                                 'podloc' => DI::baseUrl(),
430                                 'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false'),
431                                 'nickname' => $profile['nickname'],
432                                 'fullname' => $profile['name'],
433                                 'firstname' => $firstname,
434                                 'lastname' => $lastname,
435                                 'photo300' => $profile['contact_photo'] ?? '',
436                                 'photo100' => $profile['contact_thumb'] ?? '',
437                                 'photo50' => $profile['contact_micro'] ?? '',
438                         ];
439                 } else {
440                         $diaspora = false;
441                 }
442
443                 $contact_block = '';
444                 $updated = '';
445                 $contact_count = 0;
446                 if (!$block) {
447                         $contact_block = ContactBlock::getHTML($a->profile);
448
449                         if (is_array($a->profile) && !$a->profile['hide-friends']) {
450                                 $r = q(
451                                         "SELECT `gcontact`.`updated` FROM `contact` INNER JOIN `gcontact` WHERE `gcontact`.`nurl` = `contact`.`nurl` AND `self` AND `uid` = %d LIMIT 1",
452                                         intval($a->profile['uid'])
453                                 );
454                                 if (DBA::isResult($r)) {
455                                         $updated = date('c', strtotime($r[0]['updated']));
456                                 }
457
458                                 $contact_count = DBA::count('contact', [
459                                         'uid' => $profile['uid'],
460                                         'self' => false,
461                                         'blocked' => false,
462                                         'pending' => false,
463                                         'hidden' => false,
464                                         'archive' => false,
465                                         'network' => Protocol::FEDERATED,
466                                 ]);
467                         }
468                 }
469
470                 $p = [];
471                 foreach ($profile as $k => $v) {
472                         $k = str_replace('-', '_', $k);
473                         $p[$k] = $v;
474                 }
475
476                 if (isset($p['about'])) {
477                         $p['about'] = BBCode::convert($p['about']);
478                 }
479
480                 if (empty($p['address']) && !empty($p['location'])) {
481                         $p['address'] = $p['location'];
482                 }
483
484                 if (isset($p['address'])) {
485                         $p['address'] = BBCode::convert($p['address']);
486                 }
487
488                 if (isset($p['gender'])) {
489                         $p['gender'] = DI::l10n()->t($p['gender']);
490                 }
491
492                 if (isset($p['marital'])) {
493                         $p['marital'] = DI::l10n()->t($p['marital']);
494                 }
495
496                 if (isset($p['photo'])) {
497                         $p['photo'] = ProxyUtils::proxifyUrl($p['photo'], false, ProxyUtils::SIZE_SMALL);
498                 }
499
500                 $p['url'] = Contact::magicLink(($p['url'] ?? '') ?: $profile_url);
501
502                 $tpl = Renderer::getMarkupTemplate('profile/vcard.tpl');
503                 $o .= Renderer::replaceMacros($tpl, [
504                         '$profile' => $p,
505                         '$xmpp' => $xmpp,
506                         '$follow' => DI::l10n()->t('Follow'),
507                         '$follow_link' => $follow_link,
508                         '$unfollow' => DI::l10n()->t('Unfollow'),
509                         '$unfollow_link' => $unfollow_link,
510                         '$subscribe_feed' => DI::l10n()->t('Atom feed'),
511                         '$subscribe_feed_link' => $subscribe_feed_link,
512                         '$wallmessage' => DI::l10n()->t('Message'),
513                         '$wallmessage_link' => $wallmessage_link,
514                         '$account_type' => $account_type,
515                         '$location' => $location,
516                         '$gender' => $gender,
517                         '$marital' => $marital,
518                         '$homepage' => $homepage,
519                         '$about' => $about,
520                         '$network' => DI::l10n()->t('Network:'),
521                         '$contacts' => $contact_count,
522                         '$updated' => $updated,
523                         '$diaspora' => $diaspora,
524                         '$contact_block' => $contact_block,
525                 ]);
526
527                 $arr = ['profile' => &$profile, 'entry' => &$o];
528
529                 Hook::callAll('profile_sidebar', $arr);
530
531                 return $o;
532         }
533
534         public static function getBirthdays()
535         {
536                 $a = DI::app();
537                 $o = '';
538
539                 if (!local_user() || DI::mode()->isMobile() || DI::mode()->isMobile()) {
540                         return $o;
541                 }
542
543                 /*
544                 * $mobile_detect = new Mobile_Detect();
545                 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
546                 *               if ($is_mobile)
547                 *                       return $o;
548                 */
549
550                 $bd_format = DI::l10n()->t('g A l F d'); // 8 AM Friday January 18
551                 $bd_short = DI::l10n()->t('F d');
552
553                 $cachekey = 'get_birthdays:' . local_user();
554                 $r = DI::cache()->get($cachekey);
555                 if (is_null($r)) {
556                         $s = DBA::p(
557                                 "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
558                                 INNER JOIN `contact`
559                                         ON `contact`.`id` = `event`.`cid`
560                                         AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
561                                         AND NOT `contact`.`pending`
562                                         AND NOT `contact`.`hidden`
563                                         AND NOT `contact`.`blocked`
564                                         AND NOT `contact`.`archive`
565                                         AND NOT `contact`.`deleted`
566                                 WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
567                                 ORDER BY `start` ASC ",
568                                 Contact::SHARING,
569                                 Contact::FRIEND,
570                                 local_user(),
571                                 DateTimeFormat::utc('now + 6 days'),
572                                 DateTimeFormat::utcNow()
573                         );
574                         if (DBA::isResult($s)) {
575                                 $r = DBA::toArray($s);
576                                 DI::cache()->set($cachekey, $r, Duration::HOUR);
577                         }
578                 }
579
580                 $total = 0;
581                 $classtoday = '';
582                 if (DBA::isResult($r)) {
583                         $now = strtotime('now');
584                         $cids = [];
585
586                         $istoday = false;
587                         foreach ($r as $rr) {
588                                 if (strlen($rr['name'])) {
589                                         $total ++;
590                                 }
591                                 if ((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) {
592                                         $istoday = true;
593                                 }
594                         }
595                         $classtoday = $istoday ? ' birthday-today ' : '';
596                         if ($total) {
597                                 foreach ($r as &$rr) {
598                                         if (!strlen($rr['name'])) {
599                                                 continue;
600                                         }
601
602                                         // avoid duplicates
603
604                                         if (in_array($rr['cid'], $cids)) {
605                                                 continue;
606                                         }
607                                         $cids[] = $rr['cid'];
608
609                                         $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
610
611                                         $rr['link'] = Contact::magicLink($rr['url']);
612                                         $rr['title'] = $rr['name'];
613                                         $rr['date'] = DI::l10n()->getDay(DateTimeFormat::convert($rr['start'], $a->timezone, 'UTC', $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '');
614                                         $rr['startime'] = null;
615                                         $rr['today'] = $today;
616                                 }
617                         }
618                 }
619                 $tpl = Renderer::getMarkupTemplate('birthdays_reminder.tpl');
620                 return Renderer::replaceMacros($tpl, [
621                         '$classtoday' => $classtoday,
622                         '$count' => $total,
623                         '$event_reminders' => DI::l10n()->t('Birthday Reminders'),
624                         '$event_title' => DI::l10n()->t('Birthdays this week:'),
625                         '$events' => $r,
626                         '$lbr' => '{', // raw brackets mess up if/endif macro processing
627                         '$rbr' => '}'
628                 ]);
629         }
630
631         public static function getEventsReminderHTML()
632         {
633                 $a = DI::app();
634                 $o = '';
635
636                 if (!local_user() || DI::mode()->isMobile() || DI::mode()->isMobile()) {
637                         return $o;
638                 }
639
640                 /*
641                 *       $mobile_detect = new Mobile_Detect();
642                 *               $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
643                 *               if ($is_mobile)
644                 *                       return $o;
645                 */
646
647                 $bd_format = DI::l10n()->t('g A l F d'); // 8 AM Friday January 18
648                 $classtoday = '';
649
650                 $condition = ["`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?",
651                         local_user(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utc('now - 1 days')];
652                 $s = DBA::select('event', [], $condition, ['order' => ['start']]);
653
654                 $r = [];
655
656                 if (DBA::isResult($s)) {
657                         $istoday = false;
658                         $total = 0;
659
660                         while ($rr = DBA::fetch($s)) {
661                                 $condition = ['parent-uri' => $rr['uri'], 'uid' => $rr['uid'], 'author-id' => public_contact(),
662                                         'activity' => [Item::activityToIndex( Activity::ATTEND), Item::activityToIndex(Activity::ATTENDMAYBE)],
663                                         'visible' => true, 'deleted' => false];
664                                 if (!Item::exists($condition)) {
665                                         continue;
666                                 }
667
668                                 if (strlen($rr['summary'])) {
669                                         $total++;
670                                 }
671
672                                 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', 'Y-m-d');
673                                 if ($strt === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
674                                         $istoday = true;
675                                 }
676
677                                 $title = strip_tags(html_entity_decode(BBCode::convert($rr['summary']), ENT_QUOTES, 'UTF-8'));
678
679                                 if (strlen($title) > 35) {
680                                         $title = substr($title, 0, 32) . '... ';
681                                 }
682
683                                 $description = substr(strip_tags(BBCode::convert($rr['desc'])), 0, 32) . '... ';
684                                 if (!$description) {
685                                         $description = DI::l10n()->t('[No description]');
686                                 }
687
688                                 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC');
689
690                                 if (substr($strt, 0, 10) < DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
691                                         continue;
692                                 }
693
694                                 $today = ((substr($strt, 0, 10) === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) ? true : false);
695
696                                 $rr['title'] = $title;
697                                 $rr['description'] = $description;
698                                 $rr['date'] = DI::l10n()->getDay(DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', $bd_format)) . (($today) ? ' ' . DI::l10n()->t('[today]') : '');
699                                 $rr['startime'] = $strt;
700                                 $rr['today'] = $today;
701
702                                 $r[] = $rr;
703                         }
704                         DBA::close($s);
705                         $classtoday = (($istoday) ? 'event-today' : '');
706                 }
707                 $tpl = Renderer::getMarkupTemplate('events_reminder.tpl');
708                 return Renderer::replaceMacros($tpl, [
709                         '$classtoday' => $classtoday,
710                         '$count' => count($r),
711                         '$event_reminders' => DI::l10n()->t('Event Reminders'),
712                         '$event_title' => DI::l10n()->t('Upcoming events the next 7 days:'),
713                         '$events' => $r,
714                 ]);
715         }
716
717         public static function getAdvanced(App $a)
718         {
719                 $uid = intval($a->profile['uid']);
720
721                 if ($a->profile['name']) {
722                         $profile = [];
723
724                         $profile['fullname'] = [DI::l10n()->t('Full Name:'), $a->profile['name']];
725
726                         if (Feature::isEnabled($uid, 'profile_membersince')) {
727                                 $profile['membersince'] = [DI::l10n()->t('Member since:'), DateTimeFormat::local($a->profile['register_date'])];
728                         }
729
730                         if ($a->profile['gender']) {
731                                 $profile['gender'] = [DI::l10n()->t('Gender:'), DI::l10n()->t($a->profile['gender'])];
732                         }
733
734                         if (!empty($a->profile['dob']) && $a->profile['dob'] > DBA::NULL_DATE) {
735                                 $year_bd_format = DI::l10n()->t('j F, Y');
736                                 $short_bd_format = DI::l10n()->t('j F');
737
738                                 $val = DI::l10n()->getDay(
739                                         intval($a->profile['dob']) ?
740                                                 DateTimeFormat::utc($a->profile['dob'] . ' 00:00 +00:00', $year_bd_format)
741                                                 : DateTimeFormat::utc('2001-' . substr($a->profile['dob'], 5) . ' 00:00 +00:00', $short_bd_format)
742                                 );
743
744                                 $profile['birthday'] = [DI::l10n()->t('Birthday:'), $val];
745                         }
746
747                         if (!empty($a->profile['dob'])
748                                 && $a->profile['dob'] > DBA::NULL_DATE
749                                 && $age = Temporal::getAgeByTimezone($a->profile['dob'], $a->profile['timezone'])
750                         ) {
751                                 $profile['age'] = [DI::l10n()->t('Age: ') , DI::l10n()->tt('%d year old', '%d years old', $age)];
752                         }
753
754                         if ($a->profile['marital']) {
755                                 $profile['marital'] = [DI::l10n()->t('Status:'), DI::l10n()->t($a->profile['marital'])];
756                         }
757
758                         /// @TODO Maybe use x() here, plus below?
759                         if ($a->profile['with']) {
760                                 $profile['marital']['with'] = $a->profile['with'];
761                         }
762
763                         if (strlen($a->profile['howlong']) && $a->profile['howlong'] > DBA::NULL_DATETIME) {
764                                 $profile['howlong'] = Temporal::getRelativeDate($a->profile['howlong'], DI::l10n()->t('for %1$d %2$s'));
765                         }
766
767                         if ($a->profile['sexual']) {
768                                 $profile['sexual'] = [DI::l10n()->t('Sexual Preference:'), DI::l10n()->t($a->profile['sexual'])];
769                         }
770
771                         if ($a->profile['homepage']) {
772                                 $profile['homepage'] = [DI::l10n()->t('Homepage:'), HTML::toLink($a->profile['homepage'])];
773                         }
774
775                         if ($a->profile['hometown']) {
776                                 $profile['hometown'] = [DI::l10n()->t('Hometown:'), HTML::toLink($a->profile['hometown'])];
777                         }
778
779                         if ($a->profile['pub_keywords']) {
780                                 $profile['pub_keywords'] = [DI::l10n()->t('Tags:'), $a->profile['pub_keywords']];
781                         }
782
783                         if ($a->profile['politic']) {
784                                 $profile['politic'] = [DI::l10n()->t('Political Views:'), $a->profile['politic']];
785                         }
786
787                         if ($a->profile['religion']) {
788                                 $profile['religion'] = [DI::l10n()->t('Religion:'), $a->profile['religion']];
789                         }
790
791                         if ($txt = BBCode::convert($a->profile['about'])) {
792                                 $profile['about'] = [DI::l10n()->t('About:'), $txt];
793                         }
794
795                         if ($txt = BBCode::convert($a->profile['interest'])) {
796                                 $profile['interest'] = [DI::l10n()->t('Hobbies/Interests:'), $txt];
797                         }
798
799                         if ($txt = BBCode::convert($a->profile['likes'])) {
800                                 $profile['likes'] = [DI::l10n()->t('Likes:'), $txt];
801                         }
802
803                         if ($txt = BBCode::convert($a->profile['dislikes'])) {
804                                 $profile['dislikes'] = [DI::l10n()->t('Dislikes:'), $txt];
805                         }
806
807                         if ($txt = BBCode::convert($a->profile['contact'])) {
808                                 $profile['contact'] = [DI::l10n()->t('Contact information and Social Networks:'), $txt];
809                         }
810
811                         if ($txt = BBCode::convert($a->profile['music'])) {
812                                 $profile['music'] = [DI::l10n()->t('Musical interests:'), $txt];
813                         }
814
815                         if ($txt = BBCode::convert($a->profile['book'])) {
816                                 $profile['book'] = [DI::l10n()->t('Books, literature:'), $txt];
817                         }
818
819                         if ($txt = BBCode::convert($a->profile['tv'])) {
820                                 $profile['tv'] = [DI::l10n()->t('Television:'), $txt];
821                         }
822
823                         if ($txt = BBCode::convert($a->profile['film'])) {
824                                 $profile['film'] = [DI::l10n()->t('Film/dance/culture/entertainment:'), $txt];
825                         }
826
827                         if ($txt = BBCode::convert($a->profile['romance'])) {
828                                 $profile['romance'] = [DI::l10n()->t('Love/Romance:'), $txt];
829                         }
830
831                         if ($txt = BBCode::convert($a->profile['work'])) {
832                                 $profile['work'] = [DI::l10n()->t('Work/employment:'), $txt];
833                         }
834
835                         if ($txt = BBCode::convert($a->profile['education'])) {
836                                 $profile['education'] = [DI::l10n()->t('School/education:'), $txt];
837                         }
838
839                         //show subcribed forum if it is enabled in the usersettings
840                         if (Feature::isEnabled($uid, 'forumlist_profile')) {
841                                 $profile['forumlist'] = [DI::l10n()->t('Forums:'), ForumManager::profileAdvanced($uid)];
842                         }
843
844                         if ($a->profile['uid'] == local_user()) {
845                                 $profile['edit'] = [DI::baseUrl() . '/settings/profile', DI::l10n()->t('Edit profile'), '', DI::l10n()->t('Edit profile')];
846                         }
847
848                         $tpl = Renderer::getMarkupTemplate('profile/advanced.tpl');
849                         return Renderer::replaceMacros($tpl, [
850                                 '$title' => DI::l10n()->t('Profile'),
851                                 '$basic' => DI::l10n()->t('Basic'),
852                                 '$advanced' => DI::l10n()->t('Advanced'),
853                                 '$profile' => $profile
854                         ]);
855                 }
856
857                 return '';
858         }
859
860     /**
861      * @param App    $a
862      * @param string $current
863      * @param bool   $is_owner
864      * @param string $nickname
865      * @return string
866      * @throws \Friendica\Network\HTTPException\InternalServerErrorException
867      */
868         public static function getTabs(App $a, string $current, bool $is_owner, string $nickname = null)
869         {
870                 if (is_null($nickname)) {
871                         $nickname = $a->user['nickname'];
872                 }
873
874                 $baseProfileUrl = DI::baseUrl() . '/profile/' . $nickname;
875
876                 $tabs = [
877                         [
878                                 'label' => DI::l10n()->t('Profile'),
879                                 'url'   => $baseProfileUrl,
880                                 'sel'   => $current == 'profile' ? 'active' : '',
881                                 'title' => DI::l10n()->t('Profile Details'),
882                                 'id'    => 'profile-tab',
883                                 'accesskey' => 'r',
884                         ],
885                         [
886                                 'label' => DI::l10n()->t('Status'),
887                                 'url'   => $baseProfileUrl . '/status',
888                                 'sel'   => $current == 'status' ? 'active' : '',
889                                 'title' => DI::l10n()->t('Status Messages and Posts'),
890                                 'id'    => 'status-tab',
891                                 'accesskey' => 'm',
892                         ],
893                         [
894                                 'label' => DI::l10n()->t('Photos'),
895                                 'url'   => DI::baseUrl() . '/photos/' . $nickname,
896                                 'sel'   => $current == 'photos' ? 'active' : '',
897                                 'title' => DI::l10n()->t('Photo Albums'),
898                                 'id'    => 'photo-tab',
899                                 'accesskey' => 'h',
900                         ],
901                         [
902                                 'label' => DI::l10n()->t('Videos'),
903                                 'url'   => DI::baseUrl() . '/videos/' . $nickname,
904                                 'sel'   => $current == 'videos' ? 'active' : '',
905                                 'title' => DI::l10n()->t('Videos'),
906                                 'id'    => 'video-tab',
907                                 'accesskey' => 'v',
908                         ],
909                 ];
910
911                 // the calendar link for the full featured events calendar
912                 if ($is_owner && $a->theme_events_in_profile) {
913                         $tabs[] = [
914                                 'label' => DI::l10n()->t('Events'),
915                                 'url'   => DI::baseUrl() . '/events',
916                                 'sel'   => $current == 'events' ? 'active' : '',
917                                 'title' => DI::l10n()->t('Events and Calendar'),
918                                 'id'    => 'events-tab',
919                                 'accesskey' => 'e',
920                         ];
921                         // if the user is not the owner of the calendar we only show a calendar
922                         // with the public events of the calendar owner
923                 } elseif (!$is_owner) {
924                         $tabs[] = [
925                                 'label' => DI::l10n()->t('Events'),
926                                 'url'   => DI::baseUrl() . '/cal/' . $nickname,
927                                 'sel'   => $current == 'cal' ? 'active' : '',
928                                 'title' => DI::l10n()->t('Events and Calendar'),
929                                 'id'    => 'events-tab',
930                                 'accesskey' => 'e',
931                         ];
932                 }
933
934                 if ($is_owner) {
935                         $tabs[] = [
936                                 'label' => DI::l10n()->t('Personal Notes'),
937                                 'url'   => DI::baseUrl() . '/notes',
938                                 'sel'   => $current == 'notes' ? 'active' : '',
939                                 'title' => DI::l10n()->t('Only You Can See This'),
940                                 'id'    => 'notes-tab',
941                                 'accesskey' => 't',
942                         ];
943                 }
944
945                 if (empty($a->profile['hide-friends'])) {
946                         $tabs[] = [
947                                 'label' => DI::l10n()->t('Contacts'),
948                                 'url'   => $baseProfileUrl . '/contacts',
949                                 'sel'   => $current == 'contacts' ? 'active' : '',
950                                 'title' => DI::l10n()->t('Contacts'),
951                                 'id'    => 'viewcontacts-tab',
952                                 'accesskey' => 'k',
953                         ];
954                 }
955
956                 if (!empty($_SESSION['new_member']) && $is_owner) {
957                         $tabs[] = [
958                                 'label' => DI::l10n()->t('Tips for New Members'),
959                                 'url'   => DI::baseUrl() . '/newmember',
960                                 'sel'   => false,
961                                 'title' => DI::l10n()->t('Tips for New Members'),
962                                 'id'    => 'newmember-tab',
963                         ];
964                 }
965
966                 $arr = ['is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => $current, 'tabs' => $tabs];
967
968                 Hook::callAll('profile_tabs', $arr);
969
970                 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
971
972                 return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
973         }
974
975         /**
976          * Retrieves the my_url session variable
977          *
978          * @return string
979          */
980         public static function getMyURL()
981         {
982                 return Session::get('my_url');
983         }
984
985         /**
986          * Process the 'zrl' parameter and initiate the remote authentication.
987          *
988          * This method checks if the visitor has a public contact entry and
989          * redirects the visitor to his/her instance to start the magic auth (Authentication)
990          * process.
991          *
992          * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/channel.php
993          *
994          * The implementation for Friendica sadly differs in some points from the one for Hubzilla:
995          * - Hubzilla uses the "zid" parameter, while for Friendica it had been replaced with "zrl"
996          * - There seem to be some reverse authentication (rmagic) that isn't implemented in Friendica at all
997          *
998          * It would be favourable to harmonize the two implementations.
999          *
1000          * @param App $a Application instance.
1001          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1002          * @throws \ImagickException
1003          */
1004         public static function zrlInit(App $a)
1005         {
1006                 $my_url = self::getMyURL();
1007                 $my_url = Network::isUrlValid($my_url);
1008
1009                 if (empty($my_url) || local_user()) {
1010                         return;
1011                 }
1012
1013                 $addr = $_GET['addr'] ?? $my_url;
1014
1015                 $arr = ['zrl' => $my_url, 'url' => DI::args()->getCommand()];
1016                 Hook::callAll('zrl_init', $arr);
1017
1018                 // Try to find the public contact entry of the visitor.
1019                 $cid = Contact::getIdForURL($my_url);
1020                 if (!$cid) {
1021                         Logger::log('No contact record found for ' . $my_url, Logger::DEBUG);
1022                         return;
1023                 }
1024
1025                 $contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]);
1026
1027                 if (DBA::isResult($contact) && remote_user() && remote_user() == $contact['id']) {
1028                         Logger::log('The visitor ' . $my_url . ' is already authenticated', Logger::DEBUG);
1029                         return;
1030                 }
1031
1032                 // Avoid endless loops
1033                 $cachekey = 'zrlInit:' . $my_url;
1034                 if (DI::cache()->get($cachekey)) {
1035                         Logger::log('URL ' . $my_url . ' already tried to authenticate.', Logger::DEBUG);
1036                         return;
1037                 } else {
1038                         DI::cache()->set($cachekey, true, Duration::MINUTE);
1039                 }
1040
1041                 Logger::log('Not authenticated. Invoking reverse magic-auth for ' . $my_url, Logger::DEBUG);
1042
1043                 // Remove the "addr" parameter from the destination. It is later added as separate parameter again.
1044                 $addr_request = 'addr=' . urlencode($addr);
1045                 $query = rtrim(str_replace($addr_request, '', DI::args()->getQueryString()), '?&');
1046
1047                 // The other instance needs to know where to redirect.
1048                 $dest = urlencode(DI::baseUrl()->get() . '/' . $query);
1049
1050                 // We need to extract the basebath from the profile url
1051                 // to redirect the visitors '/magic' module.
1052                 $basepath = Contact::getBasepath($contact['url']);
1053
1054                 if ($basepath != DI::baseUrl()->get() && !strstr($dest, '/magic')) {
1055                         $magic_path = $basepath . '/magic' . '?owa=1&dest=' . $dest . '&' . $addr_request;
1056
1057                         // We have to check if the remote server does understand /magic without invoking something
1058                         $serverret = Network::curl($basepath . '/magic');
1059                         if ($serverret->isSuccess()) {
1060                                 Logger::log('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path, Logger::DEBUG);
1061                                 System::externalRedirect($magic_path);
1062                         }
1063                 }
1064         }
1065
1066         /**
1067          * Set the visitor cookies (see remote_user()) for the given handle
1068          *
1069          * @param string $handle Visitor handle
1070          * @return array Visitor contact array
1071          */
1072         public static function addVisitorCookieForHandle($handle)
1073         {
1074                 $a = DI::app();
1075
1076                 // Try to find the public contact entry of the visitor.
1077                 $cid = Contact::getIdForURL($handle);
1078                 if (!$cid) {
1079                         Logger::log('unable to finger ' . $handle, Logger::DEBUG);
1080                         return [];
1081                 }
1082
1083                 $visitor = DBA::selectFirst('contact', [], ['id' => $cid]);
1084
1085                 // Authenticate the visitor.
1086                 $_SESSION['authenticated'] = 1;
1087                 $_SESSION['visitor_id'] = $visitor['id'];
1088                 $_SESSION['visitor_handle'] = $visitor['addr'];
1089                 $_SESSION['visitor_home'] = $visitor['url'];
1090                 $_SESSION['my_url'] = $visitor['url'];
1091
1092                 Session::setVisitorsContacts();
1093
1094                 $a->contact = $visitor;
1095
1096                 Logger::info('Authenticated visitor', ['url' => $visitor['url']]);
1097
1098                 return $visitor;
1099         }
1100
1101         /**
1102          * OpenWebAuth authentication.
1103          *
1104          * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/zid.php
1105          *
1106          * @param string $token
1107          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1108          * @throws \ImagickException
1109          */
1110         public static function openWebAuthInit($token)
1111         {
1112                 $a = DI::app();
1113
1114                 // Clean old OpenWebAuthToken entries.
1115                 OpenWebAuthToken::purge('owt', '3 MINUTE');
1116
1117                 // Check if the token we got is the same one
1118                 // we have stored in the database.
1119                 $visitor_handle = OpenWebAuthToken::getMeta('owt', 0, $token);
1120
1121                 if ($visitor_handle === false) {
1122                         return;
1123                 }
1124
1125                 $visitor = self::addVisitorCookieForHandle($visitor_handle);
1126                 if (empty($visitor)) {
1127                         return;
1128                 }
1129
1130                 $arr = [
1131                         'visitor' => $visitor,
1132                         'url' => DI::args()->getQueryString()
1133                 ];
1134                 /**
1135                  * @hooks magic_auth_success
1136                  *   Called when a magic-auth was successful.
1137                  *   * \e array \b visitor
1138                  *   * \e string \b url
1139                  */
1140                 Hook::callAll('magic_auth_success', $arr);
1141
1142                 $a->contact = $arr['visitor'];
1143
1144                 info(DI::l10n()->t('OpenWebAuth: %1$s welcomes %2$s', DI::baseUrl()->getHostname(), $visitor['name']));
1145
1146                 Logger::log('OpenWebAuth: auth success from ' . $visitor['addr'], Logger::DEBUG);
1147         }
1148
1149         public static function zrl($s, $force = false)
1150         {
1151                 if (!strlen($s)) {
1152                         return $s;
1153                 }
1154                 if (!strpos($s, '/profile/') && !$force) {
1155                         return $s;
1156                 }
1157                 if ($force && substr($s, -1, 1) !== '/') {
1158                         $s = $s . '/';
1159                 }
1160                 $achar = strpos($s, '?') ? '&' : '?';
1161                 $mine = self::getMyURL();
1162                 if ($mine && !Strings::compareLink($mine, $s)) {
1163                         return $s . $achar . 'zrl=' . urlencode($mine);
1164                 }
1165                 return $s;
1166         }
1167
1168         /**
1169          * Get the user ID of the page owner.
1170          *
1171          * Used from within PCSS themes to set theme parameters. If there's a
1172          * profile_uid variable set in App, that is the "page owner" and normally their theme
1173          * settings take precedence; unless a local user sets the "always_my_theme"
1174          * system pconfig, which means they don't want to see anybody else's theme
1175          * settings except their own while on this site.
1176          *
1177          * @return int user ID
1178          *
1179          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1180          * @note Returns local_user instead of user ID if "always_my_theme" is set to true
1181          */
1182         public static function getThemeUid(App $a)
1183         {
1184                 $uid = !empty($a->profile_uid) ? intval($a->profile_uid) : 0;
1185                 if (local_user() && (DI::pConfig()->get(local_user(), 'system', 'always_my_theme') || !$uid)) {
1186                         return local_user();
1187                 }
1188
1189                 return $uid;
1190         }
1191
1192         /**
1193          * search for Profiles
1194          *
1195          * @param int  $start
1196          * @param int  $count
1197          * @param null $search
1198          *
1199          * @return array [ 'total' => 123, 'entries' => [...] ];
1200          *
1201          * @throws \Exception
1202          */
1203         public static function searchProfiles($start = 0, $count = 100, $search = null)
1204         {
1205                 $publish = (DI::config()->get('system', 'publish_all') ? '' : " AND `publish` = 1 ");
1206                 $total = 0;
1207
1208                 if (!empty($search)) {
1209                         $searchTerm = '%' . $search . '%';
1210                         $cnt = DBA::fetchFirst("SELECT COUNT(*) AS `total`
1211                                 FROM `profile`
1212                                 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1213                                 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed`
1214                                 AND ((`profile`.`name` LIKE ?) OR
1215                                 (`user`.`nickname` LIKE ?) OR
1216                                 (`profile`.`pdesc` LIKE ?) OR
1217                                 (`profile`.`locality` LIKE ?) OR
1218                                 (`profile`.`region` LIKE ?) OR
1219                                 (`profile`.`country-name` LIKE ?) OR
1220                                 (`profile`.`gender` LIKE ?) OR
1221                                 (`profile`.`marital` LIKE ?) OR
1222                                 (`profile`.`sexual` LIKE ?) OR
1223                                 (`profile`.`about` LIKE ?) OR
1224                                 (`profile`.`romance` LIKE ?) OR
1225                                 (`profile`.`work` LIKE ?) OR
1226                                 (`profile`.`education` LIKE ?) OR
1227                                 (`profile`.`pub_keywords` LIKE ?) OR
1228                                 (`profile`.`prv_keywords` LIKE ?))",
1229                                 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1230                                 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm);
1231                 } else {
1232                         $cnt = DBA::fetchFirst("SELECT COUNT(*) AS `total`
1233                                 FROM `profile`
1234                                 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1235                                 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed`");
1236                 }
1237
1238                 if (DBA::isResult($cnt)) {
1239                         $total = $cnt['total'];
1240                 }
1241
1242                 $order = " ORDER BY `name` ASC ";
1243                 $profiles = [];
1244
1245                 // If nothing found, don't try to select details
1246                 if ($total > 0) {
1247                         if (!empty($search)) {
1248                                 $searchTerm = '%' . $search . '%';
1249
1250                                 $profiles = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
1251                         `contact`.`addr`, `contact`.`url` AS `profile_url`
1252                         FROM `profile`
1253                         LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1254                         LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1255                         WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
1256                         AND ((`profile`.`name` LIKE ?) OR
1257                                 (`user`.`nickname` LIKE ?) OR
1258                                 (`profile`.`pdesc` LIKE ?) OR
1259                                 (`profile`.`locality` LIKE ?) OR
1260                                 (`profile`.`region` LIKE ?) OR
1261                                 (`profile`.`country-name` LIKE ?) OR
1262                                 (`profile`.`gender` LIKE ?) OR
1263                                 (`profile`.`marital` LIKE ?) OR
1264                                 (`profile`.`sexual` LIKE ?) OR
1265                                 (`profile`.`about` LIKE ?) OR
1266                                 (`profile`.`romance` LIKE ?) OR
1267                                 (`profile`.`work` LIKE ?) OR
1268                                 (`profile`.`education` LIKE ?) OR
1269                                 (`profile`.`pub_keywords` LIKE ?) OR
1270                                 (`profile`.`prv_keywords` LIKE ?))
1271                         $order LIMIT ?,?",
1272                                         $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1273                                         $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1274                                         $start, $count
1275                                 );
1276                         } else {
1277                                 $profiles = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
1278                         `contact`.`addr`, `contact`.`url` AS `profile_url`
1279                         FROM `profile`
1280                         LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1281                         LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1282                         WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
1283                         $order LIMIT ?,?",
1284                                         $start, $count
1285                                 );
1286                         }
1287                 }
1288
1289                 if (DBA::isResult($profiles) && $total > 0) {
1290                         return [
1291                                 'total'   => $total,
1292                                 'entries' => DBA::toArray($profiles),
1293                         ];
1294
1295                 } else {
1296                         return [
1297                                 'total'   => $total,
1298                                 'entries' => [],
1299                         ];
1300                 }
1301         }
1302 }