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