File:  [LON-CAPA] / loncom / LONCAPA.pm
Revision 1.21: download - view: text, annotated - select for diffs
Sun Dec 10 23:06:13 2006 UTC (17 years, 4 months ago) by albertel
Branches: MAIN
CVS tags: version_2_2_99_0, HEAD
- require a word char to satr a username

    1: # The LearningOnline Network
    2: # Base routines
    3: #
    4: # $Id: LONCAPA.pm,v 1.21 2006/12/10 23:06:13 albertel Exp $
    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;
   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: 
   41: 
   42: use vars qw($match_domain   $match_not_domain
   43: 	    $match_username $match_not_username
   44: 	    $match_courseid $match_not_courseid
   45: 	    $match_name
   46: 	    $match_handle   $match_not_handle);
   47: 
   48: require Exporter;
   49: our @ISA = qw (Exporter);
   50: our @EXPORT = qw(&add_get_param    &escape            &unescape       
   51: 		 &tie_domain_hash  &untie_domain_hash &tie_user_hash
   52: 		 &untie_user_hash  &propath);
   53: our @EXPORT_OK = qw($match_domain   $match_not_domain
   54: 		    $match_username $match_not_username
   55: 		    $match_courseid $match_not_courseid
   56: 		    $match_name
   57: 		    $match_handle   $match_not_handle);
   58: our %EXPORT_TAGS = ( 'match' =>[qw($match_domain   $match_not_domain
   59: 				   $match_username $match_not_username
   60: 				   $match_courseid $match_not_courseid
   61: 				   $match_name
   62: 				   $match_handle   $match_not_handle)],);
   63: my %perlvar;
   64: 
   65: 
   66: 
   67: # Inputs are a url, and a hash ref of
   68: # form name => value pairs
   69: # takes care of properly adding the form name elements and values to the 
   70: # the url doing proper escaping of the values and joining with ? or & as 
   71: # needed
   72: 
   73: sub add_get_param {
   74:     my ($url,$form_data) = @_;
   75:     my $needs_question_mark = ($url !~ /\?/);
   76: 
   77:     while (my ($name,$value) = each(%$form_data)) {
   78: 	if ($needs_question_mark) {
   79: 	    $url.='?';
   80: 	    $needs_question_mark = 0;
   81: 	} else { 
   82: 	    $url.='&';
   83: 	}
   84: 	$url.=$name.'='.&escape($form_data->{$name});
   85:     }
   86:     return $url;
   87: }
   88: 
   89: # -------------------------------------------------------- Escape Special Chars
   90: 
   91: sub escape {
   92:     my $str=shift;
   93:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
   94:     return $str;
   95: }
   96: 
   97: # ----------------------------------------------------- Un-Escape Special Chars
   98: 
   99: sub unescape {
  100:     my $str=shift;
  101:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  102:     return $str;
  103: }
  104: 
  105: $match_domain     = $LONCAPA::domain_re     = qr{[\w\-.]+};
  106: $match_not_domain = $LONCAPA::not_domain_re = qr{[^\w\-.]+};
  107: sub clean_domain {
  108:     my ($domain) = @_;
  109:     $domain =~ s/$match_not_domain//g;
  110:     return $domain;
  111: }
  112: 
  113: $match_username     = $LONCAPA::username_re     = qr{\w[\w\-.]+};
  114: $match_not_username = $LONCAPA::not_username_re = qr{[^\w\-.]+};
  115: sub clean_username {
  116:     my ($username) = @_;
  117:     $username =~ s/^\W+//;
  118:     $username =~ s/$match_not_username//g;
  119:     return $username;
  120: }
  121: 
  122: 
  123: $match_courseid     = $LONCAPA::courseid_re     = qr{\d[\w\-.]+};
  124: $match_not_courseid = $LONCAPA::not_courseid_re = qr{[^\w\-.]+};
  125: 
  126: $match_name         = $LONCAPA::name = qr{$match_username|$match_courseid};
  127: sub clean_name {
  128:     my ($name) = @_;
  129:     $name =~ s/$match_not_username//g;
  130:     return $name;
  131: }
  132: 
  133: sub split_courseid {
  134:     my ($courseid) = @_;
  135:     my  ($domain,$coursenum) = 
  136: 	($courseid=~m{^/($match_domain)/($match_courseid)});
  137:     return ($domain,$coursenum);
  138: }
  139: 
  140: $match_handle     = $LONCAPA::handle_re     = qr{[\w\-.]+};
  141: $match_not_handle = $LONCAPA::not_handle_re = qr{[^\w\-.]+};
  142: sub clean_handle {
  143:     my ($handle) = @_;
  144:     $handle =~ s/$match_not_handle//g;
  145:     return $handle;
  146: }
  147: 
  148: # -------------------------------------------- Return path to profile directory
  149: 
  150: sub propath {
  151:     my ($udom,$uname)=@_;
  152:     $udom = &clean_domain($udom);
  153:     $uname= &clean_name($uname);
  154:     my $subdir=$uname.'__';
  155:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
  156:     my $proname="$perlvar{'lonUsersDir'}/$udom/$subdir/$uname";
  157:     return $proname;
  158: } 
  159: 
  160: 
  161: #---------------------------------------------------------------
  162: #
  163: # Manipulation of hash based databases (factoring out common code
  164: # for later use as we refactor.
  165: #
  166: #  Ties a domain level resource file to a hash.
  167: #  If requested a history entry is created in the associated hist file.
  168: #
  169: #  Parameters:
  170: #     domain    - Name of the domain in which the resource file lives.
  171: #     namespace - Name of the hash within that domain.
  172: #     how       - How to tie the hash (e.g. GDBM_WRCREAT()).
  173: #     loghead   - Optional parameter, if present a log entry is created
  174: #                 in the associated history file and this is the first part
  175: #                  of that entry.
  176: #     logtail   - Goes along with loghead,  The actual logentry is of the
  177: #                 form $loghead:<timestamp>:logtail.
  178: # Returns:
  179: #    Reference to a hash bound to the db file or alternatively undef
  180: #    if the tie failed.
  181: #
  182: sub tie_domain_hash {
  183:     my ($domain,$namespace,$how,$loghead,$logtail) = @_;
  184:     
  185:     # Filter out any whitespace in the domain name:
  186:     
  187:     $domain = &clean_domain($domain);
  188:     
  189:     # We have enough to go on to tie the hash:
  190:     
  191:     my $user_top_dir   = $perlvar{'lonUsersDir'};
  192:     my $domain_dir     = $user_top_dir."/$domain";
  193:     my $resource_file  = $domain_dir."/$namespace";
  194:     return &_locking_hash_tie($resource_file,$namespace,$how,$loghead,$logtail);
  195: }
  196: 
  197: sub untie_domain_hash {
  198:     return &_locking_hash_untie(@_);
  199: }
  200: #
  201: #   Ties a user's resource file to a hash.  
  202: #   If necessary, an appropriate history
  203: #   log file entry is made as well.
  204: #   This sub factors out common code from the subs that manipulate
  205: #   the various gdbm files that keep keyword value pairs.
  206: # Parameters:
  207: #   domain       - Name of the domain the user is in.
  208: #   user         - Name of the 'current user'.
  209: #   namespace    - Namespace representing the file to tie.
  210: #   how          - What the tie is done to (e.g. GDBM_WRCREAT().
  211: #   loghead      - Optional first part of log entry if there may be a
  212: #                  history file.
  213: #   what         - Optional tail of log entry if there may be a history
  214: #                  file.
  215: # Returns:
  216: #   hash to which the database is tied.  It's up to the caller to untie.
  217: #   undef if the has could not be tied.
  218: #
  219: sub tie_user_hash {
  220:     my ($domain,$user,$namespace,$how,$loghead,$what) = @_;
  221: 
  222:     $namespace=~s{/}{_}g;	# / -> _
  223:     $namespace     = &clean_username($namespace);
  224:     my $proname    = &propath($domain, $user);
  225:     my $file_prefix="$proname/$namespace";
  226:     return &_locking_hash_tie($file_prefix,$namespace,$how,$loghead,$what);
  227: }
  228: 
  229: sub untie_user_hash {
  230:     return &_locking_hash_untie(@_);
  231: }
  232: 
  233: # routines if you just have a filename
  234: # return tied hashref or undef
  235: 
  236: sub locking_hash_tie {
  237:     my ($filename,$how)=@_;
  238:     my ($file_prefix,$namespace)=&db_filename_parts($filename);
  239:     if ($namespace eq '') { return undef; }
  240:     return &_locking_hash_tie($file_prefix,$namespace,$how);
  241: }
  242: 
  243: sub locking_hash_untie {
  244:     return &_locking_hash_untie(@_);
  245: }
  246: 
  247: sub db_filename_parts {
  248:     my ($filename)=@_;
  249:     my ($file_path,$namespace)=($filename=~/^(.*)\/([^\/]+)\.db$/);
  250:     if ($namespace eq '') { return undef; }
  251:     return ($file_path.'/'.$namespace,$namespace);
  252: }
  253: 
  254: # internal routines that handle the actual tieing and untieing process
  255: 
  256: sub _do_hash_tie {
  257:     my ($file_prefix,$namespace,$how,$loghead,$what) = @_;
  258:     my %hash;
  259:     if(tie(%hash, 'GDBM_File', "$file_prefix.db", $how, 0640)) {
  260: 	# If this is a namespace for which a history is kept,
  261: 	# make the history log entry:    
  262: 	if (($namespace !~/^nohist\_/) && (defined($loghead))) {
  263: 	    my $hfh = IO::File->new(">>$file_prefix.hist"); 
  264: 	    if($hfh) {
  265: 		my $now = time();
  266: 		print $hfh ("$loghead:$now:$what\n");
  267: 	    }
  268: 	    $hfh->close;
  269: 	}
  270: 	return \%hash;
  271:     } else {
  272: 	return undef;
  273:     }
  274: }
  275: 
  276: sub _do_hash_untie {
  277:     my ($hashref) = @_;
  278:     my $result = untie(%$hashref);
  279:     return $result;
  280: }
  281: 
  282: {
  283:     my $sym;
  284:     my @pushed_syms;
  285: 
  286:     sub clean_sym {
  287: 	undef($sym);
  288:     }
  289:     sub push_locking_hash_tie {
  290: 	if (!defined($sym)) {
  291: 	    die("Invalid used of push_locking_hash_tie, should only be called after a lock has occurred and before and unlock.");
  292: 	}
  293: 	push(@pushed_syms,$sym);
  294: 	undef($sym);
  295:     }
  296: 
  297:     sub pop_locking_hash_tie {
  298: 	if (defined($sym)) {
  299: 	    die("Invalid nested used of pop_locking_hash_tie, should only be called after a unlock has occurred.");
  300: 	}
  301: 	$sym = pop(@pushed_syms);
  302:     }
  303: 
  304:     sub _locking_hash_tie {
  305: 	my ($file_prefix,$namespace,$how,$loghead,$what) = @_;
  306: 	if (defined($sym)) {
  307: 	    die('Nested locking attempted without proper use of push_locking_hash_tie, this is unsupported');
  308: 	}
  309: 
  310:         my $lock_type=LOCK_SH;
  311: # Are we reading or writing?
  312:         if ($how eq &GDBM_READER()) {
  313: # We are reading
  314:            if (!open($sym,"$file_prefix.db.lock")) {
  315: # We don't have a lock file. This could mean
  316: # - that there is no such db-file
  317: # - that it does not have a lock file yet
  318:                if ((! -e "$file_prefix.db") && (! -e "$file_prefix.db.gz")) {
  319: # No such file. Forget it.                
  320:                    $! = 2;
  321: 		   &clean_sym();
  322:                    return undef;
  323:                }
  324: # Apparently just no lock file yet. Make one
  325:                open($sym,">>$file_prefix.db.lock");
  326:            }
  327: # Do a shared lock
  328:            if (!&flock_sym(LOCK_SH)) { 
  329: 	       &clean_sym();
  330: 	       return undef; 
  331: 	   } 
  332: # If this is compressed, we will actually need an exclusive lock
  333: 	   if (-e "$file_prefix.db.gz") {
  334: 	       if (!&flock_sym(LOCK_EX)) {
  335: 		   &clean_sym();
  336: 		   return undef;
  337: 	       }
  338: 	   }
  339:         } elsif ($how eq &GDBM_WRCREAT()) {
  340: # We are writing
  341:            open($sym,">>$file_prefix.db.lock");
  342: # Writing needs exclusive lock
  343:            if (!&flock_sym(LOCK_EX)) {
  344: 	       &clean_sym();
  345: 	       return undef;
  346: 	   }
  347:         } else {
  348:            die("Unknown method $how for $file_prefix");
  349:         }
  350: # The file is ours!
  351: # If it is archived, un-archive it now
  352:        if (-e "$file_prefix.db.gz") {
  353:            system("gunzip $file_prefix.db.gz");
  354: 	   if (-e "$file_prefix.hist.gz") {
  355: 	       system("gunzip $file_prefix.hist.gz");
  356: 	   }
  357:        }
  358: # Change access mode to non-blocking
  359:        $how=$how|&GDBM_NOLOCK();
  360: # Go ahead and tie the hash
  361:       	my $result = 
  362: 	    &_do_hash_tie($file_prefix,$namespace,$how,$loghead,$what);
  363: 	if (!$result) {
  364: 	    &clean_sym();
  365: 	}
  366: 	return $result;
  367:     }
  368: 
  369:     sub flock_sym {
  370:         my ($lock_type)=@_;
  371: 	my $failed=0;
  372: 	eval {
  373: 	    local $SIG{__DIE__}='DEFAULT';
  374: 	    local $SIG{ALRM}=sub {
  375: 		$failed=1;
  376: 		die("failed lock");
  377: 	    };
  378: 	    alarm($loncapa_max_wait_time);
  379: 	    flock($sym,$lock_type);
  380: 	    alarm(0);
  381: 	};
  382: 	if ($failed) {
  383: 	    $! = 100; # throwing error # 100
  384: 	    return undef;
  385: 	} else {
  386: 	    return 1;
  387: 	}
  388:     }
  389: 
  390:     sub _locking_hash_untie {
  391: 	my ($hashref) = @_;
  392: 	my $result = untie(%$hashref);
  393: 	flock($sym,LOCK_UN);
  394: 	close($sym);
  395: 	&clean_sym();
  396: 	return $result;
  397:     }
  398: }
  399: 
  400: BEGIN {
  401:     %perlvar=%{&LONCAPA::Configuration::read_conf('loncapa.conf')};
  402: }
  403: 
  404: 1;
  405: 
  406: __END__
  407: 
  408: =pod
  409: 
  410: =head1 NAME
  411: 
  412: LONCAPA - Basic routines
  413: 
  414: =head1 SYNOPSIS
  415: 
  416: Generally useful routines
  417: 
  418: =head1 EXPORTED SUBROUTINES
  419: 
  420: =over 4
  421: 
  422: =item *
  423: 
  424: escape() : unpack non-word characters into CGI-compatible hex codes
  425: 
  426: =item *
  427: 
  428: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
  429: 
  430: =item *
  431: 
  432: add_get_param() :
  433:  Inputs:  url (with or without exit GET from parameters), hash ref of
  434:               form name => value pairs
  435: 
  436:  Return: url with properly added the form name elements and values to the 
  437:          the url doing proper escaping of the values and joining with ? or &
  438:          as needed
  439: 
  440: =back

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