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