source: trunk/LATMOS-Accounts-Web/lib/LATMOS/Accounts/Web/Model/AttrFormsA.pm @ 2098

Last change on this file since 2098 was 1953, checked in by nanardon, 7 years ago

Add sshPublicKey attribute to user

File size: 11.1 KB
Line 
1package LATMOS::Accounts::Web::Model::AttrFormsA;
2
3use strict;
4use warnings;
5use base 'LATMOS::Accounts::Bases::Attributes';
6use base 'Catalyst::Model';
7use LATMOS::Accounts::Log;
8use Date::Parse;
9use DateTime;
10use DateTime::TimeZone;
11
12=head1 NAME
13
14LATMOS::Accounts::Web::Model::AttrForms - Catalyst Model
15
16=head1 DESCRIPTION
17
18Catalyst Model.
19
20=cut
21
22sub escape {
23    my ($self, $text) = @_;
24    $text ||= '';
25    for ($text) {
26        s/&/&/g;
27        s/</&lt;/g;
28        s/>/&gt;/g;
29        s/"/&quot;/g;
30    }
31    $text;
32}
33
34sub new {
35    my ($class) = @_;
36    bless({}, $class);
37}
38
39# call either OBJ or type + base
40
41sub ACCEPT_CONTEXT {
42    my ($self, $c, $attributes, $base_or_object, $maybe_otype) = @_;
43
44    my $new = LATMOS::Accounts::Bases::Attributes->new($attributes, $base_or_object, $maybe_otype);
45    $new->{c} = $c;
46    $new->{htmlname} = $attributes;
47    $new->{htmlname} =~ s/[\.-]/_/g;
48    $new->{htmlid} = $attributes;
49    $new->{htmlid} =~ s/[\.-]/_/g;
50    $new->{valcount} = 0;
51    $new->{hconfig} = LATMOS::Accounts::Web->config->{attrs}{$attributes} || {};
52    bless($new, __PACKAGE__);
53}
54
55sub htmlname {
56    $_[0]->{htmlname};
57}
58
59sub htmlid {
60    my ($self) = @_;
61
62    if ($self->{valcount}) {
63        return sprintf('%s_%03d', $self->{htmlid}, $self->{valcount});
64    } else {
65        return $_[0]->{htmlid};
66    }
67}
68
69sub htmlnewid {
70    my ($self) = @_;
71
72    $self->{valcount}++;
73
74    return $self->htmlid;
75}
76
77sub hconfig {
78    my ($self, $val) = @_;
79    $self->{hconfig}{$val}
80}
81
82sub attr_label {
83    my ($self, $label, $hint) = @_;
84    $label ||= '';
85   
86    $hint = $self->hconfig('hint');
87
88    return sprintf('<label %sfor="%s">%s</label>',
89        ($hint ? sprintf('title="%s"', $self->escape($hint)) : ''),
90        $self->escape($self->htmlname),
91        $self->escape($self->label || $self->htmlname),
92    );
93}
94
95sub attr_raw_value {
96    my ($self) = @_;
97
98    my @val = grep { $_ } (exists($self->{c}->req->params->{$self->htmlname}))
99        ? ($self->{c}->req->param($self->htmlname))
100        : $self->getValues;
101
102    if (@val) {
103        return @val;
104    } elsif(!$self->object) {
105        return (grep { $_ } ($self->default_value))
106    }
107}
108
109sub attr_field_name {
110    my ($self) = @_;
111
112    $self->htmlname;
113}
114
115sub attr_field {
116    my ($self, $type) = @_;
117
118    # Force Array context:
119    my @attr_raw_value = $self->attr_raw_value;
120    if (!$self->multiple) {
121        push(@attr_raw_value, undef) unless(@attr_raw_value);
122    }
123    my @htmls = ();
124
125    foreach my $attr_raw_value (@attr_raw_value) {
126        $self->htmlnewid;
127        push(@htmls, $self->attr_item($attr_raw_value));
128    }
129
130    if (my $js = $self->attr_js) {
131        push(@htmls,
132            qq[ <script>
133            \$( function() {
134            $js
135            });
136            </script>]
137        );
138    }
139
140    my $addempty = '';
141    if ($self->{multiple} && !$self->readonly) {
142
143        my $old = $self->{valcount} + 1;
144        $self->{valcount} = 999;
145        my $code = $self->attr_item('');
146        $code =~ s/'/\\'/g;
147        $code =~ s/\n/ /gm;
148
149        $addempty = sprintf('<div id="%s_div"></div>', $self->htmlid);
150        $addempty .= "\n";
151        $addempty .= sprintf(q|
152            <button id="%s_add" type="button" style="display:block">+</button>
153            <script type="text/javascript">
154            var cn_%s = %d;
155            $( '#%s_add' ).click(function(even, ui) {
156                $('#%s_div').append('%s'.replace(/%d/g, cn_%s)).append('<br>');
157
158                cn_%s++;
159                %s
160            });
161            </script>
162            |,
163            $self->htmlid,
164            $self->htmlid,
165            $old,
166            $self->htmlid,
167            $self->htmlid,
168            $code,
169            $self->{valcount},
170            $self->htmlid,
171            $self->htmlid,
172            $self->attr_js,
173        );
174
175        $addempty .= "\n";
176
177    }
178
179    return join("<br>\n", @htmls) . $addempty;
180}
181
182sub attr_item {
183    my ($self, $value) = @_;
184
185    my $html = '';
186
187    my $type = 'attr_' . uc($self->form_type);
188
189    if ($self->can($type)) {
190        $html .= $self->$type($value);
191    } else {
192        $html .= $self->attr_TEXT($value);
193    }
194
195    $html .= q|<span class="inputvalidate" id="|. $self->htmlid . q|_check"></span>|;
196
197    if (my $ref = $self->reference) {
198        my $uri_part = $self->_uri_part($ref);
199        if ($self->base->attribute($ref, 'displayName')) {
200            my $text = '';
201            if ($value &&
202                (my $obj = $self->base->get_object($ref, $value))) {
203                $text = $obj->get_attributes('displayName');
204            }
205            #$html .= sprintf(
206                #qq|<span id="${htmlid}_ref" style="margin-left: 1em">$text</span>|,
207                #   $self->escape($text),
208                #);
209        } elsif($value && $uri_part) {
210            $html .= sprintf(
211                '<a href="%s"><img class="attr" src="%s" title="%s"></a>',
212                $self->{c}->uri_for('/', $uri_part, $value),
213                $self->{c}->uri_for('/static', 'images', 'arrow-right.png'),
214                $value,
215            );
216        }
217    }
218
219    $html
220}
221
222sub attr_js {
223    my ($self, $value) = @_;
224
225    my $type = 'attr_' . uc($self->form_type) . '_js';
226
227    if ($self->can($type)) {
228        return $self->$type($value);
229    } else {
230        return '';
231    }
232}
233
234
235sub attr_TEXT {
236    my ($self, $value, $name, $id) = @_;
237
238    return sprintf(
239        '<input type="text" id="%s" name="%s" value="%s" size="%d">',
240        $self->escape($id   || $self->htmlid),
241        $self->escape($name || $self->htmlname),
242        $self->escape($value),
243        $self->form_option('length') || 20,
244    );
245
246}
247
248sub attr_TEXT_js {
249    my ($self) = @_;
250
251    my $html = '';
252
253    if ($self->uniq) {
254        $html .= sprintf(q|
255                $( '[name="%s"]' ).on('input', function() {
256                    var id = $(this).attr('id');
257                    $.ajax({
258                        method: "POST",
259                        url: '%s',
260                        data: { val: $(this).val() },
261                    }). done(function( msg ) {
262                        $( '#' + id + '_check' ).html (msg);
263                    });
264                    return false;
265                });
266        |,
267        $self->htmlname,
268        $self->{c}->uri_for('/ajax', 'objattrexist', $self->otype, $self->name),
269        );
270    }
271
272    $html;
273}
274
275sub attr_LABEL {
276    my ($self, $value) = @_;
277
278    if ($self->real_form_type =~ m/(DATE|DATETIME)/) {
279        if (my $time = str2time($value)) {
280            my $dt = DateTime->from_epoch(epoch => $time);
281            $dt->set_time_zone( DateTime::TimeZone->new( name => 'local' ) );
282            $value = $dt->dmy('/') . ($self->real_form_type eq 'DATE'
283                ? ''
284                : ' ' . $dt->hms(':'));
285        }
286    }
287
288    return $self->escape($value);
289}
290
291sub attr_TEXTAREA {
292    my ($self, $value) = @_;
293    return sprintf(
294        '<textarea id="%s" name="%s" cols="40">%s</textarea>',
295        $self->escape($self->htmlid),
296        $self->escape($self->htmlname),
297        $self->escape($value || ''),
298    );
299}
300
301
302sub attr_DATE {
303    my ($self, $value, $name, $id) = @_;
304
305    if (my $time = str2time($value)) {
306        my $dt = DateTime->from_epoch(epoch => $time);
307        $dt->set_time_zone( DateTime::TimeZone->new( name => 'local' ) );
308        $value = $dt->dmy('/')
309    }
310
311    return sprintf(
312        '<input type="text" id="%s" name="%s" value="%s" size="%d">',
313        $self->escape($id   || $self->htmlid),
314        $self->escape($name || $self->htmlname),
315        $self->escape($value),
316        $self->form_option('length') || 20,
317    );
318}
319
320sub attr_DATE_js {
321    my ($self, $value) = @_;
322    return sprintf(q|
323        $('[name="%s"]').datepicker( {
324            changeMonth: true,
325            changeYear: true,
326            dateFormat: 'dd/mm/yy'
327        } );
328    |, $self->escape($self->htmlname));
329}
330
331sub attr_DATETIME {
332    my ($self, $value, $name, $id) = @_;
333
334    if (my $time = str2time($value)) {
335        my $dt = DateTime->from_epoch(epoch => $time);
336        $dt->set_time_zone( DateTime::TimeZone->new( name => 'local' ) );
337        $value = $dt->dmy('/') . ' ' . $dt->hms(':')
338    }
339
340    return sprintf(
341        '<input type="text" id="%s" name="%s" value="%s" size="%d">',
342        $self->escape($id   || $self->htmlid),
343        $self->escape($name || $self->htmlname),
344        $self->escape($value),
345        $self->form_option('length') || 20,
346    );
347}
348
349sub attr_DATETIME_js {
350    my ($self, $value) = @_;
351    return sprintf(q|
352        $('[name="%s"]').datepicker( {
353            changeMonth: true,
354            changeYear: true,
355            dateFormat: 'dd/mm/yy'
356        } );
357    |, $self->escape($self->htmlname));
358}
359
360sub attr_CHECKBOX {
361    my ($self, $value) = @_;
362    $value ||= '';
363
364    return sprintf('<input type="checkbox" id="%s" name="%s"%s>%s',
365        $self->escape($self->htmlid),
366        $self->escape($self->htmlname),
367        ($value ? '  checked="yes"' : ''),
368        ($self->form_option('rawvalue') ? " $value" : ''),
369    );
370}
371
372sub attr_LIST {
373    my ($self, $value) = @_;
374
375    my @values = $self->can_values;
376    $value ||= '';
377
378    if (@values < 5) {
379        return sprintf(q|<select id="%s" name="%s">%s%s</select>|,
380            $self->htmlid,
381            $self->htmlname,
382            ($self->mandatory ? '' : '<option value="">--</option>'),
383            join(",\n", map { $_ = sprintf('<option value="%s"%s>%s</option>', $_, ($_ eq $value ? ' selected="selected"' : ''), $self->display($_)) } sort $self->can_values),
384        );
385    } else {
386        my $html = $self->attr_TEXT($self->display($value));
387    }
388}
389
390sub attr_LIST_js {
391    my ($self) = @_;
392    return sprintf(q|
393            $('[name="%s"]').autocomplete({
394                delay: 200,
395                minLength: 0,
396                source: '%s',
397            })
398            .autocomplete( "instance" )._renderItem = function( ul, item ) {
399                return $( "<li>" )
400                .append( "<a>" + item.label + " (" + item.value +  ")</a>" )
401                .appendTo( ul );
402            };
403        |,
404        $self->htmlname,
405        $self->{c}->uri_for('/json/refval', $self->otype, $self->name),
406    );
407}
408
409sub _uri_part {
410    my ($self, $ref) = @_;
411    my $uri_part = {
412        user => 'users',
413        group => 'groups',
414        nethost => 'nethosts',
415        netzone => 'netzones',
416        site => 'sites',
417        aliasess => 'aliases',
418    }->{$ref};
419}
420
421sub _attr_js_item {
422    my ($self, $value, $htmlid) = @_;
423
424    $htmlid = $self->htmlid;
425    my (@js);
426
427    if (my $ref = $self->reference) {
428        my $uri_part = $self->_uri_part($ref);
429        if ($self->base->attribute($ref, 'displayName')) {
430            push(@js, 
431                $self->{c}->prototype->observe_field( $htmlid,
432                    {
433                        update => "${htmlid}_ref",
434                        url => $self->{c}->uri_for('/ajax', 'rawattr', $ref),
435                        frequency => 1,
436                        with   => "'attr=displayName&id=' + element.options[element.selectedIndex].text",
437                    }
438                )
439            ) if ($self->form_type =~ /list/i);
440        }
441    }
442
443    return(join("\n", @js));
444}
445
446
447=head1 AUTHOR
448
449Thauvin Olivier
450
451=head1 LICENSE
452
453This library is free software, you can redistribute it and/or modify
454it under the same terms as Perl itself.
455
456=cut
457
4581;
Note: See TracBrowser for help on using the repository browser.