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