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