]> git.mxchange.org Git - friendica.git/blob - src/Content/Widget.php
dcfc1d0e3d95da631db6899dc781c10eff9f017c
[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\Database\DBA;
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 use Friendica\Util\XML;
25
26 class Widget
27 {
28         /**
29          * Return the follow widget
30          *
31          * @param string $value optional, default empty
32          * @return string
33          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
34          */
35         public static function follow($value = "")
36         {
37                 return Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/follow.tpl'), array(
38                         '$connect' => L10n::t('Add New Contact'),
39                         '$desc' => L10n::t('Enter address or web location'),
40                         '$hint' => L10n::t('Example: bob@example.com, http://example.com/barbara'),
41                         '$value' => $value,
42                         '$follow' => L10n::t('Connect')
43                 ));
44         }
45
46         /**
47          * Return Find People widget
48          */
49         public static function findPeople()
50         {
51                 $a = \get_app();
52                 $global_dir = Config::get('system', 'directory');
53
54                 if (Config::get('system', 'invitation_only')) {
55                         $x = PConfig::get(local_user(), 'system', 'invites_remaining');
56                         if ($x || is_site_admin()) {
57                                 $a->page['aside'] .= '<div class="side-link widget" id="side-invite-remain">'
58                                         . L10n::tt('%d invitation available', '%d invitations available', $x)
59                                         . '</div>';
60                         }
61                 }
62
63                 $nv = [];
64                 $nv['findpeople'] = L10n::t('Find People');
65                 $nv['desc'] = L10n::t('Enter name or interest');
66                 $nv['label'] = L10n::t('Connect/Follow');
67                 $nv['hint'] = L10n::t('Examples: Robert Morgenstein, Fishing');
68                 $nv['findthem'] = L10n::t('Find');
69                 $nv['suggest'] = L10n::t('Friend Suggestions');
70                 $nv['similar'] = L10n::t('Similar Interests');
71                 $nv['random'] = L10n::t('Random Profile');
72                 $nv['inv'] = L10n::t('Invite Friends');
73                 $nv['directory'] = L10n::t('Global Directory');
74                 $nv['global_dir'] = $global_dir;
75                 $nv['local_directory'] = L10n::t('Local Directory');
76
77                 $aside = [];
78                 $aside['$nv'] = $nv;
79
80                 return Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/peoplefind.tpl'), $aside);
81         }
82
83         /**
84          * Return unavailable networks
85          */
86         public static function unavailableNetworks()
87         {
88                 // Always hide content from these networks
89                 $networks = ['face', 'apdn'];
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 (Config::get("system", "ostatus_disabled")) {
104                         $networks[] = Protocol::OSTATUS;
105                 }
106
107                 if (!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' => L10n::t('Followers')],
193                         ['ref' => 'following', 'name' => L10n::t('Following')],
194                         ['ref' => 'mutuals', 'name' => L10n::t('Mutual friends')],
195                 ];
196
197                 return self::filter(
198                         'rel',
199                         L10n::t('Relationships'),
200                         '',
201                         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                         L10n::t('Protocols'),
245                         '',
246                         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 = 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                 return self::filter(
278                         'file',
279                         L10n::t('Saved Folders'),
280                         '',
281                         L10n::t('Everything'),
282                         $baseurl,
283                         $terms,
284                         $selected
285                 );
286         }
287
288         /**
289          * Return categories widget
290          *
291          * @param string $baseurl  baseurl
292          * @param string $selected optional, default empty
293          * @return string|void
294          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
295          */
296         public static function categories($baseurl, $selected = '')
297         {
298                 $a = \get_app();
299
300                 if (!Feature::isEnabled($a->profile['profile_uid'], 'categories')) {
301                         return '';
302                 }
303
304                 $saved = PConfig::get($a->profile['profile_uid'], 'system', 'filetags');
305                 if (!strlen($saved)) {
306                         return;
307                 }
308
309                 $terms = array();
310                 foreach (FileTag::fileToArray($saved, 'category') as $savedFolderName) {
311                         $terms[] = ['ref' => $savedFolderName, 'name' => $savedFolderName];
312                 }
313
314                 return self::filter(
315                         'category',
316                         L10n::t('Categories'),
317                         '',
318                         L10n::t('Everything'),
319                         $baseurl,
320                         $terms,
321                         $selected
322                 );
323         }
324
325         /**
326          * Return common friends visitor widget
327          *
328          * @param string $profile_uid uid
329          * @return string|void
330          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
331          */
332         public static function commonFriendsVisitor($profile_uid)
333         {
334                 if (local_user() == $profile_uid) {
335                         return;
336                 }
337
338                 $cid = $zcid = 0;
339
340                 if (!empty($_SESSION['remote'])) {
341                         foreach ($_SESSION['remote'] as $visitor) {
342                                 if ($visitor['uid'] == $profile_uid) {
343                                         $cid = $visitor['cid'];
344                                         break;
345                                 }
346                         }
347                 }
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'     => L10n::tt("%d contact in common", "%d contacts in common", $t),
401                         '$base'     => System::baseUrl(),
402                         '$uid'      => $profile_uid,
403                         '$cid'      => (($cid) ? $cid : '0'),
404                         '$linkmore' => (($t > 5) ? 'true' : ''),
405                         '$more'     => L10n::t('show more'),
406                         '$items'    => $entries
407                 ]);
408         }
409
410         /**
411          * Insert a tag cloud widget for the present profile.
412          *
413          * @brief Insert a tag cloud widget for the present profile.
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 = \get_app();
422
423                 if (!$a->profile['profile_uid'] || !$a->profile['url']) {
424                         return '';
425                 }
426
427                 if (Feature::isEnabled($a->profile['profile_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($a->profile['profile_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 = 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 = 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' => L10n::t('Archives'),
498                         '$size' => $visible_years,
499                         '$cutoff_year' => $cutoff_year,
500                         '$cutoff' => $cutoff,
501                         '$url' => $url,
502                         '$dates' => $ret,
503                         '$showmore' => L10n::t('show more')
504                 ]);
505
506                 return $o;
507         }
508 }