]> git.mxchange.org Git - friendica.git/blob - src/Model/Profile.php
Fix mods/README.md format
[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 App     $a
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_link'] = Strings::formatNetworkName($profile['network'], $profile['url']);
301                 } else {
302                         $profile['network_link'] = '';
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                 // Is the remote user already connected to that user?
341                 if ($connect && Contact::isFollower(remote_user(), $profile['uid'])) {
342                         $connect = false;
343                 }
344
345                 if ($connect && ($profile['network'] != Protocol::DFRN) && !isset($profile['remoteconnect'])) {
346                         $connect = false;
347                 }
348
349                 $remoteconnect = null;
350                 if (isset($profile['remoteconnect'])) {
351                         $remoteconnect = $profile['remoteconnect'];
352                 }
353
354                 if ($connect && ($profile['network'] == Protocol::DFRN) && !isset($remoteconnect)) {
355                         $subscribe_feed = L10n::t('Atom feed');
356                 } else {
357                         $subscribe_feed = false;
358                 }
359
360                 $wallmessage = false;
361                 $wallmessage_link = false;
362
363                 // See issue https://github.com/friendica/friendica/issues/3838
364                 // Either we remove the message link for remote users or we enable creating messages from remote users
365                 if (remote_user() || (self::getMyURL() && !empty($profile['unkmail']) && ($profile['uid'] != local_user()))) {
366                         $wallmessage = L10n::t('Message');
367
368                         if (remote_user()) {
369                                 $r = q(
370                                         "SELECT `url` FROM `contact` WHERE `uid` = %d AND `id` = '%s' AND `rel` = %d",
371                                         intval($profile['uid']),
372                                         intval(remote_user()),
373                                         intval(Contact::FRIEND)
374                                 );
375                         } else {
376                                 $r = q(
377                                         "SELECT `url` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `rel` = %d",
378                                         intval($profile['uid']),
379                                         DBA::escape(Strings::normaliseLink(self::getMyURL())),
380                                         intval(Contact::FRIEND)
381                                 );
382                         }
383                         if ($r) {
384                                 $remote_url = $r[0]['url'];
385                                 $message_path = preg_replace('=(.*)/profile/(.*)=ism', '$1/message/new/', $remote_url);
386                                 $wallmessage_link = $message_path . base64_encode(defaults($profile, 'addr', ''));
387                         } else if (!empty($profile['nickname'])) {
388                                 $wallmessage_link = 'wallmessage/' . $profile['nickname'];
389                         }
390                 }
391
392                 // show edit profile to yourself
393                 if (!$is_contact && $profile['uid'] == local_user() && Feature::isEnabled(local_user(), 'multi_profiles')) {
394                         $profile['edit'] = [System::baseUrl() . '/profiles', L10n::t('Profiles'), '', L10n::t('Manage/edit profiles')];
395                         $r = q(
396                                 "SELECT * FROM `profile` WHERE `uid` = %d",
397                                 local_user()
398                         );
399
400                         $profile['menu'] = [
401                                 'chg_photo' => L10n::t('Change profile photo'),
402                                 'cr_new' => L10n::t('Create New Profile'),
403                                 'entries' => [],
404                         ];
405
406                         if (DBA::isResult($r)) {
407                                 foreach ($r as $rr) {
408                                         $profile['menu']['entries'][] = [
409                                                 'photo' => $rr['thumb'],
410                                                 'id' => $rr['id'],
411                                                 'alt' => L10n::t('Profile Image'),
412                                                 'profile_name' => $rr['profile-name'],
413                                                 'isdefault' => $rr['is-default'],
414                                                 'visibile_to_everybody' => L10n::t('visible to everybody'),
415                                                 'edit_visibility' => L10n::t('Edit visibility'),
416                                         ];
417                                 }
418                         }
419                 }
420                 if (!$is_contact && $profile['uid'] == local_user() && !Feature::isEnabled(local_user(), 'multi_profiles')) {
421                         $profile['edit'] = [System::baseUrl() . '/profiles/' . $profile['id'], L10n::t('Edit profile'), '', L10n::t('Edit profile')];
422                         $profile['menu'] = [
423                                 'chg_photo' => L10n::t('Change profile photo'),
424                                 'cr_new' => null,
425                                 'entries' => [],
426                         ];
427                 }
428
429                 // Fetch the account type
430                 $account_type = Contact::getAccountType($profile);
431
432                 if (!empty($profile['address'])
433                         || !empty($profile['location'])
434                         || !empty($profile['locality'])
435                         || !empty($profile['region'])
436                         || !empty($profile['postal-code'])
437                         || !empty($profile['country-name'])
438                 ) {
439                         $location = L10n::t('Location:');
440                 }
441
442                 $gender   = !empty($profile['gender'])   ? L10n::t('Gender:')   : false;
443                 $marital  = !empty($profile['marital'])  ? L10n::t('Status:')   : false;
444                 $homepage = !empty($profile['homepage']) ? L10n::t('Homepage:') : false;
445                 $about    = !empty($profile['about'])    ? L10n::t('About:')    : false;
446                 $xmpp     = !empty($profile['xmpp'])     ? L10n::t('XMPP:')     : false;
447
448                 if ((!empty($profile['hidewall']) || $block) && !local_user() && !remote_user()) {
449                         $location = $gender = $marital = $homepage = $about = false;
450                 }
451
452                 $split_name = Diaspora::splitName($profile['name']);
453                 $firstname = $split_name['first'];
454                 $lastname = $split_name['last'];
455
456                 if (!empty($profile['guid'])) {
457                         $diaspora = [
458                                 'guid' => $profile['guid'],
459                                 'podloc' => System::baseUrl(),
460                                 'searchable' => (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false' ),
461                                 'nickname' => $profile['nickname'],
462                                 'fullname' => $profile['name'],
463                                 'firstname' => $firstname,
464                                 'lastname' => $lastname,
465                                 'photo300' => defaults($profile, 'contact_photo', ''),
466                                 'photo100' => defaults($profile, 'contact_thumb', ''),
467                                 'photo50' => defaults($profile, 'contact_micro', ''),
468                         ];
469                 } else {
470                         $diaspora = false;
471                 }
472
473                 $contact_block = '';
474                 $updated = '';
475                 $contacts = 0;
476                 if (!$block) {
477                         $contact_block = HTML::contactBlock();
478
479                         if (is_array($a->profile) && !$a->profile['hide-friends']) {
480                                 $r = q(
481                                         "SELECT `gcontact`.`updated` FROM `contact` INNER JOIN `gcontact` WHERE `gcontact`.`nurl` = `contact`.`nurl` AND `self` AND `uid` = %d LIMIT 1",
482                                         intval($a->profile['uid'])
483                                 );
484                                 if (DBA::isResult($r)) {
485                                         $updated = date('c', strtotime($r[0]['updated']));
486                                 }
487
488                                 $r = q(
489                                         "SELECT COUNT(*) AS `total` FROM `contact`
490                                         WHERE `uid` = %d
491                                                 AND NOT `self` AND NOT `blocked` AND NOT `pending`
492                                                 AND NOT `hidden` AND NOT `archive`
493                                                 AND `network` IN ('%s', '%s', '%s', '')",
494                                         intval($profile['uid']),
495                                         DBA::escape(Protocol::DFRN),
496                                         DBA::escape(Protocol::DIASPORA),
497                                         DBA::escape(Protocol::OSTATUS)
498                                 );
499                                 if (DBA::isResult($r)) {
500                                         $contacts = intval($r[0]['total']);
501                                 }
502                         }
503                 }
504
505                 $p = [];
506                 foreach ($profile as $k => $v) {
507                         $k = str_replace('-', '_', $k);
508                         $p[$k] = $v;
509                 }
510
511                 if (isset($p['about'])) {
512                         $p['about'] = BBCode::convert($p['about']);
513                 }
514
515                 if (empty($p['address']) && !empty($p['location'])) {
516                         $p['address'] = $p['location'];
517                 }
518
519                 if (isset($p['photo'])) {
520                         $p['photo'] = ProxyUtils::proxifyUrl($p['photo'], false, ProxyUtils::SIZE_SMALL);
521                 }
522
523                 $p['url'] = Contact::magicLink(defaults($p, 'url', $profile_url));
524
525                 $tpl = Renderer::getMarkupTemplate('profile_vcard.tpl');
526                 $o .= Renderer::replaceMacros($tpl, [
527                         '$profile' => $p,
528                         '$xmpp' => $xmpp,
529                         '$connect' => $connect,
530                         '$remoteconnect' => $remoteconnect,
531                         '$subscribe_feed' => $subscribe_feed,
532                         '$wallmessage' => $wallmessage,
533                         '$wallmessage_link' => $wallmessage_link,
534                         '$account_type' => $account_type,
535                         '$location' => $location,
536                         '$gender' => $gender,
537                         '$marital' => $marital,
538                         '$homepage' => $homepage,
539                         '$about' => $about,
540                         '$network' => L10n::t('Network:'),
541                         '$contacts' => $contacts,
542                         '$updated' => $updated,
543                         '$diaspora' => $diaspora,
544                         '$contact_block' => $contact_block,
545                 ]);
546
547                 $arr = ['profile' => &$profile, 'entry' => &$o];
548
549                 Addon::callHooks('profile_sidebar', $arr);
550
551                 return $o;
552         }
553
554         public static function getBirthdays()
555         {
556                 $a = get_app();
557                 $o = '';
558
559                 if (!local_user() || $a->is_mobile || $a->is_tablet) {
560                         return $o;
561                 }
562
563                 /*
564                 * $mobile_detect = new Mobile_Detect();
565                 * $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
566                 *               if ($is_mobile)
567                 *                       return $o;
568                 */
569
570                 $bd_format = L10n::t('g A l F d'); // 8 AM Friday January 18
571                 $bd_short = L10n::t('F d');
572
573                 $cachekey = 'get_birthdays:' . local_user();
574                 $r = Cache::get($cachekey);
575                 if (is_null($r)) {
576                         $s = DBA::p(
577                                 "SELECT `event`.*, `event`.`id` AS `eid`, `contact`.* FROM `event`
578                                 INNER JOIN `contact`
579                                         ON `contact`.`id` = `event`.`cid`
580                                         AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
581                                         AND NOT `contact`.`pending`
582                                         AND NOT `contact`.`hidden`
583                                         AND NOT `contact`.`blocked`
584                                         AND NOT `contact`.`archive`
585                                         AND NOT `contact`.`deleted`
586                                 WHERE `event`.`uid` = ? AND `type` = 'birthday' AND `start` < ? AND `finish` > ?
587                                 ORDER BY `start` ASC ",
588                                 Contact::SHARING,
589                                 Contact::FRIEND,
590                                 local_user(),
591                                 DateTimeFormat::utc('now + 6 days'),
592                                 DateTimeFormat::utcNow()
593                         );
594                         if (DBA::isResult($s)) {
595                                 $r = DBA::toArray($s);
596                                 Cache::set($cachekey, $r, Cache::HOUR);
597                         }
598                 }
599
600                 $total = 0;
601                 $classtoday = '';
602                 if (DBA::isResult($r)) {
603                         $now = strtotime('now');
604                         $cids = [];
605
606                         $istoday = false;
607                         foreach ($r as $rr) {
608                                 if (strlen($rr['name'])) {
609                                         $total ++;
610                                 }
611                                 if ((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) {
612                                         $istoday = true;
613                                 }
614                         }
615                         $classtoday = $istoday ? ' birthday-today ' : '';
616                         if ($total) {
617                                 foreach ($r as &$rr) {
618                                         if (!strlen($rr['name'])) {
619                                                 continue;
620                                         }
621
622                                         // avoid duplicates
623
624                                         if (in_array($rr['cid'], $cids)) {
625                                                 continue;
626                                         }
627                                         $cids[] = $rr['cid'];
628
629                                         $today = (((strtotime($rr['start'] . ' +00:00') < $now) && (strtotime($rr['finish'] . ' +00:00') > $now)) ? true : false);
630
631                                         $rr['link'] = Contact::magicLink($rr['url']);
632                                         $rr['title'] = $rr['name'];
633                                         $rr['date'] = L10n::getDay(DateTimeFormat::convert($rr['start'], $a->timezone, 'UTC', $rr['adjust'] ? $bd_format : $bd_short)) . (($today) ? ' ' . L10n::t('[today]') : '');
634                                         $rr['startime'] = null;
635                                         $rr['today'] = $today;
636                                 }
637                         }
638                 }
639                 $tpl = Renderer::getMarkupTemplate('birthdays_reminder.tpl');
640                 return Renderer::replaceMacros($tpl, [
641                         '$baseurl' => System::baseUrl(),
642                         '$classtoday' => $classtoday,
643                         '$count' => $total,
644                         '$event_reminders' => L10n::t('Birthday Reminders'),
645                         '$event_title' => L10n::t('Birthdays this week:'),
646                         '$events' => $r,
647                         '$lbr' => '{', // raw brackets mess up if/endif macro processing
648                         '$rbr' => '}'
649                 ]);
650         }
651
652         public static function getEventsReminderHTML()
653         {
654                 $a = get_app();
655                 $o = '';
656
657                 if (!local_user() || $a->is_mobile || $a->is_tablet) {
658                         return $o;
659                 }
660
661                 /*
662                 *       $mobile_detect = new Mobile_Detect();
663                 *               $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
664                 *               if ($is_mobile)
665                 *                       return $o;
666                 */
667
668                 $bd_format = L10n::t('g A l F d'); // 8 AM Friday January 18
669                 $classtoday = '';
670
671                 $condition = ["`uid` = ? AND `type` != 'birthday' AND `start` < ? AND `start` >= ?",
672                         local_user(), DateTimeFormat::utc('now + 7 days'), DateTimeFormat::utc('now - 1 days')];
673                 $s = DBA::select('event', [], $condition, ['order' => ['start']]);
674
675                 $r = [];
676
677                 if (DBA::isResult($s)) {
678                         $istoday = false;
679                         $total = 0;
680
681                         while ($rr = DBA::fetch($s)) {
682                                 $condition = ['parent-uri' => $rr['uri'], 'uid' => $rr['uid'], 'author-id' => public_contact(),
683                                         'activity' => [Item::activityToIndex(ACTIVITY_ATTEND), Item::activityToIndex(ACTIVITY_ATTENDMAYBE)],
684                                         'visible' => true, 'deleted' => false];
685                                 if (!Item::exists($condition)) {
686                                         continue;
687                                 }
688
689                                 if (strlen($rr['summary'])) {
690                                         $total++;
691                                 }
692
693                                 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', 'Y-m-d');
694                                 if ($strt === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
695                                         $istoday = true;
696                                 }
697
698                                 $title = strip_tags(html_entity_decode(BBCode::convert($rr['summary']), ENT_QUOTES, 'UTF-8'));
699
700                                 if (strlen($title) > 35) {
701                                         $title = substr($title, 0, 32) . '... ';
702                                 }
703
704                                 $description = substr(strip_tags(BBCode::convert($rr['desc'])), 0, 32) . '... ';
705                                 if (!$description) {
706                                         $description = L10n::t('[No description]');
707                                 }
708
709                                 $strt = DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC');
710
711                                 if (substr($strt, 0, 10) < DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) {
712                                         continue;
713                                 }
714
715                                 $today = ((substr($strt, 0, 10) === DateTimeFormat::timezoneNow($a->timezone, 'Y-m-d')) ? true : false);
716
717                                 $rr['title'] = $title;
718                                 $rr['description'] = $description;
719                                 $rr['date'] = L10n::getDay(DateTimeFormat::convert($rr['start'], $rr['adjust'] ? $a->timezone : 'UTC', 'UTC', $bd_format)) . (($today) ? ' ' . L10n::t('[today]') : '');
720                                 $rr['startime'] = $strt;
721                                 $rr['today'] = $today;
722
723                                 $r[] = $rr;
724                         }
725                         DBA::close($s);
726                         $classtoday = (($istoday) ? 'event-today' : '');
727                 }
728                 $tpl = Renderer::getMarkupTemplate('events_reminder.tpl');
729                 return Renderer::replaceMacros($tpl, [
730                         '$baseurl' => System::baseUrl(),
731                         '$classtoday' => $classtoday,
732                         '$count' => count($r),
733                         '$event_reminders' => L10n::t('Event Reminders'),
734                         '$event_title' => L10n::t('Upcoming events the next 7 days:'),
735                         '$events' => $r,
736                 ]);
737         }
738
739         public static function getAdvanced(App $a)
740         {
741                 $o = '';
742                 $uid = $a->profile['uid'];
743
744                 $o .= Renderer::replaceMacros(
745                         Renderer::getMarkupTemplate('section_title.tpl'),
746                         ['$title' => L10n::t('Profile')]
747                 );
748
749                 if ($a->profile['name']) {
750                         $tpl = Renderer::getMarkupTemplate('profile_advanced.tpl');
751
752                         $profile = [];
753
754                         $profile['fullname'] = [L10n::t('Full Name:'), $a->profile['name']];
755
756                         if (Feature::isEnabled($uid, 'profile_membersince')) {
757                                 $profile['membersince'] = [L10n::t('Member since:'), DateTimeFormat::local($a->profile['register_date'])];
758                         }
759
760                         if ($a->profile['gender']) {
761                                 $profile['gender'] = [L10n::t('Gender:'), $a->profile['gender']];
762                         }
763
764                         if (!empty($a->profile['dob']) && $a->profile['dob'] > DBA::NULL_DATE) {
765                                 $year_bd_format = L10n::t('j F, Y');
766                                 $short_bd_format = L10n::t('j F');
767
768                                 $val = L10n::getDay(
769                                         intval($a->profile['dob']) ?
770                                                 DateTimeFormat::utc($a->profile['dob'] . ' 00:00 +00:00', $year_bd_format)
771                                                 : DateTimeFormat::utc('2001-' . substr($a->profile['dob'], 5) . ' 00:00 +00:00', $short_bd_format)
772                                 );
773
774                                 $profile['birthday'] = [L10n::t('Birthday:'), $val];
775                         }
776
777                         if (!empty($a->profile['dob'])
778                                 && $a->profile['dob'] > DBA::NULL_DATE
779                                 && $age = Temporal::getAgeByTimezone($a->profile['dob'], $a->profile['timezone'], '')
780                         ) {
781                                 $profile['age'] = [L10n::t('Age:'), $age];
782                         }
783
784                         if ($a->profile['marital']) {
785                                 $profile['marital'] = [L10n::t('Status:'), $a->profile['marital']];
786                         }
787
788                         /// @TODO Maybe use x() here, plus below?
789                         if ($a->profile['with']) {
790                                 $profile['marital']['with'] = $a->profile['with'];
791                         }
792
793                         if (strlen($a->profile['howlong']) && $a->profile['howlong'] >= DBA::NULL_DATETIME) {
794                                 $profile['howlong'] = Temporal::getRelativeDate($a->profile['howlong'], L10n::t('for %1$d %2$s'));
795                         }
796
797                         if ($a->profile['sexual']) {
798                                 $profile['sexual'] = [L10n::t('Sexual Preference:'), $a->profile['sexual']];
799                         }
800
801                         if ($a->profile['homepage']) {
802                                 $profile['homepage'] = [L10n::t('Homepage:'), HTML::toLink($a->profile['homepage'])];
803                         }
804
805                         if ($a->profile['hometown']) {
806                                 $profile['hometown'] = [L10n::t('Hometown:'), HTML::toLink($a->profile['hometown'])];
807                         }
808
809                         if ($a->profile['pub_keywords']) {
810                                 $profile['pub_keywords'] = [L10n::t('Tags:'), $a->profile['pub_keywords']];
811                         }
812
813                         if ($a->profile['politic']) {
814                                 $profile['politic'] = [L10n::t('Political Views:'), $a->profile['politic']];
815                         }
816
817                         if ($a->profile['religion']) {
818                                 $profile['religion'] = [L10n::t('Religion:'), $a->profile['religion']];
819                         }
820
821                         if ($txt = prepare_text($a->profile['about'])) {
822                                 $profile['about'] = [L10n::t('About:'), $txt];
823                         }
824
825                         if ($txt = prepare_text($a->profile['interest'])) {
826                                 $profile['interest'] = [L10n::t('Hobbies/Interests:'), $txt];
827                         }
828
829                         if ($txt = prepare_text($a->profile['likes'])) {
830                                 $profile['likes'] = [L10n::t('Likes:'), $txt];
831                         }
832
833                         if ($txt = prepare_text($a->profile['dislikes'])) {
834                                 $profile['dislikes'] = [L10n::t('Dislikes:'), $txt];
835                         }
836
837                         if ($txt = prepare_text($a->profile['contact'])) {
838                                 $profile['contact'] = [L10n::t('Contact information and Social Networks:'), $txt];
839                         }
840
841                         if ($txt = prepare_text($a->profile['music'])) {
842                                 $profile['music'] = [L10n::t('Musical interests:'), $txt];
843                         }
844
845                         if ($txt = prepare_text($a->profile['book'])) {
846                                 $profile['book'] = [L10n::t('Books, literature:'), $txt];
847                         }
848
849                         if ($txt = prepare_text($a->profile['tv'])) {
850                                 $profile['tv'] = [L10n::t('Television:'), $txt];
851                         }
852
853                         if ($txt = prepare_text($a->profile['film'])) {
854                                 $profile['film'] = [L10n::t('Film/dance/culture/entertainment:'), $txt];
855                         }
856
857                         if ($txt = prepare_text($a->profile['romance'])) {
858                                 $profile['romance'] = [L10n::t('Love/Romance:'), $txt];
859                         }
860
861                         if ($txt = prepare_text($a->profile['work'])) {
862                                 $profile['work'] = [L10n::t('Work/employment:'), $txt];
863                         }
864
865                         if ($txt = prepare_text($a->profile['education'])) {
866                                 $profile['education'] = [L10n::t('School/education:'), $txt];
867                         }
868
869                         //show subcribed forum if it is enabled in the usersettings
870                         if (Feature::isEnabled($uid, 'forumlist_profile')) {
871                                 $profile['forumlist'] = [L10n::t('Forums:'), ForumManager::profileAdvanced($uid)];
872                         }
873
874                         if ($a->profile['uid'] == local_user()) {
875                                 $profile['edit'] = [System::baseUrl() . '/profiles/' . $a->profile['id'], L10n::t('Edit profile'), '', L10n::t('Edit profile')];
876                         }
877
878                         return Renderer::replaceMacros($tpl, [
879                                 '$title' => L10n::t('Profile'),
880                                 '$basic' => L10n::t('Basic'),
881                                 '$advanced' => L10n::t('Advanced'),
882                                 '$profile' => $profile
883                         ]);
884                 }
885
886                 return '';
887         }
888
889         public static function getTabs($a, $is_owner = false, $nickname = null)
890         {
891                 if (is_null($nickname)) {
892                         $nickname = $a->user['nickname'];
893                 }
894
895                 $tab = false;
896                 if (!empty($_GET['tab'])) {
897                         $tab = Strings::escapeTags(trim($_GET['tab']));
898                 }
899
900                 $url = System::baseUrl() . '/profile/' . $nickname;
901
902                 $tabs = [
903                         [
904                                 'label' => L10n::t('Status'),
905                                 'url'   => $url,
906                                 'sel'   => !$tab && $a->argv[0] == 'profile' ? 'active' : '',
907                                 'title' => L10n::t('Status Messages and Posts'),
908                                 'id'    => 'status-tab',
909                                 'accesskey' => 'm',
910                         ],
911                         [
912                                 'label' => L10n::t('Profile'),
913                                 'url'   => $url . '/?tab=profile',
914                                 'sel'   => $tab == 'profile' ? 'active' : '',
915                                 'title' => L10n::t('Profile Details'),
916                                 'id'    => 'profile-tab',
917                                 'accesskey' => 'r',
918                         ],
919                         [
920                                 'label' => L10n::t('Photos'),
921                                 'url'   => System::baseUrl() . '/photos/' . $nickname,
922                                 'sel'   => !$tab && $a->argv[0] == 'photos' ? 'active' : '',
923                                 'title' => L10n::t('Photo Albums'),
924                                 'id'    => 'photo-tab',
925                                 'accesskey' => 'h',
926                         ],
927                         [
928                                 'label' => L10n::t('Videos'),
929                                 'url'   => System::baseUrl() . '/videos/' . $nickname,
930                                 'sel'   => !$tab && $a->argv[0] == 'videos' ? 'active' : '',
931                                 'title' => L10n::t('Videos'),
932                                 'id'    => 'video-tab',
933                                 'accesskey' => 'v',
934                         ],
935                 ];
936
937                 // the calendar link for the full featured events calendar
938                 if ($is_owner && $a->theme_events_in_profile) {
939                         $tabs[] = [
940                                 'label' => L10n::t('Events'),
941                                 'url'   => System::baseUrl() . '/events',
942                                 'sel'   => !$tab && $a->argv[0] == 'events' ? 'active' : '',
943                                 'title' => L10n::t('Events and Calendar'),
944                                 'id'    => 'events-tab',
945                                 'accesskey' => 'e',
946                         ];
947                         // if the user is not the owner of the calendar we only show a calendar
948                         // with the public events of the calendar owner
949                 } elseif (!$is_owner) {
950                         $tabs[] = [
951                                 'label' => L10n::t('Events'),
952                                 'url'   => System::baseUrl() . '/cal/' . $nickname,
953                                 'sel'   => !$tab && $a->argv[0] == 'cal' ? 'active' : '',
954                                 'title' => L10n::t('Events and Calendar'),
955                                 'id'    => 'events-tab',
956                                 'accesskey' => 'e',
957                         ];
958                 }
959
960                 if ($is_owner) {
961                         $tabs[] = [
962                                 'label' => L10n::t('Personal Notes'),
963                                 'url'   => System::baseUrl() . '/notes',
964                                 'sel'   => !$tab && $a->argv[0] == 'notes' ? 'active' : '',
965                                 'title' => L10n::t('Only You Can See This'),
966                                 'id'    => 'notes-tab',
967                                 'accesskey' => 't',
968                         ];
969                 }
970
971                 if (!empty($_SESSION['new_member']) && $is_owner) {
972                         $tabs[] = [
973                                 'label' => L10n::t('Tips for New Members'),
974                                 'url'   => System::baseUrl() . '/newmember',
975                                 'sel'   => false,
976                                 'title' => L10n::t('Tips for New Members'),
977                                 'id'    => 'newmember-tab',
978                         ];
979                 }
980
981                 if (!$is_owner && empty($a->profile['hide-friends'])) {
982                         $tabs[] = [
983                                 'label' => L10n::t('Contacts'),
984                                 'url'   => System::baseUrl() . '/viewcontacts/' . $nickname,
985                                 'sel'   => !$tab && $a->argv[0] == 'viewcontacts' ? 'active' : '',
986                                 'title' => L10n::t('Contacts'),
987                                 'id'    => 'viewcontacts-tab',
988                                 'accesskey' => 'k',
989                         ];
990                 }
991
992                 $arr = ['is_owner' => $is_owner, 'nickname' => $nickname, 'tab' => $tab, 'tabs' => $tabs];
993                 Addon::callHooks('profile_tabs', $arr);
994
995                 $tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
996
997                 return Renderer::replaceMacros($tpl, ['$tabs' => $arr['tabs']]);
998         }
999
1000         /**
1001          * Retrieves the my_url session variable
1002          *
1003          * @return string
1004          */
1005         public static function getMyURL()
1006         {
1007                 if (!empty($_SESSION['my_url'])) {
1008                         return $_SESSION['my_url'];
1009                 }
1010                 return null;
1011         }
1012
1013         /**
1014          * Process the 'zrl' parameter and initiate the remote authentication.
1015          *
1016          * This method checks if the visitor has a public contact entry and
1017          * redirects the visitor to his/her instance to start the magic auth (Authentication)
1018          * process.
1019          *
1020          * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/channel.php
1021          *
1022          * @param App $a Application instance.
1023          */
1024         public static function zrlInit(App $a)
1025         {
1026                 $my_url = self::getMyURL();
1027                 $my_url = Network::isUrlValid($my_url);
1028
1029                 if (empty($my_url) || local_user()) {
1030                         return;
1031                 }
1032
1033                 $arr = ['zrl' => $my_url, 'url' => $a->cmd];
1034                 Addon::callHooks('zrl_init', $arr);
1035
1036                 // Try to find the public contact entry of the visitor.
1037                 $cid = Contact::getIdForURL($my_url);
1038                 if (!$cid) {
1039                         Logger::log('No contact record found for ' . $my_url, Logger::DEBUG);
1040                         return;
1041                 }
1042
1043                 $contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]);
1044
1045                 if (DBA::isResult($contact) && remote_user() && remote_user() == $contact['id']) {
1046                         Logger::log('The visitor ' . $my_url . ' is already authenticated', Logger::DEBUG);
1047                         return;
1048                 }
1049
1050                 // Avoid endless loops
1051                 $cachekey = 'zrlInit:' . $my_url;
1052                 if (Cache::get($cachekey)) {
1053                         Logger::log('URL ' . $my_url . ' already tried to authenticate.', Logger::DEBUG);
1054                         return;
1055                 } else {
1056                         Cache::set($cachekey, true, Cache::MINUTE);
1057                 }
1058
1059                 Logger::log('Not authenticated. Invoking reverse magic-auth for ' . $my_url, Logger::DEBUG);
1060
1061                 Worker::add(PRIORITY_LOW, 'GProbe', $my_url);
1062
1063                 // Try to avoid recursion - but send them home to do a proper magic auth.
1064                 $query = str_replace(array('?zrl=', '&zid='), array('?rzrl=', '&rzrl='), $a->query_string);
1065                 // The other instance needs to know where to redirect.
1066                 $dest = urlencode($a->getBaseURL() . '/' . $query);
1067
1068                 // We need to extract the basebath from the profile url
1069                 // to redirect the visitors '/magic' module.
1070                 // Note: We should have the basepath of a contact also in the contact table.
1071                 $urlarr = explode('/profile/', $contact['url']);
1072                 $basepath = $urlarr[0];
1073
1074                 if ($basepath != $a->getBaseURL() && !strstr($dest, '/magic') && !strstr($dest, '/rmagic')) {
1075                         $magic_path = $basepath . '/magic' . '?f=&owa=1&dest=' . $dest;
1076
1077                         // We have to check if the remote server does understand /magic without invoking something
1078                         $serverret = Network::curl($basepath . '/magic');
1079                         if ($serverret->isSuccess()) {
1080                                 Logger::log('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path, Logger::DEBUG);
1081                                 System::externalRedirect($magic_path);
1082                         }
1083                 }
1084         }
1085
1086         /**
1087          * OpenWebAuth authentication.
1088          *
1089          * Ported from Hubzilla: https://framagit.org/hubzilla/core/blob/master/include/zid.php
1090          *
1091          * @param string $token
1092          */
1093         public static function openWebAuthInit($token)
1094         {
1095                 $a = get_app();
1096
1097                 // Clean old OpenWebAuthToken entries.
1098                 OpenWebAuthToken::purge('owt', '3 MINUTE');
1099
1100                 // Check if the token we got is the same one
1101                 // we have stored in the database.
1102                 $visitor_handle = OpenWebAuthToken::getMeta('owt', 0, $token);
1103
1104                 if($visitor_handle === false) {
1105                         return;
1106                 }
1107
1108                 // Try to find the public contact entry of the visitor.
1109                 $cid = Contact::getIdForURL($visitor_handle);
1110                 if(!$cid) {
1111                         Logger::log('owt: unable to finger ' . $visitor_handle, Logger::DEBUG);
1112                         return;
1113                 }
1114
1115                 $visitor = DBA::selectFirst('contact', [], ['id' => $cid]);
1116
1117                 // Authenticate the visitor.
1118                 $_SESSION['authenticated'] = 1;
1119                 $_SESSION['visitor_id'] = $visitor['id'];
1120                 $_SESSION['visitor_handle'] = $visitor['addr'];
1121                 $_SESSION['visitor_home'] = $visitor['url'];
1122                 $_SESSION['my_url'] = $visitor['url'];
1123
1124                 /// @todo replace this and the query for this variable with some cleaner functionality
1125                 $_SESSION['remote'] = [];
1126
1127                 $remote_contacts = DBA::select('contact', ['id', 'uid'], ['nurl' => $visitor['nurl'], 'rel' => [Contact::FOLLOWER, Contact::FRIEND]]);
1128                 while ($contact = DBA::fetch($remote_contacts)) {
1129                         if (($contact['uid'] == 0) || Contact::isBlockedByUser($visitor['id'], $contact['uid'])) {
1130                                 continue;
1131                         }
1132
1133                         $_SESSION['remote'][] = ['cid' => $contact['id'], 'uid' => $contact['uid'], 'url' => $visitor['url']];
1134                 }
1135                 $arr = [
1136                         'visitor' => $visitor,
1137                         'url' => $a->query_string
1138                 ];
1139                 /**
1140                  * @hooks magic_auth_success
1141                  *   Called when a magic-auth was successful.
1142                  *   * \e array \b visitor
1143                  *   * \e string \b url
1144                  */
1145                 Addon::callHooks('magic_auth_success', $arr);
1146
1147                 $a->contact = $arr['visitor'];
1148
1149                 info(L10n::t('OpenWebAuth: %1$s welcomes %2$s', $a->getHostName(), $visitor['name']));
1150
1151                 Logger::log('OpenWebAuth: auth success from ' . $visitor['addr'], Logger::DEBUG);
1152         }
1153
1154         public static function zrl($s, $force = false)
1155         {
1156                 if (!strlen($s)) {
1157                         return $s;
1158                 }
1159                 if ((!strpos($s, '/profile/')) && (!$force)) {
1160                         return $s;
1161                 }
1162                 if ($force && substr($s, -1, 1) !== '/') {
1163                         $s = $s . '/';
1164                 }
1165                 $achar = strpos($s, '?') ? '&' : '?';
1166                 $mine = self::getMyURL();
1167                 if ($mine && !Strings::compareLink($mine, $s)) {
1168                         return $s . $achar . 'zrl=' . urlencode($mine);
1169                 }
1170                 return $s;
1171         }
1172
1173         /**
1174          * Get the user ID of the page owner.
1175          *
1176          * Used from within PCSS themes to set theme parameters. If there's a
1177          * puid request variable, that is the "page owner" and normally their theme
1178          * settings take precedence; unless a local user sets the "always_my_theme"
1179          * system pconfig, which means they don't want to see anybody else's theme
1180          * settings except their own while on this site.
1181          *
1182          * @brief Get the user ID of the page owner
1183          * @return int user ID
1184          *
1185          * @note Returns local_user instead of user ID if "always_my_theme"
1186          *      is set to true
1187          */
1188         public static function getThemeUid()
1189         {
1190                 $uid = (!empty($_REQUEST['puid']) ? intval($_REQUEST['puid']) : 0);
1191                 if ((local_user()) && ((PConfig::get(local_user(), 'system', 'always_my_theme')) || (!$uid))) {
1192                         return local_user();
1193                 }
1194
1195                 return $uid;
1196         }
1197
1198         /**
1199         * Stip zrl parameter from a string.
1200         *
1201         * @param string $s The input string.
1202         * @return string The zrl.
1203         */
1204         public static function stripZrls($s)
1205         {
1206                 return preg_replace('/[\?&]zrl=(.*?)([\?&]|$)/is', '', $s);
1207         }
1208
1209         /**
1210         * Stip query parameter from a string.
1211         *
1212         * @param string $s The input string.
1213         * @return string The query parameter.
1214         */
1215         public static function stripQueryParam($s, $param)
1216         {
1217                 return preg_replace('/[\?&]' . $param . '=(.*?)(&|$)/ism', '$2', $s);
1218         }
1219 }