Annotation of loncom/LONCAPA.pm, revision 1.7

1.1       albertel    1: # The LearningOnline Network
                      2: # Base routines
                      3: #
1.7     ! albertel    4: # $Id: LONCAPA.pm,v 1.6 2006/06/19 09:35:08 www Exp $
1.1       albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
                     28: ###
                     29: 
                     30: package LONCAPA;
                     31: 
                     32: use strict;
1.2       www        33: use lib '/home/httpd/lib/perl/';
                     34: use LONCAPA::Configuration;
                     35: use Fcntl qw(:flock);
                     36: use GDBM_File;
                     37: use POSIX;
                     38: 
                     39: my $loncapa_max_wait_time = 13;
                     40: 
1.1       albertel   41: require Exporter;
                     42: our @ISA = qw (Exporter);
1.2       www        43: our @EXPORT = qw(&add_get_param &escape &unescape &tie_domain_hash &untie_domain_hash &tie_user_hash &untie_user_hash &propath);
                     44: my %perlvar;
1.1       albertel   45: 
1.2       www        46: # Inputs are a url, and a hash ref of
1.1       albertel   47: # form name => value pairs
                     48: # takes care of properly adding the form name elements and values to the 
                     49: # the url doing proper escaping of the values and joining with ? or & as 
                     50: # needed
                     51: 
                     52: sub add_get_param {
                     53:     my ($url,$form_data) = @_;
                     54:     my $needs_question_mark = ($url !~ /\?/);
                     55: 
                     56:     while (my ($name,$value) = each(%$form_data)) {
                     57: 	if ($needs_question_mark) {
                     58: 	    $url.='?';
                     59: 	    $needs_question_mark = 0;
                     60: 	} else { 
                     61: 	    $url.='&';
                     62: 	}
                     63: 	$url.=$name.'='.&escape($form_data->{$name});
                     64:     }
                     65:     return $url;
                     66: }
                     67: 
                     68: # -------------------------------------------------------- Escape Special Chars
                     69: 
                     70: sub escape {
                     71:     my $str=shift;
                     72:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                     73:     return $str;
                     74: }
                     75: 
                     76: # ----------------------------------------------------- Un-Escape Special Chars
                     77: 
                     78: sub unescape {
                     79:     my $str=shift;
                     80:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
                     81:     return $str;
                     82: }
                     83: 
1.2       www        84: # -------------------------------------------- Return path to profile directory
                     85: 
                     86: sub propath {
                     87:     my ($udom,$uname)=@_;
                     88:     $udom=~s/\W//g;
                     89:     $uname=~s/\W//g;
                     90:     my $subdir=$uname.'__';
                     91:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                     92:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
                     93:     return $proname;
                     94: } 
                     95: 
                     96: 
                     97: #---------------------------------------------------------------
                     98: #
                     99: # Manipulation of hash based databases (factoring out common code
                    100: # for later use as we refactor.
                    101: #
                    102: #  Ties a domain level resource file to a hash.
                    103: #  If requested a history entry is created in the associated hist file.
                    104: #
                    105: #  Parameters:
                    106: #     domain    - Name of the domain in which the resource file lives.
                    107: #     namespace - Name of the hash within that domain.
                    108: #     how       - How to tie the hash (e.g. GDBM_WRCREAT()).
                    109: #     loghead   - Optional parameter, if present a log entry is created
                    110: #                 in the associated history file and this is the first part
                    111: #                  of that entry.
                    112: #     logtail   - Goes along with loghead,  The actual logentry is of the
                    113: #                 form $loghead:<timestamp>:logtail.
                    114: # Returns:
                    115: #    Reference to a hash bound to the db file or alternatively undef
                    116: #    if the tie failed.
                    117: #
                    118: sub tie_domain_hash {
                    119:     my ($domain,$namespace,$how,$loghead,$logtail) = @_;
                    120:     
                    121:     # Filter out any whitespace in the domain name:
                    122:     
                    123:     $domain =~ s/\W//g;
                    124:     
                    125:     # We have enough to go on to tie the hash:
                    126:     
                    127:     my $user_top_dir   = $perlvar{'lonUsersDir'};
                    128:     my $domain_dir     = $user_top_dir."/$domain";
                    129:     my $resource_file  = $domain_dir."/$namespace";
                    130:     return &_locking_hash_tie($resource_file,$namespace,$how,$loghead,$logtail);
                    131: }
                    132: 
                    133: sub untie_domain_hash {
                    134:     return &_locking_hash_untie(@_);
                    135: }
                    136: #
                    137: #   Ties a user's resource file to a hash.  
                    138: #   If necessary, an appropriate history
                    139: #   log file entry is made as well.
                    140: #   This sub factors out common code from the subs that manipulate
                    141: #   the various gdbm files that keep keyword value pairs.
                    142: # Parameters:
                    143: #   domain       - Name of the domain the user is in.
                    144: #   user         - Name of the 'current user'.
                    145: #   namespace    - Namespace representing the file to tie.
                    146: #   how          - What the tie is done to (e.g. GDBM_WRCREAT().
                    147: #   loghead      - Optional first part of log entry if there may be a
                    148: #                  history file.
                    149: #   what         - Optional tail of log entry if there may be a history
                    150: #                  file.
                    151: # Returns:
                    152: #   hash to which the database is tied.  It's up to the caller to untie.
                    153: #   undef if the has could not be tied.
                    154: #
                    155: sub tie_user_hash {
                    156:     my ($domain,$user,$namespace,$how,$loghead,$what) = @_;
                    157: 
                    158:     $namespace=~s/\//\_/g;	# / -> _
                    159:     $namespace=~s/\W//g;		# whitespace eliminated.
                    160:     my $proname     = &propath($domain, $user);
                    161: 
                    162:     my $file_prefix="$proname/$namespace";
                    163:     return &_locking_hash_tie($file_prefix,$namespace,$how,$loghead,$what);
                    164: }
                    165: 
                    166: sub untie_user_hash {
                    167:     return &_locking_hash_untie(@_);
                    168: }
                    169: 
1.6       www       170: # routines if you just have a filename
                    171: # return tied hashref or undef
                    172: 
                    173: sub locking_hash_tie {
                    174:     my ($filename,$how)=@_;
                    175:     my ($file_prefix,$namespace)=&db_filename_parts($filename);
1.7     ! albertel  176:     if ($namespace eq '') { return undef; }
1.6       www       177:     return &_locking_hash_tie($file_prefix,$namespace,$how);
                    178: }
                    179: 
                    180: sub locking_hash_untie {
                    181:     return &_locking_hash_untie(@_);
                    182: }
                    183: 
                    184: sub db_filename_parts {
                    185:     my ($filename)=@_;
                    186:     my ($file_path,$namespace)=($filename=~/^(.*)\/([^\/]+)\.db$/);
1.7     ! albertel  187:     if ($namespace eq '') { return undef; }
1.6       www       188:     return ($file_path.'/'.$namespace,$namespace);
                    189: }
                    190: 
1.2       www       191: # internal routines that handle the actual tieing and untieing process
                    192: 
                    193: sub _do_hash_tie {
                    194:     my ($file_prefix,$namespace,$how,$loghead,$what) = @_;
                    195:     my %hash;
                    196:     if(tie(%hash, 'GDBM_File', "$file_prefix.db", $how, 0640)) {
                    197: 	# If this is a namespace for which a history is kept,
                    198: 	# make the history log entry:    
                    199: 	if (($namespace !~/^nohist\_/) && (defined($loghead))) {
                    200: 	    my $hfh = IO::File->new(">>$file_prefix.hist"); 
                    201: 	    if($hfh) {
1.5       albertel  202: 		my $now = time();
                    203: 		print $hfh ("$loghead:$now:$what\n");
1.2       www       204: 	    }
                    205: 	    $hfh->close;
                    206: 	}
                    207: 	return \%hash;
                    208:     } else {
                    209: 	return undef;
                    210:     }
                    211: }
                    212: 
                    213: sub _do_hash_untie {
                    214:     my ($hashref) = @_;
                    215:     my $result = untie(%$hashref);
                    216:     return $result;
                    217: }
                    218: 
                    219: {
                    220:     my $sym;
                    221: 
                    222:     sub _locking_hash_tie {
                    223: 	my ($file_prefix,$namespace,$how,$loghead,$what) = @_;
                    224:         my $lock_type=LOCK_SH;
                    225: # Are we reading or writing?
                    226:         if ($how eq &GDBM_READER()) {
                    227: # We are reading
                    228:            if (!open($sym,"$file_prefix.db.lock")) {
                    229: # We don't have a lock file. This could mean
                    230: # - that there is no such db-file
                    231: # - that it does not have a lock file yet
                    232:                if ((! -e "$file_prefix.db") && (! -e "$file_prefix.db.gz")) {
                    233: # No such file. Forget it.                
                    234:                    $! = 2;
                    235:                    return undef;
                    236:                }
                    237: # Apparently just no lock file yet. Make one
                    238:                open($sym,">>$file_prefix.db.lock");
                    239:            }
                    240: # Do a shared lock
                    241:            if (!&flock_sym(LOCK_SH)) { return undef; } 
                    242: # If this is compressed, we will actually need an exclusive lock
                    243: 	   if (-e "$file_prefix.db.gz") {
                    244: 	       if (!&flock_sym(LOCK_EX)) { return undef; }
                    245: 	   }
                    246:         } elsif ($how eq &GDBM_WRCREAT()) {
                    247: # We are writing
                    248:            open($sym,">>$file_prefix.db.lock");
                    249: # Writing needs exclusive lock
                    250:            if (!&flock_sym(LOCK_EX)) { return undef; }
                    251:         } else {
1.5       albertel  252:            die("Unknown method $how for $file_prefix");
1.2       www       253:         }
                    254: # The file is ours!
                    255: # If it is archived, un-archive it now
                    256:        if (-e "$file_prefix.db.gz") {
                    257:            system("gunzip $file_prefix.db.gz");
                    258: 	   if (-e "$file_prefix.hist.gz") {
                    259: 	       system("gunzip $file_prefix.hist.gz");
                    260: 	   }
                    261:        }
                    262: # Change access mode to non-blocking
                    263:        $how=$how|&GDBM_NOLOCK();
                    264: # Go ahead and tie the hash
                    265:        return &_do_hash_tie($file_prefix,$namespace,$how,$loghead,$what);
                    266:     }
                    267: 
                    268:     sub flock_sym {
                    269:         my ($lock_type)=@_;
                    270: 	my $failed=0;
                    271: 	eval {
                    272: 	    local $SIG{__DIE__}='DEFAULT';
                    273: 	    local $SIG{ALRM}=sub {
                    274: 		$failed=1;
                    275: 		die("failed lock");
                    276: 	    };
                    277: 	    alarm($loncapa_max_wait_time);
                    278: 	    flock($sym,$lock_type);
                    279: 	    alarm(0);
                    280: 	};
                    281: 	if ($failed) {
                    282: 	    $! = 100; # throwing error # 100
                    283: 	    return undef;
                    284: 	} else {
                    285: 	    return 1;
                    286: 	}
                    287:     }
                    288: 
                    289:     sub _locking_hash_untie {
                    290: 	my ($hashref) = @_;
                    291: 	my $result = untie(%$hashref);
                    292: 	flock($sym,LOCK_UN);
                    293: 	close($sym);
                    294: 	undef($sym);
                    295: 	return $result;
                    296:     }
                    297: }
                    298: 
                    299: BEGIN {
1.4       albertel  300:     %perlvar=%{&LONCAPA::Configuration::read_conf('loncapa.conf')};
1.2       www       301: }
                    302: 
1.1       albertel  303: 1;
                    304: 
                    305: __END__
                    306: 
                    307: =pod
                    308: 
                    309: =head1 NAME
                    310: 
                    311: LONCAPA - Basic routines
                    312: 
                    313: =head1 SYNOPSIS
                    314: 
                    315: Generally useful routines
                    316: 
                    317: =head1 EXPORTED SUBROUTINES
                    318: 
                    319: =over 4
                    320: 
                    321: =item *
                    322: 
                    323: escape() : unpack non-word characters into CGI-compatible hex codes
                    324: 
                    325: =item *
                    326: 
                    327: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                    328: 
                    329: =item *
                    330: 
                    331: add_get_param() :
                    332:  Inputs:  url (with or without exit GET from parameters), hash ref of
                    333:               form name => value pairs
                    334: 
                    335:  Return: url with properly added the form name elements and values to the 
                    336:          the url doing proper escaping of the values and joining with ? or &
                    337:          as needed
                    338: 
                    339: =back

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>