]> git.mxchange.org Git - friendica.git/blob - src/Content/Widget.php
Added asort() to the saved folders widget
[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\Core\Session;
15 use Friendica\Database\DBA;
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 use Friendica\Util\XML;
26
27 class Widget
28 {
29         /**
30          * Return the follow widget
31          *
32          * @param string $value optional, default empty
33          * @return string
34          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
35          */
36         public static function follow($value = "")
37         {
38                 return Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/follow.tpl'), array(
39                         '$connect' => L10n::t('Add New Contact'),
40                         '$desc' => L10n::t('Enter address or web location'),
41                         '$hint' => L10n::t('Example: bob@example.com, http://example.com/barbara'),
42                         '$value' => $value,
43                         '$follow' => L10n::t('Connect')
44                 ));
45         }
46
47         /**
48          * Return Find People widget
49          */
50         public static function findPeople()
51         {
52                 $a = \get_app();
53                 $global_dir = Config::get('system', 'directory');
54
55                 if (Config::get('system', 'invitation_only')) {
56                         $x = intval(PConfig::get(local_user(), 'system', 'invites_remaining'));
57                         if ($x || is_site_admin()) {
58                                 $a->page['aside'] .= '<div class="side-link widget" id="side-invite-remain">'
59                                         . L10n::tt('%d invitation available', '%d invitations available', $x)
60                                         . '</div>';
61                         }
62                 }
63
64                 $nv = [];
65                 $nv['findpeople'] = L10n::t('Find People');
66                 $nv['desc'] = L10n::t('Enter name or interest');
67                 $nv['label'] = L10n::t('Connect/Follow');
68                 $nv['hint'] = L10n::t('Examples: Robert Morgenstein, Fishing');
69                 $nv['findthem'] = L10n::t('Find');
70                 $nv['suggest'] = L10n::t('Friend Suggestions');
71                 $nv['similar'] = L10n::t('Similar Interests');
72                 $nv['random'] = L10n::t('Random Profile');
73                 $nv['inv'] = L10n::t('Invite Friends');
74                 $nv['directory'] = L10n::t('Global Directory');
75                 $nv['global_dir'] = $global_dir;
76                 $nv['local_directory'] = L10n::t('Local Directory');
77
78                 $aside = [];
79                 $aside['$nv'] = $nv;
80
81                 return Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/peoplefind.tpl'), $aside);
82         }
83
84         /**
85          * Return unavailable networks
86          */
87         public static function unavailableNetworks()
88         {
89                 // Always hide content from these networks
90                 $networks = ['face', 'apdn'];
91
92                 if (!Addon::isEnabled("statusnet")) {
93                         $networks[] = Protocol::STATUSNET;
94                 }
95
96                 if (!Addon::isEnabled("pumpio")) {
97                         $networks[] = Protocol::PUMPIO;
98                 }
99
100                 if (!Addon::isEnabled("twitter")) {
101                         $networks[] = Protocol::TWITTER;
102                 }
103
104                 if (Config::get("system", "ostatus_disabled")) {
105                         $networks[] = Protocol::OSTATUS;
106                 }
107
108                 if (!Config::get("system", "diaspora_enabled")) {
109                         $networks[] = Protocol::DIASPORA;
110                 }
111
112                 if (!Addon::isEnabled("pnut")) {
113                         $networks[] = Protocol::PNUT;
114                 }
115
116                 if (!sizeof($networks)) {
117                         return "";
118                 }
119
120                 $network_filter = implode("','", $networks);
121
122                 $network_filter = "AND `network` NOT IN ('$network_filter')";
123
124                 return $network_filter;
125         }
126
127         /**
128          * Display a generic filter widget based on a list of options
129          *
130          * The options array must be the following format:
131          * [
132          *    [
133          *      'ref' => {filter value},
134          *      'name' => {option name}
135          *    ],
136          *    ...
137          * ]
138          *
139          * @param string $type The filter query string key
140          * @param string $title
141          * @param string $desc
142          * @param string $all The no filter label
143          * @param string $baseUrl The full page request URI
144          * @param array  $options
145          * @param string $selected The currently selected filter option value
146          * @return string
147          * @throws \Exception
148          */
149         private static function filter($type, $title, $desc, $all, $baseUrl, array $options, $selected = null)
150         {
151                 $queryString = parse_url($baseUrl, PHP_URL_QUERY);
152                 $queryArray = [];
153
154                 if ($queryString) {
155                         parse_str($queryString, $queryArray);
156                         unset($queryArray[$type]);
157
158                         if (count($queryArray)) {
159                                 $baseUrl = substr($baseUrl, 0, strpos($baseUrl, '?')) . '?' . http_build_query($queryArray) . '&';
160                         } else {
161                                 $baseUrl = substr($baseUrl, 0, strpos($baseUrl, '?')) . '?';
162                         }
163                 } else {
164                         $baseUrl = trim($baseUrl, '?') . '?';
165                 }
166
167                 return Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/filter.tpl'), [
168                         '$type'      => $type,
169                         '$title'     => $title,
170                         '$desc'      => $desc,
171                         '$selected'  => $selected,
172                         '$all_label' => $all,
173                         '$options'   => $options,
174                         '$base'      => $baseUrl,
175                 ]);
176         }
177
178         /**
179          * Return networks widget
180          *
181          * @param string $baseurl  baseurl
182          * @param string $selected optional, default empty
183          * @return string
184          * @throws \Exception
185          */
186         public static function contactRels($baseurl, $selected = '')
187         {
188                 if (!local_user()) {
189                         return '';
190                 }
191
192                 $options = [
193                         ['ref' => 'followers', 'name' => L10n::t('Followers')],
194                         ['ref' => 'following', 'name' => L10n::t('Following')],
195                         ['ref' => 'mutuals', 'name' => L10n::t('Mutual friends')],
196                 ];
197
198                 return self::filter(
199                         'rel',
200                         L10n::t('Relationships'),
201                         '',
202                         L10n::t('All Contacts'),
203                         $baseurl,
204                         $options,
205                         $selected
206                 );
207         }
208
209         /**
210          * Return networks widget
211          *
212          * @param string $baseurl  baseurl
213          * @param string $selected optional, default empty
214          * @return string
215          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
216          */
217         public static function networks($baseurl, $selected = '')
218         {
219                 if (!local_user()) {
220                         return '';
221                 }
222
223                 if (!Feature::isEnabled(local_user(), 'networks')) {
224                         return '';
225                 }
226
227                 $extra_sql = self::unavailableNetworks();
228
229                 $r = DBA::p("SELECT DISTINCT(`network`) FROM `contact` WHERE `uid` = ? AND NOT `deleted` AND `network` != '' $extra_sql ORDER BY `network`",
230                         local_user()
231                 );
232
233                 $nets = array();
234                 while ($rr = DBA::fetch($r)) {
235                         $nets[] = ['ref' => $rr['network'], 'name' => ContactSelector::networkToName($rr['network'])];
236                 }
237                 DBA::close($r);
238
239                 if (count($nets) < 2) {
240                         return '';
241                 }
242
243                 return self::filter(
244                         'nets',
245                         L10n::t('Protocols'),
246                         '',
247                         L10n::t('All Protocols'),
248                         $baseurl,
249                         $nets,
250                         $selected
251                 );
252         }
253
254         /**
255          * Return file as widget
256          *
257          * @param string $baseurl  baseurl
258          * @param string $selected optional, default empty
259          * @return string|void
260          * @throws \Exception
261          */
262         public static function fileAs($baseurl, $selected = '')
263         {
264                 if (!local_user()) {
265                         return '';
266                 }
267
268                 $saved = PConfig::get(local_user(), 'system', 'filetags');
269                 if (!strlen($saved)) {
270                         return;
271                 }
272
273                 $terms = [];
274                 foreach (FileTag::fileToArray($saved) as $savedFolderName) {
275                         $terms[] = ['ref' => $savedFolderName, 'name' => $savedFolderName];
276                 }
277                 
278                 asort($terms);
279
280                 return self::filter(
281                         'file',
282                         L10n::t('Saved Folders'),
283                         '',
284                         L10n::t('Everything'),
285                         $baseurl,
286                         $terms,
287                         $selected
288                 );
289         }
290
291         /**
292          * Return categories widget
293          *
294          * @param string $baseurl  baseurl
295          * @param string $selected optional, default empty
296          * @return string|void
297          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
298          */
299         public static function categories($baseurl, $selected = '')
300         {
301                 $a = \get_app();
302
303                 $uid = intval($a->profile['profile_uid']);
304
305                 if (!Feature::isEnabled($uid, 'categories')) {
306                         return '';
307                 }
308
309                 $saved = PConfig::get($uid, 'system', 'filetags');
310                 if (!strlen($saved)) {
311                         return;
312                 }
313
314                 $terms = array();
315                 foreach (FileTag::fileToArray($saved, 'category') as $savedFolderName) {
316                         $terms[] = ['ref' => $savedFolderName, 'name' => $savedFolderName];
317                 }
318
319                 return self::filter(
320                         'category',
321                         L10n::t('Categories'),
322                         '',
323                         L10n::t('Everything'),
324                         $baseurl,
325                         $terms,
326                         $selected
327                 );
328         }
329
330         /**
331          * Return common friends visitor widget
332          *
333          * @param string $profile_uid uid
334          * @return string|void
335          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
336          */
337         public static function commonFriendsVisitor($profile_uid)
338         {
339                 if (local_user() == $profile_uid) {
340                         return;
341                 }
342
343                 $zcid = 0;
344
345                 $cid = Session::getRemoteContactID($profile_uid);
346
347                 if (!$cid) {
348                         if (Profile::getMyURL()) {
349                                 $contact = DBA::selectFirst('contact', ['id'],
350                                                 ['nurl' => Strings::normaliseLink(Profile::getMyURL()), 'uid' => $profile_uid]);
351                                 if (DBA::isResult($contact)) {
352                                         $cid = $contact['id'];
353                                 } else {
354                                         $gcontact = DBA::selectFirst('gcontact', ['id'], ['nurl' => Strings::normaliseLink(Profile::getMyURL())]);
355                                         if (DBA::isResult($gcontact)) {
356                                                 $zcid = $gcontact['id'];
357                                         }
358                                 }
359                         }
360                 }
361
362                 if ($cid == 0 && $zcid == 0) {
363                         return;
364                 }
365
366                 if ($cid) {
367                         $t = GContact::countCommonFriends($profile_uid, $cid);
368                 } else {
369                         $t = GContact::countCommonFriendsZcid($profile_uid, $zcid);
370                 }
371
372                 if (!$t) {
373                         return;
374                 }
375
376                 if ($cid) {
377                         $r = GContact::commonFriends($profile_uid, $cid, 0, 5, true);
378                 } else {
379                         $r = GContact::commonFriendsZcid($profile_uid, $zcid, 0, 5, true);
380                 }
381
382                 if (!DBA::isResult($r)) {
383                         return;
384                 }
385
386                 $entries = [];
387                 foreach ($r as $rr) {
388                         $entry = [
389                                 'url'   => Contact::magicLink($rr['url']),
390                                 'name'  => $rr['name'],
391                                 'photo' => ProxyUtils::proxifyUrl($rr['photo'], false, ProxyUtils::SIZE_THUMB),
392                         ];
393                         $entries[] = $entry;
394                 }
395
396                 $tpl = Renderer::getMarkupTemplate('widget/remote_friends_common.tpl');
397                 return Renderer::replaceMacros($tpl, [
398                         '$desc'     => L10n::tt("%d contact in common", "%d contacts in common", $t),
399                         '$base'     => System::baseUrl(),
400                         '$uid'      => $profile_uid,
401                         '$cid'      => (($cid) ? $cid : '0'),
402                         '$linkmore' => (($t > 5) ? 'true' : ''),
403                         '$more'     => L10n::t('show more'),
404                         '$items'    => $entries
405                 ]);
406         }
407
408         /**
409          * Insert a tag cloud widget for the present profile.
410          *
411          * @brief Insert a tag cloud widget for the present profile.
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 = \get_app();
420
421                 $uid = intval($a->profile['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 = 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 }