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