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