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