Several speed improvements (magiclink, caching, indexes)
[friendica.git/.git] / src / Content / Widget.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
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
95          */
96         public static function unavailableNetworks()
97         {
98                 // Always hide content from these networks
99                 $networks = [Protocol::PHANTOM, Protocol::FACEBOOK, Protocol::APPNET];
100
101                 if (!Addon::isEnabled("discourse")) {
102                         $networks[] = Protocol::DISCOURSE;
103                 }
104
105                 if (!Addon::isEnabled("statusnet")) {
106                         $networks[] = Protocol::STATUSNET;
107                 }
108
109                 if (!Addon::isEnabled("pumpio")) {
110                         $networks[] = Protocol::PUMPIO;
111                 }
112
113                 if (!Addon::isEnabled("twitter")) {
114                         $networks[] = Protocol::TWITTER;
115                 }
116
117                 if (DI::config()->get("system", "ostatus_disabled")) {
118                         $networks[] = Protocol::OSTATUS;
119                 }
120
121                 if (!DI::config()->get("system", "diaspora_enabled")) {
122                         $networks[] = Protocol::DIASPORA;
123                 }
124
125                 if (!Addon::isEnabled("pnut")) {
126                         $networks[] = Protocol::PNUT;
127                 }
128
129                 if (!sizeof($networks)) {
130                         return "";
131                 }
132
133                 $network_filter = implode("','", $networks);
134
135                 $network_filter = "AND `network` NOT IN ('$network_filter')";
136
137                 return $network_filter;
138         }
139
140         /**
141          * Display a generic filter widget based on a list of options
142          *
143          * The options array must be the following format:
144          * [
145          *    [
146          *      'ref' => {filter value},
147          *      'name' => {option name}
148          *    ],
149          *    ...
150          * ]
151          *
152          * @param string $type The filter query string key
153          * @param string $title
154          * @param string $desc
155          * @param string $all The no filter label
156          * @param string $baseUrl The full page request URI
157          * @param array  $options
158          * @param string $selected The currently selected filter option value
159          * @return string
160          * @throws \Exception
161          */
162         private static function filter($type, $title, $desc, $all, $baseUrl, array $options, $selected = null)
163         {
164                 $queryString = parse_url($baseUrl, PHP_URL_QUERY);
165                 $queryArray = [];
166
167                 if ($queryString) {
168                         parse_str($queryString, $queryArray);
169                         unset($queryArray[$type]);
170
171                         if (count($queryArray)) {
172                                 $baseUrl = substr($baseUrl, 0, strpos($baseUrl, '?')) . '?' . http_build_query($queryArray) . '&';
173                         } else {
174                                 $baseUrl = substr($baseUrl, 0, strpos($baseUrl, '?')) . '?';
175                         }
176                 } else {
177                         $baseUrl = trim($baseUrl, '?') . '?';
178                 }
179
180                 return Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/filter.tpl'), [
181                         '$type'      => $type,
182                         '$title'     => $title,
183                         '$desc'      => $desc,
184                         '$selected'  => $selected,
185                         '$all_label' => $all,
186                         '$options'   => $options,
187                         '$base'      => $baseUrl,
188                 ]);
189         }
190
191         /**
192          * Return group membership widget
193          *
194          * @param string $baseurl
195          * @param string $selected
196          * @return string
197          * @throws \Exception
198          */
199         public static function groups($baseurl, $selected = '')
200         {
201                 if (!local_user()) {
202                         return '';
203                 }
204
205                 $options = array_map(function ($group) {
206                         return [
207                                 'ref'  => $group['id'],
208                                 'name' => $group['name']
209                         ];
210                 }, Group::getByUserId(local_user()));
211
212                 return self::filter(
213                         'group',
214                         DI::l10n()->t('Groups'),
215                         '',
216                         DI::l10n()->t('Everyone'),
217                         $baseurl,
218                         $options,
219                         $selected
220                 );
221         }
222
223         /**
224          * Return contact relationship widget
225          *
226          * @param string $baseurl  baseurl
227          * @param string $selected optional, default empty
228          * @return string
229          * @throws \Exception
230          */
231         public static function contactRels($baseurl, $selected = '')
232         {
233                 if (!local_user()) {
234                         return '';
235                 }
236
237                 $options = [
238                         ['ref' => 'followers', 'name' => DI::l10n()->t('Followers')],
239                         ['ref' => 'following', 'name' => DI::l10n()->t('Following')],
240                         ['ref' => 'mutuals', 'name' => DI::l10n()->t('Mutual friends')],
241                 ];
242
243                 return self::filter(
244                         'rel',
245                         DI::l10n()->t('Relationships'),
246                         '',
247                         DI::l10n()->t('All Contacts'),
248                         $baseurl,
249                         $options,
250                         $selected
251                 );
252         }
253
254         /**
255          * Return networks widget
256          *
257          * @param string $baseurl  baseurl
258          * @param string $selected optional, default empty
259          * @return string
260          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
261          */
262         public static function networks($baseurl, $selected = '')
263         {
264                 if (!local_user()) {
265                         return '';
266                 }
267
268                 $extra_sql = self::unavailableNetworks();
269
270                 $r = DBA::p("SELECT `network` FROM `contact` WHERE `uid` = ? AND NOT `deleted` AND `network` != '' $extra_sql GROUP BY `network` ORDER BY `network`",
271                         local_user()
272                 );
273
274                 $nets = array();
275                 while ($rr = DBA::fetch($r)) {
276                         $nets[] = ['ref' => $rr['network'], 'name' => ContactSelector::networkToName($rr['network'])];
277                 }
278                 DBA::close($r);
279
280                 if (count($nets) < 2) {
281                         return '';
282                 }
283
284                 return self::filter(
285                         'nets',
286                         DI::l10n()->t('Protocols'),
287                         '',
288                         DI::l10n()->t('All Protocols'),
289                         $baseurl,
290                         $nets,
291                         $selected
292                 );
293         }
294
295         /**
296          * Return file as widget
297          *
298          * @param string $baseurl  baseurl
299          * @param string $selected optional, default empty
300          * @return string|void
301          * @throws \Exception
302          */
303         public static function fileAs($baseurl, $selected = '')
304         {
305                 if (!local_user()) {
306                         return '';
307                 }
308
309                 $terms = [];
310                 foreach (Post\Category::getArray(local_user(), Post\Category::FILE) as $savedFolderName) {
311                         $terms[] = ['ref' => $savedFolderName, 'name' => $savedFolderName];
312                 }
313
314                 return self::filter(
315                         'file',
316                         DI::l10n()->t('Saved Folders'),
317                         '',
318                         DI::l10n()->t('Everything'),
319                         $baseurl,
320                         $terms,
321                         $selected
322                 );
323         }
324
325         /**
326          * Return categories widget
327          *
328          * @param string $baseurl  baseurl
329          * @param string $selected optional, default empty
330          * @return string|void
331          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
332          */
333         public static function categories($baseurl, $selected = '')
334         {
335                 $a = DI::app();
336
337                 $uid = intval($a->profile['uid']);
338
339                 if (!Feature::isEnabled($uid, 'categories')) {
340                         return '';
341                 }
342
343                 $terms = array();
344                 foreach (Post\Category::getArray(local_user(), Post\Category::CATEGORY) as $savedFolderName) {
345                         $terms[] = ['ref' => $savedFolderName, 'name' => $savedFolderName];
346                 }
347
348                 return self::filter(
349                         'category',
350                         DI::l10n()->t('Categories'),
351                         '',
352                         DI::l10n()->t('Everything'),
353                         $baseurl,
354                         $terms,
355                         $selected
356                 );
357         }
358
359         /**
360          * Show a random selection of five common contacts between the visitor and the viewed profile user.
361          *
362          * @param int    $uid      Viewed profile user ID
363          * @param string $nickname Viewed profile user nickname
364          * @return string|void
365          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
366          * @throws \ImagickException
367          */
368         public static function commonFriendsVisitor(int $uid, string $nickname)
369         {
370                 if (local_user() == $uid) {
371                         return '';
372                 }
373
374                 $visitorPCid = local_user() ? Contact::getPublicIdByUserId(local_user()) : remote_user();
375                 if (!$visitorPCid) {
376                         return '';
377                 }
378
379                 $localPCid = Contact::getPublicIdByUserId($uid);
380
381                 $condition = [
382                         'NOT `self` AND NOT `blocked` AND NOT `hidden` AND `id` != ?',
383                         $localPCid,
384                 ];
385
386                 $total = Contact\Relation::countCommon($localPCid, $visitorPCid, $condition);
387                 if (!$total) {
388                         return '';
389                 }
390
391                 $commonContacts = Contact\Relation::listCommon($localPCid, $visitorPCid, $condition, 0, 5, true);
392                 if (!DBA::isResult($commonContacts)) {
393                         return '';
394                 }
395
396                 $entries = [];
397                 foreach ($commonContacts as $contact) {
398                         $entries[] = [
399                                 'url'   => Contact::magicLinkByContact($contact),
400                                 'name'  => $contact['name'],
401                                 'photo' => Contact::getThumb($contact),
402                         ];
403                 }
404
405                 $tpl = Renderer::getMarkupTemplate('widget/remote_friends_common.tpl');
406                 return Renderer::replaceMacros($tpl, [
407                         '$desc'     => DI::l10n()->tt("%d contact in common", "%d contacts in common", $total),
408                         '$base'     => DI::baseUrl(),
409                         '$nickname' => $nickname,
410                         '$linkmore' => $total > 5 ? 'true' : '',
411                         '$more'     => DI::l10n()->t('show more'),
412                         '$contacts' => $entries
413                 ]);
414         }
415
416         /**
417          * Insert a tag cloud widget for the present profile.
418          *
419          * @param int $limit Max number of displayed tags.
420          * @return string HTML formatted output.
421          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
422          * @throws \ImagickException
423          */
424         public static function tagCloud($limit = 50)
425         {
426                 $a = DI::app();
427
428                 $uid = intval($a->profile['uid']);
429
430                 if (!$uid || !$a->profile['url']) {
431                         return '';
432                 }
433
434                 if (Feature::isEnabled($uid, 'tagadelic')) {
435                         $owner_id = Contact::getIdForURL($a->profile['url'], 0, false);
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)
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                         $dnow = substr($dnow, 0, 8) . '01';
474                         $dthen = substr($dthen, 0, 8) . '01';
475
476                         /*
477                          * Starting with the current month, get the first and last days of every
478                          * month down to and including the month of the first post
479                          */
480                         while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
481                                 $dyear = intval(substr($dnow, 0, 4));
482                                 $dstart = substr($dnow, 0, 8) . '01';
483                                 $dend = substr($dnow, 0, 8) . Temporal::getDaysInMonth(intval($dnow), intval(substr($dnow, 5)));
484                                 $start_month = DateTimeFormat::utc($dstart, 'Y-m-d');
485                                 $end_month = DateTimeFormat::utc($dend, 'Y-m-d');
486                                 $str = DI::l10n()->getDay(DateTimeFormat::utc($dnow, 'F'));
487
488                                 if (empty($ret[$dyear])) {
489                                         $ret[$dyear] = [];
490                                 }
491
492                                 $ret[$dyear][] = [$str, $end_month, $start_month];
493                                 $dnow = DateTimeFormat::utc($dnow . ' -1 month', 'Y-m-d');
494                         }
495                 }
496
497                 if (!DBA::isResult($ret)) {
498                         return $o;
499                 }
500
501
502                 $cutoff_year = intval(DateTimeFormat::localNow('Y')) - $visible_years;
503                 $cutoff = array_key_exists($cutoff_year, $ret);
504
505                 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/posted_date.tpl'),[
506                         '$title' => DI::l10n()->t('Archives'),
507                         '$size' => $visible_years,
508                         '$cutoff_year' => $cutoff_year,
509                         '$cutoff' => $cutoff,
510                         '$url' => $url,
511                         '$dates' => $ret,
512                         '$showless' => DI::l10n()->t('show less'),
513                         '$showmore' => DI::l10n()->t('show more')
514                 ]);
515
516                 return $o;
517         }
518
519         /**
520          * Display the account types sidebar
521          * The account type value is added as a parameter to the url
522          * 
523          * @param string $base        Basepath
524          * @param int    $accounttype Acount type
525          * @return string
526          */
527         public static function accounttypes(string $base, $accounttype)
528         {
529                 $accounts = [
530                         ['ref' => 'person', 'name' => DI::l10n()->t('Persons')],
531                         ['ref' => 'organisation', 'name' => DI::l10n()->t('Organisations')],
532                         ['ref' => 'news', 'name' => DI::l10n()->t('News')],
533                         ['ref' => 'community', 'name' => DI::l10n()->t('Forums')],
534                 ];
535
536                 return self::filter('accounttype', DI::l10n()->t('Account Types'), '',
537                         DI::l10n()->t('All'), $base, $accounts, $accounttype);
538         }
539 }