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