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