]> git.mxchange.org Git - friendica.git/blob - src/Content/Widget.php
Merge pull request #13121 from MrPetovan/task/13114-rename-group-to-circle
[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                 ];
247
248                 return self::filter(
249                         'rel',
250                         DI::l10n()->t('Relationships'),
251                         '',
252                         DI::l10n()->t('All Contacts'),
253                         $baseurl,
254                         $options,
255                         $selected
256                 );
257         }
258
259         /**
260          * Return networks widget
261          *
262          * @param string $baseurl  baseurl
263          * @param string $selected optional, default empty
264          * @return string
265          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
266          */
267         public static function networks(string $baseurl, string $selected = ''): string
268         {
269                 if (!DI::userSession()->getLocalUserId()) {
270                         return '';
271                 }
272
273                 $networks = self::unavailableNetworks();
274                 $query = "`uid` = ? AND NOT `deleted` AND `network` != '' AND NOT `network` IN (" . substr(str_repeat("?, ", count($networks)), 0, -2) . ")";
275                 $condition = array_merge([$query], array_merge([DI::userSession()->getLocalUserId()], $networks));
276
277                 $r = DBA::select('contact', ['network'], $condition, ['group_by' => ['network'], 'order' => ['network']]);
278
279                 $nets = [];
280                 while ($rr = DBA::fetch($r)) {
281                         $nets[] = ['ref' => $rr['network'], 'name' => ContactSelector::networkToName($rr['network'])];
282                 }
283                 DBA::close($r);
284
285                 if (count($nets) < 2) {
286                         return '';
287                 }
288
289                 return self::filter(
290                         'nets',
291                         DI::l10n()->t('Protocols'),
292                         '',
293                         DI::l10n()->t('All Protocols'),
294                         $baseurl,
295                         $nets,
296                         $selected
297                 );
298         }
299
300         /**
301          * Return file as widget
302          *
303          * @param string $baseurl  baseurl
304          * @param string $selected optional, default empty
305          * @return string
306          * @throws \Exception
307          */
308         public static function fileAs(string $baseurl, string $selected = ''): string
309         {
310                 if (!DI::userSession()->getLocalUserId()) {
311                         return '';
312                 }
313
314                 $terms = [];
315                 foreach (Post\Category::getArray(DI::userSession()->getLocalUserId(), Post\Category::FILE) as $savedFolderName) {
316                         $terms[] = ['ref' => $savedFolderName, 'name' => $savedFolderName];
317                 }
318
319                 return self::filter(
320                         'file',
321                         DI::l10n()->t('Saved Folders'),
322                         '',
323                         DI::l10n()->t('Everything'),
324                         $baseurl,
325                         $terms,
326                         $selected
327                 );
328         }
329
330         /**
331          * Return categories widget
332          *
333          * @param int    $uid      Id of the user owning the categories
334          * @param string $baseurl  Base page URL
335          * @param string $selected Selected category
336          * @return string
337          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
338          */
339         public static function categories(int $uid, string $baseurl, string $selected = ''): string
340         {
341                 if (!Feature::isEnabled($uid, 'categories')) {
342                         return '';
343                 }
344
345                 $terms = [];
346                 foreach (Post\Category::getArray($uid, Post\Category::CATEGORY) as $savedFolderName) {
347                         $terms[] = ['ref' => $savedFolderName, 'name' => $savedFolderName];
348                 }
349
350                 return self::filter(
351                         'category',
352                         DI::l10n()->t('Categories'),
353                         '',
354                         DI::l10n()->t('Everything'),
355                         $baseurl,
356                         $terms,
357                         $selected
358                 );
359         }
360
361         /**
362          * Show a random selection of five common contacts between the visitor and the viewed profile user.
363          *
364          * @param int    $uid      Viewed profile user ID
365          * @param string $nickname Viewed profile user nickname
366          * @return string
367          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
368          * @throws \ImagickException
369          */
370         public static function commonFriendsVisitor(int $uid, string $nickname): string
371         {
372                 if (DI::userSession()->getLocalUserId() == $uid) {
373                         return '';
374                 }
375
376                 $visitorPCid = DI::userSession()->getPublicContactId() ?: DI::userSession()->getRemoteUserId();
377                 if (!$visitorPCid) {
378                         return '';
379                 }
380
381                 $localPCid = Contact::getPublicIdByUserId($uid);
382
383                 $condition = [
384                         'NOT `self` AND NOT `blocked` AND NOT `hidden` AND `id` != ?',
385                         $localPCid,
386                 ];
387
388                 $total = Contact\Relation::countCommon($localPCid, $visitorPCid, $condition);
389                 if (!$total) {
390                         return '';
391                 }
392
393                 $commonContacts = Contact\Relation::listCommon($localPCid, $visitorPCid, $condition, 0, 5, true);
394                 if (!DBA::isResult($commonContacts)) {
395                         return '';
396                 }
397
398                 $entries = [];
399                 foreach ($commonContacts as $contact) {
400                         $entries[] = [
401                                 'url'   => Contact::magicLinkByContact($contact),
402                                 'name'  => $contact['name'],
403                                 'photo' => Contact::getThumb($contact),
404                         ];
405                 }
406
407                 $tpl = Renderer::getMarkupTemplate('widget/remote_friends_common.tpl');
408                 return Renderer::replaceMacros($tpl, [
409                         '$desc'     => DI::l10n()->tt("%d contact in common", "%d contacts in common", $total),
410                         '$base'     => DI::baseUrl(),
411                         '$nickname' => $nickname,
412                         '$linkmore' => $total > 5 ? 'true' : '',
413                         '$more'     => DI::l10n()->t('show more'),
414                         '$contacts' => $entries
415                 ]);
416         }
417
418         /**
419          * Insert a tag cloud widget for the present profile.
420          *
421          * @param int $uid   User ID
422          * @param int $limit Max number of displayed tags.
423          * @return string HTML formatted output.
424          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
425          * @throws \ImagickException
426          */
427         public static function tagCloud(int $uid, int $limit = 50): string
428         {
429                 if (empty($uid)) {
430                         return '';
431                 }
432
433                 if (Feature::isEnabled($uid, 'tagadelic')) {
434                         $owner_id = Contact::getPublicIdByUserId($uid);
435
436                         if (!$owner_id) {
437                                 return '';
438                         }
439                         return Widget\TagCloud::getHTML($uid, $limit, $owner_id, 'wall');
440                 }
441
442                 return '';
443         }
444
445         /**
446          * @param string $url Base page URL
447          * @param int    $uid User ID consulting/publishing posts
448          * @param bool   $wall True: Posted by User; False: Posted to User (network timeline)
449          * @return string
450          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
451          */
452         public static function postedByYear(string $url, int $uid, bool $wall): string
453         {
454                 $o = '';
455
456                 $visible_years = DI::pConfig()->get($uid, 'system', 'archive_visible_years', 5);
457
458                 /* arrange the list in years */
459                 $dnow = DateTimeFormat::localNow('Y-m-d');
460
461                 $ret = [];
462
463                 $cachekey = 'Widget::postedByYear' . $uid . '-' . (int)$wall;
464                 $dthen = DI::cache()->get($cachekey);
465                 if (empty($dthen)) {
466                         $dthen = Item::firstPostDate($uid, $wall);
467                         DI::cache()->set($cachekey, $dthen, Duration::HOUR);
468                 }
469
470                 if ($dthen) {
471                         // Set the start and end date to the beginning of the month
472                         $dnow = substr($dnow, 0, 8) . '01';
473                         $dthen = substr($dthen, 0, 8) . '01';
474
475                         /*
476                          * Starting with the current month, get the first and last days of every
477                          * month down to and including the month of the first post
478                          */
479                         while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
480                                 $dyear = intval(substr($dnow, 0, 4));
481                                 $dstart = substr($dnow, 0, 8) . '01';
482                                 $dend = substr($dnow, 0, 8) . Temporal::getDaysInMonth(intval($dnow), intval(substr($dnow, 5)));
483                                 $start_month = DateTimeFormat::utc($dstart, 'Y-m-d');
484                                 $end_month = DateTimeFormat::utc($dend, 'Y-m-d');
485                                 $str = DI::l10n()->getDay(DateTimeFormat::utc($dnow, 'F'));
486
487                                 if (empty($ret[$dyear])) {
488                                         $ret[$dyear] = [];
489                                 }
490
491                                 $ret[$dyear][] = [$str, $end_month, $start_month];
492                                 $dnow = DateTimeFormat::utc($dnow . ' -1 month', 'Y-m-d');
493                         }
494                 }
495
496                 if (!DBA::isResult($ret)) {
497                         return $o;
498                 }
499
500
501                 $cutoff_year = intval(DateTimeFormat::localNow('Y')) - $visible_years;
502                 $cutoff = array_key_exists($cutoff_year, $ret);
503
504                 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/posted_date.tpl'),[
505                         '$title' => DI::l10n()->t('Archives'),
506                         '$size' => $visible_years,
507                         '$cutoff_year' => $cutoff_year,
508                         '$cutoff' => $cutoff,
509                         '$url' => $url,
510                         '$dates' => $ret,
511                         '$showless' => DI::l10n()->t('show less'),
512                         '$showmore' => DI::l10n()->t('show more')
513                 ]);
514
515                 return $o;
516         }
517
518         /**
519          * Display the account types sidebar
520          * The account type value is added as a parameter to the url
521          *
522          * @param string $base        Basepath
523          * @param string $accounttype Account type
524          * @return string
525          */
526         public static function accountTypes(string $base, string $accounttype): string
527         {
528                 $accounts = [
529                         ['ref' => 'person', 'name' => DI::l10n()->t('Persons')],
530                         ['ref' => 'organisation', 'name' => DI::l10n()->t('Organisations')],
531                         ['ref' => 'news', 'name' => DI::l10n()->t('News')],
532                         ['ref' => 'community', 'name' => DI::l10n()->t('Forums')],
533                 ];
534
535                 return self::filter('accounttype', DI::l10n()->t('Account Types'), '',
536                         DI::l10n()->t('All'), $base, $accounts, $accounttype);
537         }
538 }