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