]> git.mxchange.org Git - friendica.git/blob - src/Content/Widget.php
Merge pull request #7674 from annando/fix-magic-again
[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 = intval(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                 $uid = intval($a->profile['profile_uid']);
301
302                 if (!Feature::isEnabled($uid, 'categories')) {
303                         return '';
304                 }
305
306                 $saved = PConfig::get($uid, 'system', 'filetags');
307                 if (!strlen($saved)) {
308                         return;
309                 }
310
311                 $terms = array();
312                 foreach (FileTag::fileToArray($saved, 'category') as $savedFolderName) {
313                         $terms[] = ['ref' => $savedFolderName, 'name' => $savedFolderName];
314                 }
315
316                 return self::filter(
317                         'category',
318                         L10n::t('Categories'),
319                         '',
320                         L10n::t('Everything'),
321                         $baseurl,
322                         $terms,
323                         $selected
324                 );
325         }
326
327         /**
328          * Return common friends visitor widget
329          *
330          * @param string $profile_uid uid
331          * @return string|void
332          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
333          */
334         public static function commonFriendsVisitor($profile_uid)
335         {
336                 if (local_user() == $profile_uid) {
337                         return;
338                 }
339
340                 $zcid = 0;
341
342                 $cid = remote_user($profile_uid);
343
344                 if (!$cid) {
345                         if (Profile::getMyURL()) {
346                                 $contact = DBA::selectFirst('contact', ['id'],
347                                                 ['nurl' => Strings::normaliseLink(Profile::getMyURL()), 'uid' => $profile_uid]);
348                                 if (DBA::isResult($contact)) {
349                                         $cid = $contact['id'];
350                                 } else {
351                                         $gcontact = DBA::selectFirst('gcontact', ['id'], ['nurl' => Strings::normaliseLink(Profile::getMyURL())]);
352                                         if (DBA::isResult($gcontact)) {
353                                                 $zcid = $gcontact['id'];
354                                         }
355                                 }
356                         }
357                 }
358
359                 if ($cid == 0 && $zcid == 0) {
360                         return;
361                 }
362
363                 if ($cid) {
364                         $t = GContact::countCommonFriends($profile_uid, $cid);
365                 } else {
366                         $t = GContact::countCommonFriendsZcid($profile_uid, $zcid);
367                 }
368
369                 if (!$t) {
370                         return;
371                 }
372
373                 if ($cid) {
374                         $r = GContact::commonFriends($profile_uid, $cid, 0, 5, true);
375                 } else {
376                         $r = GContact::commonFriendsZcid($profile_uid, $zcid, 0, 5, true);
377                 }
378
379                 if (!DBA::isResult($r)) {
380                         return;
381                 }
382
383                 $entries = [];
384                 foreach ($r as $rr) {
385                         $entry = [
386                                 'url'   => Contact::magicLink($rr['url']),
387                                 'name'  => $rr['name'],
388                                 'photo' => ProxyUtils::proxifyUrl($rr['photo'], false, ProxyUtils::SIZE_THUMB),
389                         ];
390                         $entries[] = $entry;
391                 }
392
393                 $tpl = Renderer::getMarkupTemplate('widget/remote_friends_common.tpl');
394                 return Renderer::replaceMacros($tpl, [
395                         '$desc'     => L10n::tt("%d contact in common", "%d contacts in common", $t),
396                         '$base'     => System::baseUrl(),
397                         '$uid'      => $profile_uid,
398                         '$cid'      => (($cid) ? $cid : '0'),
399                         '$linkmore' => (($t > 5) ? 'true' : ''),
400                         '$more'     => L10n::t('show more'),
401                         '$items'    => $entries
402                 ]);
403         }
404
405         /**
406          * Insert a tag cloud widget for the present profile.
407          *
408          * @brief Insert a tag cloud widget for the present profile.
409          * @param int $limit Max number of displayed tags.
410          * @return string HTML formatted output.
411          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
412          * @throws \ImagickException
413          */
414         public static function tagCloud($limit = 50)
415         {
416                 $a = \get_app();
417
418                 $uid = intval($a->profile['profile_uid']);
419
420                 if (!$uid || !$a->profile['url']) {
421                         return '';
422                 }
423
424                 if (Feature::isEnabled($uid, 'tagadelic')) {
425                         $owner_id = Contact::getIdForURL($a->profile['url'], 0, true);
426
427                         if (!$owner_id) {
428                                 return '';
429                         }
430                         return Widget\TagCloud::getHTML($uid, $limit, $owner_id, 'wall');
431                 }
432
433                 return '';
434         }
435
436         /**
437          * @param string $url Base page URL
438          * @param int    $uid User ID consulting/publishing posts
439          * @param bool   $wall True: Posted by User; False: Posted to User (network timeline)
440          * @return string
441          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
442          */
443         public static function postedByYear(string $url, int $uid, bool $wall)
444         {
445                 $o = '';
446
447                 if (!Feature::isEnabled($uid, 'archives')) {
448                         return $o;
449                 }
450
451                 $visible_years = PConfig::get($uid, 'system', 'archive_visible_years', 5);
452
453                 /* arrange the list in years */
454                 $dnow = DateTimeFormat::localNow('Y-m-d');
455
456                 $ret = [];
457
458                 $dthen = Item::firstPostDate($uid, $wall);
459                 if ($dthen) {
460                         // Set the start and end date to the beginning of the month
461                         $dnow = substr($dnow, 0, 8) . '01';
462                         $dthen = substr($dthen, 0, 8) . '01';
463
464                         /*
465                          * Starting with the current month, get the first and last days of every
466                          * month down to and including the month of the first post
467                          */
468                         while (substr($dnow, 0, 7) >= substr($dthen, 0, 7)) {
469                                 $dyear = intval(substr($dnow, 0, 4));
470                                 $dstart = substr($dnow, 0, 8) . '01';
471                                 $dend = substr($dnow, 0, 8) . Temporal::getDaysInMonth(intval($dnow), intval(substr($dnow, 5)));
472                                 $start_month = DateTimeFormat::utc($dstart, 'Y-m-d');
473                                 $end_month = DateTimeFormat::utc($dend, 'Y-m-d');
474                                 $str = L10n::getDay(DateTimeFormat::utc($dnow, 'F'));
475
476                                 if (empty($ret[$dyear])) {
477                                         $ret[$dyear] = [];
478                                 }
479
480                                 $ret[$dyear][] = [$str, $end_month, $start_month];
481                                 $dnow = DateTimeFormat::utc($dnow . ' -1 month', 'Y-m-d');
482                         }
483                 }
484
485                 if (!DBA::isResult($ret)) {
486                         return $o;
487                 }
488
489
490                 $cutoff_year = intval(DateTimeFormat::localNow('Y')) - $visible_years;
491                 $cutoff = array_key_exists($cutoff_year, $ret);
492
493                 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/posted_date.tpl'),[
494                         '$title' => L10n::t('Archives'),
495                         '$size' => $visible_years,
496                         '$cutoff_year' => $cutoff_year,
497                         '$cutoff' => $cutoff,
498                         '$url' => $url,
499                         '$dates' => $ret,
500                         '$showmore' => L10n::t('show more')
501                 ]);
502
503                 return $o;
504         }
505 }