]> git.mxchange.org Git - friendica.git/blob - src/Model/Profile.php
Reworked "remote" cookie handling
[friendica.git] / src / Model / Profile.php
1 <?php
2 /**
3  * @file src/Model/Profile.php
4  */
5 namespace Friendica\Model;
6
7 use Friendica\App;
8 use Friendica\Content\Feature;
9 use Friendica\Content\ForumManager;
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Content\Text\HTML;
12 use Friendica\Content\Widget\ContactBlock;
13 use Friendica\Core\Cache;
14 use Friendica\Core\Config;
15 use Friendica\Core\Hook;
16 use Friendica\Core\L10n;
17 use Friendica\Core\Logger;
18 use Friendica\Core\PConfig;
19 use Friendica\Core\Protocol;
20 use Friendica\Core\Renderer;
21 use Friendica\Core\Session;
22 use Friendica\Core\System;
23 use Friendica\Core\Worker;
24 use Friendica\Database\DBA;
25 use Friendica\Protocol\Diaspora;
26 use Friendica\Util\DateTimeFormat;
27 use Friendica\Util\Network;
28 use Friendica\Util\Proxy as ProxyUtils;
29 use Friendica\Util\Strings;
30 use Friendica\Util\Temporal;
31
32 class Profile
33 {
34         /**
35          * @brief Returns default profile for a given user id
36          *
37          * @param integer User ID
38          *
39          * @return array Profile data
40          * @throws \Exception
41          */
42         public static function getByUID($uid)
43         {
44                 $profile = DBA::selectFirst('profile', [], ['uid' => $uid, 'is-default' => true]);
45                 return $profile;
46         }
47
48         /**
49          * @brief Returns default profile for a given user ID and ID
50          *
51          * @param int $uid The contact ID
52          * @param int $id The contact owner ID
53          * @param array $fields The selected fields
54          *
55          * @return array Profile data for the ID
56          * @throws \Exception
57          */
58         public static function getById(int $uid, int $id, array $fields = [])
59         {
60                 return DBA::selectFirst('profile', $fields, ['uid' => $uid, 'id' => $id]);
61         }
62
63         /**
64          * @brief Returns profile data for the contact owner
65          *
66          * @param int $uid The User ID
67          * @param array $fields The fields to retrieve
68          *
69          * @return array Array of profile data
70          * @throws \Exception
71          */
72         public static function getListByUser(int $uid, array $fields = [])
73         {
74                 return DBA::selectToArray('profile', $fields, ['uid' => $uid]);
75         }
76
77         /**
78          * @brief Returns a formatted location string from the given profile array
79          *
80          * @param array $profile Profile array (Generated from the "profile" table)
81          *
82          * @return string Location string
83          */
84         public static function formatLocation(array $profile)
85         {
86                 $location = '';
87
88                 if (!empty($profile['locality'])) {
89                         $location .= $profile['locality'];
90                 }
91
92                 if (!empty($profile['region']) && (defaults($profile, 'locality', '') != $profile['region'])) {
93                         if ($location) {
94                                 $location .= ', ';
95                         }
96
97                         $location .= $profile['region'];
98                 }
99
100                 if (!empty($profile['country-name'])) {
101                         if ($location) {
102                                 $location .= ', ';
103                         }
104
105                         $location .= $profile['country-name'];
106                 }
107
108                 return $location;
109         }
110
111         /**
112          *
113          * Loads a profile into the page sidebar.
114          *
115          * The function requires a writeable copy of the main App structure, and the nickname
116          * of a registered local account.
117          *
118          * If the viewer is an authenticated remote viewer, the profile displayed is the
119          * one that has been configured for his/her viewing in the Contact manager.
120          * Passing a non-zero profile ID can also allow a preview of a selected profile
121          * by the owner.
122          *
123          * Profile information is placed in the App structure for later retrieval.
124          * Honours the owner's chosen theme for display.
125          *
126          * @attention Should only be run in the _init() functions of a module. That ensures that
127          *      the theme is chosen before the _init() function of a theme is run, which will usually
128          *      load a lot of theme-specific content
129          *
130          * @brief Loads a profile into the page sidebar.
131          * @param App     $a
132          * @param string  $nickname     string
133          * @param int     $profile      int
134          * @param array   $profiledata  array
135          * @param boolean $show_connect Show connect link
136          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
137          * @throws \ImagickException
138          */
139         public static function load(App $a, $nickname, $profile = 0, array $profiledata = [], $show_connect = true)
140         {
141                 $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nickname, 'account_removed' => false]);
142
143                 if (!DBA::isResult($user) && empty($profiledata)) {
144                         Logger::log('profile error: ' . $a->query_string, Logger::DEBUG);
145                         return;
146                 }
147
148                 if (count($profiledata) > 0) {
149                         // Ensure to have a "nickname" field
150                         if (empty($profiledata['nickname']) && !empty($profiledata['nick'])) {
151                                 $profiledata['nickname'] = $profiledata['nick'];
152                         }
153
154                         // Add profile data to sidebar
155                         $a->page['aside'] .= self::sidebar($a, $profiledata, true, $show_connect);
156
157                         if (!DBA::isResult($user)) {
158                                 return;
159                         }
160                 }
161
162                 $pdata = self::getByNickname($nickname, $user['uid'], $profile);
163
164                 if (empty($pdata) && empty($profiledata)) {
165                         Logger::log('profile error: ' . $a->query_string, Logger::DEBUG);
166                         return;
167                 }
168
169                 if (empty($pdata)) {
170                         $pdata = ['uid' => 0, 'profile_uid' => 0, 'is-default' => false,'name' => $nickname];
171                 }
172
173                 // fetch user tags if this isn't the default profile
174
175                 if (!$pdata['is-default']) {
176                         $condition = ['uid' => $pdata['profile_uid'], 'is-default' => true];
177                         $profile = DBA::selectFirst('profile', ['pub_keywords'], $condition);
178                         if (DBA::isResult($profile)) {
179                                 $pdata['pub_keywords'] = $profile['pub_keywords'];
180                         }
181                 }
182
183                 $a->profile = $pdata;
184                 $a->profile_uid = $pdata['profile_uid'];
185
186                 $a->profile['mobile-theme'] = PConfig::get($a->profile['profile_uid'], 'system', 'mobile_theme');
187                 $a->profile['network'] = Protocol::DFRN;
188
189                 $a->page['title'] = $a->profile['name'] . ' @ ' . Config::get('config', 'sitename');
190
191                 if (!$profiledata && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
192                         $_SESSION['theme'] = $a->profile['theme'];
193                 }
194
195                 $_SESSION['mobile-theme'] = $a->profile['mobile-theme'];
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') && !local_user() && !remote_user()) ? 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(remote_user($uid))) {
252                         $contact = DBA::selectFirst('contact', ['profile-id'], ['id' => remote_user($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(defaults($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(defaults($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) && !local_user() && !remote_user()) {
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' => defaults($profile, 'contact_photo', ''),
469                                 'photo100' => defaults($profile, 'contact_thumb', ''),
470                                 'photo50' => defaults($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(defaults($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          * @param App $a Application instance.
1028          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1029          * @throws \ImagickException
1030          */
1031         public static function zrlInit(App $a)
1032         {
1033                 $my_url = self::getMyURL();
1034                 $my_url = Network::isUrlValid($my_url);
1035
1036                 if (empty($my_url) || local_user()) {
1037                         return;
1038                 }
1039
1040                 $arr = ['zrl' => $my_url, 'url' => $a->cmd];
1041                 Hook::callAll('zrl_init', $arr);
1042
1043                 // Try to find the public contact entry of the visitor.
1044                 $cid = Contact::getIdForURL($my_url);
1045                 if (!$cid) {
1046                         Logger::log('No contact record found for ' . $my_url, Logger::DEBUG);
1047                         return;
1048                 }
1049
1050                 $contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]);
1051
1052                 if (DBA::isResult($contact) && remote_user() && remote_user() == $contact['id']) {
1053                         Logger::log('The visitor ' . $my_url . ' is already authenticated', Logger::DEBUG);
1054                         return;
1055                 }
1056
1057                 // Avoid endless loops
1058                 $cachekey = 'zrlInit:' . $my_url;
1059                 if (Cache::get($cachekey)) {
1060                         Logger::log('URL ' . $my_url . ' already tried to authenticate.', Logger::DEBUG);
1061                         return;
1062                 } else {
1063                         Cache::set($cachekey, true, Cache::MINUTE);
1064                 }
1065
1066                 Logger::log('Not authenticated. Invoking reverse magic-auth for ' . $my_url, Logger::DEBUG);
1067
1068                 Worker::add(PRIORITY_LOW, 'GProbe', $my_url);
1069
1070                 // Try to avoid recursion - but send them home to do a proper magic auth.
1071                 $query = str_replace(array('?zrl=', '&zid='), array('?rzrl=', '&rzrl='), $a->query_string);
1072                 // The other instance needs to know where to redirect.
1073                 $dest = urlencode($a->getBaseURL() . '/' . $query);
1074
1075                 // We need to extract the basebath from the profile url
1076                 // to redirect the visitors '/magic' module.
1077                 // Note: We should have the basepath of a contact also in the contact table.
1078                 $urlarr = explode('/profile/', $contact['url']);
1079                 $basepath = $urlarr[0];
1080
1081                 if ($basepath != $a->getBaseURL() && !strstr($dest, '/magic') && !strstr($dest, '/rmagic')) {
1082                         $magic_path = $basepath . '/magic' . '?f=&owa=1&dest=' . $dest;
1083
1084                         // We have to check if the remote server does understand /magic without invoking something
1085                         $serverret = Network::curl($basepath . '/magic');
1086                         if ($serverret->isSuccess()) {
1087                                 Logger::log('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path, Logger::DEBUG);
1088                                 System::externalRedirect($magic_path);
1089                         }
1090                 }
1091         }
1092
1093         /**
1094          * Set the visitor cookies (see remote_user()) for the given handle
1095          *
1096          * @param string $handle Visitor handle
1097          * @return array Visitor contact array
1098          */
1099         public static function addVisitorCookieForHandle($handle)
1100         {
1101                 $a = \get_app();
1102
1103                 // Try to find the public contact entry of the visitor.
1104                 $cid = Contact::getIdForURL($handle);
1105                 if (!$cid) {
1106                         Logger::log('unable to finger ' . $handle, Logger::DEBUG);
1107                         return [];
1108                 }
1109
1110                 $visitor = DBA::selectFirst('contact', [], ['id' => $cid]);
1111
1112                 // Authenticate the visitor.
1113                 $_SESSION['authenticated'] = 1;
1114                 $_SESSION['visitor_id'] = $visitor['id'];
1115                 $_SESSION['visitor_handle'] = $visitor['addr'];
1116                 $_SESSION['visitor_home'] = $visitor['url'];
1117                 $_SESSION['my_url'] = $visitor['url'];
1118
1119                 /// @todo replace this and the query for this variable with some cleaner functionality
1120                 $_SESSION['remote'] = [];
1121
1122                 $remote_contacts = DBA::select('contact', ['id', 'uid'], ['nurl' => $visitor['nurl'], 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'self' => false]);
1123                 while ($contact = DBA::fetch($remote_contacts)) {
1124                         if (($contact['uid'] == 0) || Contact::isBlockedByUser($visitor['id'], $contact['uid'])) {
1125                                 continue;
1126                         }
1127
1128                         $_SESSION['remote'][$contact['uid']] = $contact['id'];
1129                 }
1130
1131                 $a->contact = $visitor;
1132
1133                 Logger::info('Authenticated visitor', ['url' => $visitor['url']]);
1134
1135                 return $visitor;
1136         }
1137
1138         /**
1139          * OpenWebAuth authentication.
1140          *
1141          * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/zid.php
1142          *
1143          * @param string $token
1144          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1145          * @throws \ImagickException
1146          */
1147         public static function openWebAuthInit($token)
1148         {
1149                 $a = \get_app();
1150
1151                 // Clean old OpenWebAuthToken entries.
1152                 OpenWebAuthToken::purge('owt', '3 MINUTE');
1153
1154                 // Check if the token we got is the same one
1155                 // we have stored in the database.
1156                 $visitor_handle = OpenWebAuthToken::getMeta('owt', 0, $token);
1157
1158                 if ($visitor_handle === false) {
1159                         return;
1160                 }
1161
1162                 $visitor = self::addVisitorCookieForHandle($visitor_handle);
1163                 if (empty($visitor)) {
1164                         return;
1165                 }
1166
1167                 $arr = [
1168                         'visitor' => $visitor,
1169                         'url' => $a->query_string
1170                 ];
1171                 /**
1172                  * @hooks magic_auth_success
1173                  *   Called when a magic-auth was successful.
1174                  *   * \e array \b visitor
1175                  *   * \e string \b url
1176                  */
1177                 Hook::callAll('magic_auth_success', $arr);
1178
1179                 $a->contact = $arr['visitor'];
1180
1181                 info(L10n::t('OpenWebAuth: %1$s welcomes %2$s', $a->getHostName(), $visitor['name']));
1182
1183                 Logger::log('OpenWebAuth: auth success from ' . $visitor['addr'], Logger::DEBUG);
1184         }
1185
1186         public static function zrl($s, $force = false)
1187         {
1188                 if (!strlen($s)) {
1189                         return $s;
1190                 }
1191                 if ((!strpos($s, '/profile/')) && (!$force)) {
1192                         return $s;
1193                 }
1194                 if ($force && substr($s, -1, 1) !== '/') {
1195                         $s = $s . '/';
1196                 }
1197                 $achar = strpos($s, '?') ? '&' : '?';
1198                 $mine = self::getMyURL();
1199                 if ($mine && !Strings::compareLink($mine, $s)) {
1200                         return $s . $achar . 'zrl=' . urlencode($mine);
1201                 }
1202                 return $s;
1203         }
1204
1205         /**
1206          * Get the user ID of the page owner.
1207          *
1208          * Used from within PCSS themes to set theme parameters. If there's a
1209          * profile_uid variable set in App, that is the "page owner" and normally their theme
1210          * settings take precedence; unless a local user sets the "always_my_theme"
1211          * system pconfig, which means they don't want to see anybody else's theme
1212          * settings except their own while on this site.
1213          *
1214          * @brief Get the user ID of the page owner
1215          * @return int user ID
1216          *
1217          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1218          * @note Returns local_user instead of user ID if "always_my_theme" is set to true
1219          */
1220         public static function getThemeUid(App $a)
1221         {
1222                 $uid = !empty($a->profile_uid) ? intval($a->profile_uid) : 0;
1223                 if (local_user() && (PConfig::get(local_user(), 'system', 'always_my_theme') || !$uid)) {
1224                         return local_user();
1225                 }
1226
1227                 return $uid;
1228         }
1229
1230         /**
1231          * search for Profiles
1232          *
1233          * @param int  $start
1234          * @param int  $count
1235          * @param null $search
1236          *
1237          * @return array [ 'total' => 123, 'entries' => [...] ];
1238          *
1239          * @throws \Exception
1240          */
1241         public static function searchProfiles($start = 0, $count = 100, $search = null)
1242         {
1243                 $publish = (Config::get('system', 'publish_all') ? '' : " AND `publish` = 1 ");
1244                 $total = 0;
1245
1246                 if (!empty($search)) {
1247                         $searchTerm = '%' . $search . '%';
1248                         $cnt = DBA::fetchFirst("SELECT COUNT(*) AS `total` 
1249                                 FROM `profile`
1250                                 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1251                                 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed`
1252                                 AND ((`profile`.`name` LIKE ?) OR
1253                                 (`user`.`nickname` LIKE ?) OR
1254                                 (`profile`.`pdesc` LIKE ?) OR
1255                                 (`profile`.`locality` LIKE ?) OR
1256                                 (`profile`.`region` LIKE ?) OR
1257                                 (`profile`.`country-name` LIKE ?) OR
1258                                 (`profile`.`gender` LIKE ?) OR
1259                                 (`profile`.`marital` LIKE ?) OR
1260                                 (`profile`.`sexual` LIKE ?) OR
1261                                 (`profile`.`about` LIKE ?) OR
1262                                 (`profile`.`romance` LIKE ?) OR
1263                                 (`profile`.`work` LIKE ?) OR
1264                                 (`profile`.`education` LIKE ?) OR
1265                                 (`profile`.`pub_keywords` LIKE ?) OR
1266                                 (`profile`.`prv_keywords` LIKE ?))",
1267                                 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1268                                 $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm);
1269                 } else {
1270                         $cnt = DBA::fetchFirst("SELECT COUNT(*) AS `total` 
1271                                 FROM `profile`
1272                                 LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1273                                 WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed`");
1274                 }
1275
1276                 if (DBA::isResult($cnt)) {
1277                         $total = $cnt['total'];
1278                 }
1279
1280                 $order = " ORDER BY `name` ASC ";
1281                 $profiles = [];
1282
1283                 // If nothing found, don't try to select details
1284                 if ($total > 0) {
1285                         if (!empty($search)) {
1286                                 $searchTerm = '%' . $search . '%';
1287
1288                                 $profiles = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
1289                         `contact`.`addr`, `contact`.`url` AS `profile_url`
1290                         FROM `profile`
1291                         LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1292                         LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1293                         WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
1294                         AND ((`profile`.`name` LIKE ?) OR
1295                                 (`user`.`nickname` LIKE ?) OR
1296                                 (`profile`.`pdesc` LIKE ?) OR
1297                                 (`profile`.`locality` LIKE ?) OR
1298                                 (`profile`.`region` LIKE ?) OR
1299                                 (`profile`.`country-name` LIKE ?) OR
1300                                 (`profile`.`gender` LIKE ?) OR
1301                                 (`profile`.`marital` LIKE ?) OR
1302                                 (`profile`.`sexual` LIKE ?) OR
1303                                 (`profile`.`about` LIKE ?) OR
1304                                 (`profile`.`romance` LIKE ?) OR
1305                                 (`profile`.`work` LIKE ?) OR
1306                                 (`profile`.`education` LIKE ?) OR
1307                                 (`profile`.`pub_keywords` LIKE ?) OR
1308                                 (`profile`.`prv_keywords` LIKE ?))
1309                         $order LIMIT ?,?",
1310                                         $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1311                                         $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm, $searchTerm,
1312                                         $start, $count
1313                                 );
1314                         } else {
1315                                 $profiles = DBA::p("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname`, `user`.`timezone` , `user`.`page-flags`,
1316                         `contact`.`addr`, `contact`.`url` AS `profile_url`
1317                         FROM `profile`
1318                         LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid`
1319                         LEFT JOIN `contact` ON `contact`.`uid` = `user`.`uid`
1320                         WHERE `is-default` $publish AND NOT `user`.`blocked` AND NOT `user`.`account_removed` AND `contact`.`self`
1321                         $order LIMIT ?,?",
1322                                         $start, $count
1323                                 );
1324                         }
1325                 }
1326
1327                 if (DBA::isResult($profiles) && $total > 0) {
1328                         return [
1329                                 'total'   => $total,
1330                                 'entries' => DBA::toArray($profiles),
1331                         ];
1332
1333                 } else {
1334                         return [
1335                                 'total'   => $total,
1336                                 'entries' => [],
1337                         ];
1338                 }
1339         }
1340 }