]> git.mxchange.org Git - friendica.git/blob - src/Model/Profile.php
Use short form array syntax everywhere
[friendica.git] / src / Model / Profile.php
1 <?php
2 /**
3  * @file src/Model/Profile.php
4  */
5
6 namespace Friendica\Model;
7
8 use Friendica\App;
9 use Friendica\Content\Feature;
10 use Friendica\Content\ForumManager;
11 use Friendica\Core\Cache;
12 use Friendica\Core\Config;
13 use Friendica\Core\PConfig;
14 use Friendica\Core\System;
15 use Friendica\Core\Worker;
16 use Friendica\Database\DBM;
17 use Friendica\Model\Contact;
18 use Friendica\Protocol\Diaspora;
19 use dba;
20
21 require_once 'include/dba.php';
22 require_once 'include/bbcode.php';
23 require_once 'mod/proxy.php';
24
25 class Profile
26 {
27         /**
28          * @brief Returns a formatted location string from the given profile array
29          *
30          * @param array $profile Profile array (Generated from the "profile" table)
31          *
32          * @return string Location string
33          */
34         public static function formatLocation(array $profile)
35         {
36                 $location = '';
37
38                 if ($profile['locality']) {
39                         $location .= $profile['locality'];
40                 }
41
42                 if ($profile['region'] && ($profile['locality'] != $profile['region'])) {
43                         if ($location) {
44                                 $location .= ', ';
45                         }
46
47                         $location .= $profile['region'];
48                 }
49
50                 if ($profile['country-name']) {
51                         if ($location) {
52                                 $location .= ', ';
53                         }
54
55                         $location .= $profile['country-name'];
56                 }
57
58                 return $location;
59         }
60
61         /**
62          *
63          * Loads a profile into the page sidebar.
64          *
65          * The function requires a writeable copy of the main App structure, and the nickname
66          * of a registered local account.
67          *
68          * If the viewer is an authenticated remote viewer, the profile displayed is the
69          * one that has been configured for his/her viewing in the Contact manager.
70          * Passing a non-zero profile ID can also allow a preview of a selected profile
71          * by the owner.
72          *
73          * Profile information is placed in the App structure for later retrieval.
74          * Honours the owner's chosen theme for display.
75          *
76          * @attention Should only be run in the _init() functions of a module. That ensures that
77          *      the theme is chosen before the _init() function of a theme is run, which will usually
78          *      load a lot of theme-specific content
79          *
80          * @brief Loads a profile into the page sidebar.
81          * @param object  $a            App
82          * @param string  $nickname     string
83          * @param int     $profile      int
84          * @param array   $profiledata  array
85          * @param boolean $show_connect Show connect link
86          */
87         public static function load(App $a, $nickname, $profile = 0, $profiledata = [], $show_connect = true)
88         {
89                 $user = dba::selectFirst('user', ['uid'], ['nickname' => $nickname]);
90
91                 if (!$user && !count($user) && !count($profiledata)) {
92                         logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
93                         notice(t('Requested account is not available.') . EOL);
94                         $a->error = 404;
95                         return;
96                 }
97
98                 if (!x($a->page, 'aside')) {
99                         $a->page['aside'] = '';
100                 }
101
102                 if ($profiledata) {
103                         $a->page['aside'] .= self::sidebar($profiledata, true, $show_connect);
104
105                         if (!DBM::is_result($user)) {
106                                 return;
107                         }
108                 }
109
110                 $pdata = self::getByNickname($nickname, $user[0]['uid'], $profile);
111
112                 if (empty($pdata) && empty($profiledata)) {
113                         logger('profile error: ' . $a->query_string, LOGGER_DEBUG);
114                         notice(t('Requested profile is not available.') . EOL);
115                         $a->error = 404;
116                         return;
117                 }
118
119                 // fetch user tags if this isn't the default profile
120
121                 if (!$pdata['is-default']) {
122                         $x = q(
123                                 "SELECT `pub_keywords` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
124                                 intval($pdata['profile_uid'])
125                         );
126                         if ($x && count($x)) {
127                                 $pdata['pub_keywords'] = $x[0]['pub_keywords'];
128                         }
129                 }
130
131                 $a->profile = $pdata;
132                 $a->profile_uid = $pdata['profile_uid'];
133
134                 $a->profile['mobile-theme'] = PConfig::get($a->profile['profile_uid'], 'system', 'mobile_theme');
135                 $a->profile['network'] = NETWORK_DFRN;
136
137                 $a->page['title'] = $a->profile['name'] . ' @ ' . $a->config['sitename'];
138
139                 if (!$profiledata && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
140                         $_SESSION['theme'] = $a->profile['theme'];
141                 }
142
143                 $_SESSION['mobile-theme'] = $a->profile['mobile-theme'];
144
145                 /*
146                 * load/reload current theme info
147                 */
148
149                 $a->set_template_engine(); // reset the template engine to the default in case the user's theme doesn't specify one
150
151                 $theme_info_file = 'view/theme/' . current_theme() . '/theme.php';
152                 if (file_exists($theme_info_file)) {
153                         require_once $theme_info_file;
154                 }
155
156                 if (!x($a->page, 'aside')) {
157                         $a->page['aside'] = '';
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' => 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 HTML string suitable for sidebar inclusion
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                 call_hooks('profile_sidebar_enter', $profile);
290
291
292                 // don't show connect link to yourself
293                 $connect = $profile['uid'] != local_user() ? 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 = 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 = 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', t('Profiles'), '', 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' => t('Change profile photo'),
376                                 'cr_new' => 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' => t('Profile Image'),
386                                                 'profile_name' => $rr['profile-name'],
387                                                 'isdefault' => $rr['is-default'],
388                                                 'visibile_to_everybody' => t('visible to everybody'),
389                                                 'edit_visibility' => 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'], t('Edit profile'), '', t('Edit profile')];
396                         $profile['menu'] = [
397                                 'chg_photo' => 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 = t('Location:');
414                 }
415
416                 $gender   = x($profile, 'gender')   ? t('Gender:')   : false;
417                 $marital  = x($profile, 'marital')  ? t('Status:')   : false;
418                 $homepage = x($profile, 'homepage') ? t('Homepage:') : false;
419                 $about    = x($profile, 'about')    ? t('About:')    : false;
420                 $xmpp     = x($profile, 'xmpp')     ? 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($p['about']);
487                 }
488
489                 if (isset($p['address'])) {
490                         $p['address'] = bbcode($p['address']);
491                 } else {
492                         $p['address'] = bbcode($p['location']);
493                 }
494
495                 if (isset($p['photo'])) {
496                         $p['photo'] = proxy_url($p['photo'], false, PROXY_SIZE_SMALL);
497                 }
498
499                 $tpl = get_markup_template('profile_vcard.tpl');
500                 $o .= replace_macros($tpl, [
501                         '$profile' => $p,
502                         '$xmpp' => $xmpp,
503                         '$connect' => $connect,
504                         '$remoteconnect' => $remoteconnect,
505                         '$subscribe_feed' => $subscribe_feed,
506                         '$wallmessage' => $wallmessage,
507                         '$wallmessage_link' => $wallmessage_link,
508                         '$account_type' => $account_type,
509                         '$location' => $location,
510                         '$gender' => $gender,
511                         '$marital' => $marital,
512                         '$homepage' => $homepage,
513                         '$about' => $about,
514                         '$network' => t('Network:'),
515                         '$contacts' => $contacts,
516                         '$updated' => $updated,
517                         '$diaspora' => $diaspora,
518                         '$contact_block' => $contact_block,
519                 ]);
520
521                 $arr = ['profile' => &$profile, 'entry' => &$o];
522
523                 call_hooks('profile_sidebar', $arr);
524
525                 return $o;
526         }
527
528         public static function getBirthdays()
529         {
530                 $a = get_app();
531                 $o = '';
532
533                 if (!local_user() || $a->is_mobile || $a->is_tablet) {
534                         return $o;
535                 }
536
537                 /*
538                 * $mobile_detect = new Mobile_Detect();
539                 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
540                 *               if ($is_mobile)
541                 *                       return $o;
542                 */
543
544                 $bd_format = t('g A l F d'); // 8 AM Friday January 18
545                 $bd_short = t('F d');
546
547                 $cachekey = 'get_birthdays:' . local_user();
548                 $r = Cache::get($cachekey);
549                 if (is_null($r)) {
550                         $s = dba::p(
551                                 "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
552                                 INNER JOIN `contact` ON `contact`.`id` = `event`.`cid`
553                                 WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
554                                 ORDER BY `start` ASC ",
555                                 local_user(),
556                                 datetime_convert('UTC', 'UTC', 'now + 6 days'),
557                                 datetime_convert('UTC', 'UTC', 'now')
558                         );
559                         if (DBM::is_result($s)) {
560                                 $r = dba::inArray($s);
561                                 Cache::set($cachekey, $r, CACHE_HOUR);
562                         }
563                 }
564                 if (DBM::is_result($r)) {
565                         $total = 0;
566                         $now = strtotime('now');
567                         $cids = [];
568
569                         $istoday = false;
570                         foreach ($r as $rr) {
571                                 if (strlen($rr['name'])) {
572                                         $total ++;
573                                 }
574                                 if ((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) {
575                                         $istoday = true;
576                                 }
577                         }
578                         $classtoday = $istoday ? ' birthday-today ' : '';
579                         if ($total) {
580                                 foreach ($r as &$rr) {
581                                         if (!strlen($rr['name'])) {
582                                                 continue;
583                                         }
584
585                                         // avoid duplicates
586
587                                         if (in_array($rr['cid'], $cids)) {
588                                                 continue;
589                                         }
590                                         $cids[] = $rr['cid'];
591
592                                         $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
593                                         $url = $rr['url'];
594                                         if ($rr['network'] === NETWORK_DFRN) {
595                                                 $url = System::baseUrl() . '/redir/' . $rr['cid'];
596                                         }
597
598                                         $rr['link'] = $url;
599                                         $rr['title'] = $rr['name'];
600                                         $rr['date'] = day_translate(datetime_convert('UTC', $a->timezone, $rr['start'], $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . 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' => t('Birthday Reminders'),
612                         '$event_title' => 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 getEvents()
620         {
621                 require_once 'include/bbcode.php';
622
623                 $a = get_app();
624
625                 if (!local_user() || $a->is_mobile || $a->is_tablet) {
626                         return $o;
627                 }
628
629                 /*
630                 *       $mobile_detect = new Mobile_Detect();
631                 *               $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
632                 *               if ($is_mobile)
633                 *                       return $o;
634                 */
635
636                 $bd_format = t('g A l F d'); // 8 AM Friday January 18
637                 $classtoday = '';
638
639                 $s = dba::p(
640                         "SELECT `event`.* FROM `event`
641                         WHERE `event`.`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?
642                         ORDER BY `start` ASC ",
643                         local_user(),
644                         datetime_convert('UTC', 'UTC', 'now + 7 days'),
645                         datetime_convert('UTC', 'UTC', 'now - 1 days')
646                 );
647
648                 $r = [];
649
650                 if (DBM::is_result($s)) {
651                         $istoday = false;
652
653                         while ($rr = dba::fetch($s)) {
654                                 if (strlen($rr['name'])) {
655                                         $total ++;
656                                 }
657
658                                 $strt = datetime_convert('UTC', $rr['convert'] ? $a->timezone : 'UTC', $rr['start'], 'Y-m-d');
659                                 if ($strt === datetime_convert('UTC', $a->timezone, 'now', 'Y-m-d')) {
660                                         $istoday = true;
661                                 }
662
663                                 $title = strip_tags(html_entity_decode(bbcode($rr['summary']), ENT_QUOTES, 'UTF-8'));
664
665                                 if (strlen($title) > 35) {
666                                         $title = substr($title, 0, 32) . '... ';
667                                 }
668
669                                 $description = substr(strip_tags(bbcode($rr['desc'])), 0, 32) . '... ';
670                                 if (!$description) {
671                                         $description = t('[No description]');
672                                 }
673
674                                 $strt = datetime_convert('UTC', $rr['convert'] ? $a->timezone : 'UTC', $rr['start']);
675
676                                 if (substr($strt, 0, 10) < datetime_convert('UTC', $a->timezone, 'now', 'Y-m-d')) {
677                                         continue;
678                                 }
679
680                                 $today = ((substr($strt, 0, 10) === datetime_convert('UTC', $a->timezone, 'now', 'Y-m-d')) ? true : false);
681
682                                 $rr['title'] = $title;
683                                 $rr['description'] = $description;
684                                 $rr['date'] = day_translate(datetime_convert('UTC', $rr['adjust'] ? $a->timezone : 'UTC', $rr['start'], $bd_format)) . (($today) ? ' ' . t('[today]') : '');
685                                 $rr['startime'] = $strt;
686                                 $rr['today'] = $today;
687
688                                 $r[] = $rr;
689                         }
690                         dba::close($s);
691                         $classtoday = (($istoday) ? 'event-today' : '');
692                 }
693                 $tpl = get_markup_template('events_reminder.tpl');
694                 return replace_macros($tpl, [
695                         '$baseurl' => System::baseUrl(),
696                         '$classtoday' => $classtoday,
697                         '$count' => count($r),
698                         '$event_reminders' => t('Event Reminders'),
699                         '$event_title' => t('Events this week:'),
700                         '$events' => $r,
701                 ]);
702         }
703
704         public static function getAdvanced(App $a)
705         {
706                 $o = '';
707                 $uid = $a->profile['uid'];
708
709                 $o .= replace_macros(
710                         get_markup_template('section_title.tpl'),
711                         ['$title' => t('Profile')]
712                 );
713
714                 if ($a->profile['name']) {
715                         $tpl = get_markup_template('profile_advanced.tpl');
716
717                         $profile = [];
718
719                         $profile['fullname'] = [t('Full Name:'), $a->profile['name']];
720
721                         if ($a->profile['gender']) {
722                                 $profile['gender'] = [t('Gender:'), $a->profile['gender']];
723                         }
724
725                         if (($a->profile['dob']) && ($a->profile['dob'] > '0001-01-01')) {
726                                 $year_bd_format = t('j F, Y');
727                                 $short_bd_format = t('j F');
728
729                                 $val = intval($a->profile['dob']) ?
730                                         day_translate(datetime_convert('UTC', 'UTC', $a->profile['dob'] . ' 00:00 +00:00', $year_bd_format))
731                                         : day_translate(datetime_convert('UTC', 'UTC', '2001-' . substr($a->profile['dob'], 5) . ' 00:00 +00:00', $short_bd_format));
732
733                                 $profile['birthday'] = [t('Birthday:'), $val];
734                         }
735
736                         if (!empty($a->profile['dob'])
737                                 && $a->profile['dob'] > '0001-01-01'
738                                 && $age = age($a->profile['dob'], $a->profile['timezone'], '')
739                         ) {
740                                 $profile['age'] = [t('Age:'), $age];
741                         }
742
743                         if ($a->profile['marital']) {
744                                 $profile['marital'] = [t('Status:'), $a->profile['marital']];
745                         }
746
747                         /// @TODO Maybe use x() here, plus below?
748                         if ($a->profile['with']) {
749                                 $profile['marital']['with'] = $a->profile['with'];
750                         }
751
752                         if (strlen($a->profile['howlong']) && $a->profile['howlong'] >= NULL_DATE) {
753                                 $profile['howlong'] = relative_date($a->profile['howlong'], t('for %1$d %2$s'));
754                         }
755
756                         if ($a->profile['sexual']) {
757                                 $profile['sexual'] = [t('Sexual Preference:'), $a->profile['sexual']];
758                         }
759
760                         if ($a->profile['homepage']) {
761                                 $profile['homepage'] = [t('Homepage:'), linkify($a->profile['homepage'])];
762                         }
763
764                         if ($a->profile['hometown']) {
765                                 $profile['hometown'] = [t('Hometown:'), linkify($a->profile['hometown'])];
766                         }
767
768                         if ($a->profile['pub_keywords']) {
769                                 $profile['pub_keywords'] = [t('Tags:'), $a->profile['pub_keywords']];
770                         }
771
772                         if ($a->profile['politic']) {
773                                 $profile['politic'] = [t('Political Views:'), $a->profile['politic']];
774                         }
775
776                         if ($a->profile['religion']) {
777                                 $profile['religion'] = [t('Religion:'), $a->profile['religion']];
778                         }
779
780                         if ($txt = prepare_text($a->profile['about'])) {
781                                 $profile['about'] = [t('About:'), $txt];
782                         }
783
784                         if ($txt = prepare_text($a->profile['interest'])) {
785                                 $profile['interest'] = [t('Hobbies/Interests:'), $txt];
786                         }
787
788                         if ($txt = prepare_text($a->profile['likes'])) {
789                                 $profile['likes'] = [t('Likes:'), $txt];
790                         }
791
792                         if ($txt = prepare_text($a->profile['dislikes'])) {
793                                 $profile['dislikes'] = [t('Dislikes:'), $txt];
794                         }
795
796                         if ($txt = prepare_text($a->profile['contact'])) {
797                                 $profile['contact'] = [t('Contact information and Social Networks:'), $txt];
798                         }
799
800                         if ($txt = prepare_text($a->profile['music'])) {
801                                 $profile['music'] = [t('Musical interests:'), $txt];
802                         }
803
804                         if ($txt = prepare_text($a->profile['book'])) {
805                                 $profile['book'] = [t('Books, literature:'), $txt];
806                         }
807
808                         if ($txt = prepare_text($a->profile['tv'])) {
809                                 $profile['tv'] = [t('Television:'), $txt];
810                         }
811
812                         if ($txt = prepare_text($a->profile['film'])) {
813                                 $profile['film'] = [t('Film/dance/culture/entertainment:'), $txt];
814                         }
815
816                         if ($txt = prepare_text($a->profile['romance'])) {
817                                 $profile['romance'] = [t('Love/Romance:'), $txt];
818                         }
819
820                         if ($txt = prepare_text($a->profile['work'])) {
821                                 $profile['work'] = [t('Work/employment:'), $txt];
822                         }
823
824                         if ($txt = prepare_text($a->profile['education'])) {
825                                 $profile['education'] = [t('School/education:'), $txt];
826                         }
827
828                         //show subcribed forum if it is enabled in the usersettings
829                         if (Feature::isEnabled($uid, 'forumlist_profile')) {
830                                 $profile['forumlist'] = [t('Forums:'), ForumManager::profileAdvanced($uid)];
831                         }
832
833                         if ($a->profile['uid'] == local_user()) {
834                                 $profile['edit'] = [System::baseUrl() . '/profiles/' . $a->profile['id'], t('Edit profile'), '', t('Edit profile')];
835                         }
836
837                         return replace_macros($tpl, [
838                                 '$title' => t('Profile'),
839                                 '$basic' => t('Basic'),
840                                 '$advanced' => t('Advanced'),
841                                 '$profile' => $profile
842                         ]);
843                 }
844
845                 return '';
846         }
847
848         public static function getTabs($a, $is_owner = false, $nickname = null)
849         {
850                 if (is_null($nickname)) {
851                         $nickname = $a->user['nickname'];
852                 }
853
854                 $tab = false;
855                 if (x($_GET, 'tab')) {
856                         $tab = notags(trim($_GET['tab']));
857                 }
858
859                 $url = System::baseUrl() . '/profile/' . $nickname;
860
861                 $tabs = [
862                         [
863                                 'label' => t('Status'),
864                                 'url'   => $url,
865                                 'sel'   => !$tab && $a->argv[0] == 'profile' ? 'active' : '',
866                                 'title' => t('Status Messages and Posts'),
867                                 'id'    => 'status-tab',
868                                 'accesskey' => 'm',
869                         ],
870                         [
871                                 'label' => t('Profile'),
872                                 'url'   => $url . '/?tab=profile',
873                                 'sel'   => $tab == 'profile' ? 'active' : '',
874                                 'title' => t('Profile Details'),
875                                 'id'    => 'profile-tab',
876                                 'accesskey' => 'r',
877                         ],
878                         [
879                                 'label' => t('Photos'),
880                                 'url'   => System::baseUrl() . '/photos/' . $nickname,
881                                 'sel'   => !$tab && $a->argv[0] == 'photos' ? 'active' : '',
882                                 'title' => t('Photo Albums'),
883                                 'id'    => 'photo-tab',
884                                 'accesskey' => 'h',
885                         ],
886                         [
887                                 'label' => t('Videos'),
888                                 'url'   => System::baseUrl() . '/videos/' . $nickname,
889                                 'sel'   => !$tab && $a->argv[0] == 'videos' ? 'active' : '',
890                                 'title' => t('Videos'),
891                                 'id'    => 'video-tab',
892                                 'accesskey' => 'v',
893                         ],
894                 ];
895
896                 // the calendar link for the full featured events calendar
897                 if ($is_owner && $a->theme_events_in_profile) {
898                         $tabs[] = [
899                                 'label' => t('Events'),
900                                 'url'   => System::baseUrl() . '/events',
901                                 'sel'   => !$tab && $a->argv[0] == 'events' ? 'active' : '',
902                                 'title' => t('Events and Calendar'),
903                                 'id'    => 'events-tab',
904                                 'accesskey' => 'e',
905                         ];
906                         // if the user is not the owner of the calendar we only show a calendar
907                         // with the public events of the calendar owner
908                 } elseif (!$is_owner) {
909                         $tabs[] = [
910                                 'label' => t('Events'),
911                                 'url'   => System::baseUrl() . '/cal/' . $nickname,
912                                 'sel'   => !$tab && $a->argv[0] == 'cal' ? 'active' : '',
913                                 'title' => t('Events and Calendar'),
914                                 'id'    => 'events-tab',
915                                 'accesskey' => 'e',
916                         ];
917                 }
918
919                 if ($is_owner) {
920                         $tabs[] = [
921                                 'label' => t('Personal Notes'),
922                                 'url'   => System::baseUrl() . '/notes',
923                                 'sel'   => !$tab && $a->argv[0] == 'notes' ? 'active' : '',
924                                 'title' => t('Only You Can See This'),
925                                 'id'    => 'notes-tab',
926                                 'accesskey' => 't',
927                         ];
928                 }
929
930                 if ((!$is_owner) && ((count($a->profile)) || (!$a->profile['hide-friends']))) {
931                         $tabs[] = [
932                                 'label' => t('Contacts'),
933                                 'url'   => System::baseUrl() . '/viewcontacts/' . $nickname,
934                                 'sel'   => !$tab && $a->argv[0] == 'viewcontacts' ? 'active' : '',
935                                 'title' => t('Contacts'),
936                                 'id'    => 'viewcontacts-tab',
937                                 'accesskey' => 'k',
938                         ];
939                 }
940
941                 $arr = ['is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => $tab, 'tabs' => $tabs];
942                 call_hooks('profile_tabs', $arr);
943
944                 $tpl = get_markup_template('common_tabs.tpl');
945
946                 return replace_macros($tpl, ['$tabs' => $arr['tabs']]);
947         }
948
949         /**
950          * Retrieves the my_url session variable
951          *
952          * @return string
953          */
954         public static function getMyURL()
955         {
956                 if (x($_SESSION, 'my_url')) {
957                         return $_SESSION['my_url'];
958                 }
959                 return null;
960         }
961
962         public static function zrlInit(App $a)
963         {
964                 $my_url = self::getMyURL();
965                 $my_url = validate_url($my_url);
966                 if ($my_url) {
967                         // Is it a DDoS attempt?
968                         // The check fetches the cached value from gprobe to reduce the load for this system
969                         $urlparts = parse_url($my_url);
970
971                         $result = Cache::get('gprobe:' . $urlparts['host']);
972                         if ((!is_null($result)) && (in_array($result['network'], [NETWORK_FEED, NETWORK_PHANTOM]))) {
973                                 logger('DDoS attempt detected for ' . $urlparts['host'] . ' by ' . $_SERVER['REMOTE_ADDR'] . '. server data: ' . print_r($_SERVER, true), LOGGER_DEBUG);
974                                 return;
975                         }
976
977                         Worker::add(PRIORITY_LOW, 'GProbe', $my_url);
978                         $arr = ['zrl' => $my_url, 'url' => $a->cmd];
979                         call_hooks('zrl_init', $arr);
980                 }
981         }
982
983         public static function zrl($s, $force = false)
984         {
985                 if (!strlen($s)) {
986                         return $s;
987                 }
988                 if ((!strpos($s, '/profile/')) && (!$force)) {
989                         return $s;
990                 }
991                 if ($force && substr($s, -1, 1) !== '/') {
992                         $s = $s . '/';
993                 }
994                 $achar = strpos($s, '?') ? '&' : '?';
995                 $mine = self::getMyURL();
996                 if ($mine && !link_compare($mine, $s)) {
997                         return $s . $achar . 'zrl=' . urlencode($mine);
998                 }
999                 return $s;
1000         }
1001
1002         /**
1003          * Get the user ID of the page owner.
1004          *
1005          * Used from within PCSS themes to set theme parameters. If there's a
1006          * puid request variable, that is the "page owner" and normally their theme
1007          * settings take precedence; unless a local user sets the "always_my_theme"
1008          * system pconfig, which means they don't want to see anybody else's theme
1009          * settings except their own while on this site.
1010          *
1011          * @brief Get the user ID of the page owner
1012          * @return int user ID
1013          *
1014          * @note Returns local_user instead of user ID if "always_my_theme"
1015          *      is set to true
1016          */
1017         public static function getThemeUid()
1018         {
1019                 $uid = ((!empty($_REQUEST['puid'])) ? intval($_REQUEST['puid']) : 0);
1020                 if ((local_user()) && ((PConfig::get(local_user(), 'system', 'always_my_theme')) || (!$uid))) {
1021                         return local_user();
1022                 }
1023
1024                 return $uid;
1025         }
1026 }