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