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