]> git.mxchange.org Git - friendica.git/blob - src/Content/Widget.php
Decouple conversation creation from rendering
[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\Circle;
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 representing "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 (!Addon::isEnabled("tumblr")) {
124                         $networks[] = Protocol::TUMBLR;
125                 }
126
127                 if (DI::config()->get("system", "ostatus_disabled")) {
128                         $networks[] = Protocol::OSTATUS;
129                 }
130
131                 if (!DI::config()->get("system", "diaspora_enabled")) {
132                         $networks[] = Protocol::DIASPORA;
133                 }
134
135                 if (!Addon::isEnabled("pnut")) {
136                         $networks[] = Protocol::PNUT;
137                 }
138                 return $networks;
139         }
140
141         /**
142          * Display a generic filter widget based on a list of options
143          *
144          * The options array must be the following format:
145          * [
146          *    [
147          *      'ref' => {filter value},
148          *      'name' => {option name}
149          *    ],
150          *    ...
151          * ]
152          *
153          * @param string $type The filter query string key
154          * @param string $title
155          * @param string $desc
156          * @param string $all The no filter label
157          * @param string $baseUrl The full page request URI
158          * @param array  $options
159          * @param string $selected The currently selected filter option value
160          * @return string
161          * @throws \Exception
162          */
163         private static function filter(string $type, string $title, string $desc, string $all, string $baseUrl, array $options, string $selected = null): string
164         {
165                 $queryString = parse_url($baseUrl, PHP_URL_QUERY);
166                 $queryArray = [];
167
168                 if ($queryString) {
169                         parse_str($queryString, $queryArray);
170                         unset($queryArray[$type]);
171
172                         if (count($queryArray)) {
173                                 $baseUrl = substr($baseUrl, 0, strpos($baseUrl, '?')) . '?' . http_build_query($queryArray) . '&';
174                         } else {
175                                 $baseUrl = substr($baseUrl, 0, strpos($baseUrl, '?')) . '?';
176                         }
177                 } else {
178                         $baseUrl = trim($baseUrl, '?') . '?';
179                 }
180
181                 array_walk($options, function (&$value) {
182                         $value['ref'] = rawurlencode($value['ref']);
183                 });
184
185                 return Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/filter.tpl'), [
186                         '$type'      => $type,
187                         '$title'     => $title,
188                         '$desc'      => $desc,
189                         '$selected'  => $selected,
190                         '$all_label' => $all,
191                         '$options'   => $options,
192                         '$base'      => $baseUrl,
193                 ]);
194         }
195
196         /**
197          * Return circle membership widget
198          *
199          * @param string $baseurl
200          * @param string $selected
201          * @return string
202          * @throws \Exception
203          */
204         public static function circles(string $baseurl, string $selected = ''): string
205         {
206                 if (!DI::userSession()->getLocalUserId()) {
207                         return '';
208                 }
209
210                 $options = array_map(function ($circle) {
211                         return [
212                                 'ref'  => $circle['id'],
213                                 'name' => $circle['name']
214                         ];
215                 }, Circle::getByUserId(DI::userSession()->getLocalUserId()));
216
217                 return self::filter(
218                         'circle',
219                         DI::l10n()->t('Circles'),
220                         '',
221                         DI::l10n()->t('Everyone'),
222                         $baseurl,
223                         $options,
224                         $selected
225                 );
226         }
227
228         /**
229          * Return contact relationship widget
230          *
231          * @param string $baseurl  baseurl
232          * @param string $selected optional, default empty
233          * @return string
234          * @throws \Exception
235          */
236         public static function contactRels(string $baseurl, string $selected = ''): string
237         {
238                 if (!DI::userSession()->getLocalUserId()) {
239                         return '';
240                 }
241
242                 $options = [
243                         ['ref' => 'followers', 'name' => DI::l10n()->t('Followers')],
244                         ['ref' => 'following', 'name' => DI::l10n()->t('Following')],
245                         ['ref' => 'mutuals', 'name' => DI::l10n()->t('Mutual friends')],
246                         ['ref' => 'nothing', 'name' => DI::l10n()->t('No relationship')],
247                 ];
248
249                 return self::filter(
250                         'rel',
251                         DI::l10n()->t('Relationships'),
252                         '',
253                         DI::l10n()->t('All Contacts'),
254                         $baseurl,
255                         $options,
256                         $selected
257                 );
258         }
259
260         /**
261          * Return networks widget
262          *
263          * @param string $baseurl  baseurl
264          * @param string $selected optional, default empty
265          * @return string
266          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
267          */
268         public static function networks(string $baseurl, string $selected = ''): string
269         {
270                 if (!DI::userSession()->getLocalUserId()) {
271                         return '';
272                 }
273
274                 $networks = self::unavailableNetworks();
275                 $query = "`uid` = ? AND NOT `deleted` AND `network` != '' AND NOT `network` IN (" . substr(str_repeat("?, ", count($networks)), 0, -2) . ")";
276                 $condition = array_merge([$query], array_merge([DI::userSession()->getLocalUserId()], $networks));
277
278                 $r = DBA::select('contact', ['network'], $condition, ['group_by' => ['network'], 'order' => ['network']]);
279
280                 $nets = [];
281                 while ($rr = DBA::fetch($r)) {
282                         $nets[] = ['ref' => $rr['network'], 'name' => ContactSelector::networkToName($rr['network'])];
283                 }
284                 DBA::close($r);
285
286                 if (count($nets) < 2) {
287                         return '';
288                 }
289
290                 return self::filter(
291                         'nets',
292                         DI::l10n()->t('Protocols'),
293                         '',
294                         DI::l10n()->t('All Protocols'),
295                         $baseurl,
296                         $nets,
297                         $selected
298                 );
299         }
300
301         /**
302          * Return file as widget
303          *
304          * @param string $baseurl  baseurl
305          * @param string $selected optional, default empty
306          * @return string
307          * @throws \Exception
308          */
309         public static function fileAs(string $baseurl, string $selected = ''): string
310         {
311                 if (!DI::userSession()->getLocalUserId()) {
312                         return '';
313                 }
314
315                 $terms = [];
316                 foreach (Post\Category::getArray(DI::userSession()->getLocalUserId(), Post\Category::FILE) as $savedFolderName) {
317                         $terms[] = ['ref' => $savedFolderName, 'name' => $savedFolderName];
318                 }
319
320                 return self::filter(
321                         'file',
322                         DI::l10n()->t('Saved Folders'),
323                         '',
324                         DI::l10n()->t('Everything'),
325                         $baseurl,
326                         $terms,
327                         $selected
328                 );
329         }
330
331         /**
332          * Return categories widget
333          *
334          * @param int    $uid      Id of the user owning the categories
335          * @param string $baseurl  Base page URL
336          * @param string $selected Selected category
337          * @return string
338          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
339          */
340         public static function categories(int $uid, string $baseurl, string $selected = ''): string
341         {
342                 if (!Feature::isEnabled($uid, 'categories')) {
343                         return '';
344                 }
345
346                 $terms = [];
347                 foreach (Post\Category::getArray($uid, Post\Category::CATEGORY) as $savedFolderName) {
348                         $terms[] = ['ref' => $savedFolderName, 'name' => $savedFolderName];
349                 }
350
351                 return self::filter(
352                         'category',
353                         DI::l10n()->t('Categories'),
354                         '',
355                         DI::l10n()->t('Everything'),
356                         $baseurl,
357                         $terms,
358                         $selected
359                 );
360         }
361
362         /**
363          * Show a random selection of five common contacts between the visitor and the viewed profile user.
364          *
365          * @param int    $uid      Viewed profile user ID
366          * @param string $nickname Viewed profile user nickname
367          * @return string
368          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
369          * @throws \ImagickException
370          */
371         public static function commonFriendsVisitor(int $uid, string $nickname): string
372         {
373                 if (DI::userSession()->getLocalUserId() == $uid) {
374                         return '';
375                 }
376
377                 $visitorPCid = DI::userSession()->getPublicContactId() ?: DI::userSession()->getRemoteUserId();
378                 if (!$visitorPCid) {
379                         return '';
380                 }
381
382                 $localPCid = Contact::getPublicIdByUserId($uid);
383
384                 $condition = [
385                         'NOT `self` AND NOT `blocked` AND NOT `hidden` AND `id` != ?',
386                         $localPCid,
387                 ];
388
389                 $total = Contact\Relation::countCommon($localPCid, $visitorPCid, $condition);
390                 if (!$total) {
391                         return '';
392                 }
393
394                 $commonContacts = Contact\Relation::listCommon($localPCid, $visitorPCid, $condition, 0, 5, true);
395                 if (!DBA::isResult($commonContacts)) {
396                         return '';
397                 }
398
399                 $entries = [];
400                 foreach ($commonContacts as $contact) {
401                         $entries[] = [
402                                 'url'   => Contact::magicLinkByContact($contact),
403                                 'name'  => $contact['name'],
404                                 'photo' => Contact::getThumb($contact),
405                         ];
406                 }
407
408                 $tpl = Renderer::getMarkupTemplate('widget/remote_friends_common.tpl');
409                 return Renderer::replaceMacros($tpl, [
410                         '$desc'     => DI::l10n()->tt("%d contact in common", "%d contacts in common", $total),
411                         '$base'     => DI::baseUrl(),
412                         '$nickname' => $nickname,
413                         '$linkmore' => $total > 5 ? 'true' : '',
414                         '$more'     => DI::l10n()->t('show more'),
415                         '$contacts' => $entries
416                 ]);
417         }
418
419         /**
420          * Insert a tag cloud widget for the present profile.
421          *
422          * @param int $uid   User ID
423          * @param int $limit Max number of displayed tags.
424          * @return string HTML formatted output.
425          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
426          * @throws \ImagickException
427          */
428         public static function tagCloud(int $uid, int $limit = 50): string
429         {
430                 if (empty($uid)) {
431                         return '';
432                 }
433
434                 if (Feature::isEnabled($uid, 'tagadelic')) {
435                         $owner_id = Contact::getPublicIdByUserId($uid);
436
437                         if (!$owner_id) {
438                                 return '';
439                         }
440                         return Widget\TagCloud::getHTML($uid, $limit, $owner_id, 'wall');
441                 }
442
443                 return '';
444         }
445
446         /**
447          * @param string $url Base page URL
448          * @param int    $uid User ID consulting/publishing posts
449          * @param bool   $wall True: Posted by User; False: Posted to User (network timeline)
450          * @return string
451          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
452          */
453         public static function postedByYear(string $url, int $uid, bool $wall): string
454         {
455                 $o = '';
456
457                 $visible_years = DI::pConfig()->get($uid, 'system', 'archive_visible_years', 5);
458
459                 /* arrange the list in years */
460                 $dnow = DateTimeFormat::localNow('Y-m-d');
461
462                 $ret = [];
463
464                 $cachekey = 'Widget::postedByYear' . $uid . '-' . (int)$wall;
465                 $dthen = DI::cache()->get($cachekey);
466                 if (empty($dthen)) {
467                         $dthen = Item::firstPostDate($uid, $wall);
468                         DI::cache()->set($cachekey, $dthen, Duration::HOUR);
469                 }
470
471                 if ($dthen) {
472                         // Set the start and end date to the beginning of the month
473                         $cutoffday = $dthen;
474                         $thisday = substr($dnow, 4);
475                         $nextday = date('Y-m-d', strtotime($dnow . ' + 1 day'));
476                         $nextday = substr($nextday, 4);
477                         $dnow = substr($dnow, 0, 8) . '01';
478                         $dthen = substr($dthen, 0, 8) . '01';
479
480                         /*
481                          * Starting with the current month, get the first and last days of every
482                          * month down to and including the month of the first post
483                          */
484                         while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
485                                 $dyear = intval(substr($dnow, 0, 4));
486                                 $dstart = substr($dnow, 0, 8) . '01';
487                                 $dend = substr($dnow, 0, 8) . Temporal::getDaysInMonth(intval($dnow), intval(substr($dnow, 5)));
488                                 $start_month = DateTimeFormat::utc($dstart, 'Y-m-d');
489                                 $end_month = DateTimeFormat::utc($dend, 'Y-m-d');
490                                 $str = DI::l10n()->getDay(DateTimeFormat::utc($dnow, 'F'));
491
492                                 if (empty($ret[$dyear])) {
493                                         $ret[$dyear] = [];
494                                 }
495
496                                 $ret[$dyear][] = [$str, $end_month, $start_month];
497                                 $dnow = DateTimeFormat::utc($dnow . ' -1 month', 'Y-m-d');
498                         }
499                 }
500
501                 if (!DBA::isResult($ret)) {
502                         return $o;
503                 }
504
505
506                 $cutoff_year = intval(DateTimeFormat::localNow('Y')) - $visible_years;
507                 $cutoff = array_key_exists($cutoff_year, $ret);
508
509                 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/posted_date.tpl'), [
510                         '$title' => DI::l10n()->t('Archives'),
511                         '$size' => $visible_years,
512                         '$cutoff_year' => $cutoff_year,
513                         '$cutoff' => $cutoff,
514                         '$url' => $url,
515                         '$dates' => $ret,
516                         '$showless' => DI::l10n()->t('show less'),
517                         '$showmore' => DI::l10n()->t('show more'),
518                         '$onthisdate' => DI::l10n()->t('On this date'),
519                         '$thisday' => $thisday,
520                         '$nextday' => $nextday,
521                         '$cutoffday' => $cutoffday
522                 ]);
523
524                 return $o;
525         }
526
527         /**
528          * Display the account types sidebar
529          * The account type value is added as a parameter to the url
530          *
531          * @param string $base        Basepath
532          * @param string $accounttype Account type
533          * @return string
534          */
535         public static function accountTypes(string $base, string $accounttype): string
536         {
537                 $accounts = [
538                         ['ref' => 'person', 'name' => DI::l10n()->t('Persons')],
539                         ['ref' => 'organisation', 'name' => DI::l10n()->t('Organisations')],
540                         ['ref' => 'news', 'name' => DI::l10n()->t('News')],
541                         ['ref' => 'community', 'name' => DI::l10n()->t('Groups')],
542                 ];
543
544                 return self::filter(
545                         'accounttype',
546                         DI::l10n()->t('Account Types'),
547                         '',
548                         DI::l10n()->t('All'),
549                         $base,
550                         $accounts,
551                         $accounttype
552                 );
553         }
554 }