Merge branch 'b-3.6.1' of ../kivitendo-erp_20220811
[kivitendo-erp.git] / SL / Presenter / EscapedText.pm
index 2fc04fd..1c92f6f 100644 (file)
@@ -2,14 +2,23 @@ package SL::Presenter::EscapedText;
 
 use strict;
 use Exporter qw(import);
+use Scalar::Util qw(looks_like_number);
 
-our @EXPORT_OK = qw(escape is_escaped escape_js);
+our @EXPORT_OK = qw(escape is_escaped escape_js escape_js_call);
 our %EXPORT_TAGS = (ALL => \@EXPORT_OK);
 
 use JSON ();
 
 use overload '""' => \&escaped_text;
 
+my %html_entities = (
+  '<' => '&lt;',
+  '>' => '&gt;',
+  '&' => '&amp;',
+  '"' => '&quot;',
+  "'" => '&apos;',
+);
+
 # static constructors
 sub new {
   my ($class, %params) = @_;
@@ -17,11 +26,17 @@ sub new {
   return $params{text} if ref($params{text}) eq $class;
 
   my $self      = bless {}, $class;
-  $self->{text} = $params{is_escaped} ? $params{text} : $::locale->quote_special_chars('HTML', $params{text});
+  $self->{text} = $params{is_escaped} ? $params{text} : quote_html($params{text});
 
   return $self;
 }
 
+sub quote_html {
+  return undef unless defined $_[0];
+  (my $x = $_[0]) =~ s/(["'<>&])/$html_entities{$1}/ge;
+  $x
+}
+
 sub escape {
   __PACKAGE__->new(text => $_[0]);
 }
@@ -40,6 +55,20 @@ sub escape_js {
   __PACKAGE__->new(text => $text, is_escaped => 1);
 }
 
+sub escape_js_call {
+  my ($func, @args) = @_;
+
+  escape(
+      sprintf "%s(%s)",
+      escape_js($func),
+      join ", ", map {
+        looks_like_number($_)
+          ? $_
+          : '"' . escape_js($_) . '"'
+      } @args
+  );
+}
+
 # internal magic
 sub escaped_text {
   my ($self) = @_;
@@ -127,6 +156,18 @@ Static constructor, can be exported. Equivalent to calling C<< new(text => $text
 
 Static constructor, can be exported. Like C<escape> but also escapes Javascript.
 
+=item C<escape_js_call $func_name, @args>
+
+Static constructor, can be exported. Used to construct a javascript call than
+can be used for onclick handlers in other Presenter functions.
+
+For example:
+
+  L.button_tag(
+    P.escape_js_call("kivi.Package.some_func", arg_one, arg_two, arg_three)
+    title
+  )
+
 =back
 
 =head1 METHODS