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