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