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