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