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