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