import rt 3.8.10
[freeside.git] / rt / lib / RT / Interface / REST.pm
1 # BEGIN BPS TAGGED BLOCK {{{
2 #
3 # COPYRIGHT:
4 #
5 # This software is Copyright (c) 1996-2011 Best Practical Solutions, LLC
6 #                                          <sales@bestpractical.com>
7 #
8 # (Except where explicitly superseded by other copyright notices)
9 #
10 #
11 # LICENSE:
12 #
13 # This work is made available to you under the terms of Version 2 of
14 # the GNU General Public License. A copy of that license should have
15 # been provided with this software, but in any event can be snarfed
16 # from www.gnu.org.
17 #
18 # This work is distributed in the hope that it will be useful, but
19 # WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21 # General Public License for more details.
22 #
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
26 # 02110-1301 or visit their web page on the internet at
27 # http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
28 #
29 #
30 # CONTRIBUTION SUBMISSION POLICY:
31 #
32 # (The following paragraph is not intended to limit the rights granted
33 # to you to modify and distribute this software under the terms of
34 # the GNU General Public License and is only of importance to you if
35 # you choose to contribute your changes and enhancements to the
36 # community by submitting them to Best Practical Solutions, LLC.)
37 #
38 # By intentionally submitting any modifications, corrections or
39 # derivatives to this work, or any other work intended for use with
40 # Request Tracker, to Best Practical Solutions, LLC, you confirm that
41 # you are the copyright holder for those contributions and you grant
42 # Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
43 # royalty-free, perpetual, license to use, copy, create derivative
44 # works based on those contributions, and sublicense and distribute
45 # those contributions and any derivatives thereof.
46 #
47 # END BPS TAGGED BLOCK }}}
48
49 # lib/RT/Interface/REST.pm
50 #
51
52 package RT::Interface::REST;
53 use strict;
54 use warnings;
55 use RT;
56
57 BEGIN {
58     use base 'Exporter';
59     use vars qw($VERSION @EXPORT);
60
61     $VERSION = do { my @r = (q$Revision: 1.1.1.10 $ =~ /\d+/g); sprintf "%d."."%02d"x$#r, @r };
62
63     @EXPORT = qw(expand_list form_parse form_compose vpush vsplit);
64 }
65
66 sub custom_field_spec {
67     my $self    = shift;
68     my $capture = shift;
69
70     my $CF_char = '[\sa-z0-9_ :()/-]';
71     my $CF_name = $CF_char . '+';
72     $CF_name = '(' . $CF_name . ')' if $capture;
73
74     my $new_style = 'CF\.\{'.$CF_name.'\}';
75     my $old_style = 'C(?:ustom)?F(?:ield)?-'.$CF_name;
76
77     return '(?i:' . join('|', $new_style, $old_style) . ')';
78 }
79
80 sub field_spec {
81     my $self    = shift;
82     my $capture = shift;
83
84     my $field = '[a-z][a-z0-9_-]*';
85     $field = '(' . $field . ')' if $capture;
86
87     my $custom_field = __PACKAGE__->custom_field_spec($capture);
88
89     return '(?i:' . join('|', $field, $custom_field) . ')';
90 }
91
92 # WARN: this code is duplicated in bin/rt.in,
93 # change both functions at once
94 sub expand_list {
95     my ($list) = @_;
96
97     my @elts;
98     foreach (split /\s*,\s*/, $list) {
99         push @elts, /^(\d+)-(\d+)$/? ($1..$2): $_;
100     }
101
102     return map $_->[0], # schwartzian transform
103         sort {
104             defined $a->[1] && defined $b->[1]?
105                 # both numbers
106                 $a->[1] <=> $b->[1]
107                 :!defined $a->[1] && !defined $b->[1]?
108                     # both letters
109                     $a->[2] cmp $b->[2]
110                     # mix, number must be first
111                     :defined $a->[1]? -1: 1
112         }
113         map [ $_, (defined( /^(\d+)$/ )? $1: undef), lc($_) ],
114         @elts;
115 }
116
117 # Returns a reference to an array of parsed forms.
118 sub form_parse {
119     my $state = 0;
120     my @forms = ();
121     my @lines = split /\n/, $_[0];
122     my ($c, $o, $k, $e) = ("", [], {}, "");
123     my $field = __PACKAGE__->field_spec;
124
125     LINE:
126     while (@lines) {
127         my $line = shift @lines;
128
129         next LINE if $line eq '';
130
131         if ($line eq '--') {
132             # We reached the end of one form. We'll ignore it if it was
133             # empty, and store it otherwise, errors and all.
134             if ($e || $c || @$o) {
135                 push @forms, [ $c, $o, $k, $e ];
136                 $c = ""; $o = []; $k = {}; $e = "";
137             }
138             $state = 0;
139         }
140         elsif ($state != -1) {
141             if ($state == 0 && $line =~ /^#/) {
142                 # Read an optional block of comments (only) at the start
143                 # of the form.
144                 $state = 1;
145                 $c = $line;
146                 while (@lines && $lines[0] =~ /^#/) {
147                     $c .= "\n".shift @lines;
148                 }
149                 $c .= "\n";
150             }
151             elsif ($state <= 1 && $line =~ /^($field):(?:\s+(.*))?$/i) {
152                 # Read a field: value specification.
153                 my $f  = $1;
154                 my @v  = ($2);
155                 $v[0] = '' unless defined $v[0];
156
157                 # Read continuation lines, if any.
158                 while (@lines && ($lines[0] eq '' || $lines[0] =~ /^\s+/)) {
159                     push @v, shift @lines;
160                 }
161                 pop @v while (@v && $v[-1] eq '');
162
163                 # Strip longest common leading indent from text.
164                 my $ws = ("");
165                 foreach my $ls (map {/^(\s+)/} @v[1..$#v]) {
166                     $ws = $ls if (!$ws || length($ls) < length($ws));
167                 }
168                 s/^$ws// foreach @v;
169
170                 shift @v while (@v && $v[0] eq '');
171
172                 push(@$o, $f) unless exists $k->{$f};
173                 vpush($k, $f, join("\n", @v));
174
175                 $state = 1;
176             }
177             elsif ($line =~ /^#/) {
178                 # We've found a syntax error, so we'll reconstruct the
179                 # form parsed thus far, and add an error marker. (>>)
180                 $state = -1;
181                 $e = form_compose([[ "", $o, $k, "" ]]);
182                 $e.= $line =~ /^>>/ ? "$line\n" : ">> $line\n";
183             }
184         }
185         else {
186             # We saw a syntax error earlier, so we'll accumulate the
187             # contents of this form until the end.
188             $e .= "$line\n";
189         }
190     }
191     push(@forms, [ $c, $o, $k, $e ]) if ($e || $c || @$o);
192
193     foreach my $l (keys %$k) {
194         $k->{$l} = vsplit($k->{$l}) if (ref $k->{$l} eq 'ARRAY');
195     }
196
197     return \@forms;
198 }
199
200 # Returns text representing a set of forms.
201 sub form_compose {
202     my ($forms) = @_;
203     my (@text, $form);
204
205     foreach my $form (@$forms) {
206         my ($c, $o, $k, $e) = @$form;
207         my $text = "";
208
209         if ($c) {
210             $c =~ s/\n*$/\n/;
211             $text = "$c\n";
212         }
213         if ($e) {
214             $text .= $e;
215         }
216         elsif ($o) {
217             my (@lines, $key);
218
219             foreach my $key (@$o) {
220                 my ($line, $sp, $v);
221                 my @values = (ref $k->{$key} eq 'ARRAY') ?
222                                @{ $k->{$key} } :
223                                   $k->{$key};
224
225                 $sp = " "x(length("$key: "));
226                 $sp = " "x4 if length($sp) > 16;
227
228                 foreach my $v (@values) {
229                     $v = '' unless defined $v;
230                     if ( $v =~ /\n/) {
231                         $v =~ s/^/$sp/gm;
232                         $v =~ s/^$sp//;
233
234                         if ($line) {
235                             push @lines, "$line\n\n";
236                             $line = "";
237                         }
238                         elsif (@lines && $lines[-1] !~ /\n\n$/) {
239                             $lines[-1] .= "\n";
240                         }
241                         push @lines, "$key: $v\n\n";
242                     }
243                     elsif ($line &&
244                            length($line)+length($v)-rindex($line, "\n") >= 70)
245                     {
246                         $line .= ",\n$sp$v";
247                     }
248                     else {
249                         $line = $line ? "$line, $v" : "$key: $v";
250                     }
251                 }
252
253                 $line = "$key:" unless @values;
254                 if ($line) {
255                     if ($line =~ /\n/) {
256                         if (@lines && $lines[-1] !~ /\n\n$/) {
257                             $lines[-1] .= "\n";
258                         }
259                         $line .= "\n";
260                     }
261                     push @lines, "$line\n";
262                 }
263             }
264
265             $text .= join "", @lines;
266         }
267         else {
268             chomp $text;
269         }
270         push @text, $text;
271     }
272
273     return join "\n--\n\n", @text;
274 }
275
276 # Add a value to a (possibly multi-valued) hash key.
277 sub vpush {
278     my ($hash, $key, $val) = @_;
279     my @val = ref $val eq 'ARRAY' ? @$val : $val;
280
281     if (exists $hash->{$key}) {
282         unless (ref $hash->{$key} eq 'ARRAY') {
283             my @v = $hash->{$key} ne '' ? $hash->{$key} : ();
284             $hash->{$key} = \@v;
285         }
286         push @{ $hash->{$key} }, @val;
287     }
288     else {
289         $hash->{$key} = $val;
290     }
291 }
292
293 # "Normalise" a hash key that's known to be multi-valued.
294 sub vsplit {
295     my ($val) = @_;
296     my @words;
297
298     foreach my $line (map {split /\n/} (ref $val eq 'ARRAY') ? @$val : ($val||''))
299     {
300         # XXX: This should become a real parser, ? la Text::ParseWords.
301         $line =~ s/^\s+//;
302         $line =~ s/\s+$//;
303         push @words, split /\s*,\s*/, $line;
304     }
305
306     return \@words;
307 }
308
309 RT::Base->_ImportOverlays();
310
311 1;
312
313 =head1 NAME
314
315   RT::Interface::REST - helper functions for the REST interface.
316
317 =head1 SYNOPSIS
318
319   Only the REST should use this module.