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