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