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