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