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