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