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