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