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