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