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