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