source: trunk/LATMOS-Accounts-Web/lib/LATMOS/Accounts/Web/Model/AttrForms.pm @ 1291

Last change on this file since 1291 was 1291, checked in by nanardon, 9 years ago

Add comment attribute label

File size: 17.5 KB
Line 
1package LATMOS::Accounts::Web::Model::AttrForms;
2
3use strict;
4use warnings;
5use base 'Catalyst::Model';
6use LATMOS::Accounts::Log;
7use HTML::Prototype;
8
9=head1 NAME
10
11LATMOS::Accounts::Web::Model::AttrForms - Catalyst Model
12
13=head1 DESCRIPTION
14
15Catalyst Model.
16
17=cut
18
19my $forms = {
20    usersys => {
21        name => 'SystÚme',
22        attrs => [ qw(
23            sn givenName description
24            comment
25            uid uidNumber gidNumber gecos homeDirectory loginShell
26            mail initials nickname
27            expire
28            locked
29            create
30            date
31        ) ],
32    },
33    user => {
34        name => 'Statut RH',
35        attrs => [ qw(
36            sn givenName description
37            comment
38            company
39            department
40            manager
41            managerContact
42            contratType
43            expire
44            snNative
45            givenNameNative
46            wWWHomePage
47            halReference
48            create
49            date
50        ) ],
51    },
52    useraddress => {
53        name => 'Adresse',
54        attrs => [ qw(
55            initials
56            mail
57        ) ],
58    },
59    usermy => {
60        name => 'My',
61        attrs => [ qw(
62            snNative
63            givenNameNative
64            wWWHomePage
65            halReference
66        ) ],
67    },
68    site => {
69        name => 'Site',
70        attrs => [ qw(
71            description
72            siteNick
73            streetAddress
74            postOfficeBox
75            postalCode
76            l
77            st
78            co
79            facsimileTelephoneNumber
80            create
81            date
82        ) ],
83    },
84    address => {
85        name => 'Adresse',
86        attrs => [ qw(
87            isMainAddress
88            telephoneNumber
89            streetAddress
90            postOfficeBox
91            postalCode
92            l
93            st
94            physicalDeliveryOfficeName
95            site
96            co
97            unexported
98            description
99        ) ],
100    },
101    group => {
102        name => 'SystÚme',
103        attrs => [ qw(
104            gidNumber
105            description label
106            comment
107            managedBy
108            managedAlsoBy
109            autoMemberFilter
110            sutype
111            create
112            date
113        ) ],
114    },
115    nethost => {
116        name => 'Ordinateur',
117        attrs => [ qw(
118            name
119            description
120            comment
121            serialNumber
122            encryptKey
123            owner
124            user
125            ip
126            macaddr
127            puppetClass
128            noInheritPuppet
129            noDynamic
130            cname
131            otherName
132            reverse
133            create
134            date
135            unexported
136            sshfp
137        ) ],
138    },
139    netzone => {
140        name => 'Zone réseau',
141        attrs => [ qw(
142            name
143            description
144            type
145            net
146            netExclude
147            puppetClass
148            outputD
149            templateD
150            site
151            allow_dyn
152            dynFrom
153            domain
154            ipCount
155            freeIPCount
156            create
157            date
158            dnsRevision
159            lastUpdate
160            unexported
161        ) ],
162    },
163    aliases => {
164        name => 'Alias mail',
165        attrs => [ qw(
166            forward
167            expire
168            description
169            comment
170            finalpoint
171            parents
172            created
173            date
174            unexported
175        )],
176    },
177};
178
179sub escape {
180    my ($self, $text) = @_;
181    $text ||= '';
182    for ($text) {
183        s/&/&/g;
184        s/</&lt;/g;
185        s/>/&gt;/g;
186        s/"/&quot;/g;
187    }
188    $text;
189}
190
191sub new {
192    my ($class) = @_;
193    bless({}, $class);
194}
195
196# call either OBJ or type + base
197
198sub ACCEPT_CONTEXT {
199    my ($self, $c, $form, $object, $base) = @_;
200    my $new = {};
201    $new->{c} = $c;
202    $new->{form} = $form;
203    $new->{object} = $object if (ref $object);
204    $new->{base} = $base || (ref $object ? $object->base : undef) or return $self;
205    $new->{otype} = ref $object ? $object->type : $object;
206    bless($new, __PACKAGE__);
207}
208
209sub base {
210    my ( $self ) = @_;
211    $self->{base}
212}
213
214sub otype {
215    my ($self) = @_;
216    $self->{otype};
217}
218
219sub label {
220    my ($self) = @_;
221    $forms->{$self->{form}}->{name} || ''
222}
223
224sub attributes {
225    my ($self, $for) = @_;
226    grep { $_ }
227    grep { $self->base->attribute($self->otype, $_) }
228    @{ $forms->{$self->{form}}->{attrs} };
229}
230
231sub attr_label {
232    my ($self, $attr, $label, $hint) = @_;
233    $label ||= '';
234    $hint ||= '';
235    LATMOS::Accounts::Web->config->{attrs} ||= {};
236    my $attribute = $self->base->attribute($self->otype, $attr);
237    my $htmlname = $self->escape($self->attr_field_name($attr));
238    if (my $attr_config = LATMOS::Accounts::Web->config->{attrs}{$attr}) {
239        $label ||= $attr_config->{label} || '';
240        #utf8::is_utf8($label) && utf8::encode($label);
241        $hint ||= $attr_config->{hint} || '';
242        #utf8::is_utf8($hint) && utf8::encode($hint);
243    }
244    return sprintf('<label %sfor="%s">%s</label>',
245        ($hint ? sprintf('title="%s"', $self->escape($hint)) : ''),
246        $self->escape($htmlname),
247        $self->escape($label || $attr),
248    );
249}
250
251sub attr_hint {
252    my ($self, $attr) = @_;
253    LATMOS::Accounts::Web->config->{attrs} ||= {};
254    if (my $attr_config = LATMOS::Accounts::Web->config->{attrs}{$attr}) {
255        return $attr_config->{hint} || '';
256    }
257    return;
258}
259
260sub attr_raw_value {
261    my ($self, $attribute) = @_;
262    my @val = grep { $_ } 
263        ($self->{c}->req->param($attribute->name))
264        || ($self->{object}
265            ? ($self->{object}->get_attributes($attribute->name))
266            : ());
267
268    if (@val) {
269        return @val;
270    } else {
271        return (grep { $_ } ($attribute->default_value))
272    }
273}
274
275sub attr_field_name {
276    my ($self, $attr) = @_;
277    my $id = $self->{object}
278        ? ($self->{object}->id || '')
279        : '';
280    $id .= '_' if ($id);
281    $id =~ s/\./_/g;
282    $id =~ s/-/_/g;
283    $id . $attr;
284}
285
286sub attr_item {
287    my ($self, $attribute, $value, $htmlid) = @_;
288
289    my $html = $self->_attr_item($attribute, $value, $htmlid);
290   
291    if ($attribute->uniq) {
292        $html .= qq|<span class="inputvalidate" id="${htmlid}_uniq"></span>|;
293    }
294    if (my $ref = $attribute->reference) {
295        my $uri_part = $self->_uri_part($ref);
296        if ($self->base->attribute($ref, 'displayName')) {
297            my $text = '';
298            if ($value &&
299                (my $obj = $self->base->get_object($ref, $value))) {
300                $text = $obj->get_attributes('displayName');
301            }
302            $html .= sprintf(
303                qq|<span id="${htmlid}_ref" style="margin-left: 1em">$text</span>|,
304                $self->escape($text),
305            );
306        } elsif($value && $uri_part) {
307            $html .= sprintf(
308                '<a href="%s"><img class="attr" src="%s" title="%s"></a>',
309                $self->{c}->uri_for('/', $uri_part, $value),
310                $self->{c}->uri_for('/static', 'images', 'arrow-right.png'),
311                $value,
312            );
313        }
314    }
315
316    $html
317}
318
319sub _attr_item {
320    my ($self, $attribute, $value, $htmlid) = @_;
321
322    my $htmlname = $self->escape($self->attr_field_name($attribute->name));
323    $htmlid ||= $htmlname;
324
325    for ($attribute->form_type) {
326            /^textarea$/i and do {
327                return sprintf(
328                    '<textarea id="%s" name="%s" cols="40">%s</textarea>',
329                    $self->escape($htmlid),
330                    $self->escape($htmlname),
331                    $self->escape($value || ''),
332                );
333                last;
334            };
335
336            /^label$/i and do {
337                $value or last;
338                my $html_field = $self->escape($value);
339                $html_field =~ s/\n/<br>/g;
340                $html_field .= sprintf('<input type="hidden" name="%s" value="%s">',
341                    $self->escape($htmlname), ($value || ''));
342                return $html_field;
343                last;
344            };
345
346            /^date$/i and do {
347                my ($date, $time) = split(/ /, $value || '');
348                if ($date && $date =~ /^(\d+)-(\d+)-(\d+)$/) {
349                    $date = "$3/$2/$1";
350                }
351                my $html = "\n" . q{<SCRIPT LANGUAGE="JavaScript" ID="js13">
352                var cal13 = new CalendarPopup();
353                </SCRIPT>} . "\n";
354                $html .= sprintf(
355                    '<input type="text" id="%s" name="%s" value="%s" size="12">',
356                    $self->escape($htmlid),
357                    $self->escape($htmlname),
358                    $self->escape($date)
359                );
360                $html .= q{<DIV ID="testdiv1" STYLE="position:absolute;visibility:hidden;background-color:white;layer-background-color:white;"></DIV>};
361                $html .= qq|
362                <A HREF="#"
363                    onClick="cal13.select(document.getElementById('$htmlid'),'${htmlid}_anc','dd/MM/yyyy');return false;"
364                    TITLE="Date"
365                    NAME="${htmlid}_anc" ID="${htmlid}_anc">
366                    <img class="attr" src="| . $self->{c}->uri_for(qw(/static images view-calendar-day.png))
367                    . qq{" style="ref"></A>
368                    } . "\n";
369                return $html;
370                last;
371            };
372
373            /^checkbox/i and do {
374                my $options = $1 || '';
375                my $html = sprintf('<input type="checkbox" id="%s" name="%s"%s>',
376                    $htmlid,
377                    $self->escape($htmlname),
378                    $value ? '  checked="yes"' : ''
379                ); 
380                $html .= sprintf('<input type="hidden" name="%s">',
381                    $self->escape($htmlname));
382                if ($attribute->form_option('rawvalue')) {
383                    $html .= $value
384                        ? ' ' . $value
385                        : ''; 
386                }
387                return $html;
388                last;
389            };
390
391            /^LIST/i and do {
392                my $select = sprintf('<select id="%s" name="%s">',
393                    $self->escape($htmlid),
394                    $self->escape($htmlname)) . "\n";
395                $select .= '<option value="">--</option>' . "\n"
396                    unless($attribute->mandatory);
397                $value ||= '';
398                my $initial_observed = '';
399                my @valslist;
400                foreach my $val (sort $attribute->can_values) {
401                    push(@valslist, {
402                        val => $val,
403                        disp => $attribute->display($val || ''),
404                    });
405                }
406                foreach (sort { $a->{disp} cmp $b->{disp} } @valslist) {
407                    $select .= sprintf(
408                        '    <option value="%s"%s>%s</option>',
409                        $self->escape($_->{val} || ''),
410                        $value eq $_->{val} ? ' selected="selected"' : '',
411                        $self->escape($_->{disp} || ''),
412                    );
413                    $select .= "\n";
414                }
415                $select .= "</select>\n";
416
417                return $select;
418                last;
419            };
420
421            /^text/i and do {
422                return sprintf(
423                    '<input type="text" id="%s" name="%s" value="%s" size="%d">',
424                    $self->escape($htmlid),
425                    $self->escape($htmlname),
426                    $self->escape($value),
427                    $attribute->form_option('length') || 30,
428                );
429                last;
430            };
431        }
432    return '';
433}
434
435sub _uri_part {
436    my ($self, $ref) = @_;
437    my $uri_part = {
438        user => 'users',
439        group => 'groups',
440        nethost => 'nethosts',
441        netzone => 'netzones',
442        site => 'sites',
443        aliasess => 'aliases',
444    }->{$ref};
445}
446
447sub attr_js {
448    my ($self, $attribute, $value, $htmlid) = @_;
449
450    my (@js);
451
452    if (my $ref = $attribute->reference) {
453        my $uri_part = $self->_uri_part($ref);
454        if ($self->base->attribute($ref, 'displayName')) {
455            push(@js, 
456                $self->{c}->prototype->observe_field( $htmlid,
457                    {
458                        update => "${htmlid}_ref",
459                        url => $self->{c}->uri_for('/ajax', 'rawattr', $ref),
460                        frequency => 1,
461                        with   => "'attr=displayName&id=' + element.options[element.selectedIndex].text",
462                    }
463                )
464            ) if ($attribute->form_type =~ /list/i);
465        }
466    }
467
468    if ($attribute->uniq) {
469        push(@js,
470            $self->{c}->prototype->observe_field( $htmlid,
471                {
472                    update => "${htmlid}_uniq",
473                    url => $self->{c}->uri_for('/ajax', 'objattrexist',
474                        $self->otype, $attribute->name),
475                    frequency => 1,
476                    with => "'val='+element.value" .
477                    ($self->{object} ?
478                        "+'&exclude=" . ($self->{object}->id || '') . "'" 
479                        : ''),
480                }
481            )
482        );
483    }
484
485    return(join("\n", @js));
486}
487
488sub attr_field {
489    my ($self, $attr, $type) = @_;
490
491    my $attribute;
492    if ($type) {
493        if (ref $type) {
494            $attribute = $self->base->attribute(
495                $self->otype,
496                { %$type, name => $attr },
497            );
498        } else {
499            $attribute =  $self->base->attribute(
500                $self->otype,
501                { formtype => $type , name => $attr },
502            );
503        }
504    } else {
505        if ($self->{object}) {
506            $attribute = $self->{object}->attribute($attr);
507        } else {
508            $attribute = $self->base->attribute(
509                $self->otype, $attr,
510                { formtype => $type }
511            );
512        }
513    }
514    $attribute ||= $self->base->attribute($self->otype, { name => $attr });
515
516
517    my $htmlname = $self->escape($self->attr_field_name($attr));
518
519    my @html_fields;
520
521    # Force Array context:
522    my @attr_raw_value = ();
523
524    if ($attribute->multiple) {
525        @attr_raw_value = grep { $_ } $self->attr_raw_value($attribute);
526    } else {
527        my ($val) = $self->attr_raw_value($attribute);
528        @attr_raw_value = ($val || '');
529    }
530
531    foreach my $attr_raw_value (@attr_raw_value) {
532
533        my $html_id = $htmlname .
534            (scalar(@html_fields) ? scalar(@html_fields) : '');
535        push(@html_fields,
536            join("\n",
537                $self->attr_item(
538                    $attribute, $attr_raw_value, $html_id
539                ),
540                $self->attr_js(
541                    $attribute, $attr_raw_value, $html_id
542                )
543            )
544        );
545    }
546
547    if ($attribute->{multiple} && !$attribute->readonly) {
548        my $html_id = $htmlname . '_m_SUBID';
549
550        my $attr = $self->attr_item($attribute, '', $html_id);
551        # JS: string are on the line only
552        $attr =~ s/\n//mg;
553        $attr =~ s/'/\'/g;
554
555        my $js = $self->attr_js($attribute, '', 'NANAR');
556        $js =~ s!'NANAR([_\w]*)'!('$html_id$1'.replace(/SUBID/g, cn))!gm;
557        $js =~ s!<script[^>]+>!!gm;
558        $js =~ s!</script>!!gm;
559        $js =~ s!-->!!gm;
560        $js =~ s/<!--//gm;
561
562        my $addempty = sprintf('<div id="%s"></div>', "${htmlname}_div_0");
563        $addempty .= "\n";
564        $addempty .= sprintf(qq#
565            <script type="text/javascript">
566            var cn_${htmlname} = 0;
567            function add_${htmlname} () {
568            cn_${htmlname}++;
569            // It work only using temporary variable
570            var cn = cn_${htmlname};
571            document.getElementById('${htmlname}_div_' + (cn - 1)).innerHTML +=
572                '$attr'.replace(/SUBID/g, cn );
573            document.getElementById('${htmlname}_div_' + (cn - 1)).innerHTML +=
574                '<div id="${htmlname}_div_'+ cn +'" style="display:block"></div>';
575            %s
576            }
577            </script>
578            #, $js
579        );
580
581        $addempty .= "\n";
582        $addempty .=
583            qq|<button type="button" style="display:block" onclick="add_${htmlname}()">+</button>|,
584
585        push(@html_fields, $addempty);
586    }
587
588    return join("<br>\n", @html_fields);
589}
590
591sub submit {
592    my ($self) = @_;
593    return sprintf(
594        '<input type="submit" name="%s" value="Enregistrer">',
595        $self->escape($self->label),
596    );
597}
598
599sub write_attributes {
600    my ($self) = @_;
601    my @attrs;
602    foreach ($self->attributes) {
603        my $attr = ($self->{object}
604            ? $self->{object}->attribute($_)
605            : $self->base->attribute($self->otype, $_)) or next;
606        $attr->readonly and next;
607        push(@attrs, $_);
608    }
609    @attrs;
610}
611
612sub set_attrs {
613    my ($self, $attrs) = @_;
614    $self->{c}->req->param($self->label) || $attrs or return;
615    my $prefix = $self->attr_field_name('');
616    my %fields;
617    foreach ($attrs ? @{ $attrs } : $self->write_attributes) {
618        my $attr = ($self->{object}
619            ? $self->{object}->attribute($_)
620            : $self->base->attribute($self->otype, $_)) or next;
621        if ($attr->{multiple}) {
622            $fields{$_} = [ grep { $_ } $self->{c}->req->param("$prefix$_") ];
623        } else {
624            $fields{$_} = $self->{c}->req->param("$prefix$_");
625        }
626    }
627    $self->{object}->set_c_fields(%fields) or do {
628        $self->{c}->stash->{page}{error} =
629            LATMOS::Accounts::Log::lastmessage(LA_ERR);
630        $self->{object}->base->rollback;
631        return;
632    };
633    $self->{object}->base->commit;
634}
635
636=head1 AUTHOR
637
638Thauvin Olivier
639
640=head1 LICENSE
641
642This library is free software, you can redistribute it and/or modify
643it under the same terms as Perl itself.
644
645=cut
646
6471;
Note: See TracBrowser for help on using the repository browser.