]> git.mxchange.org Git - friendica.git/blob - src/Content/Widget.php
Merge pull request #8886 from annando/getidforurl-update
[friendica.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\Protocol;
26 use Friendica\Core\Renderer;
27 use Friendica\Core\Session;
28 use Friendica\Database\DBA;
29 use Friendica\DI;
30 use Friendica\Model\Contact;
31 use Friendica\Model\FileTag;
32 use Friendica\Model\GContact;
33 use Friendica\Model\Group;
34 use Friendica\Model\Item;
35 use Friendica\Model\Profile;
36 use Friendica\Util\DateTimeFormat;
37 use Friendica\Util\Proxy as ProxyUtils;
38 use Friendica\Util\Strings;
39 use Friendica\Util\Temporal;
40
41 class Widget
42 {
43         /**
44          * Return the follow widget
45          *
46          * @param string $value optional, default empty
47          * @return string
48          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
49          */
50         public static function follow($value = "")
51         {
52                 return Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/follow.tpl'), array(
53                         '$connect' => DI::l10n()->t('Add New Contact'),
54                         '$desc' => DI::l10n()->t('Enter address or web location'),
55                         '$hint' => DI::l10n()->t('Example: bob@example.com, http://example.com/barbara'),
56                         '$value' => $value,
57                         '$follow' => DI::l10n()->t('Connect')
58                 ));
59         }
60
61         /**
62          * Return Find People widget
63          */
64         public static function findPeople()
65         {
66                 $global_dir = DI::config()->get('system', 'directory');
67
68                 if (DI::config()->get('system', 'invitation_only')) {
69                         $x = intval(DI::pConfig()->get(local_user(), 'system', 'invites_remaining'));
70                         if ($x || is_site_admin()) {
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'] = $global_dir;
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
99          */
100         public static function unavailableNetworks()
101         {
102                 // Always hide content from these networks
103                 $networks = [Protocol::PHANTOM, Protocol::FACEBOOK, Protocol::APPNET];
104
105                 if (!Addon::isEnabled("discourse")) {
106                         $networks[] = Protocol::DISCOURSE;
107                 }
108
109                 if (!Addon::isEnabled("statusnet")) {
110                         $networks[] = Protocol::STATUSNET;
111                 }
112
113                 if (!Addon::isEnabled("pumpio")) {
114                         $networks[] = Protocol::PUMPIO;
115                 }
116
117                 if (!Addon::isEnabled("twitter")) {
118                         $networks[] = Protocol::TWITTER;
119                 }
120
121                 if (DI::config()->get("system", "ostatus_disabled")) {
122                         $networks[] = Protocol::OSTATUS;
123                 }
124
125                 if (!DI::config()->get("system", "diaspora_enabled")) {
126                         $networks[] = Protocol::DIASPORA;
127                 }
128
129                 if (!Addon::isEnabled("pnut")) {
130                         $networks[] = Protocol::PNUT;
131                 }
132
133                 if (!sizeof($networks)) {
134                         return "";
135                 }
136
137                 $network_filter = implode("','", $networks);
138
139                 $network_filter = "AND `network` NOT IN ('$network_filter')";
140
141                 return $network_filter;
142         }
143
144         /**
145          * Display a generic filter widget based on a list of options
146          *
147          * The options array must be the following format:
148          * [
149          *    [
150          *      'ref' => {filter value},
151          *      'name' => {option name}
152          *    ],
153          *    ...
154          * ]
155          *
156          * @param string $type The filter query string key
157          * @param string $title
158          * @param string $desc
159          * @param string $all The no filter label
160          * @param string $baseUrl The full page request URI
161          * @param array  $options
162          * @param string $selected The currently selected filter option value
163          * @return string
164          * @throws \Exception
165          */
166         private static function filter($type, $title, $desc, $all, $baseUrl, array $options, $selected = null)
167         {
168                 $queryString = parse_url($baseUrl, PHP_URL_QUERY);
169                 $queryArray = [];
170
171                 if ($queryString) {
172                         parse_str($queryString, $queryArray);
173                         unset($queryArray[$type]);
174
175                         if (count($queryArray)) {
176                                 $baseUrl = substr($baseUrl, 0, strpos($baseUrl, '?')) . '?' . http_build_query($queryArray) . '&';
177                         } else {
178                                 $baseUrl = substr($baseUrl, 0, strpos($baseUrl, '?')) . '?';
179                         }
180                 } else {
181                         $baseUrl = trim($baseUrl, '?') . '?';
182                 }
183
184                 return Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/filter.tpl'), [
185                         '$type'      => $type,
186                         '$title'     => $title,
187                         '$desc'      => $desc,
188                         '$selected'  => $selected,
189                         '$all_label' => $all,
190                         '$options'   => $options,
191                         '$base'      => $baseUrl,
192                 ]);
193         }
194
195         /**
196          * Return group membership widget
197          *
198          * @param string $baseurl
199          * @param string $selected
200          * @return string
201          * @throws \Exception
202          */
203         public static function groups($baseurl, $selected = '')
204         {
205                 if (!local_user()) {
206                         return '';
207                 }
208
209                 $options = array_map(function ($group) {
210                         return [
211                                 'ref'  => $group['id'],
212                                 'name' => $group['name']
213                         ];
214                 }, Group::getByUserId(local_user()));
215
216                 return self::filter(
217                         'group',
218                         DI::l10n()->t('Groups'),
219                         '',
220                         DI::l10n()->t('Everyone'),
221                         $baseurl,
222                         $options,
223                         $selected
224                 );
225         }
226
227         /**
228          * Return contact relationship widget
229          *
230          * @param string $baseurl  baseurl
231          * @param string $selected optional, default empty
232          * @return string
233          * @throws \Exception
234          */
235         public static function contactRels($baseurl, $selected = '')
236         {
237                 if (!local_user()) {
238                         return '';
239                 }
240
241                 $options = [
242                         ['ref' => 'followers', 'name' => DI::l10n()->t('Followers')],
243                         ['ref' => 'following', 'name' => DI::l10n()->t('Following')],
244                         ['ref' => 'mutuals', 'name' => DI::l10n()->t('Mutual friends')],
245                 ];
246
247                 return self::filter(
248                         'rel',
249                         DI::l10n()->t('Relationships'),
250                         '',
251                         DI::l10n()->t('All Contacts'),
252                         $baseurl,
253                         $options,
254                         $selected
255                 );
256         }
257
258         /**
259          * Return networks widget
260          *
261          * @param string $baseurl  baseurl
262          * @param string $selected optional, default empty
263          * @return string
264          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
265          */
266         public static function networks($baseurl, $selected = '')
267         {
268                 if (!local_user()) {
269                         return '';
270                 }
271
272                 $extra_sql = self::unavailableNetworks();
273
274                 $r = DBA::p("SELECT DISTINCT(`network`) FROM `contact` WHERE `uid` = ? AND NOT `deleted` AND `network` != '' $extra_sql ORDER BY `network`",
275                         local_user()
276                 );
277
278                 $nets = array();
279                 while ($rr = DBA::fetch($r)) {
280                         $nets[] = ['ref' => $rr['network'], 'name' => ContactSelector::networkToName($rr['network'])];
281                 }
282                 DBA::close($r);
283
284                 if (count($nets) < 2) {
285                         return '';
286                 }
287
288                 return self::filter(
289                         'nets',
290                         DI::l10n()->t('Protocols'),
291                         '',
292                         DI::l10n()->t('All Protocols'),
293                         $baseurl,
294                         $nets,
295                         $selected
296                 );
297         }
298
299         /**
300          * Return file as widget
301          *
302          * @param string $baseurl  baseurl
303          * @param string $selected optional, default empty
304          * @return string|void
305          * @throws \Exception
306          */
307         public static function fileAs($baseurl, $selected = '')
308         {
309                 if (!local_user()) {
310                         return '';
311                 }
312
313                 $saved = DI::pConfig()->get(local_user(), 'system', 'filetags');
314                 if (!strlen($saved)) {
315                         return;
316                 }
317
318                 $terms = [];
319                 foreach (FileTag::fileToArray($saved) as $savedFolderName) {
320                         $terms[] = ['ref' => $savedFolderName, 'name' => $savedFolderName];
321                 }
322                 
323                 usort($terms, function ($a, $b) {
324                         return strcmp($a['name'], $b['name']);
325                 });
326
327                 return self::filter(
328                         'file',
329                         DI::l10n()->t('Saved Folders'),
330                         '',
331                         DI::l10n()->t('Everything'),
332                         $baseurl,
333                         $terms,
334                         $selected
335                 );
336         }
337
338         /**
339          * Return categories widget
340          *
341          * @param string $baseurl  baseurl
342          * @param string $selected optional, default empty
343          * @return string|void
344          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
345          */
346         public static function categories($baseurl, $selected = '')
347         {
348                 $a = DI::app();
349
350                 $uid = intval($a->profile['uid']);
351
352                 if (!Feature::isEnabled($uid, 'categories')) {
353                         return '';
354                 }
355
356                 $saved = DI::pConfig()->get($uid, 'system', 'filetags');
357                 if (!strlen($saved)) {
358                         return;
359                 }
360
361                 $terms = array();
362                 foreach (FileTag::fileToArray($saved, 'category') as $savedFolderName) {
363                         $terms[] = ['ref' => $savedFolderName, 'name' => $savedFolderName];
364                 }
365
366                 return self::filter(
367                         'category',
368                         DI::l10n()->t('Categories'),
369                         '',
370                         DI::l10n()->t('Everything'),
371                         $baseurl,
372                         $terms,
373                         $selected
374                 );
375         }
376
377         /**
378          * Return common friends visitor widget
379          *
380          * @param string $profile_uid uid
381          * @return string|void
382          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
383          */
384         public static function commonFriendsVisitor($profile_uid)
385         {
386                 if (local_user() == $profile_uid) {
387                         return;
388                 }
389
390                 $zcid = 0;
391
392                 $cid = Session::getRemoteContactID($profile_uid);
393
394                 if (!$cid) {
395                         if (Profile::getMyURL()) {
396                                 $contact = DBA::selectFirst('contact', ['id'],
397                                                 ['nurl' => Strings::normaliseLink(Profile::getMyURL()), 'uid' => $profile_uid]);
398                                 if (DBA::isResult($contact)) {
399                                         $cid = $contact['id'];
400                                 } else {
401                                         $gcontact = DBA::selectFirst('gcontact', ['id'], ['nurl' => Strings::normaliseLink(Profile::getMyURL())]);
402                                         if (DBA::isResult($gcontact)) {
403                                                 $zcid = $gcontact['id'];
404                                         }
405                                 }
406                         }
407                 }
408
409                 if ($cid == 0 && $zcid == 0) {
410                         return;
411                 }
412
413                 if ($cid) {
414                         $t = GContact::countCommonFriends($profile_uid, $cid);
415                 } else {
416                         $t = GContact::countCommonFriendsZcid($profile_uid, $zcid);
417                 }
418
419                 if (!$t) {
420                         return;
421                 }
422
423                 if ($cid) {
424                         $r = GContact::commonFriends($profile_uid, $cid, 0, 5, true);
425                 } else {
426                         $r = GContact::commonFriendsZcid($profile_uid, $zcid, 0, 5, true);
427                 }
428
429                 if (!DBA::isResult($r)) {
430                         return;
431                 }
432
433                 $entries = [];
434                 foreach ($r as $rr) {
435                         $entry = [
436                                 'url'   => Contact::magicLink($rr['url']),
437                                 'name'  => $rr['name'],
438                                 'photo' => ProxyUtils::proxifyUrl($rr['photo'], false, ProxyUtils::SIZE_THUMB),
439                         ];
440                         $entries[] = $entry;
441                 }
442
443                 $tpl = Renderer::getMarkupTemplate('widget/remote_friends_common.tpl');
444                 return Renderer::replaceMacros($tpl, [
445                         '$desc'     => DI::l10n()->tt("%d contact in common", "%d contacts in common", $t),
446                         '$base'     => DI::baseUrl(),
447                         '$uid'      => $profile_uid,
448                         '$cid'      => (($cid) ? $cid : '0'),
449                         '$linkmore' => (($t > 5) ? 'true' : ''),
450                         '$more'     => DI::l10n()->t('show more'),
451                         '$items'    => $entries
452                 ]);
453         }
454
455         /**
456          * Insert a tag cloud widget for the present profile.
457          *
458          * @param int $limit Max number of displayed tags.
459          * @return string HTML formatted output.
460          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
461          * @throws \ImagickException
462          */
463         public static function tagCloud($limit = 50)
464         {
465                 $a = DI::app();
466
467                 $uid = intval($a->profile['uid']);
468
469                 if (!$uid || !$a->profile['url']) {
470                         return '';
471                 }
472
473                 if (Feature::isEnabled($uid, 'tagadelic')) {
474                         $owner_id = Contact::getIdForURL($a->profile['url'], 0, false);
475
476                         if (!$owner_id) {
477                                 return '';
478                         }
479                         return Widget\TagCloud::getHTML($uid, $limit, $owner_id, 'wall');
480                 }
481
482                 return '';
483         }
484
485         /**
486          * @param string $url Base page URL
487          * @param int    $uid User ID consulting/publishing posts
488          * @param bool   $wall True: Posted by User; False: Posted to User (network timeline)
489          * @return string
490          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
491          */
492         public static function postedByYear(string $url, int $uid, bool $wall)
493         {
494                 $o = '';
495
496                 $visible_years = DI::pConfig()->get($uid, 'system', 'archive_visible_years', 5);
497
498                 /* arrange the list in years */
499                 $dnow = DateTimeFormat::localNow('Y-m-d');
500
501                 $ret = [];
502
503                 $dthen = Item::firstPostDate($uid, $wall);
504                 if ($dthen) {
505                         // Set the start and end date to the beginning of the month
506                         $dnow = substr($dnow, 0, 8) . '01';
507                         $dthen = substr($dthen, 0, 8) . '01';
508
509                         /*
510                          * Starting with the current month, get the first and last days of every
511                          * month down to and including the month of the first post
512                          */
513                         while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
514                                 $dyear = intval(substr($dnow, 0, 4));
515                                 $dstart = substr($dnow, 0, 8) . '01';
516                                 $dend = substr($dnow, 0, 8) . Temporal::getDaysInMonth(intval($dnow), intval(substr($dnow, 5)));
517                                 $start_month = DateTimeFormat::utc($dstart, 'Y-m-d');
518                                 $end_month = DateTimeFormat::utc($dend, 'Y-m-d');
519                                 $str = DI::l10n()->getDay(DateTimeFormat::utc($dnow, 'F'));
520
521                                 if (empty($ret[$dyear])) {
522                                         $ret[$dyear] = [];
523                                 }
524
525                                 $ret[$dyear][] = [$str, $end_month, $start_month];
526                                 $dnow = DateTimeFormat::utc($dnow . ' -1 month', 'Y-m-d');
527                         }
528                 }
529
530                 if (!DBA::isResult($ret)) {
531                         return $o;
532                 }
533
534
535                 $cutoff_year = intval(DateTimeFormat::localNow('Y')) - $visible_years;
536                 $cutoff = array_key_exists($cutoff_year, $ret);
537
538                 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/posted_date.tpl'),[
539                         '$title' => DI::l10n()->t('Archives'),
540                         '$size' => $visible_years,
541                         '$cutoff_year' => $cutoff_year,
542                         '$cutoff' => $cutoff,
543                         '$url' => $url,
544                         '$dates' => $ret,
545                         '$showmore' => DI::l10n()->t('show more')
546                 ]);
547
548                 return $o;
549         }
550 }