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