summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/flattr.pm
blob: 3aee1eb93320eb1f0631eb58b39b50137c7f17bc (plain)
  1. #!/usr/bin/perl
  2. package IkiWiki::Plugin::flattr;
  3. use warnings;
  4. use strict;
  5. use IkiWiki 3.00;
  6. sub import {
  7. hook(type => "getsetup", id => "flattr", call => \&getsetup);
  8. hook(type => "preprocess", id => "flattr", call => \&preprocess);
  9. hook(type => "format", id => "flattr", call => \&format);
  10. }
  11. sub getsetup () {
  12. return
  13. plugin => {
  14. safe => 1,
  15. rebuild => undef,
  16. },
  17. flattr_userid => {
  18. type => "string",
  19. example => 'joeyh',
  20. description => "userid or user name to use by default for Flattr buttons",
  21. advanced => 0,
  22. safe => 1,
  23. rebuild => undef,
  24. },
  25. }
  26. my %flattr_pages;
  27. sub preprocess (@) {
  28. my %params=@_;
  29. $flattr_pages{$params{destpage}}=1;
  30. my $url=$params{url};
  31. if (! defined $url) {
  32. $url=urlto($params{page}, "", 1);
  33. }
  34. my @fields;
  35. foreach my $field (qw{language uid button hidden category tags}) {
  36. if (exists $params{$field}) {
  37. push @fields, "$field:$params{$field}";
  38. }
  39. }
  40. return '<a class="FlattrButton" href="'.$url.'"'.
  41. (exists $params{title} ? ' title="'.$params{title}.'"' : '').
  42. ' rev="flattr;'.join(';', @fields).';"'.
  43. '>'.
  44. (exists $params{description} ? $params{description} : '').
  45. '</a>';
  46. }
  47. sub format (@) {
  48. my %params=@_;
  49. # Add flattr's javascript to pages with flattr buttons.
  50. if ($flattr_pages{$params{page}}) {
  51. if (! ($params{content}=~s!^(<body[^>]*>)!$1.flattrjs()!em)) {
  52. # no <body> tag, probably in preview mode
  53. $params{content}=flattrjs().$params{content};
  54. }
  55. }
  56. return $params{content};
  57. }
  58. my $js_cached;
  59. sub flattrjs {
  60. return $js_cached if defined $js_cached;
  61. my $js_url='https://api.flattr.com/js/0.5.0/load.js?mode=auto';
  62. if (defined $config{flattr_userid}) {
  63. my $userid=$config{flattr_userid};
  64. $userid=~s/[^-A-Za-z0-9_]//g; # sanitize for inclusion in javascript
  65. $js_url.="&uid=$userid";
  66. }
  67. # This is Flattr's standard javascript snippet to include their
  68. # external javascript file, asynchronously.
  69. return $js_cached=<<"EOF";
  70. <script type="text/javascript">
  71. <!--//--><![CDATA[//><!--
  72. (function() {
  73. var s = document.createElement('script'), t = document.getElementsByTagName('script')[0];
  74. s.type = 'text/javascript';
  75. s.async = true;
  76. s.src = '$js_url';
  77. t.parentNode.insertBefore(s, t);
  78. })();//--><!]]>
  79. </script>
  80. EOF
  81. }
  82. 1