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