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