source: trunk/LATMOS-Accounts/lib/LATMOS/Accounts/Bases/Sql.pm @ 2614

Last change on this file since 2614 was 2614, checked in by nanardon, 3 weeks ago

Switch to schema 41

  • Property svn:keywords set to Id Rev
File size: 28.2 KB
Line 
1package LATMOS::Accounts::Bases::Sql;
2
3use 5.010000;
4use strict;
5use warnings;
6
7use base qw(LATMOS::Accounts::Bases);
8use LATMOS::Accounts::Log;
9use DBI;
10use Crypt::RSA;
11use Crypt::RSA::Key::Public::SSH;
12use Crypt::RSA::Key::Private::SSH;
13use Crypt::RSA::Key::Public;
14use Crypt::RSA::Key::Private;
15use Crypt::Blowfish;
16use MIME::Base64;
17
18our $VERSION = (q$Rev$ =~ /^Rev: (\d+) /)[0];
19
20sub SCHEMA_VERSION { 41 };
21
22=head1 NAME
23
24LATMOS::Ad - Perl extension for blah blah blah
25
26=head1 SYNOPSIS
27
28  use LATMOS::Accounts::Bases;
29  my $base = LATMOS::Accounts::Bases->new('unix');
30  ...
31
32=head1 DESCRIPTION
33
34Account base access over standard unix file format.
35
36=head1 FUNCTIONS
37
38=cut
39
40=head2 SCHEMA_VERSION
41
42Return the SQL schema version to use for this software version.
43
44=head2 new(%config)
45
46Create a new LATMOS::Ad object for windows AD $domain.
47
48domain / server: either the Ad domain or directly the server
49
50ldap_args is an optionnal list of arguments to pass to L<Net::LDAP>.
51
52=cut
53
54sub new {
55    my ($class, %config) = @_;
56   
57    my $base = {
58        db_conn => $config{db_conn},
59    };
60
61    bless($base, $class);
62}
63
64sub DESTROY {
65    my ($self) = @_;
66    $self->{_db} && $self->{_db}->rollback;
67}
68
69=head2 db
70
71Return a L<DBI> handle over database, load it if need.
72
73=cut
74
75sub db {
76    my ($self) = @_;
77
78    if ($self->{_db} && $self->{_db}->ping) {
79        return $self->{_db};
80    } else {
81        $self->{_db} = DBI->connect_cached(
82            'dbi:Pg:' . $self->{db_conn},
83            undef, undef,
84            {
85                RaiseError => 0,
86                AutoCommit => 0,
87                PrintWarn => 1,
88                PrintError => 1,
89            }
90        ) or do {
91            $self->log(LA_ERR, "Cannot connect to database: %s", $DBI::errstr);   
92            return;
93        };
94        $self->{_db}->do(q{set DATESTYLE to 'DMY'});
95        $self->log(LA_DEBUG, 'New connection to DB');
96
97        $self->get_global_value('sambaSID') or do {
98            $self->_setSambaSID;
99            $self->commit;
100        };
101
102        return $self->{_db};
103    }
104}
105
106sub IsSchemaUpToDate {
107    my ($self) = @_;
108
109    my $sv = $self->get_global_value('schema_version') || 1;
110
111    return $sv == SCHEMA_VERSION;
112}
113
114sub SchemaUpgrade {
115    my ($self) = @_;
116
117    if (!$self->IsSchemaUpToDate) {
118        require LATMOS::Accounts::Bases::Sql::upgrade;
119        if ($self->_SchemaUpgrade()) {
120            $self->commit;
121        } else {
122            $self->rollback;
123            return;
124        }
125    } else {
126        return 1;
127    }
128}
129
130=head2 load
131
132Read file and load data into memory
133
134=cut
135
136sub load {
137    my ($self) = @_;
138    if (!$self->db) { return 0 };
139
140    if (!$self->IsSchemaUpToDate) {
141        my $sv = $self->get_global_value('schema_version') || 1;
142        $self->log(LA_ERR, "Schema need update, please run `la-sql-upgrade -b %s'", $self->label); 
143        return;
144    }
145
146    if (!$self->_CreateInternalObjects) {
147        $self->rollback;
148    }
149
150    1;
151}
152
153sub _CreateInternalObjects {
154    my ($self) = @_;
155
156    my $dbi = $self->{_db};
157
158    my @objects = (
159        {
160            name => 'dpmt',
161            otype => 'sutype',
162            attrs => {
163                description => 'Department',
164            },
165        },
166        {
167            name => 'contrattype',
168            otype => 'sutype',
169            attrs => {
170                description => 'Contract',
171            },
172        },
173        {
174            name => '-useralias',
175            otype => 'group',
176            attrs => {
177                description => 'Internal group for user alias object',
178                gidnumber => -1,
179                unexported => 1,
180            },
181            intern => 1,
182        },
183    );
184
185    my $change = 0;
186
187    $self->temp_switch_unexported( sub {
188
189            my $setnodel  = $dbi->prepare('UPDATE objects SET nodelete     = true where name = ? and nodelete     = false');
190            my $setintern = $dbi->prepare('UPDATE objects SET internobject = true where name = ? and internobject = false');
191
192            foreach (@objects) {
193                if (!$self->GetRawObject($_->{otype}, $_->{name})) {
194                    printf("Creating object %s/%s\n", $_->{otype}, $_->{name});
195                    $self->create_object($_->{otype}, $_->{name}, %{$_->{attrs} || {}})
196                        or warn sprintf("cannot create %s/%s\n", $_->{otype}, $_->{name});
197            $change += 1;
198                }
199
200                $change +=  $setnodel->execute($_->{name});
201            $change +=  $setintern->execute($_->{name}) if ($_->{intern});
202            }
203
204    }, 1);
205
206    if ($change > 0) {
207        $self->db->commit;
208    }
209
210    return 1;
211}
212
213=head2 ListInternalObjects($otype)
214
215List objects flags as internal for type C<$otype>
216
217=cut
218
219sub ListInternalObjects {
220    my ($self, $otype) = @_;
221
222    my $pclass = $self->_load_obj_class($otype) or return;
223
224    # Object Alias: checking if object is alias, then returning it:
225    my $sth = $self->db->prepare_cached(
226        sprintf(q{select %s as k from %s where and internobject = true},
227            $self->db->quote_identifier($pclass->_key_field),
228            $self->db->quote_identifier($pclass->_object_table),
229        ),
230    );
231    $sth->execute();
232    my @list;
233    while (my $res = $sth->fetchrow_hashref) {
234       push(@list, $_->{k});
235   }
236   return(@list);
237}
238
239=head2 GetRawObject($otype, $id)
240
241Return an object even it is internal, alias are not follow and even
242unexported object are returned
243
244This function must be used only for maintenance operation.
245
246=cut
247
248sub GetRawObject {
249    my ($self, $otype, $id) = @_;
250
251    my $pclass = $self->_load_obj_class($otype) or return;
252
253    return $self->SUPER::get_object($otype, $id);
254}
255
256sub _derefObject {
257    my ($self, $otype, $oalias) = @_;
258    $oalias or return;
259    if (my ($aliasotype, $aliasoname, $aliasattr) = $oalias =~ m/^([^\/]+)\.([^\.]+)\.(.*)$/) {
260        my $attribute = $self->attribute($aliasotype, $aliasattr) or do {
261            $self->log(LA_DEBUG, "Oalias %s (%s): can fetch attibute %s/%s",
262                $otype, $oalias, $aliasotype, $aliasattr);
263            return;
264        };
265        my $refotype = $attribute->reference or do {
266            $self->log(LA_DEBUG, "Oalias %s (%s): Attribute does not reference an object",
267                $otype, $oalias);
268            return;
269        };
270        $refotype eq $otype or do {
271            $self->log(LA_DEBUG, "Oalias %s (%s): Attribute does not reference same object type",
272                $otype, $oalias, $refotype);
273            return;
274        };
275        my $robj = $self->get_object($aliasotype, $aliasoname) or do {
276            $self->log(LA_DEBUG, "Oalias %s (%s): can fetch object %s/%s",
277                $otype, $oalias, $aliasotype, $aliasoname);
278            return;
279        };
280        my $rvalue = $robj->get_attributes($aliasattr) or do {
281            $self->log(LA_DEBUG, "Oalias %s (%s): attribute value is empty",
282                $otype, $oalias);
283            return;
284        };
285        return $self->get_object($refotype, $rvalue);
286    } else {
287        return $self->get_object( $otype, $oalias )
288    }
289}
290
291sub get_object {
292    my ($self, $otype, $id) = @_;
293
294    my $pclass = $self->_load_obj_class($otype) or return;
295
296    # Object Alias: checking if object is alias, then returning it:
297    my $sth = $self->db->prepare_cached(
298        sprintf(q{select oalias from %s where %s = ? and internobject = false %s},
299            $self->db->quote_identifier($pclass->_object_table),
300            $self->db->quote_identifier($pclass->_key_field),
301            ($self->{wexported} ? '' : 'and exported = true'),
302        ),
303    );
304    $sth->execute($id);
305    my $res = $sth->fetchrow_hashref;
306    $sth->finish;
307    if (my $oalias = $res->{oalias}) {
308        # Cross reference over object/attribute
309        $self->_derefObject($otype, $oalias);
310    } else {
311        return $self->SUPER::get_object($otype, $id);
312    }
313}
314
315=head2 getObjectFromOKey ($okey)
316
317Return the object from the db internal key
318
319=cut
320
321sub getObjectFromOKey {
322    my ($self, $okey) = @_;
323
324    my $findobj = $self->{_db}->prepare_cached(q{
325        select * from objects_table where ikey = ?
326    });
327
328    $findobj->execute($okey);
329
330    my $res = $findobj->fetchrow_hashref;
331    $findobj->finish;
332
333    if ($res) {
334        return $self->get_object($res->{relname}, $res->{name});
335    } else {
336        return;
337    }
338}
339
340sub _sync_dyn_group {
341    my ($self) = @_;
342
343    my @groups = $self->search_objects('group', 'autoMemberFilter=*');
344
345    my $gres = 0;
346    foreach (@groups) {
347        my $g = $self->get_object('group', $_) or next;
348        my $res = $g->populate_dyn_group;
349        $self->log( LA_INFO, "Group Dyn $_ has been updated (res: $res)" ) if ($res);
350        $gres += $res
351    }
352
353    $self->log(LA_DEBUG, "Group Dyn res %d", $gres);
354    $gres
355}
356
357sub _sync_dyn_aliases {
358    my ($self) = @_;
359
360    my @aliases = $self->search_objects('aliases', 'autoMemberFilter=*');
361
362    my $gres = 0;
363    foreach (@aliases) {
364        my $g = $self->get_object('aliases', $_) or next;
365        my $res += $g->populate_dyn_aliases;
366        $self->log( LA_INFO, "Alias Dyn $_ has been updated (res: $res)" ) if ($res);
367        $gres += $res
368    }
369
370    $self->log(LA_DEBUG, "Aliases Dyn res %d", $gres);
371    $gres
372}
373
374=head2 PopulateDynData
375
376Recomputate dynamics attributes (autoMembersFilters) if need
377
378=cut
379
380sub PopulateDynData {
381    my ($self) = @_;
382
383    $self->log(LA_DEBUG, 'Running PopulateDynData()');
384
385    $self->temp_switch_unexported(sub {
386
387        foreach (1 .. 5) {
388            $self->log(LA_DEBUG, "%d loop for PopulateDynData", $_);
389            my $res = 0;
390            $res += $self->_sync_dyn_group   || 0;
391            $res += $self->_sync_dyn_aliases || 0;
392
393            if ($res == 0) {
394                last;
395            }
396        }
397
398        { # Trick for ssh keys
399            my %sshUser = map { $_ => 1 } (
400                $self->search_objects('user', 'authorizedKeys=*', 'oalias=NULL'),
401                $self->search_objects('user', 'sshPublicKeyFilter=*', 'oalias=NULL'),
402                $self->search_objects('user', 'sshPublicKey=*', 'oalias=NULL'),
403            );
404
405            foreach my $user (keys %sshUser) {
406                my $ouser = $self->get_object('user', $user) or next;
407                my $rawold = $ouser->_get_c_field('authorizedKeys');
408                my @old = sort grep { ! /^#/ } grep { defined $_ } ( ref $rawold ? @{ $rawold } : ( $rawold ) );
409                my $rawnew = $ouser->_get_c_field('_authorizedKeys');
410                my @new = sort grep { ! /^#/ } grep { defined $_ } ( ref $rawnew ? @{ $rawnew } : ( $rawnew ) );
411                if ( join( "\n", @old ) ne join( "\n", @new ) ) {
412                    $self->log(LA_INFO, "Updating authorizedKeys from filter for user $user" );
413                    $ouser->set_fields( 'authorizedKeys', $rawnew )
414                }
415            }
416        }
417
418    }, 0);
419
420    return 1;
421}
422
423sub _commit {
424    my ($self) = @_;
425
426    # Let sync-manager update data in background
427    $self->PopulateDynData unless($self->config('ASyncDynData'));
428
429    if ($ENV{LA_NO_COMMIT}) {
430        $self->log(LA_DEBUG, 'DB::COMMIT (ignore due to LA_NO_COMMIT)');
431        return 1;
432    } else {
433        $self->log(LA_DEBUG, 'DB::COMMIT');
434    }
435    $self->{__cache} = undef;
436    $self->db->commit;
437}
438
439sub _rollback {
440    my ($self) = @_;
441    if ($ENV{LA_NO_COMMIT}) {
442        $self->log(LA_DEBUG, 'DB::ROLLBACK (ignore due to LA_NO_COMMIT)');
443        return 1
444    } else {
445        $self->log(LA_DEBUG, 'DB::ROLLBACK');
446    }
447    $self->{__cache} = undef;
448    $self->db->rollback;
449}
450
451sub list_supported_objects {
452    my ($self, @otype) = @_;
453    $self->SUPER::list_supported_objects(qw(site), @otype);
454}
455
456# For SQL listRealObjects != list_objects
457sub listRealObjects {
458    my ($self, $otype) = @_;
459    my $pclass = $self->_load_obj_class($otype) or return;
460    $pclass->listReal($self);
461}
462
463sub key_field {
464    my ( $self, $otype ) = @_;
465
466    my $pclass = $self->_load_obj_class($otype) or return;
467    return $pclass->_key_field;
468}
469
470sub current_rev {
471    my ($self) = @_;
472    my $sth = $self->db->prepare_cached(
473        q{select max(rev) from revisions}
474    );
475    $sth->execute;
476    my $res = $sth->fetchrow_hashref;
477    $sth->finish;
478    return ($res->{max});
479} 
480
481sub authenticate_user {
482    my ($self, $username, $passwd) = @_;
483    $username or return;
484    my $uobj = $self->get_object('user', $username) or do {
485        la_log(LA_ERR, "Cannot authenticate non existing SQL user $username");
486        return;
487    };
488
489    if ($self->attribute('user', 'exported')) {
490        if (!$uobj->_get_c_field('exported')) {
491            la_log(LA_ERR, "User $username found but currently unexported");
492            return;
493        }
494    }
495
496    $self->SUPER::authenticate_user($username, $passwd);
497}
498
499=head1 SPECIFICS FUNCTIONS
500
501=head2 GetAlias($base, $id)
502
503Return object having id C<$id> only if it is an object alias
504
505=cut
506
507sub GetAlias {
508    my ($self, $otype, $id) = @_;
509
510    my $pclass = $self->_load_obj_class($otype) or return;
511
512    # Object Alias: checking if object is alias, then returning it:
513    my $sth = $self->db->prepare_cached(
514        sprintf(q{select oalias from %s where %s = ? and oalias IS NOT NULL and internobject = false %s},
515            $self->db->quote_identifier($pclass->_object_table),
516            $self->db->quote_identifier($pclass->_key_field),
517            ($self->{wexported} ? '' : 'and exported = true'),
518        ),
519    );
520    $sth->execute($id);
521    my $res = $sth->fetchrow_hashref;
522    $sth->finish;
523    if ($res) {
524        return $self->SUPER::get_object($otype, $id);
525    } else {
526        return;
527    }
528}
529
530=head2 CreateAlias($otype, $name, $for)
531
532Create an object alias named C<$name> for ovbject C<$for>
533
534=cut
535
536sub CreateAlias {
537    my ($self, $otype, $name, $for) = @_;
538
539    my $pclass = $self->_load_obj_class($otype) or return;
540
541    $for or die "Cannot create alias without giving object to point";
542
543    my $res = $pclass->CreateAlias($self, $name, $for);
544
545    if ($res) {
546        $self->ReportChange(
547            $otype,
548            $name,
549            $pclass->_get_ikey($self, $name),
550            'Create', "Alias %s %s => %s", $otype, $name, $for
551        );
552        $self->log(LA_DEBUG, "Alias $otype $name => $for created");
553        my $oalias = $self->GetAlias($otype, $name);
554        $oalias->_update_aliases_ptr();
555        return 1;
556    } else {
557        $self->log(LA_ERR, "Error when creating alias $otype $name");
558        return;
559    }
560}
561
562=head2 RenameAlias($otype, $name, $to)
563
564Rename an object alias
565
566=cut
567
568sub RenameAlias {
569    my ($self, $otype, $name, $to) = @_;
570
571    my $pclass = $self->_load_obj_class($otype) or return;
572
573    my $obj = $self->GetAlias($otype, $name) or do {
574        $self->log('Cannot get alias %s/%s for removal', $otype, $name);
575        return;
576    };
577
578    my $sth = $self->db->prepare_cached(sprintf(
579        'UPDATE %s SET %s = ? WHERE %s = ?',
580        $self->db->quote_identifier($pclass->_key_field),
581        $self->db->quote_identifier($pclass->_object_table),
582        $self->db->quote_identifier($pclass->_key_field),
583    ));
584
585    my $res = $sth->execute($to, $name);
586
587    return $res;
588}
589
590=head2 RemoveAlias($otype, $name, $for)
591
592Create an object alias named C<$name> for ovbject C<$for>
593
594=cut
595
596sub RemoveAlias {
597    my ($self, $otype, $name) = @_;
598
599    my $pclass = $self->_load_obj_class($otype) or return;
600
601    my $obj = $self->GetAlias($otype, $name) or do {
602        $self->log('Cannot get alias %s/%s for removal', $otype, $name);
603        return;
604    };
605
606    if ($obj->_get_attributes('internobject')) {
607        # Cannot happend: internal are not fetchable
608        $self->log(LA_ERR,'Cannot delete %s/%s: is an internal object', $pclass->type, $name);
609        return;
610    }
611    if ($obj->_get_attributes('nodelete')) {
612        $self->log(LA_ERR,'Cannot delete %s/%s: is write protected', $pclass->type, $name);
613        return;
614    }
615
616    my $id = $obj->Iid;
617
618    my $sth = $self->db->prepare_cached(sprintf(
619        'DELETE FROM %s WHERE %s = ?',
620        $self->db->quote_identifier($pclass->_object_table),
621        $self->db->quote_identifier($pclass->_key_field),
622    ));
623
624    $obj->_update_aliases_ptr;
625    my $res = $sth->execute($name);
626
627    if ($res) {
628        $self->ReportChange(
629            $otype,
630            $name,
631            $id,
632            'Delete', "Alias %s %s deleted", $otype, $name
633        );
634        $self->log(LA_DEBUG, "Alias $otype $name removed");
635        return 1;
636    } else {
637        $self->log(LA_ERR, "Error when removing alias $otype $name");
638        return;
639    }
640}
641
642=head2 get_global_value ($varname)
643
644Return global value set into base
645
646=cut
647
648sub get_global_value {
649    my ($self, $varname) = @_;
650
651    my $sth = $self->db->prepare_cached(q{
652        select val from settings where varname = ?
653        });
654    $sth->execute($varname);
655    my $res = $sth->fetchrow_hashref;
656    $sth->finish;
657    $res->{val}
658}
659
660=head2 set_global_value ($varname, $value)
661
662Set global value.
663
664=cut
665
666sub set_global_value {
667    my ($self, $varname, $value) = @_;
668    my $sth = $self->db->prepare(q{
669        update settings set val = ? where varname = ?
670        });
671    $sth->execute($value, $varname) == 0 and do {
672        my $sth2 = $self->db->prepare(q{
673            insert into settings (val, varname) values (?,?)
674            });
675        $sth2->execute($value, $varname);
676    };
677}
678
679=head2 del_global_value ($varname)
680
681Delete global value from base
682
683=cut
684
685sub del_global_value {
686    my ($self, $varname) = @_;
687
688    my $sth = $self->db->prepare_cached(q{
689        delete from settings where varname = ?
690        });
691    return $sth->execute($varname);
692}
693
694=head2 generate_rsa_key ($password)
695
696Return public and private peer rsa keys
697
698=cut
699
700sub generate_rsa_key {
701    my ($self, $password) = @_;
702
703    my $rsa = new Crypt::RSA ES => 'PKCS1v15';
704    my ($public, $private) = $rsa->keygen (
705        Identity  => 'LATMOS-Accounts',
706        Size      => 2048,
707        Password  => $password,
708        Verbosity => 0,
709    ) or die $rsa->errstr(); # TODO avoid die
710    return ($public, $private);
711}
712
713=head2 private_key ($password)
714
715Load and return private rsa key
716
717=cut
718
719sub private_key {
720    my ($self, $password) = @_;
721    my $base = $self;
722    my $serialize = $base->get_global_value('rsa_private_key') or return;
723    my $string = decode_base64($serialize);
724    my $privkey = $string =~ /^SSH PRIVATE KEY FILE/
725        ? Crypt::RSA::Key::Private::SSH->new
726        : Crypt::RSA::Key::Private->new;
727    $privkey = $privkey->deserialize(
728        String => [ $string ],
729        Password => $password
730    );
731    $privkey->reveal( Password => $password );
732    $privkey;
733}
734
735=head2 get_rsa_password
736
737Return hash with peer username => encryptedPassword
738
739=cut
740
741sub get_rsa_password {
742    my ($self) = @_;
743    my $base = $self;
744    my $sth = $base->db->prepare(q{
745        select "name", value from "user" join user_attributes_base
746        on "user".ikey = user_attributes_base.okey
747        where user_attributes_base.attr = 'encryptedPassword'
748    });
749    $sth->execute;
750    my %users;
751    while (my $res = $sth->fetchrow_hashref) {
752        $users{$res->{name}} = $res->{value};
753    }
754    %users
755}
756
757=head2 store_rsa_key ($public, $private)
758
759Store public and private RSA key info data base
760
761=cut
762
763sub store_rsa_key {
764    my ($self, $public, $private) = @_;
765    my $base = $self;
766    $private->hide;
767    $base->set_global_value('rsa_private_key',
768        encode_base64($private->serialize));
769    $base->set_global_value('rsa_public_key',
770        $public->serialize);
771    return;
772}
773
774=head2 find_next_expire_users ($expire)
775
776Search user expiring in C<$expire> delay
777
778=cut
779
780sub find_next_expire_users {
781    my ($self, $expire) = @_;
782
783    my $sth= $self->db->prepare(q{
784        select name from "user" where
785            expire < now() + ?::interval
786            and expire > now()
787            and expire is not null
788            and internobject = false
789            } . ($self->{wexported} ? '' : 'and exported = true') . q{
790            order by expire
791        }
792    );
793    $sth->execute($expire || '1 month');
794    my @users;
795    while (my $res = $sth->fetchrow_hashref) {
796        push(@users, $res->{name});
797    }
798    @users
799}
800
801=head2 sambaSID($id)
802
803Return the base samba SID set in the config or a default one if none is set.
804
805If C<$id> is given return the full SID suitable for an object.
806
807=cut
808
809sub sambaSID {
810    my ($self, $id) = @_;
811
812    my $ssid = $self->get_global_value('sambaSID');
813    if (defined($id)) {
814        $ssid .= '-' . $id;
815    }
816    return $ssid;
817}
818
819sub _setSambaSID {
820    my ( $self ) = @_;
821
822    my $sid = sprintf(
823        'S-1-5-21-%d-%d',
824        int(rand 1000000000),
825        int(rand 1000000000),
826    );
827
828    $self->set_global_value( 'sambaSID', $sid );
829    return $sid;
830}
831
832
833
834=head2 find_expired_users ($expire)
835
836Return list of user going to expires in C<$expire> delay
837
838=cut
839
840sub find_expired_users {
841    my ($self, $expire) = @_;
842
843    my $sth= $self->db->prepare(q{
844        select name from "user" where
845            expire < now() - ?::interval
846            and expire is not null
847            and internobject = false
848        } . ($self->{wexported} ? '' : 'and exported = true') . q{
849            order by expire
850        }
851    );
852    $sth->execute($expire || '1 second');
853    my @users;
854    while (my $res = $sth->fetchrow_hashref) {
855        push(@users, $res->{name});
856    }
857    @users
858}
859
860=head2 rename_nethost ($nethostname, $to, %config)
861
862Facility function to rename computer to new name
863
864=cut
865
866sub rename_nethost {
867    my ($self, $nethostname, $to, %config) = @_;
868    {
869        my $obj = $self->get_object('nethost', $nethostname) or do {
870            $self->log(LA_ERR, 'Unable to rename non exisant host %s', $nethostname);
871            return;
872        };
873        $obj->_delAttributeValue(cname => $to);
874    }
875    $self->rename_object('nethost', $nethostname, $to) or return;
876    if ($config{'addcname'}) {
877        my $obj = $self->get_object('nethost', $to);
878        $obj->_addAttributeValue(cname => $nethostname);
879    }
880    return 1;
881}
882
883=head2 nethost_exchange_ip ($ip1, $ip2)
884
885Exchange ip1 with ip2 in base
886
887=cut
888
889sub nethost_exchange_ip {
890    my ($self, $ip1, $ip2) = @_;
891    my ($obj1, $obj2);
892    if (my ($host1) = $self->search_objects('nethost', "ip=$ip1")) {
893        $obj1 = $self->get_object('nethost', $host1);
894    } else {
895        $self->log(LA_ERR, "Cannot find host having $ip1");
896        return;
897    }
898    if (my ($host2) = $self->search_objects('nethost', "ip=$ip2")) {
899        $obj2 = $self->get_object('nethost', $host2);
900    } else {
901        $self->log(LA_ERR, "Cannot find host having $ip2");
902        return;
903    }
904    if ($obj1->id eq $obj2->id) {
905        $self->log(LA_ERR, "Both ip belong to same host (%s)", $obj1->id);
906        return;
907    }
908
909    $self->log(LA_NOTICE, "Exchanging IP between %s and %s", $obj1->id, $obj2->id);
910    $obj1->delAttributeValue('ip', $ip1) ;
911    $obj2->delAttributeValue('ip', $ip2) ;
912    $obj1->addAttributeValue('ip', $ip2) ;
913    $obj2->addAttributeValue('ip', $ip1) ;
914    return 1;
915}
916
917=head1 ATTRIBUTES FUNCTIONS
918
919=cut
920
921sub obj_attr_allowed_values {
922    my ($self, $otype, $attr) = @_;
923    if (my @values = $self->SUPER::obj_attr_allowed_values($otype, $attr)) {
924        return @values;
925    } else {
926        $self->ListAttrValue($otype, $attr);
927    }
928}
929
930=head2 ListAttrValue($otype, $attribute)
931
932List values allow for an attribute set into SQL database
933
934=cut
935
936sub ListAttrValue {
937    my ($self, $otype, $attr) = @_;
938
939    my @sqlvalues;
940    my $getAllow = $self->db->prepare_cached(q{
941        SELECT * FROM attributes_values WHERE otype = ? AND attributes = ?
942        ORDER BY "value"
943    });
944    $getAllow->execute($otype, $attr);
945    while (my $res = $getAllow->fetchrow_hashref) {
946        push(@sqlvalues, $res->{value});
947    }
948    return @sqlvalues;
949}
950
951=head2 AddAttrValue($otype, $attr, @values)
952
953Add given values to allowed attribute list
954
955=cut
956
957sub AddAttrValue {
958    my ($self, $otype, $attr, @values) = @_;
959   
960    my $addAllow = $self->db->prepare_cached(q{
961        INSERT INTO attributes_values (otype, attributes, "value") values (?,?,?)
962    });
963   
964    foreach my $value (@values) {
965        if ($addAllow->execute($otype, $attr, $value)) {
966        } else {
967            $self->rollback;
968            return;
969        }
970    }
971
972    return 1;
973}
974
975=head2 DelAttrValue
976
977Delete a
978
979=cut
980
981sub DelAttrValue {
982    my ($self, $otype, $attr, @values) = @_;
983
984    if (@values) {
985        my $delAllow = $self->db->prepare_cached(q{
986            DELETE FROM attributes_values WHERE otype = ? and attributes = ? and "value" = ?
987        });
988
989        foreach my $value (@values) {
990
991            if ($delAllow->execute($otype, $attr, $value)) {
992            } else {
993                $self->rollback;
994                return;
995            }
996
997        }
998        return 1;
999    } else {
1000        my $delAllow = $self->db->prepare_cached(q{
1001            DELETE FROM attributes_values WHERE otype = ? and attributes = ?
1002        });
1003        if ($delAllow->execute($otype, $attr)) {
1004            return 1;
1005        } else {
1006            $self->rollback;
1007            return;
1008        }
1009    }
1010}
1011
1012=head2 getEmploymentRange
1013
1014Return date range within employment can be found in database
1015
1016=cut
1017
1018sub getEmploymentRange {
1019    my ($self, @filters) = @_;
1020
1021    my ($min,$max);
1022
1023    if (@filters) {
1024        my @flist = $self->search_objects('employment', @filters);
1025        my $minSql = $self->db->prepare(q{
1026            SELECT min(firstday) as min FROM employment
1027            WHERE name = ANY (?)
1028        });
1029        $minSql->execute(\@flist);
1030        if (my $res = $minSql->fetchrow_hashref) {
1031            $min = $res->{min}
1032        }
1033        my $maxSql = $self->db->prepare(q{
1034            SELECT max(lastday) as max FROM employment
1035            WHERE name = ANY (?)
1036        });
1037        $maxSql->execute(\@flist);
1038        if (my $res = $maxSql->fetchrow_hashref) {
1039            $max = $res->{max}
1040        }
1041    } else {
1042        my $minSql = $self->db->prepare(q{
1043            SELECT min(firstday) as min FROM employment
1044        });
1045        $minSql->execute;
1046        if (my $res = $minSql->fetchrow_hashref) {
1047            $min = $res->{min}
1048        }
1049        my $maxSql = $self->db->prepare(q{
1050            SELECT max(lastday) as max FROM employment
1051        });
1052        $maxSql->execute;
1053        if (my $res = $maxSql->fetchrow_hashref) {
1054            $max = $res->{max}
1055        }
1056    }
1057
1058    return ($min,$max);
1059}
1060
1061sub ReportChange {
1062    my ($self, $otype, $name, $ref, $changetype, $message, @args) = @_;
1063
1064    my $sthmodifiedby = $self->db->prepare(q{
1065        UPDATE objects set modifiedby = ? where ikey = ?
1066    });
1067
1068    $sthmodifiedby->execute(
1069        $self->LogUser,
1070        $ref,
1071    );
1072
1073    my ($potype, $pname, $pikey);
1074
1075    if (my $obj = $self->get_object($otype, $name)) {
1076        if (my $parent = $obj->ParentObject) {
1077            $potype = $parent->type;
1078            $pname  = $parent->id;
1079            $pikey  = $parent->Iid; 
1080        }
1081    }
1082
1083    my $sth = $self->db->prepare(q{
1084        INSERT into objectslogs (ikey, irev, otype, name, changetype, username, message, parentotype, parentname, parentikey)
1085        VALUES (?,?,?,?,?,?,?,?,?,?)
1086        });
1087
1088    $sth->execute(
1089        $ref,
1090        $self->current_rev,
1091        $otype,
1092        $name,
1093        $changetype,
1094        $self->LogUser,
1095        sprintf($message, @args),
1096        $potype, $pname, $pikey,
1097    );
1098}
1099
1100=head2 getobjectlogs($otype, @names)
1101
1102Return logs for object type C<$otype> having C<$name>.
1103
1104=cut 
1105
1106sub getobjectlogs {
1107    my ($self, $otype, @names) = @_;
1108
1109    my $sth = $self->db->prepare(q{
1110        select ikey from objectslogs where
1111            (otype = $1 and name  = $2)
1112        group by ikey
1113    });
1114    my @ids;
1115    foreach my $name (@names) {
1116        $sth->execute($otype, $name);
1117        while (my $res = $sth->fetchrow_hashref) {
1118            push(@ids, $res->{ikey});
1119        }
1120    }
1121    @ids or return;
1122
1123    my $sth2 = $self->db->prepare(
1124        q{
1125            select * from objectslogs where ikey = ANY ($1)
1126                or parentikey = ANY ($1)
1127            order by logdate asc
1128        },
1129    );
1130
1131    $sth2->execute( \@ids );
1132    my @logs;
1133    while (my $res = $sth2->fetchrow_hashref) {
1134        push(@logs, $res);
1135    }
1136
1137    return @logs;
1138}
1139
1140=head2 getlogs
1141
1142Return logs for last year
1143
1144=cut
1145
1146sub getlogs {
1147    my ($self) = @_;
1148    my $sth2 = $self->db->prepare(
1149        q{
1150            select * from objectslogs
1151            where logdate > now() - '1 year'::interval
1152            order by logdate asc
1153        },
1154    );
1155
1156    $sth2->execute();
1157    my @logs;
1158    while (my $res = $sth2->fetchrow_hashref) {
1159        push(@logs, $res);
1160    }
1161
1162    return @logs;
1163}
1164
11651;
1166
1167__END__
1168
1169=head1 SEE ALSO
1170
1171=head1 AUTHOR
1172
1173Olivier Thauvin, E<lt>olivier.thauvin@latmos.ipsl.frE<gt>
1174
1175=head1 COPYRIGHT AND LICENSE
1176
1177Copyright (C) 2008, 2009 CNRS SA/CETP/LATMOS
1178
1179This library is free software; you can redistribute it and/or modify
1180it under the same terms as Perl itself, either Perl version 5.10.0 or,
1181at your option, any later version of Perl 5 you may have available.
1182
1183
1184=cut
Note: See TracBrowser for help on using the repository browser.