]> git.mxchange.org Git - friendica.git/blob - src/Content/Widget.php
Merge pull request #12941 from xundeenergie/attend-buttons
[friendica.git] / src / Content / Widget.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Content;
23
24 use Friendica\Core\Addon;
25 use Friendica\Core\Cache\Enum\Duration;
26 use Friendica\Core\Protocol;
27 use Friendica\Core\Renderer;
28 use Friendica\Core\Search;
29 use Friendica\Database\DBA;
30 use Friendica\DI;
31 use Friendica\Model\Contact;
32 use Friendica\Model\Group;
33 use Friendica\Model\Item;
34 use Friendica\Model\Post;
35 use Friendica\Model\Profile;
36 use Friendica\Util\DateTimeFormat;
37 use Friendica\Util\Temporal;
38
39 class Widget
40 {
41         /**
42          * Return the follow widget
43          *
44          * @param string $value optional, default empty
45          * @return string
46          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
47          */
48         public static function follow(string $value = ''): string
49         {
50                 return Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/follow.tpl'), array(
51                         '$connect' => DI::l10n()->t('Add New Contact'),
52                         '$desc' => DI::l10n()->t('Enter address or web location'),
53                         '$hint' => DI::l10n()->t('Example: bob@example.com, http://example.com/barbara'),
54                         '$value' => $value,
55                         '$follow' => DI::l10n()->t('Connect')
56                 ));
57         }
58
59         /**
60          * Return Find People widget
61          *
62          * @return string HTML code respresenting "People Widget"
63          */
64         public static function findPeople(): string
65         {
66                 $global_dir = Search::getGlobalDirectory();
67
68                 if (DI::config()->get('system', 'invitation_only')) {
69                         $x = intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'invites_remaining'));
70                         if ($x || DI::app()->isSiteAdmin()) {
71                                 DI::page()['aside'] .= '<div class="side-link widget" id="side-invite-remain">'
72                                         . DI::l10n()->tt('%d invitation available', '%d invitations available', $x)
73                                         . '</div>';
74                         }
75                 }
76
77                 $nv = [];
78                 $nv['findpeople'] = DI::l10n()->t('Find People');
79                 $nv['desc'] = DI::l10n()->t('Enter name or interest');
80                 $nv['label'] = DI::l10n()->t('Connect/Follow');
81                 $nv['hint'] = DI::l10n()->t('Examples: Robert Morgenstein, Fishing');
82                 $nv['findthem'] = DI::l10n()->t('Find');
83                 $nv['suggest'] = DI::l10n()->t('Friend Suggestions');
84                 $nv['similar'] = DI::l10n()->t('Similar Interests');
85                 $nv['random'] = DI::l10n()->t('Random Profile');
86                 $nv['inv'] = DI::l10n()->t('Invite Friends');
87                 $nv['directory'] = DI::l10n()->t('Global Directory');
88                 $nv['global_dir'] = Profile::zrl($global_dir, true);
89                 $nv['local_directory'] = DI::l10n()->t('Local Directory');
90
91                 $aside = [];
92                 $aside['$nv'] = $nv;
93
94                 return Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/peoplefind.tpl'), $aside);
95         }
96
97         /**
98          * Return unavailable networks as array
99          *
100          * @return array Unsupported networks
101          */
102         public static function unavailableNetworks(): array
103         {
104                 // Always hide content from these networks
105                 $networks = [Protocol::PHANTOM, Protocol::FACEBOOK, Protocol::APPNET, Protocol::ZOT];
106
107                 if (!Addon::isEnabled("discourse")) {
108                         $networks[] = Protocol::DISCOURSE;
109                 }
110
111                 if (!Addon::isEnabled("statusnet")) {
112                         $networks[] = Protocol::STATUSNET;
113                 }
114
115                 if (!Addon::isEnabled("pumpio")) {
116                         $networks[] = Protocol::PUMPIO;
117                 }
118
119                 if (!Addon::isEnabled("twitter")) {
120                         $networks[] = Protocol::TWITTER;
121                 }
122
123                 if (DI::config()->get("system", "ostatus_disabled")) {
124                         $networks[] = Protocol::OSTATUS;
125                 }
126
127                 if (!DI::config()->get("system", "diaspora_enabled")) {
128                         $networks[] = Protocol::DIASPORA;
129                 }
130
131                 if (!Addon::isEnabled("pnut")) {
132                         $networks[] = Protocol::PNUT;
133                 }
134                 return $networks;
135         }
136
137         /**
138          * Display a generic filter widget based on a list of options
139          *
140          * The options array must be the following format:
141          * [
142          *    [
143          *      'ref' => {filter value},
144          *      'name' => {option name}
145          *    ],
146          *    ...
147          * ]
148          *
149          * @param string $type The filter query string key
150          * @param string $title
151          * @param string $desc
152          * @param string $all The no filter label
153          * @param string $baseUrl The full page request URI
154          * @param array  $options
155          * @param string $selected The currently selected filter option value
156          * @return string
157          * @throws \Exception
158          */
159         private static function filter(string $type, string $title, string $desc, string $all, string $baseUrl, array $options, string $selected = null): string
160         {
161                 $queryString = parse_url($baseUrl, PHP_URL_QUERY);
162                 $queryArray = [];
163
164                 if ($queryString) {
165                         parse_str($queryString, $queryArray);
166                         unset($queryArray[$type]);
167
168                         if (count($queryArray)) {
169                                 $baseUrl = substr($baseUrl, 0, strpos($baseUrl, '?')) . '?' . http_build_query($queryArray) . '&';
170                         } else {
171                                 $baseUrl = substr($baseUrl, 0, strpos($baseUrl, '?')) . '?';
172                         }
173                 } else {
174                         $baseUrl = trim($baseUrl, '?') . '?';
175                 }
176
177                 return Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/filter.tpl'), [
178                         '$type'      => $type,
179                         '$title'     => $title,
180                         '$desc'      => $desc,
181                         '$selected'  => $selected,
182                         '$all_label' => $all,
183                         '$options'   => $options,
184                         '$base'      => $baseUrl,
185                 ]);
186         }
187
188         /**
189          * Return group membership widget
190          *
191          * @param string $baseurl
192          * @param string $selected
193          * @return string
194          * @throws \Exception
195          */
196         public static function groups(string $baseurl, string $selected = ''): string
197         {
198                 if (!DI::userSession()->getLocalUserId()) {
199                         return '';
200                 }
201
202                 $options = array_map(function ($group) {
203                         return [
204                                 'ref'  => $group['id'],
205                                 'name' => $group['name']
206                         ];
207                 }, Group::getByUserId(DI::userSession()->getLocalUserId()));
208
209                 return self::filter(
210                         'group',
211                         DI::l10n()->t('Groups'),
212                         '',
213                         DI::l10n()->t('Everyone'),
214                         $baseurl,
215                         $options,
216                         $selected
217                 );
218         }
219
220         /**
221          * Return contact relationship widget
222          *
223          * @param string $baseurl  baseurl
224          * @param string $selected optional, default empty
225          * @return string
226          * @throws \Exception
227          */
228         public static function contactRels(string $baseurl, string $selected = ''): string
229         {
230                 if (!DI::userSession()->getLocalUserId()) {
231                         return '';
232                 }
233
234                 $options = [
235                         ['ref' => 'followers', 'name' => DI::l10n()->t('Followers')],
236                         ['ref' => 'following', 'name' => DI::l10n()->t('Following')],
237                         ['ref' => 'mutuals', 'name' => DI::l10n()->t('Mutual friends')],
238                 ];
239
240                 return self::filter(
241                         'rel',
242                         DI::l10n()->t('Relationships'),
243                         '',
244                         DI::l10n()->t('All Contacts'),
245                         $baseurl,
246                         $options,
247                         $selected
248                 );
249         }
250
251         /**
252          * Return networks widget
253          *
254          * @param string $baseurl  baseurl
255          * @param string $selected optional, default empty
256          * @return string
257          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
258          */
259         public static function networks(string $baseurl, string $selected = ''): string
260         {
261                 if (!DI::userSession()->getLocalUserId()) {
262                         return '';
263                 }
264
265                 $networks = self::unavailableNetworks();
266                 $query = "`uid` = ? AND NOT `deleted` AND `network` != '' AND NOT `network` IN (" . substr(str_repeat("?, ", count($networks)), 0, -2) . ")";
267                 $condition = array_merge([$query], array_merge([DI::userSession()->getLocalUserId()], $networks));
268
269                 $r = DBA::select('contact', ['network'], $condition, ['group_by' => ['network'], 'order' => ['network']]);
270
271                 $nets = [];
272                 while ($rr = DBA::fetch($r)) {
273                         $nets[] = ['ref' => $rr['network'], 'name' => ContactSelector::networkToName($rr['network'])];
274                 }
275                 DBA::close($r);
276
277                 if (count($nets) < 2) {
278                         return '';
279                 }
280
281                 return self::filter(
282                         'nets',
283                         DI::l10n()->t('Protocols'),
284                         '',
285                         DI::l10n()->t('All Protocols'),
286                         $baseurl,
287                         $nets,
288                         $selected
289                 );
290         }
291
292         /**
293          * Return file as widget
294          *
295          * @param string $baseurl  baseurl
296          * @param string $selected optional, default empty
297          * @return string
298          * @throws \Exception
299          */
300         public static function fileAs(string $baseurl, string $selected = ''): string
301         {
302                 if (!DI::userSession()->getLocalUserId()) {
303                         return '';
304                 }
305
306                 $terms = [];
307                 foreach (Post\Category::getArray(DI::userSession()->getLocalUserId(), Post\Category::FILE) as $savedFolderName) {
308                         $terms[] = ['ref' => $savedFolderName, 'name' => $savedFolderName];
309                 }
310
311                 return self::filter(
312                         'file',
313                         DI::l10n()->t('Saved Folders'),
314                         '',
315                         DI::l10n()->t('Everything'),
316                         $baseurl,
317                         $terms,
318                         $selected
319                 );
320         }
321
322         /**
323          * Return categories widget
324          *
325          * @param int    $uid      Id of the user owning the categories
326          * @param string $baseurl  Base page URL
327          * @param string $selected Selected category
328          * @return string
329          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
330          */
331         public static function categories(int $uid, string $baseurl, string $selected = ''): string
332         {
333                 if (!Feature::isEnabled($uid, 'categories')) {
334                         return '';
335                 }
336
337                 $terms = [];
338                 foreach (Post\Category::getArray($uid, Post\Category::CATEGORY) as $savedFolderName) {
339                         $terms[] = ['ref' => $savedFolderName, 'name' => $savedFolderName];
340                 }
341
342                 return self::filter(
343                         'category',
344                         DI::l10n()->t('Categories'),
345                         '',
346                         DI::l10n()->t('Everything'),
347                         $baseurl,
348                         $terms,
349                         $selected
350                 );
351         }
352
353         /**
354          * Show a random selection of five common contacts between the visitor and the viewed profile user.
355          *
356          * @param int    $uid      Viewed profile user ID
357          * @param string $nickname Viewed profile user nickname
358          * @return string
359          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
360          * @throws \ImagickException
361          */
362         public static function commonFriendsVisitor(int $uid, string $nickname): string
363         {
364                 if (DI::userSession()->getLocalUserId() == $uid) {
365                         return '';
366                 }
367
368                 $visitorPCid = DI::userSession()->getPublicContactId() ?: DI::userSession()->getRemoteUserId();
369                 if (!$visitorPCid) {
370                         return '';
371                 }
372
373                 $localPCid = Contact::getPublicIdByUserId($uid);
374
375                 $condition = [
376                         'NOT `self` AND NOT `blocked` AND NOT `hidden` AND `id` != ?',
377                         $localPCid,
378                 ];
379
380                 $total = Contact\Relation::countCommon($localPCid, $visitorPCid, $condition);
381                 if (!$total) {
382                         return '';
383                 }
384
385                 $commonContacts = Contact\Relation::listCommon($localPCid, $visitorPCid, $condition, 0, 5, true);
386                 if (!DBA::isResult($commonContacts)) {
387                         return '';
388                 }
389
390                 $entries = [];
391                 foreach ($commonContacts as $contact) {
392                         $entries[] = [
393                                 'url'   => Contact::magicLinkByContact($contact),
394                                 'name'  => $contact['name'],
395                                 'photo' => Contact::getThumb($contact),
396                         ];
397                 }
398
399                 $tpl = Renderer::getMarkupTemplate('widget/remote_friends_common.tpl');
400                 return Renderer::replaceMacros($tpl, [
401                         '$desc'     => DI::l10n()->tt("%d contact in common", "%d contacts in common", $total),
402                         '$base'     => DI::baseUrl(),
403                         '$nickname' => $nickname,
404                         '$linkmore' => $total > 5 ? 'true' : '',
405                         '$more'     => DI::l10n()->t('show more'),
406                         '$contacts' => $entries
407                 ]);
408         }
409
410         /**
411          * Insert a tag cloud widget for the present profile.
412          *
413          * @param int $uid   User ID
414          * @param int $limit Max number of displayed tags.
415          * @return string HTML formatted output.
416          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
417          * @throws \ImagickException
418          */
419         public static function tagCloud(int $uid, int $limit = 50): string
420         {
421                 if (empty($uid)) {
422                         return '';
423                 }
424
425                 if (Feature::isEnabled($uid, 'tagadelic')) {
426                         $owner_id = Contact::getPublicIdByUserId($uid);
427
428                         if (!$owner_id) {
429                                 return '';
430                         }
431                         return Widget\TagCloud::getHTML($uid, $limit, $owner_id, 'wall');
432                 }
433
434                 return '';
435         }
436
437         /**
438          * @param string $url Base page URL
439          * @param int    $uid User ID consulting/publishing posts
440          * @param bool   $wall True: Posted by User; False: Posted to User (network timeline)
441          * @return string
442          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
443          */
444         public static function postedByYear(string $url, int $uid, bool $wall): string
445         {
446                 $o = '';
447
448                 $visible_years = DI::pConfig()->get($uid, 'system', 'archive_visible_years', 5);
449
450                 /* arrange the list in years */
451                 $dnow = DateTimeFormat::localNow('Y-m-d');
452
453                 $ret = [];
454
455                 $cachekey = 'Widget::postedByYear' . $uid . '-' . (int)$wall;
456                 $dthen = DI::cache()->get($cachekey);
457                 if (empty($dthen)) {
458                         $dthen = Item::firstPostDate($uid, $wall);
459                         DI::cache()->set($cachekey, $dthen, Duration::HOUR);
460                 }
461
462                 if ($dthen) {
463                         // Set the start and end date to the beginning of the month
464                         $dnow = substr($dnow, 0, 8) . '01';
465                         $dthen = substr($dthen, 0, 8) . '01';
466
467                         /*
468                          * Starting with the current month, get the first and last days of every
469                          * month down to and including the month of the first post
470                          */
471                         while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
472                                 $dyear = intval(substr($dnow, 0, 4));
473                                 $dstart = substr($dnow, 0, 8) . '01';
474                                 $dend = substr($dnow, 0, 8) . Temporal::getDaysInMonth(intval($dnow), intval(substr($dnow, 5)));
475                                 $start_month = DateTimeFormat::utc($dstart, 'Y-m-d');
476                                 $end_month = DateTimeFormat::utc($dend, 'Y-m-d');
477                                 $str = DI::l10n()->getDay(DateTimeFormat::utc($dnow, 'F'));
478
479                                 if (empty($ret[$dyear])) {
480                                         $ret[$dyear] = [];
481                                 }
482
483                                 $ret[$dyear][] = [$str, $end_month, $start_month];
484                                 $dnow = DateTimeFormat::utc($dnow . ' -1 month', 'Y-m-d');
485                         }
486                 }
487
488                 if (!DBA::isResult($ret)) {
489                         return $o;
490                 }
491
492
493                 $cutoff_year = intval(DateTimeFormat::localNow('Y')) - $visible_years;
494                 $cutoff = array_key_exists($cutoff_year, $ret);
495
496                 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/posted_date.tpl'),[
497                         '$title' => DI::l10n()->t('Archives'),
498                         '$size' => $visible_years,
499                         '$cutoff_year' => $cutoff_year,
500                         '$cutoff' => $cutoff,
501                         '$url' => $url,
502                         '$dates' => $ret,
503                         '$showless' => DI::l10n()->t('show less'),
504                         '$showmore' => DI::l10n()->t('show more')
505                 ]);
506
507                 return $o;
508         }
509
510         /**
511          * Display the account types sidebar
512          * The account type value is added as a parameter to the url
513          *
514          * @param string $base        Basepath
515          * @param string $accounttype Account type
516          * @return string
517          */
518         public static function accountTypes(string $base, string $accounttype): string
519         {
520                 $accounts = [
521                         ['ref' => 'person', 'name' => DI::l10n()->t('Persons')],
522                         ['ref' => 'organisation', 'name' => DI::l10n()->t('Organisations')],
523                         ['ref' => 'news', 'name' => DI::l10n()->t('News')],
524                         ['ref' => 'community', 'name' => DI::l10n()->t('Forums')],
525                 ];
526
527                 return self::filter('accounttype', DI::l10n()->t('Account Types'), '',
528                         DI::l10n()->t('All'), $base, $accounts, $accounttype);
529         }
530 }