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