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