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