![]() ![]() | ![]() |
- fixes so that usenrames with _ work again
1: # The LearningOnline Network 2: # TCP networking package 3: # 4: # $Id: lonnet.pm,v 1.587 2005/01/11 22:12:22 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 Apache::lonnet; 31: 32: use strict; 33: use LWP::UserAgent(); 34: use HTTP::Headers; 35: use HTTP::Date; 36: # use Date::Parse; 37: use vars 38: qw(%perlvar %hostname %homecache %badServerCache %hostip %iphost %spareid %hostdom 39: %libserv %pr %prp %metacache %packagetab %titlecache %courseresversioncache %resversioncache 40: %courselogs %accesshash %userrolehash $processmarker $dumpcount 41: %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf %courseresdatacache 42: %userresdatacache %getsectioncache %domaindescription %domain_auth_def %domain_auth_arg_def 43: %domain_lang_def %domain_city %domain_longi %domain_lati $tmpdir $_64bit); 44: 45: use IO::Socket; 46: use GDBM_File; 47: use Apache::Constants qw(:common :http); 48: use HTML::LCParser; 49: use Fcntl qw(:flock); 50: use Apache::lonlocal; 51: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze); 52: use Time::HiRes qw( gettimeofday tv_interval ); 53: my $readit; 54: my $max_connection_retries = 10; # Or some such value. 55: 56: =pod 57: 58: =head1 Package Variables 59: 60: These are largely undocumented, so if you decipher one please note it here. 61: 62: =over 4 63: 64: =item $processmarker 65: 66: Contains the time this process was started and this servers host id. 67: 68: =item $dumpcount 69: 70: Counts the number of times a message log flush has been attempted (regardless 71: of success) by this process. Used as part of the filename when messages are 72: delayed. 73: 74: =back 75: 76: =cut 77: 78: 79: # --------------------------------------------------------------------- Logging 80: 81: sub logtouch { 82: my $execdir=$perlvar{'lonDaemons'}; 83: unless (-e "$execdir/logs/lonnet.log") { 84: open(my $fh,">>$execdir/logs/lonnet.log"); 85: close $fh; 86: } 87: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3]; 88: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log'); 89: } 90: 91: sub logthis { 92: my $message=shift; 93: my $execdir=$perlvar{'lonDaemons'}; 94: my $now=time; 95: my $local=localtime($now); 96: if (open(my $fh,">>$execdir/logs/lonnet.log")) { 97: print $fh "$local ($$): $message\n"; 98: close($fh); 99: } 100: return 1; 101: } 102: 103: sub logperm { 104: my $message=shift; 105: my $execdir=$perlvar{'lonDaemons'}; 106: my $now=time; 107: my $local=localtime($now); 108: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) { 109: print $fh "$now:$message:$local\n"; 110: close($fh); 111: } 112: return 1; 113: } 114: 115: # -------------------------------------------------- Non-critical communication 116: sub subreply { 117: my ($cmd,$server)=@_; 118: my $peerfile="$perlvar{'lonSockDir'}/$server"; 119: # 120: # With loncnew process trimming, there's a timing hole between lonc server 121: # process exit and the master server picking up the listen on the AF_UNIX 122: # socket. In that time interval, a lock file will exist: 123: 124: my $lockfile=$peerfile.".lock"; 125: while (-e $lockfile) { # Need to wait for the lockfile to disappear. 126: sleep(1); 127: } 128: # At this point, either a loncnew parent is listening or an old lonc 129: # or loncnew child is listening so we can connect or everything's dead. 130: # 131: # We'll give the connection a few tries before abandoning it. If 132: # connection is not possible, we'll con_lost back to the client. 133: # 134: my $client; 135: for (my $retries = 0; $retries < $max_connection_retries; $retries++) { 136: $client=IO::Socket::UNIX->new(Peer =>"$peerfile", 137: Type => SOCK_STREAM, 138: Timeout => 10); 139: if($client) { 140: last; # Connected! 141: } 142: sleep(1); # Try again later if failed connection. 143: } 144: my $answer; 145: if ($client) { 146: print $client "$cmd\n"; 147: $answer=<$client>; 148: if (!$answer) { $answer="con_lost"; } 149: chomp($answer); 150: } else { 151: $answer = 'con_lost'; # Failed connection. 152: } 153: return $answer; 154: } 155: 156: sub reply { 157: my ($cmd,$server)=@_; 158: unless (defined($hostname{$server})) { return 'no_such_host'; } 159: my $answer=subreply($cmd,$server); 160: if ($answer eq 'con_lost') { 161: #sleep 5; 162: #$answer=subreply($cmd,$server); 163: #if ($answer eq 'con_lost') { 164: # &logthis("Second attempt con_lost on $server"); 165: # my $peerfile="$perlvar{'lonSockDir'}/$server"; 166: # my $client=IO::Socket::UNIX->new(Peer =>"$peerfile", 167: # Type => SOCK_STREAM, 168: # Timeout => 10) 169: # or return "con_lost"; 170: # &logthis("Killing socket"); 171: # print $client "close_connection_exit\n"; 172: #sleep 5; 173: # $answer=subreply($cmd,$server); 174: #} 175: } 176: if (($answer=~/^refused/) || ($answer=~/^rejected/)) { 177: &logthis("<font color=blue>WARNING:". 178: " $cmd to $server returned $answer</font>"); 179: } 180: return $answer; 181: } 182: 183: # ----------------------------------------------------------- Send USR1 to lonc 184: 185: sub reconlonc { 186: my $peerfile=shift; 187: &logthis("Trying to reconnect for $peerfile"); 188: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid"; 189: if (open(my $fh,"<$loncfile")) { 190: my $loncpid=<$fh>; 191: chomp($loncpid); 192: if (kill 0 => $loncpid) { 193: &logthis("lonc at pid $loncpid responding, sending USR1"); 194: kill USR1 => $loncpid; 195: sleep 1; 196: if (-e "$peerfile") { return; } 197: &logthis("$peerfile still not there, give it another try"); 198: sleep 5; 199: if (-e "$peerfile") { return; } 200: &logthis( 201: "<font color=blue>WARNING: $peerfile still not there, giving up</font>"); 202: } else { 203: &logthis( 204: "<font color=blue>WARNING:". 205: " lonc at pid $loncpid not responding, giving up</font>"); 206: } 207: } else { 208: &logthis('<font color=blue>WARNING: lonc not running, giving up</font>'); 209: } 210: } 211: 212: # ------------------------------------------------------ Critical communication 213: 214: sub critical { 215: my ($cmd,$server)=@_; 216: unless ($hostname{$server}) { 217: &logthis("<font color=blue>WARNING:". 218: " Critical message to unknown server ($server)</font>"); 219: return 'no_such_host'; 220: } 221: my $answer=reply($cmd,$server); 222: if ($answer eq 'con_lost') { 223: my $pingreply=reply('ping',$server); 224: &reconlonc("$perlvar{'lonSockDir'}/$server"); 225: my $pongreply=reply('pong',$server); 226: &logthis("Ping/Pong for $server: $pingreply/$pongreply"); 227: $answer=reply($cmd,$server); 228: if ($answer eq 'con_lost') { 229: my $now=time; 230: my $middlename=$cmd; 231: $middlename=substr($middlename,0,16); 232: $middlename=~s/\W//g; 233: my $dfilename= 234: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server"; 235: $dumpcount++; 236: { 237: my $dfh; 238: if (open($dfh,">$dfilename")) { 239: print $dfh "$cmd\n"; 240: close($dfh); 241: } 242: } 243: sleep 2; 244: my $wcmd=''; 245: { 246: my $dfh; 247: if (open($dfh,"<$dfilename")) { 248: $wcmd=<$dfh>; 249: close($dfh); 250: } 251: } 252: chomp($wcmd); 253: if ($wcmd eq $cmd) { 254: &logthis("<font color=blue>WARNING: ". 255: "Connection buffer $dfilename: $cmd</font>"); 256: &logperm("D:$server:$cmd"); 257: return 'con_delayed'; 258: } else { 259: &logthis("<font color=red>CRITICAL:" 260: ." Critical connection failed: $server $cmd</font>"); 261: &logperm("F:$server:$cmd"); 262: return 'con_failed'; 263: } 264: } 265: } 266: return $answer; 267: } 268: 269: # 270: # -------------- Remove all key from the env that start witha lowercase letter 271: # (Which is always a lon-capa value) 272: 273: sub cleanenv { 274: # unless (defined(&Apache::exists_config_define("MODPERL2"))) { return; } 275: # unless (&Apache::exists_config_define("MODPERL2")) { return; } 276: foreach my $key (keys(%ENV)) { 277: if ($key =~ /^[a-z]/) { 278: delete($ENV{$key}); 279: } 280: } 281: } 282: 283: # ------------------------------------------- Transfer profile into environment 284: 285: sub transfer_profile_to_env { 286: my ($lonidsdir,$handle)=@_; 287: my @profile; 288: { 289: open(my $idf,"$lonidsdir/$handle.id"); 290: flock($idf,LOCK_SH); 291: @profile=<$idf>; 292: close($idf); 293: } 294: my $envi; 295: my %Remove; 296: for ($envi=0;$envi<=$#profile;$envi++) { 297: chomp($profile[$envi]); 298: my ($envname,$envvalue)=split(/=/,$profile[$envi]); 299: $ENV{$envname} = $envvalue; 300: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) { 301: if ($time < time-300) { 302: $Remove{$key}++; 303: } 304: } 305: } 306: $ENV{'user.environment'} = "$lonidsdir/$handle.id"; 307: foreach my $expired_key (keys(%Remove)) { 308: &delenv($expired_key); 309: } 310: } 311: 312: # ---------------------------------------------------------- Append Environment 313: 314: sub appenv { 315: my %newenv=@_; 316: foreach (keys %newenv) { 317: if (($newenv{$_}=~/^user\.role/) || ($newenv{$_}=~/^user\.priv/)) { 318: &logthis("<font color=blue>WARNING: ". 319: "Attempt to modify environment ".$_." to ".$newenv{$_} 320: .'</font>'); 321: delete($newenv{$_}); 322: } else { 323: $ENV{$_}=$newenv{$_}; 324: } 325: } 326: 327: my $lockfh; 328: unless (open($lockfh,"$ENV{'user.environment'}")) { 329: return 'error: '.$!; 330: } 331: unless (flock($lockfh,LOCK_EX)) { 332: &logthis("<font color=blue>WARNING: ". 333: 'Could not obtain exclusive lock in appenv: '.$!); 334: close($lockfh); 335: return 'error: '.$!; 336: } 337: 338: my @oldenv; 339: { 340: my $fh; 341: unless (open($fh,"$ENV{'user.environment'}")) { 342: return 'error: '.$!; 343: } 344: @oldenv=<$fh>; 345: close($fh); 346: } 347: for (my $i=0; $i<=$#oldenv; $i++) { 348: chomp($oldenv[$i]); 349: if ($oldenv[$i] ne '') { 350: my ($name,$value)=split(/=/,$oldenv[$i]); 351: unless (defined($newenv{$name})) { 352: $newenv{$name}=$value; 353: } 354: } 355: } 356: { 357: my $fh; 358: unless (open($fh,">$ENV{'user.environment'}")) { 359: return 'error'; 360: } 361: my $newname; 362: foreach $newname (keys %newenv) { 363: print $fh "$newname=$newenv{$newname}\n"; 364: } 365: close($fh); 366: } 367: 368: close($lockfh); 369: return 'ok'; 370: } 371: # ----------------------------------------------------- Delete from Environment 372: 373: sub delenv { 374: my $delthis=shift; 375: my %newenv=(); 376: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) { 377: &logthis("<font color=blue>WARNING: ". 378: "Attempt to delete from environment ".$delthis); 379: return 'error'; 380: } 381: my @oldenv; 382: { 383: my $fh; 384: unless (open($fh,"$ENV{'user.environment'}")) { 385: return 'error'; 386: } 387: unless (flock($fh,LOCK_SH)) { 388: &logthis("<font color=blue>WARNING: ". 389: 'Could not obtain shared lock in delenv: '.$!); 390: close($fh); 391: return 'error: '.$!; 392: } 393: @oldenv=<$fh>; 394: close($fh); 395: } 396: { 397: my $fh; 398: unless (open($fh,">$ENV{'user.environment'}")) { 399: return 'error'; 400: } 401: unless (flock($fh,LOCK_EX)) { 402: &logthis("<font color=blue>WARNING: ". 403: 'Could not obtain exclusive lock in delenv: '.$!); 404: close($fh); 405: return 'error: '.$!; 406: } 407: foreach (@oldenv) { 408: if ($_=~/^$delthis/) { 409: my ($key,undef) = split('=',$_); 410: delete($ENV{$key}); 411: } else { 412: print $fh $_; 413: } 414: } 415: close($fh); 416: } 417: return 'ok'; 418: } 419: 420: # ------------------------------------------ Find out current server userload 421: # there is a copy in lond 422: sub userload { 423: my $numusers=0; 424: { 425: opendir(LONIDS,$perlvar{'lonIDsDir'}); 426: my $filename; 427: my $curtime=time; 428: while ($filename=readdir(LONIDS)) { 429: if ($filename eq '.' || $filename eq '..') {next;} 430: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9]; 431: if ($curtime-$mtime < 1800) { $numusers++; } 432: } 433: closedir(LONIDS); 434: } 435: my $userloadpercent=0; 436: my $maxuserload=$perlvar{'lonUserLoadLim'}; 437: if ($maxuserload) { 438: $userloadpercent=100*$numusers/$maxuserload; 439: } 440: $userloadpercent=sprintf("%.2f",$userloadpercent); 441: return $userloadpercent; 442: } 443: 444: # ------------------------------------------ Fight off request when overloaded 445: 446: sub overloaderror { 447: my ($r,$checkserver)=@_; 448: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; } 449: my $loadavg; 450: if ($checkserver eq $perlvar{'lonHostID'}) { 451: open(my $loadfile,'/proc/loadavg'); 452: $loadavg=<$loadfile>; 453: $loadavg =~ s/\s.*//g; 454: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'}; 455: close($loadfile); 456: } else { 457: $loadavg=&reply('load',$checkserver); 458: } 459: my $overload=$loadavg-100; 460: if ($overload>0) { 461: $r->err_headers_out->{'Retry-After'}=$overload; 462: $r->log_error('Overload of '.$overload.' on '.$checkserver); 463: return 413; 464: } 465: return ''; 466: } 467: 468: # ------------------------------ Find server with least workload from spare.tab 469: 470: sub spareserver { 471: my ($loadpercent,$userloadpercent) = @_; 472: my $tryserver; 473: my $spareserver=''; 474: if ($userloadpercent !~ /\d/) { $userloadpercent=0; } 475: my $lowestserver=$loadpercent > $userloadpercent? 476: $loadpercent : $userloadpercent; 477: foreach $tryserver (keys %spareid) { 478: my $loadans=reply('load',$tryserver); 479: my $userloadans=reply('userload',$tryserver); 480: if ($loadans !~ /\d/ && $userloadans !~ /\d/) { 481: next; #didn't get a number from the server 482: } 483: my $answer; 484: if ($loadans =~ /\d/) { 485: if ($userloadans =~ /\d/) { 486: #both are numbers, pick the bigger one 487: $answer=$loadans > $userloadans? 488: $loadans : $userloadans; 489: } else { 490: $answer = $loadans; 491: } 492: } else { 493: $answer = $userloadans; 494: } 495: if (($answer =~ /\d/) && ($answer<$lowestserver)) { 496: $spareserver="http://$hostname{$tryserver}"; 497: $lowestserver=$answer; 498: } 499: } 500: return $spareserver; 501: } 502: 503: # --------------------------------------------- Try to change a user's password 504: 505: sub changepass { 506: my ($uname,$udom,$currentpass,$newpass,$server)=@_; 507: $currentpass = &escape($currentpass); 508: $newpass = &escape($newpass); 509: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass", 510: $server); 511: if (! $answer) { 512: &logthis("No reply on password change request to $server ". 513: "by $uname in domain $udom."); 514: } elsif ($answer =~ "^ok") { 515: &logthis("$uname in $udom successfully changed their password ". 516: "on $server."); 517: } elsif ($answer =~ "^pwchange_failure") { 518: &logthis("$uname in $udom was unable to change their password ". 519: "on $server. The action was blocked by either lcpasswd ". 520: "or pwchange"); 521: } elsif ($answer =~ "^non_authorized") { 522: &logthis("$uname in $udom did not get their password correct when ". 523: "attempting to change it on $server."); 524: } elsif ($answer =~ "^auth_mode_error") { 525: &logthis("$uname in $udom attempted to change their password despite ". 526: "not being locally or internally authenticated on $server."); 527: } elsif ($answer =~ "^unknown_user") { 528: &logthis("$uname in $udom attempted to change their password ". 529: "on $server but were unable to because $server is not ". 530: "their home server."); 531: } elsif ($answer =~ "^refused") { 532: &logthis("$server refused to change $uname in $udom password because ". 533: "it was sent an unencrypted request to change the password."); 534: } 535: return $answer; 536: } 537: 538: # ----------------------- Try to determine user's current authentication scheme 539: 540: sub queryauthenticate { 541: my ($uname,$udom)=@_; 542: my $uhome=&homeserver($uname,$udom); 543: if (!$uhome) { 544: &logthis("User $uname at $udom is unknown when looking for authentication mechanism"); 545: return 'no_host'; 546: } 547: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome); 548: if ($answer =~ /^(unknown_user|refused|con_lost)/) { 549: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism"); 550: } 551: return $answer; 552: } 553: 554: # --------- Try to authenticate user from domain's lib servers (first this one) 555: 556: sub authenticate { 557: my ($uname,$upass,$udom)=@_; 558: $upass=escape($upass); 559: $uname=~s/\W//g; 560: my $uhome=&homeserver($uname,$udom); 561: if (!$uhome) { 562: &logthis("User $uname at $udom is unknown in authenticate"); 563: return 'no_host'; 564: } 565: my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome); 566: if ($answer eq 'authorized') { 567: &logthis("User $uname at $udom authorized by $uhome"); 568: return $uhome; 569: } 570: if ($answer eq 'non_authorized') { 571: &logthis("User $uname at $udom rejected by $uhome"); 572: return 'no_host'; 573: } 574: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism"); 575: return 'no_host'; 576: } 577: 578: # ---------------------- Find the homebase for a user from domain's lib servers 579: 580: sub homeserver { 581: my ($uname,$udom,$ignoreBadCache)=@_; 582: my $index="$uname:$udom"; 583: 584: my ($result,$cached)=&is_cached(\%homecache,$index,'home',86400); 585: if (defined($cached)) { return $result; } 586: my $tryserver; 587: foreach $tryserver (keys %libserv) { 588: next if ($ignoreBadCache ne 'true' && 589: exists($badServerCache{$tryserver})); 590: if ($hostdom{$tryserver} eq $udom) { 591: my $answer=reply("home:$udom:$uname",$tryserver); 592: if ($answer eq 'found') { 593: return &do_cache(\%homecache,$index,$tryserver,'home'); 594: } elsif ($answer eq 'no_host') { 595: $badServerCache{$tryserver}=1; 596: } 597: } 598: } 599: return 'no_host'; 600: } 601: 602: # ------------------------------------- Find the usernames behind a list of IDs 603: 604: sub idget { 605: my ($udom,@ids)=@_; 606: my %returnhash=(); 607: 608: my $tryserver; 609: foreach $tryserver (keys %libserv) { 610: if ($hostdom{$tryserver} eq $udom) { 611: my $idlist=join('&',@ids); 612: $idlist=~tr/A-Z/a-z/; 613: my $reply=&reply("idget:$udom:".$idlist,$tryserver); 614: my @answer=(); 615: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) { 616: @answer=split(/\&/,$reply); 617: } ; 618: my $i; 619: for ($i=0;$i<=$#ids;$i++) { 620: if ($answer[$i]) { 621: $returnhash{$ids[$i]}=$answer[$i]; 622: } 623: } 624: } 625: } 626: return %returnhash; 627: } 628: 629: # ------------------------------------- Find the IDs behind a list of usernames 630: 631: sub idrget { 632: my ($udom,@unames)=@_; 633: my %returnhash=(); 634: foreach (@unames) { 635: $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1]; 636: } 637: return %returnhash; 638: } 639: 640: # ------------------------------- Store away a list of names and associated IDs 641: 642: sub idput { 643: my ($udom,%ids)=@_; 644: my %servers=(); 645: foreach (keys %ids) { 646: &cput('environment',{'id'=>$ids{$_}},$udom,$_); 647: my $uhom=&homeserver($_,$udom); 648: if ($uhom ne 'no_host') { 649: my $id=&escape($ids{$_}); 650: $id=~tr/A-Z/a-z/; 651: my $unam=&escape($_); 652: if ($servers{$uhom}) { 653: $servers{$uhom}.='&'.$id.'='.$unam; 654: } else { 655: $servers{$uhom}=$id.'='.$unam; 656: } 657: } 658: } 659: foreach (keys %servers) { 660: &critical('idput:'.$udom.':'.$servers{$_},$_); 661: } 662: } 663: 664: # --------------------------------------------------- Assign a key to a student 665: 666: sub assign_access_key { 667: # 668: # a valid key looks like uname:udom#comments 669: # comments are being appended 670: # 671: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_; 672: $kdom= 673: $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($kdom)); 674: $knum= 675: $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($knum)); 676: $cdom= 677: $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom)); 678: $cnum= 679: $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum)); 680: $udom=$ENV{'user.name'} unless (defined($udom)); 681: $uname=$ENV{'user.domain'} unless (defined($uname)); 682: my %existing=&get('accesskeys',[$ckey],$kdom,$knum); 683: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key 684: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 685: # assigned to this person 686: # - this should not happen, 687: # unless something went wrong 688: # the first time around 689: # ready to assign 690: $logentry=$1.'; '.$logentry; 691: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry}, 692: $kdom,$knum) eq 'ok') { 693: # key now belongs to user 694: my $envkey='key.'.$cdom.'_'.$cnum; 695: if (&put('environment',{$envkey => $ckey}) eq 'ok') { 696: &appenv('environment.'.$envkey => $ckey); 697: return 'ok'; 698: } else { 699: return 700: 'error: Count not permanently assign key, will need to be re-entered later.'; 701: } 702: } else { 703: return 'error: Could not assign key, try again later.'; 704: } 705: } elsif (!$existing{$ckey}) { 706: # the key does not exist 707: return 'error: The key does not exist'; 708: } else { 709: # the key is somebody else's 710: return 'error: The key is already in use'; 711: } 712: } 713: 714: # ------------------------------------------ put an additional comment on a key 715: 716: sub comment_access_key { 717: # 718: # a valid key looks like uname:udom#comments 719: # comments are being appended 720: # 721: my ($ckey,$cdom,$cnum,$logentry)=@_; 722: $cdom= 723: $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom)); 724: $cnum= 725: $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum)); 726: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum); 727: if ($existing{$ckey}) { 728: $existing{$ckey}.='; '.$logentry; 729: # ready to assign 730: if (&put('accesskeys',{$ckey=>$existing{$ckey}}, 731: $cdom,$cnum) eq 'ok') { 732: return 'ok'; 733: } else { 734: return 'error: Count not store comment.'; 735: } 736: } else { 737: # the key does not exist 738: return 'error: The key does not exist'; 739: } 740: } 741: 742: # ------------------------------------------------------ Generate a set of keys 743: 744: sub generate_access_keys { 745: my ($number,$cdom,$cnum,$logentry)=@_; 746: $cdom= 747: $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom)); 748: $cnum= 749: $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum)); 750: unless (&allowed('mky',$cdom)) { return 0; } 751: unless (($cdom) && ($cnum)) { return 0; } 752: if ($number>10000) { return 0; } 753: sleep(2); # make sure don't get same seed twice 754: srand(time()^($$+($$<<15))); # from "Programming Perl" 755: my $total=0; 756: for (my $i=1;$i<=$number;$i++) { 757: my $newkey=sprintf("%lx",int(100000*rand)).'-'. 758: sprintf("%lx",int(100000*rand)).'-'. 759: sprintf("%lx",int(100000*rand)); 760: $newkey=~s/1/g/g; # folks mix up 1 and l 761: $newkey=~s/0/h/g; # and also 0 and O 762: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum); 763: if ($existing{$newkey}) { 764: $i--; 765: } else { 766: if (&put('accesskeys', 767: { $newkey => '# generated '.localtime(). 768: ' by '.$ENV{'user.name'}.'@'.$ENV{'user.domain'}. 769: '; '.$logentry }, 770: $cdom,$cnum) eq 'ok') { 771: $total++; 772: } 773: } 774: } 775: &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'}, 776: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom); 777: return $total; 778: } 779: 780: # ------------------------------------------------------- Validate an accesskey 781: 782: sub validate_access_key { 783: my ($ckey,$cdom,$cnum,$udom,$uname)=@_; 784: $cdom= 785: $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom)); 786: $cnum= 787: $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum)); 788: $udom=$ENV{'user.domain'} unless (defined($udom)); 789: $uname=$ENV{'user.name'} unless (defined($uname)); 790: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum); 791: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/); 792: } 793: 794: # ------------------------------------- Find the section of student in a course 795: 796: sub getsection { 797: my ($udom,$unam,$courseid)=@_; 798: $courseid=~s/\_/\//g; 799: $courseid=~s/^(\w)/\/$1/; 800: 801: my $hashid="$udom:$unam:$courseid"; 802: my ($result,$cached)=&is_cached(\%getsectioncache,$hashid,'getsection'); 803: if (defined($cached)) { return $result; } 804: 805: my %Pending; 806: my %Expired; 807: # 808: # Each role can either have not started yet (pending), be active, 809: # or have expired. 810: # 811: # If there is an active role, we are done. 812: # 813: # If there is more than one role which has not started yet, 814: # choose the one which will start sooner 815: # If there is one role which has not started yet, return it. 816: # 817: # If there is more than one expired role, choose the one which ended last. 818: # If there is a role which has expired, return it. 819: # 820: foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles', 821: &homeserver($unam,$udom)))) { 822: my ($key,$value)=split(/\=/,$_); 823: $key=&unescape($key); 824: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/); 825: my $section=$1; 826: if ($key eq $courseid.'_st') { $section=''; } 827: my ($dummy,$end,$start)=split(/\_/,&unescape($value)); 828: my $now=time; 829: if (defined($end) && $end && ($now > $end)) { 830: $Expired{$end}=$section; 831: next; 832: } 833: if (defined($start) && $start && ($now < $start)) { 834: $Pending{$start}=$section; 835: next; 836: } 837: return &do_cache(\%getsectioncache,$hashid,$section,'getsection'); 838: } 839: # 840: # Presumedly there will be few matching roles from the above 841: # loop and the sorting time will be negligible. 842: if (scalar(keys(%Pending))) { 843: my ($time) = sort {$a <=> $b} keys(%Pending); 844: return &do_cache(\%getsectioncache,$hashid,$Pending{$time},'getsection'); 845: } 846: if (scalar(keys(%Expired))) { 847: my @sorted = sort {$a <=> $b} keys(%Expired); 848: my $time = pop(@sorted); 849: return &do_cache(\%getsectioncache,$hashid,$Expired{$time},'getsection'); 850: } 851: return &do_cache(\%getsectioncache,$hashid,'-1','getsection'); 852: } 853: 854: 855: my $disk_caching_disabled=1; 856: 857: sub devalidate_cache { 858: my ($cache,$id,$name) = @_; 859: delete $$cache{$id.'.time'}; 860: delete $$cache{$id.'.file'}; 861: delete $$cache{$id}; 862: if (1 || $disk_caching_disabled) { return; } 863: my $filename=$perlvar{'lonDaemons'}.'/tmp/lonnet_internal_cache_'.$name.".db"; 864: if (!-e $filename) { return; } 865: open(DB,">$filename.lock"); 866: flock(DB,LOCK_EX); 867: my %hash; 868: if (tie(%hash,'GDBM_File',$filename,&GDBM_WRCREAT(),0640)) { 869: eval <<'EVALBLOCK'; 870: delete($hash{$id}); 871: delete($hash{$id.'.time'}); 872: EVALBLOCK 873: if ($@) { 874: &logthis("<font color='red'>devalidate_cache blew up :$@:$name</font>"); 875: unlink($filename); 876: } 877: } else { 878: if (-e $filename) { 879: &logthis("Unable to tie hash (devalidate cache): $name"); 880: unlink($filename); 881: } 882: } 883: untie(%hash); 884: flock(DB,LOCK_UN); 885: close(DB); 886: } 887: 888: sub is_cached { 889: my ($cache,$id,$name,$time) = @_; 890: if (!$time) { $time=300; } 891: if (!exists($$cache{$id.'.time'})) { 892: &load_cache_item($cache,$name,$id,$time); 893: } 894: if (!exists($$cache{$id.'.time'})) { 895: # &logthis("Didn't find $id"); 896: return (undef,undef); 897: } else { 898: if (time-($$cache{$id.'.time'})>$time) { 899: if (exists($$cache{$id.'.file'})) { 900: foreach my $filename (@{ $$cache{$id.'.file'} }) { 901: my $mtime=(stat($filename))[9]; 902: #+1 is to take care of edge effects 903: if ($mtime && (($mtime+1) < ($$cache{$id.'.time'}))) { 904: # &logthis("Upping $mtime - ".$$cache{$id.'.time'}. 905: # "$id because of $filename"); 906: } else { 907: &logthis("Devalidating $filename $id - ".(time-($$cache{$id.'.time'}))); 908: &devalidate_cache($cache,$id,$name); 909: return (undef,undef); 910: } 911: } 912: $$cache{$id.'.time'}=time; 913: } else { 914: # &logthis("Devalidating $id - ".time-($$cache{$id.'.time'})); 915: &devalidate_cache($cache,$id,$name); 916: return (undef,undef); 917: } 918: } 919: } 920: return ($$cache{$id},1); 921: } 922: 923: sub do_cache { 924: my ($cache,$id,$value,$name) = @_; 925: $$cache{$id.'.time'}=time; 926: $$cache{$id}=$value; 927: # &logthis("Caching $id as :$value:"); 928: &save_cache_item($cache,$name,$id); 929: # do_cache implictly return the set value 930: $$cache{$id}; 931: } 932: 933: my %do_save_item; 934: my %do_save; 935: sub save_cache_item { 936: my ($cache,$name,$id)=@_; 937: if ($disk_caching_disabled) { return; } 938: $do_save{$name}=$cache; 939: if (!exists($do_save_item{$name})) { $do_save_item{$name}={} } 940: $do_save_item{$name}->{$id}=1; 941: return; 942: } 943: 944: sub save_cache { 945: if ($disk_caching_disabled) { return; } 946: my ($cache,$name,$id); 947: foreach $name (keys(%do_save)) { 948: $cache=$do_save{$name}; 949: 950: my $starttime=&Time::HiRes::time(); 951: &logthis("Saving :$name:"); 952: my %hash; 953: my $filename=$perlvar{'lonDaemons'}.'/tmp/lonnet_internal_cache_'.$name.".db"; 954: open(DB,">$filename.lock"); 955: flock(DB,LOCK_EX); 956: if (tie(%hash,'GDBM_File',$filename,&GDBM_WRCREAT(),0640)) { 957: foreach $id (keys(%{ $do_save_item{$name} })) { 958: eval <<'EVALBLOCK'; 959: $hash{$id.'.time'}=$$cache{$id.'.time'}; 960: $hash{$id}=freeze({'item'=>$$cache{$id}}); 961: if (exists($$cache{$id.'.file'})) { 962: $hash{$id.'.file'}=freeze({'item'=>$$cache{$id.'.file'}}); 963: } 964: EVALBLOCK 965: if ($@) { 966: &logthis("<font color='red'>save_cache blew up :$@:$name</font>"); 967: unlink($filename); 968: last; 969: } 970: } 971: } else { 972: if (-e $filename) { 973: &logthis("Unable to tie hash (save cache): $name ($!)"); 974: unlink($filename); 975: } 976: } 977: untie(%hash); 978: flock(DB,LOCK_UN); 979: close(DB); 980: &logthis("save_cache $name took ".(&Time::HiRes::time()-$starttime)); 981: } 982: undef(%do_save); 983: undef(%do_save_item); 984: 985: } 986: 987: sub load_cache_item { 988: my ($cache,$name,$id,$time)=@_; 989: if ($disk_caching_disabled) { return; } 990: my $starttime=&Time::HiRes::time(); 991: # &logthis("Before Loading $name for $id size is ".scalar(%$cache)); 992: my %hash; 993: my $filename=$perlvar{'lonDaemons'}.'/tmp/lonnet_internal_cache_'.$name.".db"; 994: if (!-e $filename) { return; } 995: open(DB,">$filename.lock"); 996: flock(DB,LOCK_SH); 997: if (tie(%hash,'GDBM_File',$filename,&GDBM_READER(),0640)) { 998: eval <<'EVALBLOCK'; 999: if (!%$cache) { 1000: my $count; 1001: while (my ($key,$value)=each(%hash)) { 1002: $count++; 1003: if ($key =~ /\.time$/) { 1004: $$cache{$key}=$value; 1005: } else { 1006: my $hashref=thaw($value); 1007: $$cache{$key}=$hashref->{'item'}; 1008: } 1009: } 1010: # &logthis("Initial load: $count"); 1011: } else { 1012: if (($$cache{$id.'.time'}+$time) < time) { 1013: $$cache{$id.'.time'}=$hash{$id.'.time'}; 1014: { 1015: my $hashref=thaw($hash{$id}); 1016: $$cache{$id}=$hashref->{'item'}; 1017: } 1018: if (exists($hash{$id.'.file'})) { 1019: my $hashref=thaw($hash{$id.'.file'}); 1020: $$cache{$id.'.file'}=$hashref->{'item'}; 1021: } 1022: } 1023: } 1024: EVALBLOCK 1025: if ($@) { 1026: &logthis("<font color='red'>load_cache blew up :$@:$name</font>"); 1027: unlink($filename); 1028: } 1029: } else { 1030: if (-e $filename) { 1031: &logthis("Unable to tie hash (load cache item): $name ($!)"); 1032: unlink($filename); 1033: } 1034: } 1035: untie(%hash); 1036: flock(DB,LOCK_UN); 1037: close(DB); 1038: # &logthis("After Loading $name size is ".scalar(%$cache)); 1039: # &logthis("load_cache_item $name took ".(&Time::HiRes::time()-$starttime)); 1040: } 1041: 1042: # ------------------------------------- Read an entry from a user's environment 1043: 1044: sub userenvironment { 1045: my ($udom,$unam,@what)=@_; 1046: my %returnhash=(); 1047: my @answer=split(/\&/, 1048: &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what), 1049: &homeserver($unam,$udom))); 1050: my $i; 1051: for ($i=0;$i<=$#what;$i++) { 1052: $returnhash{$what[$i]}=&unescape($answer[$i]); 1053: } 1054: return %returnhash; 1055: } 1056: 1057: # -------------------------------------------------------------------- New chat 1058: 1059: sub chatsend { 1060: my ($newentry,$anon)=@_; 1061: my $cnum=$ENV{'course.'.$ENV{'request.course.id'}.'.num'}; 1062: my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'}; 1063: my $chome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'}; 1064: &reply('chatsend:'.$cdom.':'.$cnum.':'. 1065: &escape($ENV{'user.domain'}.':'.$ENV{'user.name'}.':'.$anon.':'. 1066: &escape($newentry)),$chome); 1067: } 1068: 1069: # ------------------------------------------ Find current version of a resource 1070: 1071: sub getversion { 1072: my $fname=&clutter(shift); 1073: unless ($fname=~/^\/res\//) { return -1; } 1074: return ¤tversion(&filelocation('',$fname)); 1075: } 1076: 1077: sub currentversion { 1078: my $fname=shift; 1079: my ($result,$cached)=&is_cached(\%resversioncache,$fname,'resversion',600); 1080: if (defined($cached)) { return $result; } 1081: my $author=$fname; 1082: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/; 1083: my ($udom,$uname)=split(/\//,$author); 1084: my $home=homeserver($uname,$udom); 1085: if ($home eq 'no_host') { 1086: return -1; 1087: } 1088: my $answer=reply("currentversion:$fname",$home); 1089: if (($answer eq 'con_lost') || ($answer eq 'rejected')) { 1090: return -1; 1091: } 1092: return &do_cache(\%resversioncache,$fname,$answer,'resversion'); 1093: } 1094: 1095: # ----------------------------- Subscribe to a resource, return URL if possible 1096: 1097: sub subscribe { 1098: my $fname=shift; 1099: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; } 1100: $fname=~s/[\n\r]//g; 1101: my $author=$fname; 1102: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/; 1103: my ($udom,$uname)=split(/\//,$author); 1104: my $home=homeserver($uname,$udom); 1105: if ($home eq 'no_host') { 1106: return 'not_found'; 1107: } 1108: my $answer=reply("sub:$fname",$home); 1109: if (($answer eq 'con_lost') || ($answer eq 'rejected')) { 1110: $answer.=' by '.$home; 1111: } 1112: return $answer; 1113: } 1114: 1115: # -------------------------------------------------------------- Replicate file 1116: 1117: sub repcopy { 1118: my $filename=shift; 1119: $filename=~s/\/+/\//g; 1120: if ($filename=~m|^/home/httpd/html/adm/|) { return OK; } 1121: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return OK; } 1122: if ($filename=~m|^/home/httpd/html/userfiles/| or 1123: $filename=~m|^/*uploaded/|) { 1124: return &repcopy_userfile($filename); 1125: } 1126: $filename=~s/[\n\r]//g; 1127: my $transname="$filename.in.transfer"; 1128: if ((-e $filename) || (-e $transname)) { return OK; } 1129: my $remoteurl=subscribe($filename); 1130: if ($remoteurl =~ /^con_lost by/) { 1131: &logthis("Subscribe returned $remoteurl: $filename"); 1132: return HTTP_SERVICE_UNAVAILABLE; 1133: } elsif ($remoteurl eq 'not_found') { 1134: #&logthis("Subscribe returned not_found: $filename"); 1135: return HTTP_NOT_FOUND; 1136: } elsif ($remoteurl =~ /^rejected by/) { 1137: &logthis("Subscribe returned $remoteurl: $filename"); 1138: return FORBIDDEN; 1139: } elsif ($remoteurl eq 'directory') { 1140: return OK; 1141: } else { 1142: my $author=$filename; 1143: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/; 1144: my ($udom,$uname)=split(/\//,$author); 1145: my $home=homeserver($uname,$udom); 1146: unless ($home eq $perlvar{'lonHostID'}) { 1147: my @parts=split(/\//,$filename); 1148: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]"; 1149: if ($path ne "$perlvar{'lonDocRoot'}/res") { 1150: &logthis("Malconfiguration for replication: $filename"); 1151: return HTTP_BAD_REQUEST; 1152: } 1153: my $count; 1154: for ($count=5;$count<$#parts;$count++) { 1155: $path.="/$parts[$count]"; 1156: if ((-e $path)!=1) { 1157: mkdir($path,0777); 1158: } 1159: } 1160: my $ua=new LWP::UserAgent; 1161: my $request=new HTTP::Request('GET',"$remoteurl"); 1162: my $response=$ua->request($request,$transname); 1163: if ($response->is_error()) { 1164: unlink($transname); 1165: my $message=$response->status_line; 1166: &logthis("<font color=blue>WARNING:" 1167: ." LWP get: $message: $filename</font>"); 1168: return HTTP_SERVICE_UNAVAILABLE; 1169: } else { 1170: if ($remoteurl!~/\.meta$/) { 1171: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta'); 1172: my $mresponse=$ua->request($mrequest,$filename.'.meta'); 1173: if ($mresponse->is_error()) { 1174: unlink($filename.'.meta'); 1175: &logthis( 1176: "<font color=yellow>INFO: No metadata: $filename</font>"); 1177: } 1178: } 1179: rename($transname,$filename); 1180: return OK; 1181: } 1182: } 1183: } 1184: } 1185: 1186: # ------------------------------------------------ Get server side include body 1187: sub ssi_body { 1188: my ($filelink,%form)=@_; 1189: my $output=($filelink=~/^http\:/?&externalssi($filelink): 1190: &ssi($filelink,%form)); 1191: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+// END LON-CAPA Internal\s*(-->)?\s||gs; 1192: $output=~s/^.*?\<body[^\>]*\>//si; 1193: $output=~s/(.*)\<\/body\s*\>.*?$/$1/si; 1194: return $output; 1195: } 1196: 1197: # --------------------------------------------------------- Server Side Include 1198: 1199: sub ssi { 1200: 1201: my ($fn,%form)=@_; 1202: 1203: my $ua=new LWP::UserAgent; 1204: 1205: my $request; 1206: 1207: if (%form) { 1208: $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn); 1209: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form)); 1210: } else { 1211: $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn); 1212: } 1213: 1214: $request->header(Cookie => $ENV{'HTTP_COOKIE'}); 1215: my $response=$ua->request($request); 1216: 1217: return $response->content; 1218: } 1219: 1220: sub externalssi { 1221: my ($url)=@_; 1222: my $ua=new LWP::UserAgent; 1223: my $request=new HTTP::Request('GET',$url); 1224: my $response=$ua->request($request); 1225: return $response->content; 1226: } 1227: 1228: # -------------------------------- Allow a /uploaded/ URI to be vouched for 1229: 1230: sub allowuploaded { 1231: my ($srcurl,$url)=@_; 1232: $url=&clutter(&declutter($url)); 1233: my $dir=$url; 1234: $dir=~s/\/[^\/]+$//; 1235: my %httpref=(); 1236: my $httpurl=&hreflocation('',$url); 1237: $httpref{'httpref.'.$httpurl}=$srcurl; 1238: &Apache::lonnet::appenv(%httpref); 1239: } 1240: 1241: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course 1242: # input: action, courseID, current domain, home server for course, intended 1243: # path to file, source of file. 1244: # output: url to file (if action was uploaddoc), 1245: # ok if successful, or diagnostic message otherwise (if action was propagate or copy) 1246: # 1247: # Allows directory structure to be used within lonUsers/../userfiles/ for a 1248: # course. 1249: # 1250: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file 1251: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in 1252: # course's home server. 1253: # 1254: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will 1255: # be copied from $source (current location) to 1256: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file 1257: # and will then be copied to 1258: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in 1259: # course's home server. 1260: # 1261: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file 1262: # will be retrived from $ENV{form.uploaddoc} (from DOCS interface) to 1263: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file 1264: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file 1265: # in course's home server. 1266: 1267: 1268: sub process_coursefile { 1269: my ($action,$docuname,$docudom,$docuhome,$file,$source)=@_; 1270: my $fetchresult; 1271: if ($action eq 'propagate') { 1272: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file 1273: ,$docuhome); 1274: } else { 1275: my $fetchresult = ''; 1276: my $fpath = ''; 1277: my $fname = $file; 1278: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|); 1279: $fpath=$docudom.'/'.$docuname.'/'.$fpath; 1280: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles'; 1281: unless ($fpath eq '') { 1282: my @parts=split('/',$fpath); 1283: foreach my $part (@parts) { 1284: $filepath.= '/'.$part; 1285: if ((-e $filepath)!=1) { 1286: mkdir($filepath,0777); 1287: } 1288: } 1289: } 1290: if ($action eq 'copy') { 1291: if ($source eq '') { 1292: $fetchresult = 'no source file'; 1293: return $fetchresult; 1294: } else { 1295: my $destination = $filepath.'/'.$fname; 1296: rename($source,$destination); 1297: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file, 1298: $docuhome); 1299: } 1300: } elsif ($action eq 'uploaddoc') { 1301: open(my $fh,'>'.$filepath.'/'.$fname); 1302: print $fh $ENV{'form.'.$source}; 1303: close($fh); 1304: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file, 1305: $docuhome); 1306: if ($fetchresult eq 'ok') { 1307: return '/uploaded/'.$fpath.'/'.$fname; 1308: } else { 1309: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file. 1310: ' to host '.$docuhome.': '.$fetchresult); 1311: return '/adm/notfound.html'; 1312: } 1313: } 1314: } 1315: unless ( $fetchresult eq 'ok') { 1316: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file. 1317: ' to host '.$docuhome.': '.$fetchresult); 1318: } 1319: return $fetchresult; 1320: } 1321: 1322: # --------------- Take an uploaded file and put it into the userfiles directory 1323: # input: name of form element, coursedoc=1 means this is for the course 1324: # output: url of file in userspace 1325: 1326: sub clean_filename { 1327: my ($fname)=@_; 1328: # Replace Windows backslashes by forward slashes 1329: $fname=~s/\\/\//g; 1330: # Get rid of everything but the actual filename 1331: $fname=~s/^.*\/([^\/]+)$/$1/; 1332: # Replace spaces by underscores 1333: $fname=~s/\s+/\_/g; 1334: # Replace all other weird characters by nothing 1335: $fname=~s/[^\w\.\-]//g; 1336: # Replace all .\d. sequences with _\d. so they no longer look like version 1337: # numbers 1338: $fname=~s/\.(\d+)(?=\.)/_$1/g; 1339: return $fname; 1340: } 1341: 1342: sub userfileupload { 1343: my ($formname,$coursedoc,$subdir)=@_; 1344: if (!defined($subdir)) { $subdir='unknown'; } 1345: my $fname=$ENV{'form.'.$formname.'.filename'}; 1346: $fname=&clean_filename($fname); 1347: # See if there is anything left 1348: unless ($fname) { return 'error: no uploaded file'; } 1349: chop($ENV{'form.'.$formname}); 1350: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently 1351: my $now = time; 1352: my $filepath = 'tmp/helprequests/'.$now; 1353: my @parts=split(/\//,$filepath); 1354: my $fullpath = $perlvar{'lonDaemons'}; 1355: for (my $i=0;$i<@parts;$i++) { 1356: $fullpath .= '/'.$parts[$i]; 1357: if ((-e $fullpath)!=1) { 1358: mkdir($fullpath,0777); 1359: } 1360: } 1361: open(my $fh,'>'.$fullpath.'/'.$fname); 1362: print $fh $ENV{'form.'.$formname}; 1363: close($fh); 1364: return $fullpath.'/'.$fname; 1365: } 1366: # Create the directory if not present 1367: my $docuname=''; 1368: my $docudom=''; 1369: my $docuhome=''; 1370: $fname="$subdir/$fname"; 1371: if ($coursedoc) { 1372: $docuname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'}; 1373: $docudom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'}; 1374: $docuhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'}; 1375: if ($ENV{'form.folder'} =~ m/^default/) { 1376: return &finishuserfileupload($docuname,$docudom,$docuhome,$formname,$fname); 1377: } else { 1378: $fname=$ENV{'form.folder'}.'/'.$fname; 1379: return &process_coursefile('uploaddoc',$docuname,$docudom,$docuhome,$fname,$formname); 1380: } 1381: } else { 1382: $docuname=$ENV{'user.name'}; 1383: $docudom=$ENV{'user.domain'}; 1384: $docuhome=$ENV{'user.home'}; 1385: return &finishuserfileupload($docuname,$docudom,$docuhome,$formname,$fname); 1386: } 1387: } 1388: 1389: sub finishuserfileupload { 1390: my ($docuname,$docudom,$docuhome,$formname,$fname)=@_; 1391: my $path=$docudom.'/'.$docuname.'/'; 1392: my $filepath=$perlvar{'lonDocRoot'}; 1393: my ($fnamepath,$file); 1394: $file=$fname; 1395: if ($fname=~m|/|) { 1396: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|); 1397: $path.=$fnamepath.'/'; 1398: } 1399: my @parts=split(/\//,$filepath.'/userfiles/'.$path); 1400: my $count; 1401: for ($count=4;$count<=$#parts;$count++) { 1402: $filepath.="/$parts[$count]"; 1403: if ((-e $filepath)!=1) { 1404: mkdir($filepath,0777); 1405: } 1406: } 1407: # Save the file 1408: { 1409: open(FH,'>'.$filepath.'/'.$file); 1410: print FH $ENV{'form.'.$formname}; 1411: close(FH); 1412: } 1413: # Notify homeserver to grep it 1414: # 1415: &Apache::lonnet::logthis("fetching ".$path.$file); 1416: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome); 1417: if ($fetchresult eq 'ok') { 1418: # 1419: # Return the URL to it 1420: return '/uploaded/'.$path.$file; 1421: } else { 1422: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome. 1423: ': '.$fetchresult); 1424: return '/adm/notfound.html'; 1425: } 1426: } 1427: 1428: sub removeuploadedurl { 1429: my ($url)=@_; 1430: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5); 1431: return &Apache::lonnet::removeuserfile($uname,$udom,$fname); 1432: } 1433: 1434: sub removeuserfile { 1435: my ($docuname,$docudom,$fname)=@_; 1436: my $home=&homeserver($docuname,$docudom); 1437: return &reply("removeuserfile:$docudom/$docuname/$fname",$home); 1438: } 1439: 1440: sub mkdiruserfile { 1441: my ($docuname,$docudom,$dir)=@_; 1442: my $home=&homeserver($docuname,$docudom); 1443: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home); 1444: } 1445: 1446: sub renameuserfile { 1447: my ($docuname,$docudom,$old,$new)=@_; 1448: my $home=&homeserver($docuname,$docudom); 1449: return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'. 1450: &escape("$new"),$home); 1451: } 1452: 1453: # ------------------------------------------------------------------------- Log 1454: 1455: sub log { 1456: my ($dom,$nam,$hom,$what)=@_; 1457: return critical("log:$dom:$nam:$what",$hom); 1458: } 1459: 1460: # ------------------------------------------------------------------ Course Log 1461: # 1462: # This routine flushes several buffers of non-mission-critical nature 1463: # 1464: 1465: sub flushcourselogs { 1466: &logthis('Flushing log buffers'); 1467: # 1468: # course logs 1469: # This is a log of all transactions in a course, which can be used 1470: # for data mining purposes 1471: # 1472: # It also collects the courseid database, which lists last transaction 1473: # times and course titles for all courseids 1474: # 1475: my %courseidbuffer=(); 1476: foreach (keys %courselogs) { 1477: my $crsid=$_; 1478: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'. 1479: &escape($courselogs{$crsid}), 1480: $coursehombuf{$crsid}) eq 'ok') { 1481: delete $courselogs{$crsid}; 1482: } else { 1483: &logthis('Failed to flush log buffer for '.$crsid); 1484: if (length($courselogs{$crsid})>40000) { 1485: &logthis("<font color=blue>WARNING: Buffer for ".$crsid. 1486: " exceeded maximum size, deleting.</font>"); 1487: delete $courselogs{$crsid}; 1488: } 1489: } 1490: if ($courseidbuffer{$coursehombuf{$crsid}}) { 1491: $courseidbuffer{$coursehombuf{$crsid}}.='&'. 1492: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}). 1493: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}); 1494: } else { 1495: $courseidbuffer{$coursehombuf{$crsid}}= 1496: &escape($crsid).'='.&escape($coursedescrbuf{$crsid}). 1497: ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}); 1498: } 1499: } 1500: # 1501: # Write course id database (reverse lookup) to homeserver of courses 1502: # Is used in pickcourse 1503: # 1504: foreach (keys %courseidbuffer) { 1505: &courseidput($hostdom{$_},$courseidbuffer{$_},$_); 1506: } 1507: # 1508: # File accesses 1509: # Writes to the dynamic metadata of resources to get hit counts, etc. 1510: # 1511: foreach my $entry (keys(%accesshash)) { 1512: if ($entry =~ /___count$/) { 1513: my ($dom,$name); 1514: ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:); 1515: if (! defined($dom) || $dom eq '' || 1516: ! defined($name) || $name eq '') { 1517: my $cid = $ENV{'request.course.id'}; 1518: $dom = $ENV{'request.'.$cid.'.domain'}; 1519: $name = $ENV{'request.'.$cid.'.num'}; 1520: } 1521: my $value = $accesshash{$entry}; 1522: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/); 1523: my %temphash=($url => $value); 1524: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name); 1525: if ($result eq 'ok') { 1526: delete $accesshash{$entry}; 1527: } elsif ($result eq 'unknown_cmd') { 1528: # Target server has old code running on it. 1529: my %temphash=($entry => $value); 1530: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') { 1531: delete $accesshash{$entry}; 1532: } 1533: } 1534: } else { 1535: my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:); 1536: my %temphash=($entry => $accesshash{$entry}); 1537: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') { 1538: delete $accesshash{$entry}; 1539: } 1540: } 1541: } 1542: # 1543: # Roles 1544: # Reverse lookup of user roles for course faculty/staff and co-authorship 1545: # 1546: foreach (keys %userrolehash) { 1547: my $entry=$_; 1548: my ($role,$uname,$udom,$runame,$rudom,$rsec)= 1549: split(/\:/,$entry); 1550: if (&Apache::lonnet::put('nohist_userroles', 1551: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} }, 1552: $rudom,$runame) eq 'ok') { 1553: delete $userrolehash{$entry}; 1554: } 1555: } 1556: $dumpcount++; 1557: } 1558: 1559: sub courselog { 1560: my $what=shift; 1561: $what=time.':'.$what; 1562: unless ($ENV{'request.course.id'}) { return ''; } 1563: $coursedombuf{$ENV{'request.course.id'}}= 1564: $ENV{'course.'.$ENV{'request.course.id'}.'.domain'}; 1565: $coursenumbuf{$ENV{'request.course.id'}}= 1566: $ENV{'course.'.$ENV{'request.course.id'}.'.num'}; 1567: $coursehombuf{$ENV{'request.course.id'}}= 1568: $ENV{'course.'.$ENV{'request.course.id'}.'.home'}; 1569: $coursedescrbuf{$ENV{'request.course.id'}}= 1570: $ENV{'course.'.$ENV{'request.course.id'}.'.description'}; 1571: $courseinstcodebuf{$ENV{'request.course.id'}}= 1572: $ENV{'course.'.$ENV{'request.course.id'}.'.internal.coursecode'}; 1573: $courseownerbuf{$ENV{'request.course.id'}}= 1574: $ENV{'course.'.$ENV{'request.course.id'}.'.internal.courseowner'}; 1575: if (defined $courselogs{$ENV{'request.course.id'}}) { 1576: $courselogs{$ENV{'request.course.id'}}.='&'.$what; 1577: } else { 1578: $courselogs{$ENV{'request.course.id'}}.=$what; 1579: } 1580: if (length($courselogs{$ENV{'request.course.id'}})>4048) { 1581: &flushcourselogs(); 1582: } 1583: } 1584: 1585: sub courseacclog { 1586: my $fnsymb=shift; 1587: unless ($ENV{'request.course.id'}) { return ''; } 1588: my $what=$fnsymb.':'.$ENV{'user.name'}.':'.$ENV{'user.domain'}; 1589: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|page)$/) { 1590: $what.=':POST'; 1591: # FIXME: Probably ought to escape things.... 1592: foreach (keys %ENV) { 1593: if ($_=~/^form\.(.*)/) { 1594: $what.=':'.$1.'='.$ENV{$_}; 1595: } 1596: } 1597: } elsif ($fnsymb =~ m:^/adm/searchcat:) { 1598: # FIXME: We should not be depending on a form parameter that someone 1599: # editing lonsearchcat.pm might change in the future. 1600: if ($ENV{'form.phase'} eq 'course_search') { 1601: $what.= ':POST'; 1602: # FIXME: Probably ought to escape things.... 1603: foreach my $element ('courseexp','crsfulltext','crsrelated', 1604: 'crsdiscuss') { 1605: $what.=':'.$element.'='.$ENV{'form.'.$element}; 1606: } 1607: } 1608: } 1609: &courselog($what); 1610: } 1611: 1612: sub countacc { 1613: my $url=&declutter(shift); 1614: return if (! defined($url) || $url eq ''); 1615: unless ($ENV{'request.course.id'}) { return ''; } 1616: $accesshash{$ENV{'request.course.id'}.'___'.$url.'___course'}=1; 1617: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count'; 1618: $accesshash{$key}++; 1619: } 1620: 1621: sub linklog { 1622: my ($from,$to)=@_; 1623: $from=&declutter($from); 1624: $to=&declutter($to); 1625: $accesshash{$from.'___'.$to.'___comefrom'}=1; 1626: $accesshash{$to.'___'.$from.'___goto'}=1; 1627: } 1628: 1629: sub userrolelog { 1630: my ($trole,$username,$domain,$area,$tstart,$tend)=@_; 1631: if (($trole=~/^ca/) || ($trole=~/^in/) || 1632: ($trole=~/^cc/) || ($trole=~/^ep/) || 1633: ($trole=~/^cr/) || ($trole=~/^ta/)) { 1634: my (undef,$rudom,$runame,$rsec)=split(/\//,$area); 1635: $userrolehash 1636: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec} 1637: =$tend.':'.$tstart; 1638: } 1639: } 1640: 1641: sub get_course_adv_roles { 1642: my $cid=shift; 1643: $cid=$ENV{'request.course.id'} unless (defined($cid)); 1644: my %coursehash=&coursedescription($cid); 1645: my %nothide=(); 1646: foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) { 1647: $nothide{join(':',split(/[\@\:]/,$_))}=1; 1648: } 1649: my %returnhash=(); 1650: my %dumphash= 1651: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'}); 1652: my $now=time; 1653: foreach (keys %dumphash) { 1654: my ($tend,$tstart)=split(/\:/,$dumphash{$_}); 1655: if (($tstart) && ($tstart<0)) { next; } 1656: if (($tend) && ($tend<$now)) { next; } 1657: if (($tstart) && ($now<$tstart)) { next; } 1658: my ($role,$username,$domain,$section)=split(/\:/,$_); 1659: if ($username eq '' || $domain eq '') { next; } 1660: if ((&privileged($username,$domain)) && 1661: (!$nothide{$username.':'.$domain})) { next; } 1662: my $key=&plaintext($role); 1663: if ($section) { $key.=' (Sec/Grp '.$section.')'; } 1664: if ($returnhash{$key}) { 1665: $returnhash{$key}.=','.$username.':'.$domain; 1666: } else { 1667: $returnhash{$key}=$username.':'.$domain; 1668: } 1669: } 1670: return %returnhash; 1671: } 1672: 1673: sub get_my_roles { 1674: my ($uname,$udom)=@_; 1675: unless (defined($uname)) { $uname=$ENV{'user.name'}; } 1676: unless (defined($udom)) { $udom=$ENV{'user.domain'}; } 1677: my %dumphash= 1678: &dump('nohist_userroles',$udom,$uname); 1679: my %returnhash=(); 1680: my $now=time; 1681: foreach (keys %dumphash) { 1682: my ($tend,$tstart)=split(/\:/,$dumphash{$_}); 1683: if (($tstart) && ($tstart<0)) { next; } 1684: if (($tend) && ($tend<$now)) { next; } 1685: if (($tstart) && ($now<$tstart)) { next; } 1686: my ($role,$username,$domain,$section)=split(/\:/,$_); 1687: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend; 1688: } 1689: return %returnhash; 1690: } 1691: 1692: # ----------------------------------------------------- Frontpage Announcements 1693: # 1694: # 1695: 1696: sub postannounce { 1697: my ($server,$text)=@_; 1698: unless (&allowed('psa',$hostdom{$server})) { return 'refused'; } 1699: unless ($text=~/\w/) { $text=''; } 1700: return &reply('setannounce:'.&escape($text),$server); 1701: } 1702: 1703: sub getannounce { 1704: 1705: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) { 1706: my $announcement=''; 1707: while (<$fh>) { $announcement .=$_; } 1708: close($fh); 1709: if ($announcement=~/\w/) { 1710: return 1711: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'. 1712: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 1713: } else { 1714: return ''; 1715: } 1716: } else { 1717: return ''; 1718: } 1719: } 1720: 1721: # ---------------------------------------------------------- Course ID routines 1722: # Deal with domain's nohist_courseid.db files 1723: # 1724: 1725: sub courseidput { 1726: my ($domain,$what,$coursehome)=@_; 1727: return &reply('courseidput:'.$domain.':'.$what,$coursehome); 1728: } 1729: 1730: sub courseiddump { 1731: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$hostidflag,$hostidref)=@_; 1732: my %returnhash=(); 1733: unless ($domfilter) { $domfilter=''; } 1734: foreach my $tryserver (keys %libserv) { 1735: if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) { 1736: if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) { 1737: foreach ( 1738: split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'. 1739: $sincefilter.':'.&escape($descfilter).':'. 1740: &escape($instcodefilter).':'.&escape($ownerfilter), 1741: $tryserver))) { 1742: my ($key,$value)=split(/\=/,$_); 1743: if (($key) && ($value)) { 1744: $returnhash{&unescape($key)}=$value; 1745: } 1746: } 1747: } 1748: } 1749: } 1750: return %returnhash; 1751: } 1752: 1753: # 1754: # ----------------------------------------------------------- Check out an item 1755: 1756: sub get_first_access { 1757: my ($type,$argsymb)=@_; 1758: my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser(); 1759: if ($argsymb) { $symb=$argsymb; } 1760: my ($map,$id,$res)=&decode_symb($symb); 1761: if ($type eq 'map') { $res=$map; } 1762: my %times=&get('firstaccesstimes',[$res],$udom,$uname); 1763: return $times{$res}; 1764: } 1765: 1766: sub set_first_access { 1767: my ($type)=@_; 1768: my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser(); 1769: my ($map,$id,$res)=&decode_symb($symb); 1770: if ($type eq 'map') { $res=$map; } 1771: my $firstaccess=&get_first_access($type); 1772: if (!$firstaccess) { 1773: return &put('firstaccesstimes',{$res=>time},$udom,$uname); 1774: } 1775: return 'already_set'; 1776: } 1777: 1778: sub checkout { 1779: my ($symb,$tuname,$tudom,$tcrsid)=@_; 1780: my $now=time; 1781: my $lonhost=$perlvar{'lonHostID'}; 1782: my $infostr=&escape( 1783: 'CHECKOUTTOKEN&'. 1784: $tuname.'&'. 1785: $tudom.'&'. 1786: $tcrsid.'&'. 1787: $symb.'&'. 1788: $now.'&'.$ENV{'REMOTE_ADDR'}); 1789: my $token=&reply('tmpput:'.$infostr,$lonhost); 1790: if ($token=~/^error\:/) { 1791: &logthis("<font color=blue>WARNING: ". 1792: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb. 1793: "</font>"); 1794: return ''; 1795: } 1796: 1797: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/; 1798: $token=~tr/a-z/A-Z/; 1799: 1800: my %infohash=('resource.0.outtoken' => $token, 1801: 'resource.0.checkouttime' => $now, 1802: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'}); 1803: 1804: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') { 1805: return ''; 1806: } else { 1807: &logthis("<font color=blue>WARNING: ". 1808: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb. 1809: "</font>"); 1810: } 1811: 1812: if (&log($tudom,$tuname,&homeserver($tuname,$tudom), 1813: &escape('Checkout '.$infostr.' - '. 1814: $token)) ne 'ok') { 1815: return ''; 1816: } else { 1817: &logthis("<font color=blue>WARNING: ". 1818: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb. 1819: "</font>"); 1820: } 1821: return $token; 1822: } 1823: 1824: # ------------------------------------------------------------ Check in an item 1825: 1826: sub checkin { 1827: my $token=shift; 1828: my $now=time; 1829: my ($ta,$tb,$lonhost)=split(/\*/,$token); 1830: $lonhost=~tr/A-Z/a-z/; 1831: my $dtoken=$ta.'_'.$hostip{$lonhost}.'_'.$tb; 1832: $dtoken=~s/\W/\_/g; 1833: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)= 1834: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost))); 1835: 1836: unless (($tuname) && ($tudom)) { 1837: &logthis('Check in '.$token.' ('.$dtoken.') failed'); 1838: return ''; 1839: } 1840: 1841: unless (&allowed('mgr',$tcrsid)) { 1842: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '. 1843: $ENV{'user.name'}.' - '.$ENV{'user.domain'}); 1844: return ''; 1845: } 1846: 1847: my %infohash=('resource.0.intoken' => $token, 1848: 'resource.0.checkintime' => $now, 1849: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'}); 1850: 1851: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') { 1852: return ''; 1853: } 1854: 1855: if (&log($tudom,$tuname,&homeserver($tuname,$tudom), 1856: &escape('Checkin - '.$token)) ne 'ok') { 1857: return ''; 1858: } 1859: 1860: return ($symb,$tuname,$tudom,$tcrsid); 1861: } 1862: 1863: # --------------------------------------------- Set Expire Date for Spreadsheet 1864: 1865: sub expirespread { 1866: my ($uname,$udom,$stype,$usymb)=@_; 1867: my $cid=$ENV{'request.course.id'}; 1868: if ($cid) { 1869: my $now=time; 1870: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb; 1871: return &reply('put:'.$ENV{'course.'.$cid.'.domain'}.':'. 1872: $ENV{'course.'.$cid.'.num'}. 1873: ':nohist_expirationdates:'. 1874: &escape($key).'='.$now, 1875: $ENV{'course.'.$cid.'.home'}) 1876: } 1877: return 'ok'; 1878: } 1879: 1880: # ----------------------------------------------------- Devalidate Spreadsheets 1881: 1882: sub devalidate { 1883: my ($symb,$uname,$udom)=@_; 1884: my $cid=$ENV{'request.course.id'}; 1885: if ($cid) { 1886: # delete the stored spreadsheets for 1887: # - the student level sheet of this user in course's homespace 1888: # - the assessment level sheet for this resource 1889: # for this user in user's homespace 1890: # - current conditional state info 1891: my $key=$uname.':'.$udom.':'; 1892: my $status= 1893: &del('nohist_calculatedsheets', 1894: [$key.'studentcalc:'], 1895: $ENV{'course.'.$cid.'.domain'}, 1896: $ENV{'course.'.$cid.'.num'}) 1897: .' '. 1898: &del('nohist_calculatedsheets_'.$cid, 1899: [$key.'assesscalc:'.$symb],$udom,$uname); 1900: unless ($status eq 'ok ok') { 1901: &logthis('Could not devalidate spreadsheet '. 1902: $uname.' at '.$udom.' for '. 1903: $symb.': '.$status); 1904: } 1905: &delenv('user.state.'.$cid); 1906: } 1907: } 1908: 1909: sub get_scalar { 1910: my ($string,$end) = @_; 1911: my $value; 1912: if ($$string =~ s/^([^&]*?)($end)/$2/) { 1913: $value = $1; 1914: } elsif ($$string =~ s/^([^&]*?)&//) { 1915: $value = $1; 1916: } 1917: return &unescape($value); 1918: } 1919: 1920: sub array2str { 1921: my (@array) = @_; 1922: my $result=&arrayref2str(\@array); 1923: $result=~s/^__ARRAY_REF__//; 1924: $result=~s/__END_ARRAY_REF__$//; 1925: return $result; 1926: } 1927: 1928: sub arrayref2str { 1929: my ($arrayref) = @_; 1930: my $result='__ARRAY_REF__'; 1931: foreach my $elem (@$arrayref) { 1932: if(ref($elem) eq 'ARRAY') { 1933: $result.=&arrayref2str($elem).'&'; 1934: } elsif(ref($elem) eq 'HASH') { 1935: $result.=&hashref2str($elem).'&'; 1936: } elsif(ref($elem)) { 1937: #print("Got a ref of ".(ref($elem))." skipping."); 1938: } else { 1939: $result.=&escape($elem).'&'; 1940: } 1941: } 1942: $result=~s/\&$//; 1943: $result .= '__END_ARRAY_REF__'; 1944: return $result; 1945: } 1946: 1947: sub hash2str { 1948: my (%hash) = @_; 1949: my $result=&hashref2str(\%hash); 1950: $result=~s/^__HASH_REF__//; 1951: $result=~s/__END_HASH_REF__$//; 1952: return $result; 1953: } 1954: 1955: sub hashref2str { 1956: my ($hashref)=@_; 1957: my $result='__HASH_REF__'; 1958: foreach (sort(keys(%$hashref))) { 1959: if (ref($_) eq 'ARRAY') { 1960: $result.=&arrayref2str($_).'='; 1961: } elsif (ref($_) eq 'HASH') { 1962: $result.=&hashref2str($_).'='; 1963: } elsif (ref($_)) { 1964: $result.='='; 1965: #print("Got a ref of ".(ref($_))." skipping."); 1966: } else { 1967: if ($_) {$result.=&escape($_).'=';} else { last; } 1968: } 1969: 1970: if(ref($hashref->{$_}) eq 'ARRAY') { 1971: $result.=&arrayref2str($hashref->{$_}).'&'; 1972: } elsif(ref($hashref->{$_}) eq 'HASH') { 1973: $result.=&hashref2str($hashref->{$_}).'&'; 1974: } elsif(ref($hashref->{$_})) { 1975: $result.='&'; 1976: #print("Got a ref of ".(ref($hashref->{$_}))." skipping."); 1977: } else { 1978: $result.=&escape($hashref->{$_}).'&'; 1979: } 1980: } 1981: $result=~s/\&$//; 1982: $result .= '__END_HASH_REF__'; 1983: return $result; 1984: } 1985: 1986: sub str2hash { 1987: my ($string)=@_; 1988: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__'); 1989: return %$hash; 1990: } 1991: 1992: sub str2hashref { 1993: my ($string) = @_; 1994: 1995: my %hash; 1996: 1997: if($string !~ /^__HASH_REF__/) { 1998: if (! ($string eq '' || !defined($string))) { 1999: $hash{'error'}='Not hash reference'; 2000: } 2001: return (\%hash, $string); 2002: } 2003: 2004: $string =~ s/^__HASH_REF__//; 2005: 2006: while($string !~ /^__END_HASH_REF__/) { 2007: #key 2008: my $key=''; 2009: if($string =~ /^__HASH_REF__/) { 2010: ($key, $string)=&str2hashref($string); 2011: if(defined($key->{'error'})) { 2012: $hash{'error'}='Bad data'; 2013: return (\%hash, $string); 2014: } 2015: } elsif($string =~ /^__ARRAY_REF__/) { 2016: ($key, $string)=&str2arrayref($string); 2017: if($key->[0] eq 'Array reference error') { 2018: $hash{'error'}='Bad data'; 2019: return (\%hash, $string); 2020: } 2021: } else { 2022: $string =~ s/^(.*?)=//; 2023: $key=&unescape($1); 2024: } 2025: $string =~ s/^=//; 2026: 2027: #value 2028: my $value=''; 2029: if($string =~ /^__HASH_REF__/) { 2030: ($value, $string)=&str2hashref($string); 2031: if(defined($value->{'error'})) { 2032: $hash{'error'}='Bad data'; 2033: return (\%hash, $string); 2034: } 2035: } elsif($string =~ /^__ARRAY_REF__/) { 2036: ($value, $string)=&str2arrayref($string); 2037: if($value->[0] eq 'Array reference error') { 2038: $hash{'error'}='Bad data'; 2039: return (\%hash, $string); 2040: } 2041: } else { 2042: $value=&get_scalar(\$string,'__END_HASH_REF__'); 2043: } 2044: $string =~ s/^&//; 2045: 2046: $hash{$key}=$value; 2047: } 2048: 2049: $string =~ s/^__END_HASH_REF__//; 2050: 2051: return (\%hash, $string); 2052: } 2053: 2054: sub str2array { 2055: my ($string)=@_; 2056: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__'); 2057: return @$array; 2058: } 2059: 2060: sub str2arrayref { 2061: my ($string) = @_; 2062: my @array; 2063: 2064: if($string !~ /^__ARRAY_REF__/) { 2065: if (! ($string eq '' || !defined($string))) { 2066: $array[0]='Array reference error'; 2067: } 2068: return (\@array, $string); 2069: } 2070: 2071: $string =~ s/^__ARRAY_REF__//; 2072: 2073: while($string !~ /^__END_ARRAY_REF__/) { 2074: my $value=''; 2075: if($string =~ /^__HASH_REF__/) { 2076: ($value, $string)=&str2hashref($string); 2077: if(defined($value->{'error'})) { 2078: $array[0] ='Array reference error'; 2079: return (\@array, $string); 2080: } 2081: } elsif($string =~ /^__ARRAY_REF__/) { 2082: ($value, $string)=&str2arrayref($string); 2083: if($value->[0] eq 'Array reference error') { 2084: $array[0] ='Array reference error'; 2085: return (\@array, $string); 2086: } 2087: } else { 2088: $value=&get_scalar(\$string,'__END_ARRAY_REF__'); 2089: } 2090: $string =~ s/^&//; 2091: 2092: push(@array, $value); 2093: } 2094: 2095: $string =~ s/^__END_ARRAY_REF__//; 2096: 2097: return (\@array, $string); 2098: } 2099: 2100: # -------------------------------------------------------------------Temp Store 2101: 2102: sub tmpreset { 2103: my ($symb,$namespace,$domain,$stuname) = @_; 2104: if (!$symb) { 2105: $symb=&symbread(); 2106: if (!$symb) { $symb= $ENV{'request.url'}; } 2107: } 2108: $symb=escape($symb); 2109: 2110: if (!$namespace) { $namespace=$ENV{'request.state'}; } 2111: $namespace=~s/\//\_/g; 2112: $namespace=~s/\W//g; 2113: 2114: #FIXME needs to do something for /pub resources 2115: if (!$domain) { $domain=$ENV{'user.domain'}; } 2116: if (!$stuname) { $stuname=$ENV{'user.name'}; } 2117: my $path=$perlvar{'lonDaemons'}.'/tmp'; 2118: my %hash; 2119: if (tie(%hash,'GDBM_File', 2120: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db', 2121: &GDBM_WRCREAT(),0640)) { 2122: foreach my $key (keys %hash) { 2123: if ($key=~ /:$symb/) { 2124: delete($hash{$key}); 2125: } 2126: } 2127: } 2128: } 2129: 2130: sub tmpstore { 2131: my ($storehash,$symb,$namespace,$domain,$stuname) = @_; 2132: 2133: if (!$symb) { 2134: $symb=&symbread(); 2135: if (!$symb) { $symb= $ENV{'request.url'}; } 2136: } 2137: $symb=escape($symb); 2138: 2139: if (!$namespace) { 2140: # I don't think we would ever want to store this for a course. 2141: # it seems this will only be used if we don't have a course. 2142: #$namespace=$ENV{'request.course.id'}; 2143: #if (!$namespace) { 2144: $namespace=$ENV{'request.state'}; 2145: #} 2146: } 2147: $namespace=~s/\//\_/g; 2148: $namespace=~s/\W//g; 2149: #FIXME needs to do something for /pub resources 2150: if (!$domain) { $domain=$ENV{'user.domain'}; } 2151: if (!$stuname) { $stuname=$ENV{'user.name'}; } 2152: my $now=time; 2153: my %hash; 2154: my $path=$perlvar{'lonDaemons'}.'/tmp'; 2155: if (tie(%hash,'GDBM_File', 2156: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db', 2157: &GDBM_WRCREAT(),0640)) { 2158: $hash{"version:$symb"}++; 2159: my $version=$hash{"version:$symb"}; 2160: my $allkeys=''; 2161: foreach my $key (keys(%$storehash)) { 2162: $allkeys.=$key.':'; 2163: $hash{"$version:$symb:$key"}=$$storehash{$key}; 2164: } 2165: $hash{"$version:$symb:timestamp"}=$now; 2166: $allkeys.='timestamp'; 2167: $hash{"$version:keys:$symb"}=$allkeys; 2168: if (untie(%hash)) { 2169: return 'ok'; 2170: } else { 2171: return "error:$!"; 2172: } 2173: } else { 2174: return "error:$!"; 2175: } 2176: } 2177: 2178: # -----------------------------------------------------------------Temp Restore 2179: 2180: sub tmprestore { 2181: my ($symb,$namespace,$domain,$stuname) = @_; 2182: 2183: if (!$symb) { 2184: $symb=&symbread(); 2185: if (!$symb) { $symb= $ENV{'request.url'}; } 2186: } 2187: $symb=escape($symb); 2188: 2189: if (!$namespace) { $namespace=$ENV{'request.state'}; } 2190: #FIXME needs to do something for /pub resources 2191: if (!$domain) { $domain=$ENV{'user.domain'}; } 2192: if (!$stuname) { $stuname=$ENV{'user.name'}; } 2193: 2194: my %returnhash; 2195: $namespace=~s/\//\_/g; 2196: $namespace=~s/\W//g; 2197: my %hash; 2198: my $path=$perlvar{'lonDaemons'}.'/tmp'; 2199: if (tie(%hash,'GDBM_File', 2200: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db', 2201: &GDBM_READER(),0640)) { 2202: my $version=$hash{"version:$symb"}; 2203: $returnhash{'version'}=$version; 2204: my $scope; 2205: for ($scope=1;$scope<=$version;$scope++) { 2206: my $vkeys=$hash{"$scope:keys:$symb"}; 2207: my @keys=split(/:/,$vkeys); 2208: my $key; 2209: $returnhash{"$scope:keys"}=$vkeys; 2210: foreach $key (@keys) { 2211: $returnhash{"$scope:$key"}=$hash{"$scope:$symb:$key"}; 2212: $returnhash{"$key"}=$hash{"$scope:$symb:$key"}; 2213: } 2214: } 2215: if (!(untie(%hash))) { 2216: return "error:$!"; 2217: } 2218: } else { 2219: return "error:$!"; 2220: } 2221: return %returnhash; 2222: } 2223: 2224: # ----------------------------------------------------------------------- Store 2225: 2226: sub store { 2227: my ($storehash,$symb,$namespace,$domain,$stuname) = @_; 2228: my $home=''; 2229: 2230: if ($stuname) { $home=&homeserver($stuname,$domain); } 2231: 2232: $symb=&symbclean($symb); 2233: if (!$symb) { unless ($symb=&symbread()) { return ''; } } 2234: 2235: if (!$domain) { $domain=$ENV{'user.domain'}; } 2236: if (!$stuname) { $stuname=$ENV{'user.name'}; } 2237: 2238: &devalidate($symb,$stuname,$domain); 2239: 2240: $symb=escape($symb); 2241: if (!$namespace) { 2242: unless ($namespace=$ENV{'request.course.id'}) { 2243: return ''; 2244: } 2245: } 2246: if (!$home) { $home=$ENV{'user.home'}; } 2247: 2248: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'}; 2249: $$storehash{'host'}=$perlvar{'lonHostID'}; 2250: 2251: my $namevalue=''; 2252: foreach (keys %$storehash) { 2253: $namevalue.=escape($_).'='.escape($$storehash{$_}).'&'; 2254: } 2255: $namevalue=~s/\&$//; 2256: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue); 2257: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home"); 2258: } 2259: 2260: # -------------------------------------------------------------- Critical Store 2261: 2262: sub cstore { 2263: my ($storehash,$symb,$namespace,$domain,$stuname) = @_; 2264: my $home=''; 2265: 2266: if ($stuname) { $home=&homeserver($stuname,$domain); } 2267: 2268: $symb=&symbclean($symb); 2269: if (!$symb) { unless ($symb=&symbread()) { return ''; } } 2270: 2271: if (!$domain) { $domain=$ENV{'user.domain'}; } 2272: if (!$stuname) { $stuname=$ENV{'user.name'}; } 2273: 2274: &devalidate($symb,$stuname,$domain); 2275: 2276: $symb=escape($symb); 2277: if (!$namespace) { 2278: unless ($namespace=$ENV{'request.course.id'}) { 2279: return ''; 2280: } 2281: } 2282: if (!$home) { $home=$ENV{'user.home'}; } 2283: 2284: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'}; 2285: $$storehash{'host'}=$perlvar{'lonHostID'}; 2286: 2287: my $namevalue=''; 2288: foreach (keys %$storehash) { 2289: $namevalue.=escape($_).'='.escape($$storehash{$_}).'&'; 2290: } 2291: $namevalue=~s/\&$//; 2292: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue); 2293: return critical 2294: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home"); 2295: } 2296: 2297: # --------------------------------------------------------------------- Restore 2298: 2299: sub restore { 2300: my ($symb,$namespace,$domain,$stuname) = @_; 2301: my $home=''; 2302: 2303: if ($stuname) { $home=&homeserver($stuname,$domain); } 2304: 2305: if (!$symb) { 2306: unless ($symb=escape(&symbread())) { return ''; } 2307: } else { 2308: $symb=&escape(&symbclean($symb)); 2309: } 2310: if (!$namespace) { 2311: unless ($namespace=$ENV{'request.course.id'}) { 2312: return ''; 2313: } 2314: } 2315: if (!$domain) { $domain=$ENV{'user.domain'}; } 2316: if (!$stuname) { $stuname=$ENV{'user.name'}; } 2317: if (!$home) { $home=$ENV{'user.home'}; } 2318: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home"); 2319: 2320: my %returnhash=(); 2321: foreach (split(/\&/,$answer)) { 2322: my ($name,$value)=split(/\=/,$_); 2323: $returnhash{&unescape($name)}=&unescape($value); 2324: } 2325: my $version; 2326: for ($version=1;$version<=$returnhash{'version'};$version++) { 2327: foreach (split(/\:/,$returnhash{$version.':keys'})) { 2328: $returnhash{$_}=$returnhash{$version.':'.$_}; 2329: } 2330: } 2331: return %returnhash; 2332: } 2333: 2334: # ---------------------------------------------------------- Course Description 2335: 2336: sub coursedescription { 2337: my $courseid=shift; 2338: $courseid=~s/^\///; 2339: $courseid=~s/\_/\//g; 2340: my ($cdomain,$cnum)=split(/\//,$courseid); 2341: my $chome=&homeserver($cnum,$cdomain); 2342: my $normalid=$cdomain.'_'.$cnum; 2343: # need to always cache even if we get errors otherwise we keep 2344: # trying and trying and trying to get the course description. 2345: my %envhash=(); 2346: my %returnhash=(); 2347: $envhash{'course.'.$normalid.'.last_cache'}=time; 2348: if ($chome ne 'no_host') { 2349: %returnhash=&dump('environment',$cdomain,$cnum); 2350: if (!exists($returnhash{'con_lost'})) { 2351: $returnhash{'home'}= $chome; 2352: $returnhash{'domain'} = $cdomain; 2353: $returnhash{'num'} = $cnum; 2354: while (my ($name,$value) = each %returnhash) { 2355: $envhash{'course.'.$normalid.'.'.$name}=$value; 2356: } 2357: $returnhash{'url'}=&clutter($returnhash{'url'}); 2358: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'. 2359: $ENV{'user.name'}.'_'.$cdomain.'_'.$cnum; 2360: $envhash{'course.'.$normalid.'.home'}=$chome; 2361: $envhash{'course.'.$normalid.'.domain'}=$cdomain; 2362: $envhash{'course.'.$normalid.'.num'}=$cnum; 2363: } 2364: } 2365: &appenv(%envhash); 2366: return %returnhash; 2367: } 2368: 2369: # -------------------------------------------------See if a user is privileged 2370: 2371: sub privileged { 2372: my ($username,$domain)=@_; 2373: my $rolesdump=&reply("dump:$domain:$username:roles", 2374: &homeserver($username,$domain)); 2375: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; } 2376: my $now=time; 2377: if ($rolesdump ne '') { 2378: foreach (split(/&/,$rolesdump)) { 2379: if ($_!~/^rolesdef_/) { 2380: my ($area,$role)=split(/=/,$_); 2381: $area=~s/\_\w\w$//; 2382: my ($trole,$tend,$tstart)=split(/_/,$role); 2383: if (($trole eq 'dc') || ($trole eq 'su')) { 2384: my $active=1; 2385: if ($tend) { 2386: if ($tend<$now) { $active=0; } 2387: } 2388: if ($tstart) { 2389: if ($tstart>$now) { $active=0; } 2390: } 2391: if ($active) { return 1; } 2392: } 2393: } 2394: } 2395: } 2396: return 0; 2397: } 2398: 2399: # -------------------------------------------------------- Get user privileges 2400: 2401: sub rolesinit { 2402: my ($domain,$username,$authhost)=@_; 2403: my $rolesdump=reply("dump:$domain:$username:roles",$authhost); 2404: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; } 2405: my %allroles=(); 2406: my $now=time; 2407: my $userroles="user.login.time=$now\n"; 2408: 2409: if ($rolesdump ne '') { 2410: foreach (split(/&/,$rolesdump)) { 2411: if ($_!~/^rolesdef_/) { 2412: my ($area,$role)=split(/=/,$_); 2413: $area=~s/\_\w\w$//; 2414: 2415: my ($trole,$tend,$tstart); 2416: if ($role=~/^cr/) { 2417: ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|); 2418: ($tend,$tstart)=split('_',$trest); 2419: } else { 2420: ($trole,$tend,$tstart)=split(/_/,$role); 2421: } 2422: $userroles.=&set_arearole($trole,$area,$tstart,$tend,$domain,$username); 2423: if (($tend!=0) && ($tend<$now)) { $trole=''; } 2424: if (($tstart!=0) && ($tstart>$now)) { $trole=''; } 2425: if (($area ne '') && ($trole ne '')) { 2426: my $spec=$trole.'.'.$area; 2427: my ($tdummy,$tdomain,$trest)=split(/\//,$area); 2428: if ($trole =~ /^cr\//) { 2429: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area); 2430: } else { 2431: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area); 2432: } 2433: } 2434: } 2435: } 2436: my ($author,$adv) = &set_userprivs(\$userroles,\%allroles); 2437: $userroles.='user.adv='.$adv."\n". 2438: 'user.author='.$author."\n"; 2439: $ENV{'user.adv'}=$adv; 2440: } 2441: return $userroles; 2442: } 2443: 2444: sub set_arearole { 2445: my ($trole,$area,$tstart,$tend,$domain,$username) = @_; 2446: # log the associated role with the area 2447: &userrolelog($trole,$username,$domain,$area,$tstart,$tend); 2448: return 'user.role.'.$trole.'.'.$area.'='.$tstart.'.'.$tend."\n"; 2449: } 2450: 2451: sub custom_roleprivs { 2452: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_; 2453: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole); 2454: my $homsvr=homeserver($rauthor,$rdomain); 2455: if ($hostname{$homsvr} ne '') { 2456: my ($rdummy,$roledef)= 2457: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor); 2458: if (($rdummy ne 'con_lost') && ($roledef ne '')) { 2459: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef); 2460: if (defined($syspriv)) { 2461: $$allroles{'cm./'}.=':'.$syspriv; 2462: $$allroles{$spec.'./'}.=':'.$syspriv; 2463: } 2464: if ($tdomain ne '') { 2465: if (defined($dompriv)) { 2466: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv; 2467: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv; 2468: } 2469: if (($trest ne '') && (defined($coursepriv))) { 2470: $$allroles{'cm.'.$area}.=':'.$coursepriv; 2471: $$allroles{$spec.'.'.$area}.=':'.$coursepriv; 2472: } 2473: } 2474: } 2475: } 2476: } 2477: 2478: 2479: sub standard_roleprivs { 2480: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_; 2481: if (defined($pr{$trole.':s'})) { 2482: $$allroles{'cm./'}.=':'.$pr{$trole.':s'}; 2483: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'}; 2484: } 2485: if ($tdomain ne '') { 2486: if (defined($pr{$trole.':d'})) { 2487: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'}; 2488: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'}; 2489: } 2490: if (($trest ne '') && (defined($pr{$trole.':c'}))) { 2491: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'}; 2492: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'}; 2493: } 2494: } 2495: } 2496: 2497: sub set_userprivs { 2498: my ($userroles,$allroles) = @_; 2499: my $author=0; 2500: my $adv=0; 2501: foreach (keys %{$allroles}) { 2502: my %thesepriv=(); 2503: if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; } 2504: foreach (split(/:/,$$allroles{$_})) { 2505: if ($_ ne '') { 2506: my ($privilege,$restrictions)=split(/&/,$_); 2507: if ($restrictions eq '') { 2508: $thesepriv{$privilege}='F'; 2509: } elsif ($thesepriv{$privilege} ne 'F') { 2510: $thesepriv{$privilege}.=$restrictions; 2511: } 2512: if ($thesepriv{'adv'} eq 'F') { $adv=1; } 2513: } 2514: } 2515: my $thesestr=''; 2516: foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; } 2517: $$userroles.='user.priv.'.$_.'='.$thesestr."\n"; 2518: } 2519: return ($author,$adv); 2520: } 2521: 2522: # --------------------------------------------------------------- get interface 2523: 2524: sub get { 2525: my ($namespace,$storearr,$udomain,$uname)=@_; 2526: my $items=''; 2527: foreach (@$storearr) { 2528: $items.=escape($_).'&'; 2529: } 2530: $items=~s/\&$//; 2531: if (!$udomain) { $udomain=$ENV{'user.domain'}; } 2532: if (!$uname) { $uname=$ENV{'user.name'}; } 2533: my $uhome=&homeserver($uname,$udomain); 2534: 2535: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome); 2536: my @pairs=split(/\&/,$rep); 2537: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) { 2538: return @pairs; 2539: } 2540: my %returnhash=(); 2541: my $i=0; 2542: foreach (@$storearr) { 2543: $returnhash{$_}=&thaw_unescape($pairs[$i]); 2544: $i++; 2545: } 2546: return %returnhash; 2547: } 2548: 2549: # --------------------------------------------------------------- del interface 2550: 2551: sub del { 2552: my ($namespace,$storearr,$udomain,$uname)=@_; 2553: my $items=''; 2554: foreach (@$storearr) { 2555: $items.=escape($_).'&'; 2556: } 2557: $items=~s/\&$//; 2558: if (!$udomain) { $udomain=$ENV{'user.domain'}; } 2559: if (!$uname) { $uname=$ENV{'user.name'}; } 2560: my $uhome=&homeserver($uname,$udomain); 2561: 2562: return &reply("del:$udomain:$uname:$namespace:$items",$uhome); 2563: } 2564: 2565: # -------------------------------------------------------------- dump interface 2566: 2567: sub dump { 2568: my ($namespace,$udomain,$uname,$regexp)=@_; 2569: if (!$udomain) { $udomain=$ENV{'user.domain'}; } 2570: if (!$uname) { $uname=$ENV{'user.name'}; } 2571: my $uhome=&homeserver($uname,$udomain); 2572: if ($regexp) { 2573: $regexp=&escape($regexp); 2574: } else { 2575: $regexp='.'; 2576: } 2577: my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome); 2578: my @pairs=split(/\&/,$rep); 2579: my %returnhash=(); 2580: foreach (@pairs) { 2581: my ($key,$value)=split(/=/,$_); 2582: $returnhash{unescape($key)}=&thaw_unescape($value); 2583: } 2584: return %returnhash; 2585: } 2586: 2587: # -------------------------------------------------------------- keys interface 2588: 2589: sub getkeys { 2590: my ($namespace,$udomain,$uname)=@_; 2591: if (!$udomain) { $udomain=$ENV{'user.domain'}; } 2592: if (!$uname) { $uname=$ENV{'user.name'}; } 2593: my $uhome=&homeserver($uname,$udomain); 2594: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome); 2595: my @keyarray=(); 2596: foreach (split(/\&/,$rep)) { 2597: push (@keyarray,&unescape($_)); 2598: } 2599: return @keyarray; 2600: } 2601: 2602: # --------------------------------------------------------------- currentdump 2603: sub currentdump { 2604: my ($courseid,$sdom,$sname)=@_; 2605: $courseid = $ENV{'request.course.id'} if (! defined($courseid)); 2606: $sdom = $ENV{'user.domain'} if (! defined($sdom)); 2607: $sname = $ENV{'user.name'} if (! defined($sname)); 2608: my $uhome = &homeserver($sname,$sdom); 2609: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome); 2610: return if ($rep =~ /^(error:|no_such_host)/); 2611: # 2612: my %returnhash=(); 2613: # 2614: if ($rep eq "unknown_cmd") { 2615: # an old lond will not know currentdump 2616: # Do a dump and make it look like a currentdump 2617: my @tmp = &dump($courseid,$sdom,$sname,'.'); 2618: return if ($tmp[0] =~ /^(error:|no_such_host)/); 2619: my %hash = @tmp; 2620: @tmp=(); 2621: %returnhash = %{&convert_dump_to_currentdump(\%hash)}; 2622: } else { 2623: my @pairs=split(/\&/,$rep); 2624: foreach (@pairs) { 2625: my ($key,$value)=split(/=/,$_); 2626: my ($symb,$param) = split(/:/,$key); 2627: $returnhash{&unescape($symb)}->{&unescape($param)} = 2628: &thaw_unescape($value); 2629: } 2630: } 2631: return %returnhash; 2632: } 2633: 2634: sub convert_dump_to_currentdump{ 2635: my %hash = %{shift()}; 2636: my %returnhash; 2637: # Code ripped from lond, essentially. The only difference 2638: # here is the unescaping done by lonnet::dump(). Conceivably 2639: # we might run in to problems with parameter names =~ /^v\./ 2640: while (my ($key,$value) = each(%hash)) { 2641: my ($v,$symb,$param) = split(/:/,$key); 2642: next if ($v eq 'version' || $symb eq 'keys'); 2643: next if (exists($returnhash{$symb}) && 2644: exists($returnhash{$symb}->{$param}) && 2645: $returnhash{$symb}->{'v.'.$param} > $v); 2646: $returnhash{$symb}->{$param}=$value; 2647: $returnhash{$symb}->{'v.'.$param}=$v; 2648: } 2649: # 2650: # Remove all of the keys in the hashes which keep track of 2651: # the version of the parameter. 2652: while (my ($symb,$param_hash) = each(%returnhash)) { 2653: # use a foreach because we are going to delete from the hash. 2654: foreach my $key (keys(%$param_hash)) { 2655: delete($param_hash->{$key}) if ($key =~ /^v\./); 2656: } 2657: } 2658: return \%returnhash; 2659: } 2660: 2661: # --------------------------------------------------------------- inc interface 2662: 2663: sub inc { 2664: my ($namespace,$store,$udomain,$uname) = @_; 2665: if (!$udomain) { $udomain=$ENV{'user.domain'}; } 2666: if (!$uname) { $uname=$ENV{'user.name'}; } 2667: my $uhome=&homeserver($uname,$udomain); 2668: my $items=''; 2669: if (! ref($store)) { 2670: # got a single value, so use that instead 2671: $items = &escape($store).'=&'; 2672: } elsif (ref($store) eq 'SCALAR') { 2673: $items = &escape($$store).'=&'; 2674: } elsif (ref($store) eq 'ARRAY') { 2675: $items = join('=&',map {&escape($_);} @{$store}); 2676: } elsif (ref($store) eq 'HASH') { 2677: while (my($key,$value) = each(%{$store})) { 2678: $items.= &escape($key).'='.&escape($value).'&'; 2679: } 2680: } 2681: $items=~s/\&$//; 2682: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome); 2683: } 2684: 2685: # --------------------------------------------------------------- put interface 2686: 2687: sub put { 2688: my ($namespace,$storehash,$udomain,$uname)=@_; 2689: if (!$udomain) { $udomain=$ENV{'user.domain'}; } 2690: if (!$uname) { $uname=$ENV{'user.name'}; } 2691: my $uhome=&homeserver($uname,$udomain); 2692: my $items=''; 2693: foreach (keys %$storehash) { 2694: $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&'; 2695: } 2696: $items=~s/\&$//; 2697: return &reply("put:$udomain:$uname:$namespace:$items",$uhome); 2698: } 2699: 2700: # ---------------------------------------------------------- putstore interface 2701: 2702: sub putstore { 2703: my ($namespace,$storehash,$udomain,$uname)=@_; 2704: if (!$udomain) { $udomain=$ENV{'user.domain'}; } 2705: if (!$uname) { $uname=$ENV{'user.name'}; } 2706: my $uhome=&homeserver($uname,$udomain); 2707: my $items=''; 2708: my %allitems = (); 2709: foreach (keys %$storehash) { 2710: if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) { 2711: my $key = $1.':keys:'.$2; 2712: $allitems{$key} .= $3.':'; 2713: } 2714: $items.=$_.'='.&escape($$storehash{$_}).'&'; 2715: } 2716: foreach (keys %allitems) { 2717: $allitems{$_} =~ s/\:$//; 2718: $items.= $_.'='.$allitems{$_}.'&'; 2719: } 2720: $items=~s/\&$//; 2721: return &reply("put:$udomain:$uname:$namespace:$items",$uhome); 2722: } 2723: 2724: # ------------------------------------------------------ critical put interface 2725: 2726: sub cput { 2727: my ($namespace,$storehash,$udomain,$uname)=@_; 2728: if (!$udomain) { $udomain=$ENV{'user.domain'}; } 2729: if (!$uname) { $uname=$ENV{'user.name'}; } 2730: my $uhome=&homeserver($uname,$udomain); 2731: my $items=''; 2732: foreach (keys %$storehash) { 2733: $items.=escape($_).'='.&freeze_escape($$storehash{$_}).'&'; 2734: } 2735: $items=~s/\&$//; 2736: return &critical("put:$udomain:$uname:$namespace:$items",$uhome); 2737: } 2738: 2739: # -------------------------------------------------------------- eget interface 2740: 2741: sub eget { 2742: my ($namespace,$storearr,$udomain,$uname)=@_; 2743: my $items=''; 2744: foreach (@$storearr) { 2745: $items.=escape($_).'&'; 2746: } 2747: $items=~s/\&$//; 2748: if (!$udomain) { $udomain=$ENV{'user.domain'}; } 2749: if (!$uname) { $uname=$ENV{'user.name'}; } 2750: my $uhome=&homeserver($uname,$udomain); 2751: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome); 2752: my @pairs=split(/\&/,$rep); 2753: my %returnhash=(); 2754: my $i=0; 2755: foreach (@$storearr) { 2756: $returnhash{$_}=&thaw_unescape($pairs[$i]); 2757: $i++; 2758: } 2759: return %returnhash; 2760: } 2761: 2762: # ---------------------------------------------- Custom access rule evaluation 2763: 2764: sub customaccess { 2765: my ($priv,$uri)=@_; 2766: my ($urole,$urealm)=split(/\./,$ENV{'request.role'}); 2767: $urealm=~s/^\W//; 2768: my ($udom,$ucrs,$usec)=split(/\//,$urealm); 2769: my $access=0; 2770: foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) { 2771: my ($effect,$realm,$role)=split(/\:/,$_); 2772: if ($role) { 2773: if ($role ne $urole) { next; } 2774: } 2775: foreach (split(/\s*\,\s*/,$realm)) { 2776: my ($tdom,$tcrs,$tsec)=split(/\_/,$_); 2777: if ($tdom) { 2778: if ($tdom ne $udom) { next; } 2779: } 2780: if ($tcrs) { 2781: if ($tcrs ne $ucrs) { next; } 2782: } 2783: if ($tsec) { 2784: if ($tsec ne $usec) { next; } 2785: } 2786: $access=($effect eq 'allow'); 2787: last; 2788: } 2789: if ($realm eq '' && $role eq '') { 2790: $access=($effect eq 'allow'); 2791: } 2792: } 2793: return $access; 2794: } 2795: 2796: # ------------------------------------------------- Check for a user privilege 2797: 2798: sub allowed { 2799: my ($priv,$uri,$symb)=@_; 2800: $uri=&deversion($uri); 2801: my $orguri=$uri; 2802: $uri=&declutter($uri); 2803: 2804: 2805: 2806: if (defined($ENV{'allowed.'.$priv})) { return $ENV{'allowed.'.$priv}; } 2807: # Free bre access to adm and meta resources 2808: if (((($uri=~/^adm\//) && ($uri !~ m|/bulletinboard$|)) 2809: || ($uri=~/\.meta$/)) && ($priv eq 'bre')) { 2810: return 'F'; 2811: } 2812: 2813: # Free bre access to user's own portfolio contents 2814: my ($space,$domain,$name,$dir)=split('/',$uri); 2815: if (('uploaded' eq $space) && ($ENV{'user.name'} eq $name) && 2816: ($ENV{'user.domain'} eq $domain) && ('portfolio' eq $dir)) { 2817: return 'F'; 2818: } 2819: 2820: # Free bre to public access 2821: 2822: if ($priv eq 'bre') { 2823: my $copyright=&metadata($uri,'copyright'); 2824: if (($copyright eq 'public') && (!$ENV{'request.course.id'})) { 2825: return 'F'; 2826: } 2827: if ($copyright eq 'priv') { 2828: $uri=~/([^\/]+)\/([^\/]+)\//; 2829: unless (($ENV{'user.name'} eq $2) && ($ENV{'user.domain'} eq $1)) { 2830: return ''; 2831: } 2832: } 2833: if ($copyright eq 'domain') { 2834: $uri=~/([^\/]+)\/([^\/]+)\//; 2835: unless (($ENV{'user.domain'} eq $1) || 2836: ($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $1)) { 2837: return ''; 2838: } 2839: } 2840: if ($ENV{'request.role'}=~ /li\.\//) { 2841: # Library role, so allow browsing of resources in this domain. 2842: return 'F'; 2843: } 2844: if ($copyright eq 'custom') { 2845: unless (&customaccess($priv,$uri)) { return ''; } 2846: } 2847: } 2848: # Domain coordinator is trying to create a course 2849: if (($priv eq 'ccc') && ($ENV{'request.role'} =~ /^dc\./)) { 2850: # uri is the requested domain in this case. 2851: # comparison to 'request.role.domain' shows if the user has selected 2852: # a role of dc for the domain in question. 2853: return 'F' if ($uri eq $ENV{'request.role.domain'}); 2854: } 2855: 2856: my $thisallowed=''; 2857: my $statecond=0; 2858: my $courseprivid=''; 2859: 2860: # Course 2861: 2862: if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) { 2863: $thisallowed.=$1; 2864: } 2865: 2866: # Domain 2867: 2868: if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.(split(/\//,$uri))[0].'/'} 2869: =~/\Q$priv\E\&([^\:]*)/) { 2870: $thisallowed.=$1; 2871: } 2872: 2873: # Course: uri itself is a course 2874: my $courseuri=$uri; 2875: $courseuri=~s/\_(\d)/\/$1/; 2876: $courseuri=~s/^([^\/])/\/$1/; 2877: 2878: if ($ENV{'user.priv.'.$ENV{'request.role'}.'.'.$courseuri} 2879: =~/\Q$priv\E\&([^\:]*)/) { 2880: $thisallowed.=$1; 2881: } 2882: 2883: # URI is an uploaded document for this course 2884: 2885: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) { 2886: my $refuri=$ENV{'httpref.'.$orguri}; 2887: if ($refuri) { 2888: if ($refuri =~ m|^/adm/|) { 2889: $thisallowed='F'; 2890: } 2891: } 2892: } 2893: 2894: # Full access at system, domain or course-wide level? Exit. 2895: 2896: if ($thisallowed=~/F/) { 2897: return 'F'; 2898: } 2899: 2900: # If this is generating or modifying users, exit with special codes 2901: 2902: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:\Q$priv\E\:/) { 2903: return $thisallowed; 2904: } 2905: # 2906: # Gathered so far: system, domain and course wide privileges 2907: # 2908: # Course: See if uri or referer is an individual resource that is part of 2909: # the course 2910: 2911: if ($ENV{'request.course.id'}) { 2912: 2913: $courseprivid=$ENV{'request.course.id'}; 2914: if ($ENV{'request.course.sec'}) { 2915: $courseprivid.='/'.$ENV{'request.course.sec'}; 2916: } 2917: $courseprivid=~s/\_/\//; 2918: my $checkreferer=1; 2919: my ($match,$cond)=&is_on_map($uri); 2920: if ($match) { 2921: $statecond=$cond; 2922: if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid} 2923: =~/\Q$priv\E\&([^\:]*)/) { 2924: $thisallowed.=$1; 2925: $checkreferer=0; 2926: } 2927: } 2928: 2929: if ($checkreferer) { 2930: my $refuri=$ENV{'httpref.'.$orguri}; 2931: unless ($refuri) { 2932: foreach (keys %ENV) { 2933: if ($_=~/^httpref\..*\*/) { 2934: my $pattern=$_; 2935: $pattern=~s/^httpref\.\/res\///; 2936: $pattern=~s/\*/\[\^\/\]\+/g; 2937: $pattern=~s/\//\\\//g; 2938: if ($orguri=~/$pattern/) { 2939: $refuri=$ENV{$_}; 2940: } 2941: } 2942: } 2943: } 2944: 2945: if ($refuri) { 2946: $refuri=&declutter($refuri); 2947: my ($match,$cond)=&is_on_map($refuri); 2948: if ($match) { 2949: my $refstatecond=$cond; 2950: if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid} 2951: =~/\Q$priv\E\&([^\:]*)/) { 2952: $thisallowed.=$1; 2953: $uri=$refuri; 2954: $statecond=$refstatecond; 2955: } 2956: } 2957: } 2958: } 2959: } 2960: 2961: # 2962: # Gathered now: all privileges that could apply, and condition number 2963: # 2964: # 2965: # Full or no access? 2966: # 2967: 2968: if ($thisallowed=~/F/) { 2969: return 'F'; 2970: } 2971: 2972: unless ($thisallowed) { 2973: return ''; 2974: } 2975: 2976: # Restrictions exist, deal with them 2977: # 2978: # C:according to course preferences 2979: # R:according to resource settings 2980: # L:unless locked 2981: # X:according to user session state 2982: # 2983: 2984: # Possibly locked functionality, check all courses 2985: # Locks might take effect only after 10 minutes cache expiration for other 2986: # courses, and 2 minutes for current course 2987: 2988: my $envkey; 2989: if ($thisallowed=~/L/) { 2990: foreach $envkey (keys %ENV) { 2991: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) { 2992: my $courseid=$2; 2993: my $roleid=$1.'.'.$2; 2994: $courseid=~s/^\///; 2995: my $expiretime=600; 2996: if ($ENV{'request.role'} eq $roleid) { 2997: $expiretime=120; 2998: } 2999: my ($cdom,$cnum,$csec)=split(/\//,$courseid); 3000: my $prefix='course.'.$cdom.'_'.$cnum.'.'; 3001: if ((time-$ENV{$prefix.'last_cache'})>$expiretime) { 3002: &coursedescription($courseid); 3003: } 3004: if (($ENV{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/) 3005: || ($ENV{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) { 3006: if ($ENV{$prefix.'res.'.$uri.'.lock.expire'}>time) { 3007: &log($ENV{'user.domain'},$ENV{'user.name'}, 3008: $ENV{'user.home'}, 3009: 'Locked by res: '.$priv.' for '.$uri.' due to '. 3010: $cdom.'/'.$cnum.'/'.$csec.' expire '. 3011: $ENV{$prefix.'priv.'.$priv.'.lock.expire'}); 3012: return ''; 3013: } 3014: } 3015: if (($ENV{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/) 3016: || ($ENV{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) { 3017: if ($ENV{'priv.'.$priv.'.lock.expire'}>time) { 3018: &log($ENV{'user.domain'},$ENV{'user.name'}, 3019: $ENV{'user.home'}, 3020: 'Locked by priv: '.$priv.' for '.$uri.' due to '. 3021: $cdom.'/'.$cnum.'/'.$csec.' expire '. 3022: $ENV{$prefix.'priv.'.$priv.'.lock.expire'}); 3023: return ''; 3024: } 3025: } 3026: } 3027: } 3028: } 3029: 3030: # 3031: # Rest of the restrictions depend on selected course 3032: # 3033: 3034: unless ($ENV{'request.course.id'}) { 3035: return '1'; 3036: } 3037: 3038: # 3039: # Now user is definitely in a course 3040: # 3041: 3042: 3043: # Course preferences 3044: 3045: if ($thisallowed=~/C/) { 3046: my $rolecode=(split(/\./,$ENV{'request.role'}))[0]; 3047: my $unamedom=$ENV{'user.name'}.':'.$ENV{'user.domain'}; 3048: if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.roles.denied'} 3049: =~/\Q$rolecode\E/) { 3050: &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'}, 3051: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '. 3052: $ENV{'request.course.id'}); 3053: return ''; 3054: } 3055: 3056: if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.users.denied'} 3057: =~/\Q$unamedom\E/) { 3058: &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'}, 3059: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '. 3060: $ENV{'request.course.id'}); 3061: return ''; 3062: } 3063: } 3064: 3065: # Resource preferences 3066: 3067: if ($thisallowed=~/R/) { 3068: my $rolecode=(split(/\./,$ENV{'request.role'}))[0]; 3069: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) { 3070: &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'}, 3071: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode); 3072: return ''; 3073: } 3074: } 3075: 3076: # Restricted by state or randomout? 3077: 3078: if ($thisallowed=~/X/) { 3079: if ($ENV{'acc.randomout'}) { 3080: if (!$symb) { $symb=&symbread($uri,1); } 3081: if (($symb) && ($ENV{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 3082: return ''; 3083: } 3084: } 3085: if (&condval($statecond)) { 3086: return '2'; 3087: } else { 3088: return ''; 3089: } 3090: } 3091: 3092: return 'F'; 3093: } 3094: 3095: # --------------------------------------------------- Is a resource on the map? 3096: 3097: sub is_on_map { 3098: my $uri=&declutter(shift); 3099: $uri=~s/\.\d+\.(\w+)$/\.$1/; 3100: my @uriparts=split(/\//,$uri); 3101: my $filename=$uriparts[$#uriparts]; 3102: my $pathname=$uri; 3103: $pathname=~s|/\Q$filename\E$||; 3104: $pathname=~s/^adm\/wrapper\///; 3105: #Trying to find the conditional for the file 3106: my $match=($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~ 3107: /\&\Q$filename\E\:([\d\|]+)\&/); 3108: if ($match) { 3109: return (1,$1); 3110: } else { 3111: return (0,0); 3112: } 3113: } 3114: 3115: # --------------------------------------------------------- Get symb from alias 3116: 3117: sub get_symb_from_alias { 3118: my $symb=shift; 3119: my ($map,$resid,$url)=&decode_symb($symb); 3120: # Already is a symb 3121: if ($url) { return $symb; } 3122: # Must be an alias 3123: my $aliassymb=''; 3124: my %bighash; 3125: if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db', 3126: &GDBM_READER(),0640)) { 3127: my $rid=$bighash{'mapalias_'.$symb}; 3128: if ($rid) { 3129: my ($mapid,$resid)=split(/\./,$rid); 3130: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid}, 3131: $resid,$bighash{'src_'.$rid}); 3132: } 3133: untie %bighash; 3134: } 3135: return $aliassymb; 3136: } 3137: 3138: # ----------------------------------------------------------------- Define Role 3139: 3140: sub definerole { 3141: if (allowed('mcr','/')) { 3142: my ($rolename,$sysrole,$domrole,$courole)=@_; 3143: foreach (split(':',$sysrole)) { 3144: my ($crole,$cqual)=split(/\&/,$_); 3145: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; } 3146: if ($pr{'cr:s'}=~/\Q$crole\E\&/) { 3147: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 3148: return "refused:s:$crole&$cqual"; 3149: } 3150: } 3151: } 3152: foreach (split(':',$domrole)) { 3153: my ($crole,$cqual)=split(/\&/,$_); 3154: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; } 3155: if ($pr{'cr:d'}=~/\Q$crole\E\&/) { 3156: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 3157: return "refused:d:$crole&$cqual"; 3158: } 3159: } 3160: } 3161: foreach (split(':',$courole)) { 3162: my ($crole,$cqual)=split(/\&/,$_); 3163: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; } 3164: if ($pr{'cr:c'}=~/\Q$crole\E\&/) { 3165: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 3166: return "refused:c:$crole&$cqual"; 3167: } 3168: } 3169: } 3170: my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:". 3171: "$ENV{'user.domain'}:$ENV{'user.name'}:". 3172: "rolesdef_$rolename=". 3173: escape($sysrole.'_'.$domrole.'_'.$courole); 3174: return reply($command,$ENV{'user.home'}); 3175: } else { 3176: return 'refused'; 3177: } 3178: } 3179: 3180: # ---------------- Make a metadata query against the network of library servers 3181: 3182: sub metadata_query { 3183: my ($query,$custom,$customshow,$server_array)=@_; 3184: my %rhash; 3185: my @server_list = (defined($server_array) ? @$server_array 3186: : keys(%libserv) ); 3187: for my $server (@server_list) { 3188: unless ($custom or $customshow) { 3189: my $reply=&reply("querysend:".&escape($query),$server); 3190: $rhash{$server}=$reply; 3191: } 3192: else { 3193: my $reply=&reply("querysend:".&escape($query).':'. 3194: &escape($custom).':'.&escape($customshow), 3195: $server); 3196: $rhash{$server}=$reply; 3197: } 3198: } 3199: return \%rhash; 3200: } 3201: 3202: # ----------------------------------------- Send log queries and wait for reply 3203: 3204: sub log_query { 3205: my ($uname,$udom,$query,%filters)=@_; 3206: my $uhome=&homeserver($uname,$udom); 3207: if ($uhome eq 'no_host') { return 'error: no_host'; } 3208: my $uhost=$hostname{$uhome}; 3209: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters)); 3210: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command, 3211: $uhome); 3212: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; } 3213: return get_query_reply($queryid); 3214: } 3215: 3216: # ------- Request retrieval of institutional classlists for course(s) 3217: 3218: sub fetch_enrollment_query { 3219: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_; 3220: my $homeserver; 3221: my $maxtries = 1; 3222: if ($context eq 'automated') { 3223: $homeserver = $perlvar{'lonHostID'}; 3224: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout 3225: } else { 3226: $homeserver = &homeserver($cnum,$dom); 3227: } 3228: my $host=$hostname{$homeserver}; 3229: my $cmd = ''; 3230: foreach (keys %{$affiliatesref}) { 3231: $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%'; 3232: } 3233: $cmd =~ s/%%$//; 3234: $cmd = &escape($cmd); 3235: my $query = 'fetchenrollment'; 3236: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$ENV{'user.name'}.':'.$cmd,$homeserver); 3237: unless ($queryid=~/^\Q$host\E\_/) { 3238: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 3239: return 'error: '.$queryid; 3240: } 3241: my $reply = &get_query_reply($queryid); 3242: my $tries = 1; 3243: while (($reply=~/^timeout/) && ($tries < $maxtries)) { 3244: $reply = &get_query_reply($queryid); 3245: $tries ++; 3246: } 3247: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) { 3248: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$ENV{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries); 3249: } else { 3250: my @responses = split/:/,$reply; 3251: if ($homeserver eq $perlvar{'lonHostID'}) { 3252: foreach (@responses) { 3253: my ($key,$value) = split/=/,$_; 3254: $$replyref{$key} = $value; 3255: } 3256: } else { 3257: my $pathname = $perlvar{'lonDaemons'}.'/tmp'; 3258: foreach (@responses) { 3259: my ($key,$value) = split/=/,$_; 3260: $$replyref{$key} = $value; 3261: if ($value > 0) { 3262: foreach (@{$$affiliatesref{$key}}) { 3263: my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml'; 3264: my $destname = $pathname.'/'.$filename; 3265: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver); 3266: if ($xml_classlist =~ /^error/) { 3267: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum); 3268: } else { 3269: if ( open(FILE,">$destname") ) { 3270: print FILE &unescape($xml_classlist); 3271: close(FILE); 3272: } else { 3273: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum); 3274: } 3275: } 3276: } 3277: } 3278: } 3279: } 3280: return 'ok'; 3281: } 3282: return 'error'; 3283: } 3284: 3285: sub get_query_reply { 3286: my $queryid=shift; 3287: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid; 3288: my $reply=''; 3289: for (1..100) { 3290: sleep 2; 3291: if (-e $replyfile.'.end') { 3292: if (open(my $fh,$replyfile)) { 3293: $reply.=<$fh>; 3294: close($fh); 3295: } else { return 'error: reply_file_error'; } 3296: return &unescape($reply); 3297: } 3298: } 3299: return 'timeout:'.$queryid; 3300: } 3301: 3302: sub courselog_query { 3303: # 3304: # possible filters: 3305: # url: url or symb 3306: # username 3307: # domain 3308: # action: view, submit, grade 3309: # start: timestamp 3310: # end: timestamp 3311: # 3312: my (%filters)=@_; 3313: unless ($ENV{'request.course.id'}) { return 'no_course'; } 3314: if ($filters{'url'}) { 3315: $filters{'url'}=&symbclean(&declutter($filters{'url'})); 3316: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/; 3317: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/; 3318: } 3319: my $cname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'}; 3320: my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'}; 3321: return &log_query($cname,$cdom,'courselog',%filters); 3322: } 3323: 3324: sub userlog_query { 3325: my ($uname,$udom,%filters)=@_; 3326: return &log_query($uname,$udom,'userlog',%filters); 3327: } 3328: 3329: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 3330: 3331: sub auto_run { 3332: my ($cnum,$cdom) = @_; 3333: my $homeserver = &homeserver($cnum,$cdom); 3334: my $response = &reply('autorun:'.$cdom,$homeserver); 3335: return $response; 3336: } 3337: 3338: sub auto_get_sections { 3339: my ($cnum,$cdom,$inst_coursecode) = @_; 3340: my $homeserver = &homeserver($cnum,$cdom); 3341: my @secs = (); 3342: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver)); 3343: unless ($response eq 'refused') { 3344: @secs = split/:/,$response; 3345: } 3346: return @secs; 3347: } 3348: 3349: sub auto_new_course { 3350: my ($cnum,$cdom,$inst_course_id,$owner) = @_; 3351: my $homeserver = &homeserver($cnum,$cdom); 3352: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver)); 3353: return $response; 3354: } 3355: 3356: sub auto_validate_courseID { 3357: my ($cnum,$cdom,$inst_course_id) = @_; 3358: my $homeserver = &homeserver($cnum,$cdom); 3359: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver)); 3360: return $response; 3361: } 3362: 3363: sub auto_create_password { 3364: my ($cnum,$cdom,$authparam) = @_; 3365: my $homeserver = &homeserver($cnum,$cdom); 3366: my $create_passwd = 0; 3367: my $authchk = ''; 3368: my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver)); 3369: if ($response eq 'refused') { 3370: $authchk = 'refused'; 3371: } else { 3372: ($authparam,$create_passwd,$authchk) = split/:/,$response; 3373: } 3374: return ($authparam,$create_passwd,$authchk); 3375: } 3376: 3377: sub auto_instcode_format { 3378: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_; 3379: my $courses = ''; 3380: my $homeserver; 3381: if ($caller eq 'global') { 3382: foreach my $tryserver (keys %libserv) { 3383: if ($hostdom{$tryserver} eq $codedom) { 3384: $homeserver = $tryserver; 3385: last; 3386: } 3387: } 3388: if (($ENV{'user.name'}) && ($ENV{'user.domain'} eq $codedom)) { 3389: $homeserver = &homeserver($ENV{'user.name'},$codedom); 3390: } 3391: } else { 3392: $homeserver = &homeserver($caller,$codedom); 3393: } 3394: foreach (keys %{$instcodes}) { 3395: $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&'; 3396: } 3397: chop($courses); 3398: my $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$homeserver); 3399: unless ($response =~ /(con_lost|error|no_such_host|refused)/) { 3400: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = split/:/,$response; 3401: %{$codes} = &str2hash($codes_str); 3402: @{$codetitles} = &str2array($codetitles_str); 3403: %{$cat_titles} = &str2hash($cat_titles_str); 3404: %{$cat_order} = &str2hash($cat_order_str); 3405: return 'ok'; 3406: } 3407: return $response; 3408: } 3409: 3410: # ------------------------------------------------------------------ Plain Text 3411: 3412: sub plaintext { 3413: my $short=shift; 3414: return &mt($prp{$short}); 3415: } 3416: 3417: # ----------------------------------------------------------------- Assign Role 3418: 3419: sub assignrole { 3420: my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_; 3421: my $mrole; 3422: if ($role =~ /^cr\//) { 3423: my $cwosec=$url; 3424: $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/; 3425: unless (&allowed('ccr',$cwosec)) { 3426: &logthis('Refused custom assignrole: '. 3427: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '. 3428: $ENV{'user.name'}.' at '.$ENV{'user.domain'}); 3429: return 'refused'; 3430: } 3431: $mrole='cr'; 3432: } else { 3433: my $cwosec=$url; 3434: $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/; 3435: unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 3436: &logthis('Refused assignrole: '. 3437: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '. 3438: $ENV{'user.name'}.' at '.$ENV{'user.domain'}); 3439: return 'refused'; 3440: } 3441: $mrole=$role; 3442: } 3443: my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:". 3444: "$udom:$uname:$url".'_'."$mrole=$role"; 3445: if ($end) { $command.='_'.$end; } 3446: if ($start) { 3447: if ($end) { 3448: $command.='_'.$start; 3449: } else { 3450: $command.='_0_'.$start; 3451: } 3452: } 3453: # actually delete 3454: if ($deleteflag) { 3455: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) { 3456: # modify command to delete the role 3457: $command="encrypt:rolesdel:$ENV{'user.domain'}:$ENV{'user.name'}:". 3458: "$udom:$uname:$url".'_'."$mrole"; 3459: &logthis("$ENV{'user.name'} at $ENV{'user.domain'} deletes $mrole in $url for $uname at $udom"); 3460: # set start and finish to negative values for userrolelog 3461: $start=-1; 3462: $end=-1; 3463: } 3464: } 3465: # send command 3466: my $answer=&reply($command,&homeserver($uname,$udom)); 3467: # log new user role if status is ok 3468: if ($answer eq 'ok') { 3469: &userrolelog($mrole,$uname,$udom,$url,$start,$end); 3470: } 3471: return $answer; 3472: } 3473: 3474: # -------------------------------------------------- Modify user authentication 3475: # Overrides without validation 3476: 3477: sub modifyuserauth { 3478: my ($udom,$uname,$umode,$upass)=@_; 3479: my $uhome=&homeserver($uname,$udom); 3480: unless (&allowed('mau',$udom)) { return 'refused'; } 3481: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '. 3482: $umode.' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}. 3483: ' in domain '.$ENV{'request.role.domain'}); 3484: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'. 3485: &escape($upass),$uhome); 3486: &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'}, 3487: 'Authentication changed for '.$udom.', '.$uname.', '.$umode. 3488: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply); 3489: &log($udom,,$uname,$uhome, 3490: 'Authentication changed by '.$ENV{'user.domain'}.', '. 3491: $ENV{'user.name'}.', '.$umode. 3492: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply); 3493: unless ($reply eq 'ok') { 3494: &logthis('Authentication mode error: '.$reply); 3495: return 'error: '.$reply; 3496: } 3497: return 'ok'; 3498: } 3499: 3500: # --------------------------------------------------------------- Modify a user 3501: 3502: sub modifyuser { 3503: my ($udom, $uname, $uid, 3504: $umode, $upass, $first, 3505: $middle, $last, $gene, 3506: $forceid, $desiredhome, $email)=@_; 3507: $udom=~s/\W//g; 3508: $uname=~s/\W//g; 3509: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '. 3510: $umode.', '.$first.', '.$middle.', '. 3511: $last.', '.$gene.'(forceid: '.$forceid.')'. 3512: (defined($desiredhome) ? ' desiredhome = '.$desiredhome : 3513: ' desiredhome not specified'). 3514: ' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}. 3515: ' in domain '.$ENV{'request.role.domain'}); 3516: my $uhome=&homeserver($uname,$udom,'true'); 3517: # ----------------------------------------------------------------- Create User 3518: if (($uhome eq 'no_host') && 3519: (($umode && $upass) || ($umode eq 'localauth'))) { 3520: my $unhome=''; 3521: if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 3522: $unhome = $desiredhome; 3523: } elsif($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $udom) { 3524: $unhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'}; 3525: } else { # load balancing routine for determining $unhome 3526: my $tryserver; 3527: my $loadm=10000000; 3528: foreach $tryserver (keys %libserv) { 3529: if ($hostdom{$tryserver} eq $udom) { 3530: my $answer=reply('load',$tryserver); 3531: if (($answer=~/\d+/) && ($answer<$loadm)) { 3532: $loadm=$answer; 3533: $unhome=$tryserver; 3534: } 3535: } 3536: } 3537: } 3538: if (($unhome eq '') || ($unhome eq 'no_host')) { 3539: return 'error: unable to find a home server for '.$uname. 3540: ' in domain '.$udom; 3541: } 3542: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'. 3543: &escape($upass),$unhome); 3544: unless ($reply eq 'ok') { 3545: return 'error: '.$reply; 3546: } 3547: $uhome=&homeserver($uname,$udom,'true'); 3548: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) { 3549: return 'error: unable verify users home machine.'; 3550: } 3551: } # End of creation of new user 3552: # ---------------------------------------------------------------------- Add ID 3553: if ($uid) { 3554: $uid=~tr/A-Z/a-z/; 3555: my %uidhash=&idrget($udom,$uname); 3556: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 3557: && (!$forceid)) { 3558: unless ($uid eq $uidhash{$uname}) { 3559: return 'error: user id "'.$uid.'" does not match '. 3560: 'current user id "'.$uidhash{$uname}.'".'; 3561: } 3562: } else { 3563: &idput($udom,($uname => $uid)); 3564: } 3565: } 3566: # -------------------------------------------------------------- Add names, etc 3567: my @tmp=&get('environment', 3568: ['firstname','middlename','lastname','generation'], 3569: $udom,$uname); 3570: my %names; 3571: if ($tmp[0] =~ m/^error:.*/) { 3572: %names=(); 3573: } else { 3574: %names = @tmp; 3575: } 3576: # 3577: # Make sure to not trash student environment if instructor does not bother 3578: # to supply name and email information 3579: # 3580: if ($first) { $names{'firstname'} = $first; } 3581: if (defined($middle)) { $names{'middlename'} = $middle; } 3582: if ($last) { $names{'lastname'} = $last; } 3583: if (defined($gene)) { $names{'generation'} = $gene; } 3584: if ($email) { $names{'notification'} = $email; 3585: $names{'critnotification'} = $email; } 3586: 3587: my $reply = &put('environment', \%names, $udom,$uname); 3588: if ($reply ne 'ok') { return 'error: '.$reply; } 3589: &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '. 3590: $umode.', '.$first.', '.$middle.', '. 3591: $last.', '.$gene.' by '. 3592: $ENV{'user.name'}.' at '.$ENV{'user.domain'}); 3593: return 'ok'; 3594: } 3595: 3596: # -------------------------------------------------------------- Modify student 3597: 3598: sub modifystudent { 3599: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec, 3600: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_; 3601: if (!$cid) { 3602: unless ($cid=$ENV{'request.course.id'}) { 3603: return 'not_in_class'; 3604: } 3605: } 3606: # --------------------------------------------------------------- Make the user 3607: my $reply=&modifyuser 3608: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid, 3609: $desiredhome,$email); 3610: unless ($reply eq 'ok') { return $reply; } 3611: # This will cause &modify_student_enrollment to get the uid from the 3612: # students environment 3613: $uid = undef if (!$forceid); 3614: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last, 3615: $gene,$usec,$end,$start,$type,$locktype,$cid); 3616: return $reply; 3617: } 3618: 3619: sub modify_student_enrollment { 3620: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_; 3621: my ($cdom,$cnum,$chome); 3622: if (!$cid) { 3623: unless ($cid=$ENV{'request.course.id'}) { 3624: return 'not_in_class'; 3625: } 3626: $cdom=$ENV{'course.'.$cid.'.domain'}; 3627: $cnum=$ENV{'course.'.$cid.'.num'}; 3628: } else { 3629: ($cdom,$cnum)=split(/_/,$cid); 3630: } 3631: $chome=$ENV{'course.'.$cid.'.home'}; 3632: if (!$chome) { 3633: $chome=&homeserver($cnum,$cdom); 3634: } 3635: if (!$chome) { return 'unknown_course'; } 3636: # Make sure the user exists 3637: my $uhome=&homeserver($uname,$udom); 3638: if (($uhome eq '') || ($uhome eq 'no_host')) { 3639: return 'error: no such user'; 3640: } 3641: # Get student data if we were not given enough information 3642: if (!defined($first) || $first eq '' || 3643: !defined($last) || $last eq '' || 3644: !defined($uid) || $uid eq '' || 3645: !defined($middle) || $middle eq '' || 3646: !defined($gene) || $gene eq '') { 3647: # They did not supply us with enough data to enroll the student, so 3648: # we need to pick up more information. 3649: my %tmp = &get('environment', 3650: ['firstname','middlename','lastname', 'generation','id'] 3651: ,$udom,$uname); 3652: 3653: #foreach (keys(%tmp)) { 3654: # &logthis("key $_ = ".$tmp{$_}); 3655: #} 3656: $first = $tmp{'firstname'} if (!defined($first) || $first eq ''); 3657: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq ''); 3658: $last = $tmp{'lastname'} if (!defined($last) || $last eq ''); 3659: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq ''); 3660: $uid = $tmp{'id'} if (!defined($uid) || $uid eq ''); 3661: } 3662: my $fullname = &format_name($first,$middle,$last,$gene,'lastname'); 3663: my $reply=cput('classlist', 3664: {"$uname:$udom" => 3665: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) }, 3666: $cdom,$cnum); 3667: unless (($reply eq 'ok') || ($reply eq 'delayed')) { 3668: return 'error: '.$reply; 3669: } 3670: # Add student role to user 3671: my $uurl='/'.$cid; 3672: $uurl=~s/\_/\//g; 3673: if ($usec) { 3674: $uurl.='/'.$usec; 3675: } 3676: return &assignrole($udom,$uname,$uurl,'st',$end,$start); 3677: } 3678: 3679: sub format_name { 3680: my ($firstname,$middlename,$lastname,$generation,$first)=@_; 3681: my $name; 3682: if ($first ne 'lastname') { 3683: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation; 3684: } else { 3685: if ($lastname=~/\S/) { 3686: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename; 3687: $name=~s/\s+,/,/; 3688: } else { 3689: $name.= $firstname.' '.$middlename.' '.$generation; 3690: } 3691: } 3692: $name=~s/^\s+//; 3693: $name=~s/\s+$//; 3694: $name=~s/\s+/ /g; 3695: return $name; 3696: } 3697: 3698: # ------------------------------------------------- Write to course preferences 3699: 3700: sub writecoursepref { 3701: my ($courseid,%prefs)=@_; 3702: $courseid=~s/^\///; 3703: $courseid=~s/\_/\//g; 3704: my ($cdomain,$cnum)=split(/\//,$courseid); 3705: my $chome=homeserver($cnum,$cdomain); 3706: if (($chome eq '') || ($chome eq 'no_host')) { 3707: return 'error: no such course'; 3708: } 3709: my $cstring=''; 3710: foreach (keys %prefs) { 3711: $cstring.=escape($_).'='.escape($prefs{$_}).'&'; 3712: } 3713: $cstring=~s/\&$//; 3714: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome); 3715: } 3716: 3717: # ---------------------------------------------------------- Make/modify course 3718: 3719: sub createcourse { 3720: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner)=@_; 3721: $url=&declutter($url); 3722: my $cid=''; 3723: unless (&allowed('ccc',$udom)) { 3724: return 'refused'; 3725: } 3726: # ------------------------------------------------------------------- Create ID 3727: my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)). 3728: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'}; 3729: # ----------------------------------------------- Make sure that does not exist 3730: my $uhome=&homeserver($uname,$udom,'true'); 3731: unless (($uhome eq '') || ($uhome eq 'no_host')) { 3732: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)). 3733: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'}; 3734: $uhome=&homeserver($uname,$udom,'true'); 3735: unless (($uhome eq '') || ($uhome eq 'no_host')) { 3736: return 'error: unable to generate unique course-ID'; 3737: } 3738: } 3739: # ------------------------------------------------ Check supplied server name 3740: $course_server = $ENV{'user.homeserver'} if (! defined($course_server)); 3741: if (! exists($libserv{$course_server})) { 3742: return 'error:bad server name '.$course_server; 3743: } 3744: # ------------------------------------------------------------- Make the course 3745: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::', 3746: $course_server); 3747: unless ($reply eq 'ok') { return 'error: '.$reply; } 3748: $uhome=&homeserver($uname,$udom,'true'); 3749: if (($uhome eq '') || ($uhome eq 'no_host')) { 3750: return 'error: no such course'; 3751: } 3752: # ----------------------------------------------------------------- Course made 3753: # log existence 3754: &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description). 3755: ':'.&escape($inst_code).':'.&escape($course_owner),$uhome); 3756: &flushcourselogs(); 3757: # set toplevel url 3758: my $topurl=$url; 3759: unless ($nonstandard) { 3760: # ------------------------------------------ For standard courses, make top url 3761: my $mapurl=&clutter($url); 3762: if ($mapurl eq '/res/') { $mapurl=''; } 3763: $ENV{'form.initmap'}=(<<ENDINITMAP); 3764: <map> 3765: <resource id="1" type="start"></resource> 3766: <resource id="2" src="$mapurl"></resource> 3767: <resource id="3" type="finish"></resource> 3768: <link index="1" from="1" to="2"></link> 3769: <link index="2" from="2" to="3"></link> 3770: </map> 3771: ENDINITMAP 3772: $topurl=&declutter( 3773: &finishuserfileupload($uname,$udom,$uhome,'initmap','default.sequence') 3774: ); 3775: } 3776: # ----------------------------------------------------------- Write preferences 3777: &writecoursepref($udom.'_'.$uname, 3778: ('description' => $description, 3779: 'url' => $topurl)); 3780: return '/'.$udom.'/'.$uname; 3781: } 3782: 3783: # ---------------------------------------------------------- Assign Custom Role 3784: 3785: sub assigncustomrole { 3786: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_; 3787: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename, 3788: $end,$start,$deleteflag); 3789: } 3790: 3791: # ----------------------------------------------------------------- Revoke Role 3792: 3793: sub revokerole { 3794: my ($udom,$uname,$url,$role,$deleteflag)=@_; 3795: my $now=time; 3796: return &assignrole($udom,$uname,$url,$role,$now,$deleteflag); 3797: } 3798: 3799: # ---------------------------------------------------------- Revoke Custom Role 3800: 3801: sub revokecustomrole { 3802: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_; 3803: my $now=time; 3804: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now, 3805: $deleteflag); 3806: } 3807: 3808: # ------------------------------------------------------------ Disk usage 3809: sub diskusage { 3810: my ($udom,$uname,$directoryRoot)=@_; 3811: $directoryRoot =~ s/\/$//; 3812: my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom)); 3813: return $listing; 3814: } 3815: 3816: sub is_locked { 3817: my ($file_name, $domain, $user) = @_; 3818: my @check; 3819: my $is_locked; 3820: push @check, $file_name; 3821: my %locked = &Apache::lonnet::get('file_permissions',\@check, 3822: $ENV{'user.domain'},$ENV{'user.name'}); 3823: if (ref($locked{$file_name}) eq 'ARRAY') { 3824: $is_locked = 'true'; 3825: } else { 3826: $is_locked = 'false'; 3827: } 3828: } 3829: 3830: # ------------------------------------------------------------- Mark as Read Only 3831: 3832: sub mark_as_readonly { 3833: my ($domain,$user,$files,$what) = @_; 3834: my %current_permissions = &Apache::lonnet::dump('file_permissions',$domain,$user); 3835: foreach my $file (@{$files}) { 3836: push(@{$current_permissions{$file}},$what); 3837: } 3838: &Apache::lonnet::put('file_permissions',\%current_permissions,$domain,$user); 3839: return; 3840: } 3841: 3842: # ------------------------------------------------------------Save Selected Files 3843: 3844: sub save_selected_files { 3845: my ($user, $path, @files) = @_; 3846: my $filename = $user."savedfiles"; 3847: my @other_files = &files_not_in_path($user, $path); 3848: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename); 3849: foreach my $file (@files) { 3850: print (OUT $ENV{'form.currentpath'}.$file."\n"); 3851: } 3852: foreach my $file (@other_files) { 3853: print (OUT $file."\n"); 3854: } 3855: close (OUT); 3856: return 'ok'; 3857: } 3858: 3859: sub clear_selected_files { 3860: my ($user) = @_; 3861: my $filename = $user."savedfiles"; 3862: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename); 3863: print (OUT undef); 3864: close (OUT); 3865: return ("ok"); 3866: } 3867: 3868: sub files_in_path { 3869: my ($user, $path) = @_; 3870: my $filename = $user."savedfiles"; 3871: my %return_files; 3872: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename); 3873: while (my $line_in = <IN>) { 3874: chomp ($line_in); 3875: my @paths_and_file = split (m!/!, $line_in); 3876: my $file_part = pop (@paths_and_file); 3877: my $path_part = join ('/', @paths_and_file); 3878: $path_part.='/'; 3879: my $path_and_file = $path_part.$file_part; 3880: if ($path_part eq $path) { 3881: $return_files{$file_part}= 'selected'; 3882: } 3883: } 3884: close (IN); 3885: return (\%return_files); 3886: } 3887: 3888: # called in portfolio select mode, to show files selected NOT in current directory 3889: sub files_not_in_path { 3890: my ($user, $path) = @_; 3891: my $filename = $user."savedfiles"; 3892: my @return_files; 3893: my $path_part; 3894: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename); 3895: while (<IN>) { 3896: #ok, I know it's clunky, but I want it to work 3897: my @paths_and_file = split m!/!, $_; 3898: my $file_part = pop (@paths_and_file); 3899: chomp ($file_part); 3900: my $path_part = join ('/', @paths_and_file); 3901: $path_part .= '/'; 3902: my $path_and_file = $path_part.$file_part; 3903: if ($path_part ne $path) { 3904: push (@return_files, ($path_and_file)); 3905: } 3906: } 3907: close (OUT); 3908: return (@return_files); 3909: } 3910: 3911: #--------------------------------------------------------------Get Marked as Read Only 3912: 3913: sub get_marked_as_readonly { 3914: my ($domain,$user,$what) = @_; 3915: my %current_permissions = &Apache::lonnet::dump('file_permissions',$domain,$user); 3916: my @readonly_files; 3917: while (my ($file_name,$value) = each(%current_permissions)) { 3918: if (ref($value) eq "ARRAY"){ 3919: foreach my $stored_what (@{$value}) { 3920: if ($stored_what eq $what) { 3921: push(@readonly_files, $file_name); 3922: } elsif (!defined($what)) { 3923: push(@readonly_files, $file_name); 3924: } 3925: } 3926: } 3927: } 3928: return @readonly_files; 3929: } 3930: #-----------------------------------------------------------Get Marked as Read Only Hash 3931: 3932: sub get_marked_as_readonly_hash { 3933: my ($domain,$user,$what) = @_; 3934: my %current_permissions = &Apache::lonnet::dump('file_permissions',$domain,$user); 3935: my %readonly_files; 3936: while (my ($file_name,$value) = each(%current_permissions)) { 3937: if (ref($value) eq "ARRAY"){ 3938: foreach my $stored_what (@{$value}) { 3939: if ($stored_what eq $what) { 3940: $readonly_files{$file_name} = 'locked'; 3941: } elsif (!defined($what)) { 3942: $readonly_files{$file_name} = 'locked'; 3943: } 3944: } 3945: } 3946: } 3947: return %readonly_files; 3948: } 3949: # ------------------------------------------------------------ Unmark as Read Only 3950: 3951: sub unmark_as_readonly { 3952: # unmarks all files locked by $what 3953: # for portfolio submissions, $what contains $crsid and $symb 3954: my ($domain,$user,$what) = @_; 3955: my %current_permissions = &Apache::lonnet::dump('file_permissions',$domain,$user); 3956: my @readonly_files = &Apache::lonnet::get_marked_as_readonly($domain,$user,$what); 3957: foreach my $file(@readonly_files){ 3958: my $current_locks = $current_permissions{$file}; 3959: my @new_locks; 3960: my @del_keys; 3961: if (ref($current_locks) eq "ARRAY"){ 3962: foreach my $locker (@{$current_locks}) { 3963: unless ($locker eq $what) { 3964: push(@new_locks, $what); 3965: } 3966: } 3967: if (@new_locks > 0) { 3968: $current_permissions{$file} = \@new_locks; 3969: } else { 3970: push(@del_keys, $file); 3971: &Apache::lonnet::del('file_permissions',\@del_keys, $domain, $user); 3972: delete $current_permissions{$file}; 3973: } 3974: } 3975: } 3976: &Apache::lonnet::put('file_permissions',\%current_permissions,$domain,$user); 3977: return; 3978: } 3979: 3980: # ------------------------------------------------------------ Directory lister 3981: 3982: sub dirlist { 3983: my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_; 3984: 3985: $uri=~s/^\///; 3986: $uri=~s/\/$//; 3987: my ($udom, $uname); 3988: (undef,$udom,$uname)=split(/\//,$uri); 3989: if(defined($userdomain)) { 3990: $udom = $userdomain; 3991: } 3992: if(defined($username)) { 3993: $uname = $username; 3994: } 3995: 3996: my $dirRoot = $perlvar{'lonDocRoot'}; 3997: if(defined($alternateDirectoryRoot)) { 3998: $dirRoot = $alternateDirectoryRoot; 3999: $dirRoot =~ s/\/$//; 4000: } 4001: 4002: if($udom) { 4003: if($uname) { 4004: my $listing=reply('ls:'.$dirRoot.'/'.$uri, 4005: homeserver($uname,$udom)); 4006: return split(/:/,$listing); 4007: } elsif(!defined($alternateDirectoryRoot)) { 4008: my $tryserver; 4009: my %allusers=(); 4010: foreach $tryserver (keys %libserv) { 4011: if($hostdom{$tryserver} eq $udom) { 4012: my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'. 4013: $udom, $tryserver); 4014: if (($listing ne 'no_such_dir') && ($listing ne 'empty') 4015: && ($listing ne 'con_lost')) { 4016: foreach (split(/:/,$listing)) { 4017: my ($entry,@stat)=split(/&/,$_); 4018: $allusers{$entry}=1; 4019: } 4020: } 4021: } 4022: } 4023: my $alluserstr=''; 4024: foreach (sort keys %allusers) { 4025: $alluserstr.=$_.'&user:'; 4026: } 4027: $alluserstr=~s/:$//; 4028: return split(/:/,$alluserstr); 4029: } else { 4030: my @emptyResults = (); 4031: push(@emptyResults, 'missing user name'); 4032: return split(':',@emptyResults); 4033: } 4034: } elsif(!defined($alternateDirectoryRoot)) { 4035: my $tryserver; 4036: my %alldom=(); 4037: foreach $tryserver (keys %libserv) { 4038: $alldom{$hostdom{$tryserver}}=1; 4039: } 4040: my $alldomstr=''; 4041: foreach (sort keys %alldom) { 4042: $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:'; 4043: } 4044: $alldomstr=~s/:$//; 4045: return split(/:/,$alldomstr); 4046: } else { 4047: my @emptyResults = (); 4048: push(@emptyResults, 'missing domain'); 4049: return split(':',@emptyResults); 4050: } 4051: } 4052: 4053: # --------------------------------------------- GetFileTimestamp 4054: # This function utilizes dirlist and returns the date stamp for 4055: # when it was last modified. It will also return an error of -1 4056: # if an error occurs 4057: 4058: ## 4059: ## FIXME: This subroutine assumes its caller knows something about the 4060: ## directory structure of the home server for the student ($root). 4061: ## Not a good assumption to make. Since this is for looking up files 4062: ## in user directories, the full path should be constructed by lond, not 4063: ## whatever machine we request data from. 4064: ## 4065: sub GetFileTimestamp { 4066: my ($studentDomain,$studentName,$filename,$root)=@_; 4067: $studentDomain=~s/\W//g; 4068: $studentName=~s/\W//g; 4069: my $subdir=$studentName.'__'; 4070: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/; 4071: my $proname="$studentDomain/$subdir/$studentName"; 4072: $proname .= '/'.$filename; 4073: my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 4074: $studentName, $root); 4075: my @stats = split('&', $fileStat); 4076: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') { 4077: # @stats contains first the filename, then the stat output 4078: return $stats[10]; # so this is 10 instead of 9. 4079: } else { 4080: return -1; 4081: } 4082: } 4083: 4084: # -------------------------------------------------------- Value of a Condition 4085: 4086: sub directcondval { 4087: my $number=shift; 4088: if (!defined($ENV{'user.state.'.$ENV{'request.course.id'}})) { 4089: &Apache::lonuserstate::evalstate(); 4090: } 4091: if ($ENV{'user.state.'.$ENV{'request.course.id'}}) { 4092: return substr($ENV{'user.state.'.$ENV{'request.course.id'}},$number,1); 4093: } else { 4094: return 2; 4095: } 4096: } 4097: 4098: sub condval { 4099: my $condidx=shift; 4100: my $result=0; 4101: my $allpathcond=''; 4102: foreach (split(/\|/,$condidx)) { 4103: if (defined($ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_})) { 4104: $allpathcond.= 4105: '('.$ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_}.')|'; 4106: } 4107: } 4108: $allpathcond=~s/\|$//; 4109: if ($ENV{'request.course.id'}) { 4110: if ($allpathcond) { 4111: my $operand='|'; 4112: my @stack; 4113: foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) { 4114: if ($_ eq '(') { 4115: push @stack,($operand,$result) 4116: } elsif ($_ eq ')') { 4117: my $before=pop @stack; 4118: if (pop @stack eq '&') { 4119: $result=$result>$before?$before:$result; 4120: } else { 4121: $result=$result>$before?$result:$before; 4122: } 4123: } elsif (($_ eq '&') || ($_ eq '|')) { 4124: $operand=$_; 4125: } else { 4126: my $new=directcondval($_); 4127: if ($operand eq '&') { 4128: $result=$result>$new?$new:$result; 4129: } else { 4130: $result=$result>$new?$result:$new; 4131: } 4132: } 4133: } 4134: } 4135: } 4136: return $result; 4137: } 4138: 4139: # ---------------------------------------------------- Devalidate courseresdata 4140: 4141: sub devalidatecourseresdata { 4142: my ($coursenum,$coursedomain)=@_; 4143: my $hashid=$coursenum.':'.$coursedomain; 4144: &devalidate_cache(\%courseresdatacache,$hashid,'courseres'); 4145: } 4146: 4147: # --------------------------------------------------- Course Resourcedata Query 4148: 4149: sub courseresdata { 4150: my ($coursenum,$coursedomain,@which)=@_; 4151: my $coursehom=&homeserver($coursenum,$coursedomain); 4152: my $hashid=$coursenum.':'.$coursedomain; 4153: my ($result,$cached)=&is_cached(\%courseresdatacache,$hashid,'courseres'); 4154: unless (defined($cached)) { 4155: my %dumpreply=&dump('resourcedata',$coursedomain,$coursenum); 4156: $result=\%dumpreply; 4157: my ($tmp) = keys(%dumpreply); 4158: if ($tmp !~ /^(con_lost|error|no_such_host)/i) { 4159: &do_cache(\%courseresdatacache,$hashid,$result,'courseres'); 4160: } elsif ($tmp =~ /^(con_lost|no_such_host)/) { 4161: return $tmp; 4162: } elsif ($tmp =~ /^(error)/) { 4163: $result=undef; 4164: &do_cache(\%courseresdatacache,$hashid,$result,'courseres'); 4165: } 4166: } 4167: foreach my $item (@which) { 4168: if (defined($result->{$item})) { 4169: return $result->{$item}; 4170: } 4171: } 4172: return undef; 4173: } 4174: 4175: # 4176: # EXT resource caching routines 4177: # 4178: 4179: sub clear_EXT_cache_status { 4180: &delenv('cache.EXT.'); 4181: } 4182: 4183: sub EXT_cache_status { 4184: my ($target_domain,$target_user) = @_; 4185: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain; 4186: if (exists($ENV{$cachename}) && ($ENV{$cachename}+600) > time) { 4187: # We know already the user has no data 4188: return 1; 4189: } else { 4190: return 0; 4191: } 4192: } 4193: 4194: sub EXT_cache_set { 4195: my ($target_domain,$target_user) = @_; 4196: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain; 4197: &appenv($cachename => time); 4198: } 4199: 4200: # --------------------------------------------------------- Value of a Variable 4201: sub EXT { 4202: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_; 4203: 4204: unless ($varname) { return ''; } 4205: #get real user name/domain, courseid and symb 4206: my $courseid; 4207: my $publicuser; 4208: if ($symbparm) { 4209: $symbparm=&get_symb_from_alias($symbparm); 4210: } 4211: if (!($uname && $udom)) { 4212: (my $cursymb,$courseid,$udom,$uname,$publicuser)= 4213: &Apache::lonxml::whichuser($symbparm); 4214: if (!$symbparm) { $symbparm=$cursymb; } 4215: } else { 4216: $courseid=$ENV{'request.course.id'}; 4217: } 4218: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname); 4219: my $rest; 4220: if (defined($therest[0])) { 4221: $rest=join('.',@therest); 4222: } else { 4223: $rest=''; 4224: } 4225: 4226: my $qualifierrest=$qualifier; 4227: if ($rest) { $qualifierrest.='.'.$rest; } 4228: my $spacequalifierrest=$space; 4229: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; } 4230: if ($realm eq 'user') { 4231: # --------------------------------------------------------------- user.resource 4232: if ($space eq 'resource') { 4233: if (defined($Apache::lonhomework::parsing_a_problem)) { 4234: return $Apache::lonhomework::history{$qualifierrest}; 4235: } else { 4236: my %restored; 4237: if ($publicuser || $ENV{'request.state'} eq 'construct') { 4238: %restored=&tmprestore($symbparm,$courseid,$udom,$uname); 4239: } else { 4240: %restored=&restore($symbparm,$courseid,$udom,$uname); 4241: } 4242: return $restored{$qualifierrest}; 4243: } 4244: # ----------------------------------------------------------------- user.access 4245: } elsif ($space eq 'access') { 4246: # FIXME - not supporting calls for a specific user 4247: return &allowed($qualifier,$rest); 4248: # ------------------------------------------ user.preferences, user.environment 4249: } elsif (($space eq 'preferences') || ($space eq 'environment')) { 4250: if (($uname eq $ENV{'user.name'}) && 4251: ($udom eq $ENV{'user.domain'})) { 4252: return $ENV{join('.',('environment',$qualifierrest))}; 4253: } else { 4254: my %returnhash; 4255: if (!$publicuser) { 4256: %returnhash=&userenvironment($udom,$uname, 4257: $qualifierrest); 4258: } 4259: return $returnhash{$qualifierrest}; 4260: } 4261: # ----------------------------------------------------------------- user.course 4262: } elsif ($space eq 'course') { 4263: # FIXME - not supporting calls for a specific user 4264: return $ENV{join('.',('request.course',$qualifier))}; 4265: # ------------------------------------------------------------------- user.role 4266: } elsif ($space eq 'role') { 4267: # FIXME - not supporting calls for a specific user 4268: my ($role,$where)=split(/\./,$ENV{'request.role'}); 4269: if ($qualifier eq 'value') { 4270: return $role; 4271: } elsif ($qualifier eq 'extent') { 4272: return $where; 4273: } 4274: # ----------------------------------------------------------------- user.domain 4275: } elsif ($space eq 'domain') { 4276: return $udom; 4277: # ------------------------------------------------------------------- user.name 4278: } elsif ($space eq 'name') { 4279: return $uname; 4280: # ---------------------------------------------------- Any other user namespace 4281: } else { 4282: my %reply; 4283: if (!$publicuser) { 4284: %reply=&get($space,[$qualifierrest],$udom,$uname); 4285: } 4286: return $reply{$qualifierrest}; 4287: } 4288: } elsif ($realm eq 'query') { 4289: # ---------------------------------------------- pull stuff out of query string 4290: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'}, 4291: [$spacequalifierrest]); 4292: return $ENV{'form.'.$spacequalifierrest}; 4293: } elsif ($realm eq 'request') { 4294: # ------------------------------------------------------------- request.browser 4295: if ($space eq 'browser') { 4296: if ($qualifier eq 'textremote') { 4297: if (&mt('textual_remote_display') eq 'on') { 4298: return 1; 4299: } else { 4300: return 0; 4301: } 4302: } else { 4303: return $ENV{'browser.'.$qualifier}; 4304: } 4305: # ------------------------------------------------------------ request.filename 4306: } else { 4307: return $ENV{'request.'.$spacequalifierrest}; 4308: } 4309: } elsif ($realm eq 'course') { 4310: # ---------------------------------------------------------- course.description 4311: return $ENV{'course.'.$courseid.'.'.$spacequalifierrest}; 4312: } elsif ($realm eq 'resource') { 4313: 4314: my $section; 4315: if (defined($courseid) && $courseid eq $ENV{'request.course.id'}) { 4316: if (!$symbparm) { $symbparm=&symbread(); } 4317: } 4318: if ($symbparm && defined($courseid) && 4319: $courseid eq $ENV{'request.course.id'}) { 4320: 4321: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest; 4322: 4323: # ----------------------------------------------------- Cascading lookup scheme 4324: my $symbp=$symbparm; 4325: my $mapp=(&decode_symb($symbp))[0]; 4326: 4327: my $symbparm=$symbp.'.'.$spacequalifierrest; 4328: my $mapparm=$mapp.'___(all).'.$spacequalifierrest; 4329: 4330: if (($ENV{'user.name'} eq $uname) && 4331: ($ENV{'user.domain'} eq $udom)) { 4332: $section=$ENV{'request.course.sec'}; 4333: } else { 4334: if (! defined($usection)) { 4335: $section=&getsection($udom,$uname,$courseid); 4336: } else { 4337: $section = $usection; 4338: } 4339: } 4340: 4341: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest; 4342: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm; 4343: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm; 4344: 4345: my $courselevel=$courseid.'.'.$spacequalifierrest; 4346: my $courselevelr=$courseid.'.'.$symbparm; 4347: my $courselevelm=$courseid.'.'.$mapparm; 4348: 4349: # ----------------------------------------------------------- first, check user 4350: #most student don\'t have any data set, check if there is some data 4351: if (! &EXT_cache_status($udom,$uname)) { 4352: my $hashid="$udom:$uname"; 4353: my ($result,$cached)=&is_cached(\%userresdatacache,$hashid, 4354: 'userres'); 4355: if (!defined($cached)) { 4356: my %resourcedata=&dump('resourcedata',$udom,$uname); 4357: $result=\%resourcedata; 4358: &do_cache(\%userresdatacache,$hashid,$result,'userres'); 4359: } 4360: my ($tmp)=keys(%$result); 4361: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) { 4362: if ($$result{$courselevelr}) { 4363: return $$result{$courselevelr}; } 4364: if ($$result{$courselevelm}) { 4365: return $$result{$courselevelm}; } 4366: if ($$result{$courselevel}) { 4367: return $$result{$courselevel}; } 4368: } else { 4369: #error 2 occurs when the .db doesn't exist 4370: if ($tmp!~/error: 2 /) { 4371: &logthis("<font color=blue>WARNING:". 4372: " Trying to get resource data for ". 4373: $uname." at ".$udom.": ". 4374: $tmp."</font>"); 4375: } elsif ($tmp=~/error: 2 /) { 4376: &EXT_cache_set($udom,$uname); 4377: } elsif ($tmp =~ /^(con_lost|no_such_host)/) { 4378: return $tmp; 4379: } 4380: } 4381: } 4382: 4383: # -------------------------------------------------------- second, check course 4384: 4385: my $coursereply=&courseresdata($ENV{'course.'.$courseid.'.num'}, 4386: $ENV{'course.'.$courseid.'.domain'}, 4387: ($seclevelr,$seclevelm,$seclevel, 4388: $courselevelr,$courselevelm, 4389: $courselevel)); 4390: if (defined($coursereply)) { return $coursereply; } 4391: 4392: # ------------------------------------------------------ third, check map parms 4393: my %parmhash=(); 4394: my $thisparm=''; 4395: if (tie(%parmhash,'GDBM_File', 4396: $ENV{'request.course.fn'}.'_parms.db', 4397: &GDBM_READER(),0640)) { 4398: $thisparm=$parmhash{$symbparm}; 4399: untie(%parmhash); 4400: } 4401: if ($thisparm) { return $thisparm; } 4402: } 4403: # --------------------------------------------- last, look in resource metadata 4404: 4405: $spacequalifierrest=~s/\./\_/; 4406: my $filename; 4407: if (!$symbparm) { $symbparm=&symbread(); } 4408: if ($symbparm) { 4409: $filename=(&decode_symb($symbparm))[2]; 4410: } else { 4411: $filename=$ENV{'request.filename'}; 4412: } 4413: my $metadata=&metadata($filename,$spacequalifierrest); 4414: if (defined($metadata)) { return $metadata; } 4415: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest); 4416: if (defined($metadata)) { return $metadata; } 4417: 4418: # ------------------------------------------------------------------ Cascade up 4419: unless ($space eq '0') { 4420: my @parts=split(/_/,$space); 4421: my $id=pop(@parts); 4422: my $part=join('_',@parts); 4423: if ($part eq '') { $part='0'; } 4424: my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest, 4425: $symbparm,$udom,$uname,$section,1); 4426: if (defined($partgeneral)) { return $partgeneral; } 4427: } 4428: if ($recurse) { return undef; } 4429: my $pack_def=&packages_tab_default($filename,$varname); 4430: if (defined($pack_def)) { return $pack_def; } 4431: 4432: # ---------------------------------------------------- Any other user namespace 4433: } elsif ($realm eq 'environment') { 4434: # ----------------------------------------------------------------- environment 4435: if (($uname eq $ENV{'user.name'})&&($udom eq $ENV{'user.domain'})) { 4436: return $ENV{'environment.'.$spacequalifierrest}; 4437: } else { 4438: my %returnhash=&userenvironment($udom,$uname, 4439: $spacequalifierrest); 4440: return $returnhash{$spacequalifierrest}; 4441: } 4442: } elsif ($realm eq 'system') { 4443: # ----------------------------------------------------------------- system.time 4444: if ($space eq 'time') { 4445: return time; 4446: } 4447: } 4448: return ''; 4449: } 4450: 4451: sub packages_tab_default { 4452: my ($uri,$varname)=@_; 4453: my (undef,$part,$name)=split(/\./,$varname); 4454: my $packages=&metadata($uri,'packages'); 4455: foreach my $package (split(/,/,$packages)) { 4456: my ($pack_type,$pack_part)=split(/_/,$package,2); 4457: if (defined($packagetab{"$pack_type&$name&default"})) { 4458: return $packagetab{"$pack_type&$name&default"}; 4459: } 4460: if ($pack_type eq 'part') { $pack_part='0'; } 4461: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) { 4462: return $packagetab{$pack_type."_".$pack_part."&$name&default"}; 4463: } 4464: } 4465: return undef; 4466: } 4467: 4468: sub add_prefix_and_part { 4469: my ($prefix,$part)=@_; 4470: my $keyroot; 4471: if (defined($prefix) && $prefix !~ /^__/) { 4472: # prefix that has a part already 4473: $keyroot=$prefix; 4474: } elsif (defined($prefix)) { 4475: # prefix that is missing a part 4476: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); } 4477: } else { 4478: # no prefix at all 4479: if (defined($part)) { $keyroot='_'.$part; } 4480: } 4481: return $keyroot; 4482: } 4483: 4484: # ---------------------------------------------------------------- Get metadata 4485: 4486: sub metadata { 4487: my ($uri,$what,$liburi,$prefix,$depthcount)=@_; 4488: $uri=&declutter($uri); 4489: # if it is a non metadata possible uri return quickly 4490: if (($uri eq '') || 4491: (($uri =~ m|^/*adm/|) && 4492: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) || 4493: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) || 4494: ($uri =~ m|home/[^/]+/public_html/|)) { 4495: return undef; 4496: } 4497: my $filename=$uri; 4498: $uri=~s/\.meta$//; 4499: # 4500: # Is the metadata already cached? 4501: # Look at timestamp of caching 4502: # Everything is cached by the main uri, libraries are never directly cached 4503: # 4504: if (!defined($liburi)) { 4505: my ($result,$cached)=&is_cached(\%metacache,$uri,'meta'); 4506: if (defined($cached)) { return $result->{':'.$what}; } 4507: } 4508: { 4509: # 4510: # Is this a recursive call for a library? 4511: # 4512: if (! exists($metacache{$uri})) { 4513: $metacache{$uri}={}; 4514: } 4515: if ($liburi) { 4516: $liburi=&declutter($liburi); 4517: $filename=$liburi; 4518: } else { 4519: &devalidate_cache(\%metacache,$uri,'meta'); 4520: } 4521: my %metathesekeys=(); 4522: unless ($filename=~/\.meta$/) { $filename.='.meta'; } 4523: my $metastring; 4524: if ($uri !~ m|^uploaded/|) { 4525: my $file=&filelocation('',&clutter($filename)); 4526: push(@{$metacache{$uri.'.file'}},$file); 4527: $metastring=&getfile($file); 4528: } 4529: my $parser=HTML::LCParser->new(\$metastring); 4530: my $token; 4531: undef %metathesekeys; 4532: while ($token=$parser->get_token) { 4533: if ($token->[0] eq 'S') { 4534: if (defined($token->[2]->{'package'})) { 4535: # 4536: # This is a package - get package info 4537: # 4538: my $package=$token->[2]->{'package'}; 4539: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'}); 4540: if (defined($token->[2]->{'id'})) { 4541: $keyroot.='_'.$token->[2]->{'id'}; 4542: } 4543: if ($metacache{$uri}->{':packages'}) { 4544: $metacache{$uri}->{':packages'}.=','.$package.$keyroot; 4545: } else { 4546: $metacache{$uri}->{':packages'}=$package.$keyroot; 4547: } 4548: foreach (keys %packagetab) { 4549: my $part=$keyroot; 4550: $part=~s/^\_//; 4551: if ($_=~/^\Q$package\E\&/ || 4552: $_=~/^\Q$package\E_0\&/) { 4553: my ($pack,$name,$subp)=split(/\&/,$_); 4554: # ignore package.tab specified default values 4555: # here &package_tab_default() will fetch those 4556: if ($subp eq 'default') { next; } 4557: my $value=$packagetab{$_}; 4558: my $unikey; 4559: if ($pack =~ /_0$/) { 4560: $unikey='parameter_0_'.$name; 4561: $part=0; 4562: } else { 4563: $unikey='parameter'.$keyroot.'_'.$name; 4564: } 4565: if ($subp eq 'display') { 4566: $value.=' [Part: '.$part.']'; 4567: } 4568: $metacache{$uri}->{':'.$unikey.'.part'}=$part; 4569: $metathesekeys{$unikey}=1; 4570: unless (defined($metacache{$uri}->{':'.$unikey.'.'.$subp})) { 4571: $metacache{$uri}->{':'.$unikey.'.'.$subp}=$value; 4572: } 4573: if (defined($metacache{$uri}->{':'.$unikey.'.default'})) { 4574: $metacache{$uri}->{':'.$unikey}= 4575: $metacache{$uri}->{':'.$unikey.'.default'}; 4576: } 4577: } 4578: } 4579: } else { 4580: # 4581: # This is not a package - some other kind of start tag 4582: # 4583: my $entry=$token->[1]; 4584: my $unikey; 4585: if ($entry eq 'import') { 4586: $unikey=''; 4587: } else { 4588: $unikey=$entry; 4589: } 4590: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'}); 4591: 4592: if (defined($token->[2]->{'id'})) { 4593: $unikey.='_'.$token->[2]->{'id'}; 4594: } 4595: 4596: if ($entry eq 'import') { 4597: # 4598: # Importing a library here 4599: # 4600: if ($depthcount<20) { 4601: my $location=$parser->get_text('/import'); 4602: my $dir=$filename; 4603: $dir=~s|[^/]*$||; 4604: $location=&filelocation($dir,$location); 4605: foreach (sort(split(/\,/,&metadata($uri,'keys', 4606: $location,$unikey, 4607: $depthcount+1)))) { 4608: $metacache{$uri}->{':'.$_}=$metacache{$uri}->{':'.$_}; 4609: $metathesekeys{$_}=1; 4610: } 4611: } 4612: } else { 4613: 4614: if (defined($token->[2]->{'name'})) { 4615: $unikey.='_'.$token->[2]->{'name'}; 4616: } 4617: $metathesekeys{$unikey}=1; 4618: foreach (@{$token->[3]}) { 4619: $metacache{$uri}->{':'.$unikey.'.'.$_}=$token->[2]->{$_}; 4620: } 4621: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry)); 4622: my $default=$metacache{$uri}->{':'.$unikey.'.default'}; 4623: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) { 4624: # only ws inside the tag, and not in default, so use default 4625: # as value 4626: $metacache{$uri}->{':'.$unikey}=$default; 4627: } else { 4628: # either something interesting inside the tag or default 4629: # uninteresting 4630: $metacache{$uri}->{':'.$unikey}=$internaltext; 4631: } 4632: # end of not-a-package not-a-library import 4633: } 4634: # end of not-a-package start tag 4635: } 4636: # the next is the end of "start tag" 4637: } 4638: } 4639: my ($extension) = ($uri =~ /\.(\w+)$/); 4640: foreach my $key (sort(keys(%packagetab))) { 4641: #&logthis("extsion1 $extension $key !!"); 4642: #no specific packages #how's our extension 4643: if ($key!~/^extension_\Q$extension\E&/) { next; } 4644: &metadata_create_package_def($uri,$key,'extension_'.$extension, 4645: \%metathesekeys); 4646: } 4647: if (!exists($metacache{$uri}->{':packages'})) { 4648: foreach my $key (sort(keys(%packagetab))) { 4649: #no specific packages well let's get default then 4650: if ($key!~/^default&/) { next; } 4651: &metadata_create_package_def($uri,$key,'default', 4652: \%metathesekeys); 4653: } 4654: } 4655: # are there custom rights to evaluate 4656: if ($metacache{$uri}->{':copyright'} eq 'custom') { 4657: 4658: # 4659: # Importing a rights file here 4660: # 4661: unless ($depthcount) { 4662: my $location=$metacache{$uri}->{':customdistributionfile'}; 4663: my $dir=$filename; 4664: $dir=~s|[^/]*$||; 4665: $location=&filelocation($dir,$location); 4666: foreach (sort(split(/\,/,&metadata($uri,'keys', 4667: $location,'_rights', 4668: $depthcount+1)))) { 4669: $metacache{$uri}->{':'.$_}=$metacache{$uri}->{':'.$_}; 4670: $metathesekeys{$_}=1; 4671: } 4672: } 4673: } 4674: $metacache{$uri}->{':keys'}=join(',',keys %metathesekeys); 4675: &metadata_generate_part0(\%metathesekeys,$metacache{$uri},$uri); 4676: $metacache{$uri}->{':allpossiblekeys'}=join(',',keys %metathesekeys); 4677: &do_cache(\%metacache,$uri,$metacache{$uri},'meta'); 4678: # this is the end of "was not already recently cached 4679: } 4680: return $metacache{$uri}->{':'.$what}; 4681: } 4682: 4683: sub metadata_create_package_def { 4684: my ($uri,$key,$package,$metathesekeys)=@_; 4685: my ($pack,$name,$subp)=split(/\&/,$key); 4686: if ($subp eq 'default') { next; } 4687: 4688: if (defined($metacache{$uri}->{':packages'})) { 4689: $metacache{$uri}->{':packages'}.=','.$package; 4690: } else { 4691: $metacache{$uri}->{':packages'}=$package; 4692: } 4693: my $value=$packagetab{$key}; 4694: my $unikey; 4695: $unikey='parameter_0_'.$name; 4696: $metacache{$uri}->{':'.$unikey.'.part'}=0; 4697: $$metathesekeys{$unikey}=1; 4698: unless (defined($metacache{$uri}->{':'.$unikey.'.'.$subp})) { 4699: $metacache{$uri}->{':'.$unikey.'.'.$subp}=$value; 4700: } 4701: if (defined($metacache{$uri}->{':'.$unikey.'.default'})) { 4702: $metacache{$uri}->{':'.$unikey}= 4703: $metacache{$uri}->{':'.$unikey.'.default'}; 4704: } 4705: } 4706: 4707: sub metadata_generate_part0 { 4708: my ($metadata,$metacache,$uri) = @_; 4709: my %allnames; 4710: foreach my $metakey (sort keys %$metadata) { 4711: if ($metakey=~/^parameter\_(.*)/) { 4712: my $part=$$metacache{':'.$metakey.'.part'}; 4713: my $name=$$metacache{':'.$metakey.'.name'}; 4714: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) { 4715: $allnames{$name}=$part; 4716: } 4717: } 4718: } 4719: foreach my $name (keys(%allnames)) { 4720: $$metadata{"parameter_0_$name"}=1; 4721: my $key=":parameter_0_$name"; 4722: $$metacache{"$key.part"}='0'; 4723: $$metacache{"$key.name"}=$name; 4724: $$metacache{"$key.type"}=$$metacache{':parameter_'. 4725: $allnames{$name}.'_'.$name. 4726: '.type'}; 4727: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name. 4728: '.display'}; 4729: my $expr='\\[Part: '.$allnames{$name}.'\\]'; 4730: $olddis=~s/\Q$expr\E/\[Part: 0\]/; 4731: $$metacache{"$key.display"}=$olddis; 4732: } 4733: } 4734: 4735: # ------------------------------------------------- Get the title of a resource 4736: 4737: sub gettitle { 4738: my $urlsymb=shift; 4739: my $symb=&symbread($urlsymb); 4740: if ($symb) { 4741: my ($result,$cached)=&is_cached(\%titlecache,$symb,'title',600); 4742: if (defined($cached)) { 4743: return $result; 4744: } 4745: my ($map,$resid,$url)=&decode_symb($symb); 4746: my $title=''; 4747: my %bighash; 4748: if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db', 4749: &GDBM_READER(),0640)) { 4750: my $mapid=$bighash{'map_pc_'.&clutter($map)}; 4751: $title=$bighash{'title_'.$mapid.'.'.$resid}; 4752: untie %bighash; 4753: } 4754: $title=~s/\&colon\;/\:/gs; 4755: if ($title) { 4756: return &do_cache(\%titlecache,$symb,$title,'title'); 4757: } 4758: $urlsymb=$url; 4759: } 4760: my $title=&metadata($urlsymb,'title'); 4761: if (!$title) { $title=(split('/',$urlsymb))[-1]; } 4762: return $title; 4763: } 4764: 4765: # ------------------------------------------------- Update symbolic store links 4766: 4767: sub symblist { 4768: my ($mapname,%newhash)=@_; 4769: $mapname=&deversion(&declutter($mapname)); 4770: my %hash; 4771: if (($ENV{'request.course.fn'}) && (%newhash)) { 4772: if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db', 4773: &GDBM_WRCREAT(),0640)) { 4774: foreach (keys %newhash) { 4775: $hash{declutter($_)}=$mapname.'___'.&deversion($newhash{$_}); 4776: } 4777: if (untie(%hash)) { 4778: return 'ok'; 4779: } 4780: } 4781: } 4782: return 'error'; 4783: } 4784: 4785: # --------------------------------------------------------------- Verify a symb 4786: 4787: sub symbverify { 4788: my ($symb,$thisurl)=@_; 4789: my $thisfn=$thisurl; 4790: # wrapper not part of symbs 4791: $thisfn=~s/^\/adm\/wrapper//; 4792: $thisfn=&declutter($thisfn); 4793: # direct jump to resource in page or to a sequence - will construct own symbs 4794: if ($thisfn=~/\.(page|sequence)$/) { return 1; } 4795: # check URL part 4796: my ($map,$resid,$url)=&decode_symb($symb); 4797: 4798: unless ($url eq $thisfn) { return 0; } 4799: 4800: $symb=&symbclean($symb); 4801: $thisurl=&deversion($thisurl); 4802: $thisfn=&deversion($thisfn); 4803: 4804: my %bighash; 4805: my $okay=0; 4806: 4807: if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db', 4808: &GDBM_READER(),0640)) { 4809: my $ids=$bighash{'ids_'.&clutter($thisurl)}; 4810: unless ($ids) { 4811: $ids=$bighash{'ids_/'.$thisurl}; 4812: } 4813: if ($ids) { 4814: # ------------------------------------------------------------------- Has ID(s) 4815: foreach (split(/\,/,$ids)) { 4816: my ($mapid,$resid)=split(/\./,$_); 4817: if ( 4818: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn) 4819: eq $symb) { 4820: if (($ENV{'request.role.adv'}) || 4821: $bighash{'encrypted_'.$_} eq $ENV{'request.enc'}) { 4822: $okay=1; 4823: } 4824: } 4825: } 4826: } 4827: untie(%bighash); 4828: } 4829: return $okay; 4830: } 4831: 4832: # --------------------------------------------------------------- Clean-up symb 4833: 4834: sub symbclean { 4835: my $symb=shift; 4836: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); } 4837: # remove version from map 4838: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/; 4839: 4840: # remove version from URL 4841: $symb=~s/\.(\d+)\.(\w+)$/\.$2/; 4842: 4843: # remove wrapper 4844: 4845: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/; 4846: return $symb; 4847: } 4848: 4849: # ---------------------------------------------- Split symb to find map and url 4850: 4851: sub encode_symb { 4852: my ($map,$resid,$url)=@_; 4853: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url)); 4854: } 4855: 4856: sub decode_symb { 4857: my $symb=shift; 4858: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); } 4859: my ($map,$resid,$url)=split(/___/,$symb); 4860: return (&fixversion($map),$resid,&fixversion($url)); 4861: } 4862: 4863: sub fixversion { 4864: my $fn=shift; 4865: if ($fn=~/^(adm|uploaded|public)/) { return $fn; } 4866: my %bighash; 4867: my $uri=&clutter($fn); 4868: my $key=$ENV{'request.course.id'}.'_'.$uri; 4869: # is this cached? 4870: my ($result,$cached)=&is_cached(\%courseresversioncache,$key, 4871: 'courseresversion',600); 4872: if (defined($cached)) { return $result; } 4873: # unfortunately not cached, or expired 4874: if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db', 4875: &GDBM_READER(),0640)) { 4876: if ($bighash{'version_'.$uri}) { 4877: my $version=$bighash{'version_'.$uri}; 4878: unless (($version eq 'mostrecent') || 4879: ($version==&getversion($uri))) { 4880: $uri=~s/\.(\w+)$/\.$version\.$1/; 4881: } 4882: } 4883: untie %bighash; 4884: } 4885: return &do_cache 4886: (\%courseresversioncache,$key,&declutter($uri),'courseresversion'); 4887: } 4888: 4889: sub deversion { 4890: my $url=shift; 4891: $url=~s/\.\d+\.(\w+)$/\.$1/; 4892: return $url; 4893: } 4894: 4895: # ------------------------------------------------------ Return symb list entry 4896: 4897: sub symbread { 4898: my ($thisfn,$donotrecurse)=@_; 4899: my $cache_str='request.symbread.cached.'.$thisfn; 4900: if (defined($ENV{$cache_str})) { return $ENV{$cache_str}; } 4901: # no filename provided? try from environment 4902: unless ($thisfn) { 4903: if ($ENV{'request.symb'}) { 4904: return $ENV{$cache_str}=&symbclean($ENV{'request.symb'}); 4905: } 4906: $thisfn=$ENV{'request.filename'}; 4907: } 4908: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); } 4909: # is that filename actually a symb? Verify, clean, and return 4910: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) { 4911: if (&symbverify($thisfn,$1)) { 4912: return $ENV{$cache_str}=&symbclean($thisfn); 4913: } 4914: } 4915: $thisfn=declutter($thisfn); 4916: my %hash; 4917: my %bighash; 4918: my $syval=''; 4919: if (($ENV{'request.course.fn'}) && ($thisfn)) { 4920: my $targetfn = $thisfn; 4921: if ( ($thisfn =~ m/^uploaded\//) && ($thisfn !~ m/\.(page|sequence)$/) ) { 4922: $targetfn = 'adm/wrapper/'.$thisfn; 4923: } 4924: if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db', 4925: &GDBM_READER(),0640)) { 4926: $syval=$hash{$targetfn}; 4927: untie(%hash); 4928: } 4929: # ---------------------------------------------------------- There was an entry 4930: if ($syval) { 4931: unless ($syval=~/\_\d+$/) { 4932: unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) { 4933: &appenv('request.ambiguous' => $thisfn); 4934: return $ENV{$cache_str}=''; 4935: } 4936: $syval.=$1; 4937: } 4938: } else { 4939: # ------------------------------------------------------- Was not in symb table 4940: if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db', 4941: &GDBM_READER(),0640)) { 4942: # ---------------------------------------------- Get ID(s) for current resource 4943: my $ids=$bighash{'ids_'.&clutter($thisfn)}; 4944: unless ($ids) { 4945: $ids=$bighash{'ids_/'.$thisfn}; 4946: } 4947: unless ($ids) { 4948: # alias? 4949: $ids=$bighash{'mapalias_'.$thisfn}; 4950: } 4951: if ($ids) { 4952: # ------------------------------------------------------------------- Has ID(s) 4953: my @possibilities=split(/\,/,$ids); 4954: if ($#possibilities==0) { 4955: # ----------------------------------------------- There is only one possibility 4956: my ($mapid,$resid)=split(/\./,$ids); 4957: $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid; 4958: } elsif (!$donotrecurse) { 4959: # ------------------------------------------ There is more than one possibility 4960: my $realpossible=0; 4961: foreach (@possibilities) { 4962: my $file=$bighash{'src_'.$_}; 4963: if (&allowed('bre',$file)) { 4964: my ($mapid,$resid)=split(/\./,$_); 4965: if ($bighash{'map_type_'.$mapid} ne 'page') { 4966: $realpossible++; 4967: $syval=declutter($bighash{'map_id_'.$mapid}). 4968: '___'.$resid; 4969: } 4970: } 4971: } 4972: if ($realpossible!=1) { $syval=''; } 4973: } else { 4974: $syval=''; 4975: } 4976: } 4977: untie(%bighash) 4978: } 4979: } 4980: if ($syval) { 4981: return $ENV{$cache_str}=&symbclean($syval.'___'.$thisfn); 4982: } 4983: } 4984: &appenv('request.ambiguous' => $thisfn); 4985: return $ENV{$cache_str}=''; 4986: } 4987: 4988: # ---------------------------------------------------------- Return random seed 4989: 4990: sub numval { 4991: my $txt=shift; 4992: $txt=~tr/A-J/0-9/; 4993: $txt=~tr/a-j/0-9/; 4994: $txt=~tr/K-T/0-9/; 4995: $txt=~tr/k-t/0-9/; 4996: $txt=~tr/U-Z/0-5/; 4997: $txt=~tr/u-z/0-5/; 4998: $txt=~s/\D//g; 4999: if ($_64bit) { if ($txt > 2**32) { return -1; } } 5000: return int($txt); 5001: } 5002: 5003: sub numval2 { 5004: my $txt=shift; 5005: $txt=~tr/A-J/0-9/; 5006: $txt=~tr/a-j/0-9/; 5007: $txt=~tr/K-T/0-9/; 5008: $txt=~tr/k-t/0-9/; 5009: $txt=~tr/U-Z/0-5/; 5010: $txt=~tr/u-z/0-5/; 5011: $txt=~s/\D//g; 5012: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt); 5013: my $total; 5014: foreach my $val (@txts) { $total+=$val; } 5015: if ($_64bit) { if ($total > 2**32) { return -1; } } 5016: return int($total); 5017: } 5018: 5019: sub numval3 { 5020: use integer; 5021: my $txt=shift; 5022: $txt=~tr/A-J/0-9/; 5023: $txt=~tr/a-j/0-9/; 5024: $txt=~tr/K-T/0-9/; 5025: $txt=~tr/k-t/0-9/; 5026: $txt=~tr/U-Z/0-5/; 5027: $txt=~tr/u-z/0-5/; 5028: $txt=~s/\D//g; 5029: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt); 5030: my $total; 5031: foreach my $val (@txts) { $total+=$val; } 5032: if ($_64bit) { $total=(($total<<32)>>32); } 5033: return $total; 5034: } 5035: 5036: sub latest_rnd_algorithm_id { 5037: return '64bit4'; 5038: } 5039: 5040: sub get_rand_alg { 5041: my ($courseid)=@_; 5042: if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; } 5043: if ($courseid) { 5044: return $ENV{"course.$courseid.rndseed"}; 5045: } 5046: return &latest_rnd_algorithm_id(); 5047: } 5048: 5049: sub validCODE { 5050: my ($CODE)=@_; 5051: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; } 5052: return 0; 5053: } 5054: 5055: sub getCODE { 5056: if (&validCODE($ENV{'form.CODE'})) { return $ENV{'form.CODE'}; } 5057: if (defined($Apache::lonhomework::parsing_a_problem) && 5058: &validCODE($Apache::lonhomework::history{'resource.CODE'})) { 5059: return $Apache::lonhomework::history{'resource.CODE'}; 5060: } 5061: return undef; 5062: } 5063: 5064: sub rndseed { 5065: my ($symb,$courseid,$domain,$username)=@_; 5066: 5067: my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser(); 5068: if (!$symb) { 5069: unless ($symb=$wsymb) { return time; } 5070: } 5071: if (!$courseid) { $courseid=$wcourseid; } 5072: if (!$domain) { $domain=$wdomain; } 5073: if (!$username) { $username=$wusername } 5074: my $which=&get_rand_alg(); 5075: if (defined(&getCODE())) { 5076: if ($which eq '64bit4') { 5077: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username); 5078: } else { 5079: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username); 5080: } 5081: } elsif ($which eq '64bit4') { 5082: return &rndseed_64bit4($symb,$courseid,$domain,$username); 5083: } elsif ($which eq '64bit3') { 5084: return &rndseed_64bit3($symb,$courseid,$domain,$username); 5085: } elsif ($which eq '64bit2') { 5086: return &rndseed_64bit2($symb,$courseid,$domain,$username); 5087: } elsif ($which eq '64bit') { 5088: return &rndseed_64bit($symb,$courseid,$domain,$username); 5089: } 5090: return &rndseed_32bit($symb,$courseid,$domain,$username); 5091: } 5092: 5093: sub rndseed_32bit { 5094: my ($symb,$courseid,$domain,$username)=@_; 5095: { 5096: use integer; 5097: my $symbchck=unpack("%32C*",$symb) << 27; 5098: my $symbseed=numval($symb) << 22; 5099: my $namechck=unpack("%32C*",$username) << 17; 5100: my $nameseed=numval($username) << 12; 5101: my $domainseed=unpack("%32C*",$domain) << 7; 5102: my $courseseed=unpack("%32C*",$courseid); 5103: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck; 5104: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck"); 5105: #&Apache::lonxml::debug("rndseed :$num:$symb"); 5106: if ($_64bit) { $num=(($num<<32)>>32); } 5107: return $num; 5108: } 5109: } 5110: 5111: sub rndseed_64bit { 5112: my ($symb,$courseid,$domain,$username)=@_; 5113: { 5114: use integer; 5115: my $symbchck=unpack("%32S*",$symb) << 21; 5116: my $symbseed=numval($symb) << 10; 5117: my $namechck=unpack("%32S*",$username); 5118: 5119: my $nameseed=numval($username) << 21; 5120: my $domainseed=unpack("%32S*",$domain) << 10; 5121: my $courseseed=unpack("%32S*",$courseid); 5122: 5123: my $num1=$symbchck+$symbseed+$namechck; 5124: my $num2=$nameseed+$domainseed+$courseseed; 5125: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck"); 5126: #&Apache::lonxml::debug("rndseed :$num:$symb"); 5127: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); } 5128: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); } 5129: return "$num1,$num2"; 5130: } 5131: } 5132: 5133: sub rndseed_64bit2 { 5134: my ($symb,$courseid,$domain,$username)=@_; 5135: { 5136: use integer; 5137: # strings need to be an even # of cahracters long, it it is odd the 5138: # last characters gets thrown away 5139: my $symbchck=unpack("%32S*",$symb.' ') << 21; 5140: my $symbseed=numval($symb) << 10; 5141: my $namechck=unpack("%32S*",$username.' '); 5142: 5143: my $nameseed=numval($username) << 21; 5144: my $domainseed=unpack("%32S*",$domain.' ') << 10; 5145: my $courseseed=unpack("%32S*",$courseid.' '); 5146: 5147: my $num1=$symbchck+$symbseed+$namechck; 5148: my $num2=$nameseed+$domainseed+$courseseed; 5149: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck"); 5150: #&Apache::lonxml::debug("rndseed :$num:$symb"); 5151: return "$num1,$num2"; 5152: } 5153: } 5154: 5155: sub rndseed_64bit3 { 5156: my ($symb,$courseid,$domain,$username)=@_; 5157: { 5158: use integer; 5159: # strings need to be an even # of cahracters long, it it is odd the 5160: # last characters gets thrown away 5161: my $symbchck=unpack("%32S*",$symb.' ') << 21; 5162: my $symbseed=numval2($symb) << 10; 5163: my $namechck=unpack("%32S*",$username.' '); 5164: 5165: my $nameseed=numval2($username) << 21; 5166: my $domainseed=unpack("%32S*",$domain.' ') << 10; 5167: my $courseseed=unpack("%32S*",$courseid.' '); 5168: 5169: my $num1=$symbchck+$symbseed+$namechck; 5170: my $num2=$nameseed+$domainseed+$courseseed; 5171: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck"); 5172: #&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit"); 5173: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); } 5174: 5175: return "$num1:$num2"; 5176: } 5177: } 5178: 5179: sub rndseed_64bit4 { 5180: my ($symb,$courseid,$domain,$username)=@_; 5181: { 5182: use integer; 5183: # strings need to be an even # of cahracters long, it it is odd the 5184: # last characters gets thrown away 5185: my $symbchck=unpack("%32S*",$symb.' ') << 21; 5186: my $symbseed=numval3($symb) << 10; 5187: my $namechck=unpack("%32S*",$username.' '); 5188: 5189: my $nameseed=numval3($username) << 21; 5190: my $domainseed=unpack("%32S*",$domain.' ') << 10; 5191: my $courseseed=unpack("%32S*",$courseid.' '); 5192: 5193: my $num1=$symbchck+$symbseed+$namechck; 5194: my $num2=$nameseed+$domainseed+$courseseed; 5195: #&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck"); 5196: #&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit"); 5197: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); } 5198: 5199: return "$num1:$num2"; 5200: } 5201: } 5202: 5203: sub rndseed_CODE_64bit { 5204: my ($symb,$courseid,$domain,$username)=@_; 5205: { 5206: use integer; 5207: my $symbchck=unpack("%32S*",$symb.' ') << 16; 5208: my $symbseed=numval2($symb); 5209: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16; 5210: my $CODEseed=numval(&getCODE()); 5211: my $courseseed=unpack("%32S*",$courseid.' '); 5212: my $num1=$symbseed+$CODEchck; 5213: my $num2=$CODEseed+$courseseed+$symbchck; 5214: #&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck"); 5215: #&Apache::lonxml::debug("rndseed :$num1:$num2:$symb"); 5216: if ($_64bit) { $num1=(($num1<<32)>>32); } 5217: if ($_64bit) { $num2=(($num2<<32)>>32); } 5218: return "$num1:$num2"; 5219: } 5220: } 5221: 5222: sub rndseed_CODE_64bit4 { 5223: my ($symb,$courseid,$domain,$username)=@_; 5224: { 5225: use integer; 5226: my $symbchck=unpack("%32S*",$symb.' ') << 16; 5227: my $symbseed=numval3($symb); 5228: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16; 5229: my $CODEseed=numval3(&getCODE()); 5230: my $courseseed=unpack("%32S*",$courseid.' '); 5231: my $num1=$symbseed+$CODEchck; 5232: my $num2=$CODEseed+$courseseed+$symbchck; 5233: #&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck"); 5234: #&Apache::lonxml::debug("rndseed :$num1:$num2:$symb"); 5235: if ($_64bit) { $num1=(($num1<<32)>>32); } 5236: if ($_64bit) { $num2=(($num2<<32)>>32); } 5237: return "$num1:$num2"; 5238: } 5239: } 5240: 5241: sub setup_random_from_rndseed { 5242: my ($rndseed)=@_; 5243: if ($rndseed =~/([,:])/) { 5244: my ($num1,$num2)=split(/[,:]/,$rndseed); 5245: &Math::Random::random_set_seed(abs($num1),abs($num2)); 5246: } else { 5247: &Math::Random::random_set_seed_from_phrase($rndseed); 5248: } 5249: } 5250: 5251: sub latest_receipt_algorithm_id { 5252: return 'receipt2'; 5253: } 5254: 5255: sub recunique { 5256: my $fucourseid=shift; 5257: my $unique; 5258: if ($ENV{"course.$fucourseid.receiptalg"} eq 'receipt2') { 5259: $unique=$ENV{"course.$fucourseid.internal.encseed"}; 5260: } else { 5261: $unique=$perlvar{'lonReceipt'}; 5262: } 5263: return unpack("%32C*",$unique); 5264: } 5265: 5266: sub recprefix { 5267: my $fucourseid=shift; 5268: my $prefix; 5269: if ($ENV{"course.$fucourseid.receiptalg"} eq 'receipt2') { 5270: $prefix=$ENV{"course.$fucourseid.internal.encpref"}; 5271: } else { 5272: $prefix=$perlvar{'lonHostID'}; 5273: } 5274: return unpack("%32C*",$prefix); 5275: } 5276: 5277: sub ireceipt { 5278: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_; 5279: my $cuname=unpack("%32C*",$funame); 5280: my $cudom=unpack("%32C*",$fudom); 5281: my $cucourseid=unpack("%32C*",$fucourseid); 5282: my $cusymb=unpack("%32C*",$fusymb); 5283: my $cunique=&recunique($fucourseid); 5284: my $cpart=unpack("%32S*",$part); 5285: my $return =&recprefix($fucourseid).'-'; 5286: if ($ENV{"course.$fucourseid.receiptalg"} eq 'receipt2' || 5287: $ENV{'request.state'} eq 'construct') { 5288: &Apache::lonxml::debug("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname). 5289: " and ".($cpart%$cudom)); 5290: 5291: $return.= ($cunique%$cuname+ 5292: $cunique%$cudom+ 5293: $cusymb%$cuname+ 5294: $cusymb%$cudom+ 5295: $cucourseid%$cuname+ 5296: $cucourseid%$cudom+ 5297: $cpart%$cuname+ 5298: $cpart%$cudom); 5299: } else { 5300: $return.= ($cunique%$cuname+ 5301: $cunique%$cudom+ 5302: $cusymb%$cuname+ 5303: $cusymb%$cudom+ 5304: $cucourseid%$cuname+ 5305: $cucourseid%$cudom); 5306: } 5307: return $return; 5308: } 5309: 5310: sub receipt { 5311: my ($part)=@_; 5312: my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser(); 5313: return &ireceipt($name,$domain,$courseid,$symb,$part); 5314: } 5315: 5316: # ------------------------------------------------------------ Serves up a file 5317: # returns either the contents of the file or 5318: # -1 if the file doesn't exist 5319: # 5320: # if the target is a file that was uploaded via DOCS, 5321: # a check will be made to see if a current copy exists on the local server, 5322: # if it does this will be served, otherwise a copy will be retrieved from 5323: # the home server for the course and stored in /home/httpd/html/userfiles on 5324: # the local server. 5325: 5326: sub getfile { 5327: my ($file) = @_; 5328: 5329: if ($file =~ m|^/*uploaded/|) { $file=&filelocation("",$file); } 5330: &repcopy($file); 5331: return &readfile($file); 5332: } 5333: 5334: sub repcopy_userfile { 5335: my ($file)=@_; 5336: 5337: if ($file =~ m|^/*uploaded/|) { $file=&filelocation("",$file); } 5338: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return OK; } 5339: 5340: my ($cdom,$cnum,$filename) = 5341: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|); 5342: my ($info,$rtncode); 5343: my $uri="/uploaded/$cdom/$cnum/$filename"; 5344: if (-e "$file") { 5345: my @fileinfo = stat($file); 5346: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode); 5347: if ($lwpresp ne 'ok') { 5348: if ($rtncode eq '404') { 5349: unlink($file); 5350: } 5351: #my $ua=new LWP::UserAgent; 5352: #my $request=new HTTP::Request('GET',&tokenwrapper($uri)); 5353: #my $response=$ua->request($request); 5354: #if ($response->is_success()) { 5355: # return $response->content; 5356: # } else { 5357: # return -1; 5358: # } 5359: return -1; 5360: } 5361: if ($info < $fileinfo[9]) { 5362: return OK; 5363: } 5364: $info = ''; 5365: $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode); 5366: if ($lwpresp ne 'ok') { 5367: return -1; 5368: } 5369: } else { 5370: my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode); 5371: if ($lwpresp ne 'ok') { 5372: my $ua=new LWP::UserAgent; 5373: my $request=new HTTP::Request('GET',&tokenwrapper($uri)); 5374: my $response=$ua->request($request); 5375: if ($response->is_success()) { 5376: $info=$response->content; 5377: } else { 5378: return -1; 5379: } 5380: } 5381: my @parts = ($cdom,$cnum); 5382: if ($filename =~ m|^(.+)/[^/]+$|) { 5383: push @parts, split(/\//,$1); 5384: } 5385: my $path = $perlvar{'lonDocRoot'}.'/userfiles'; 5386: foreach my $part (@parts) { 5387: $path .= '/'.$part; 5388: if (!-e $path) { 5389: mkdir($path,0770); 5390: } 5391: } 5392: } 5393: open(FILE,">$file"); 5394: print FILE $info; 5395: close(FILE); 5396: return OK; 5397: } 5398: 5399: sub tokenwrapper { 5400: my $uri=shift; 5401: $uri=~s|^http\://([^/]+)||; 5402: $uri=~s|^/||; 5403: $ENV{'user.environment'}=~/\/([^\/]+)\.id/; 5404: my $token=$1; 5405: my (undef,$udom,$uname,$file)=split('/',$uri,4); 5406: if ($udom && $uname && $file) { 5407: $file=~s|(\?\.*)*$||; 5408: &appenv("userfile.$udom/$uname/$file" => $ENV{'request.course.id'}); 5409: return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri. 5410: (($uri=~/\?/)?'&':'?').'token='.$token. 5411: '&tokenissued='.$perlvar{'lonHostID'}; 5412: } else { 5413: return '/adm/notfound.html'; 5414: } 5415: } 5416: 5417: sub getuploaded { 5418: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_; 5419: $uri=~s/^\///; 5420: $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri; 5421: my $ua=new LWP::UserAgent; 5422: my $request=new HTTP::Request($reqtype,$uri); 5423: my $response=$ua->request($request); 5424: $$rtncode = $response->code; 5425: if (! $response->is_success()) { 5426: return 'failed'; 5427: } 5428: if ($reqtype eq 'HEAD') { 5429: $$info = &HTTP::Date::str2time( $response->header('Last-modified') ); 5430: } elsif ($reqtype eq 'GET') { 5431: $$info = $response->content; 5432: } 5433: return 'ok'; 5434: } 5435: 5436: sub readfile { 5437: my $file = shift; 5438: if ( (! -e $file ) || ($file eq '') ) { return -1; }; 5439: my $fh; 5440: open($fh,"<$file"); 5441: my $a=''; 5442: while (<$fh>) { $a .=$_; } 5443: return $a; 5444: } 5445: 5446: sub filelocation { 5447: my ($dir,$file) = @_; 5448: my $location; 5449: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces 5450: if ($file=~m:^/~:) { # is a contruction space reference 5451: $location = $file; 5452: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:; 5453: } elsif ($file=~/^\/*uploaded/) { # is an uploaded file 5454: my ($udom,$uname,$filename)= 5455: ($file=~m|^/+uploaded/+([^/]+)/+([^/]+)/+(.*)$|); 5456: my $home=&homeserver($uname,$udom); 5457: my $is_me=0; 5458: my @ids=¤t_machine_ids(); 5459: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } } 5460: if ($is_me) { 5461: $location=&Apache::loncommon::propath($udom,$uname). 5462: '/userfiles/'.$filename; 5463: } else { 5464: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'. 5465: $udom.'/'.$uname.'/'.$filename; 5466: } 5467: } else { 5468: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//; 5469: $file=~s:^/res/:/:; 5470: if ( !( $file =~ m:^/:) ) { 5471: $location = $dir. '/'.$file; 5472: } else { 5473: $location = '/home/httpd/html/res'.$file; 5474: } 5475: } 5476: $location=~s://+:/:g; # remove duplicate / 5477: while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/.. 5478: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./ 5479: return $location; 5480: } 5481: 5482: sub hreflocation { 5483: my ($dir,$file)=@_; 5484: unless (($file=~m-^http://-i) || ($file=~m-^/-)) { 5485: my $finalpath=filelocation($dir,$file); 5486: $finalpath=~s-^/home/httpd/html--; 5487: $finalpath=~s-^/home/(\w+)/public_html/-/~$1/-; 5488: return $finalpath; 5489: } elsif ($file=~m-^/home-) { 5490: $file=~s-^/home/httpd/html--; 5491: $file=~s-^/home/(\w+)/public_html/-/~$1/-; 5492: return $file; 5493: } 5494: return $file; 5495: } 5496: 5497: sub current_machine_domains { 5498: my $hostname=$hostname{$perlvar{'lonHostID'}}; 5499: my @domains; 5500: while( my($id, $name) = each(%hostname)) { 5501: # &logthis("-$id-$name-$hostname-"); 5502: if ($hostname eq $name) { 5503: push(@domains,$hostdom{$id}); 5504: } 5505: } 5506: return @domains; 5507: } 5508: 5509: sub current_machine_ids { 5510: my $hostname=$hostname{$perlvar{'lonHostID'}}; 5511: my @ids; 5512: while( my($id, $name) = each(%hostname)) { 5513: # &logthis("-$id-$name-$hostname-"); 5514: if ($hostname eq $name) { 5515: push(@ids,$id); 5516: } 5517: } 5518: return @ids; 5519: } 5520: 5521: # ------------------------------------------------------------- Declutters URLs 5522: 5523: sub declutter { 5524: my $thisfn=shift; 5525: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); } 5526: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//; 5527: $thisfn=~s/^\///; 5528: $thisfn=~s/^res\///; 5529: $thisfn=~s/\?.+$//; 5530: return $thisfn; 5531: } 5532: 5533: # ------------------------------------------------------------- Clutter up URLs 5534: 5535: sub clutter { 5536: my $thisfn='/'.&declutter(shift); 5537: unless ($thisfn=~/^\/(uploaded|adm|userfiles|ext|raw|priv|public)\//) { 5538: $thisfn='/res'.$thisfn; 5539: } 5540: return $thisfn; 5541: } 5542: 5543: sub freeze_escape { 5544: my ($value)=@_; 5545: if (ref($value)) { 5546: $value=&nfreeze($value); 5547: return '__FROZEN__'.&escape($value); 5548: } 5549: return &escape($value); 5550: } 5551: 5552: # -------------------------------------------------------- Escape Special Chars 5553: 5554: sub escape { 5555: my $str=shift; 5556: $str =~ s/(\W)/"%".unpack('H2',$1)/eg; 5557: return $str; 5558: } 5559: 5560: # ----------------------------------------------------- Un-Escape Special Chars 5561: 5562: sub unescape { 5563: my $str=shift; 5564: $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg; 5565: return $str; 5566: } 5567: 5568: sub thaw_unescape { 5569: my ($value)=@_; 5570: if ($value =~ /^__FROZEN__/) { 5571: substr($value,0,10,undef); 5572: $value=&unescape($value); 5573: return &thaw($value); 5574: } 5575: return &unescape($value); 5576: } 5577: 5578: sub mod_perl_version { 5579: return 1; 5580: if (defined($perlvar{'MODPERL2'})) { 5581: return 2; 5582: } 5583: } 5584: 5585: sub correct_line_ends { 5586: my ($result)=@_; 5587: $$result =~s/\r\n/\n/mg; 5588: $$result =~s/\r/\n/mg; 5589: } 5590: # ================================================================ Main Program 5591: 5592: sub goodbye { 5593: &logthis("Starting Shut down"); 5594: #not converted to using infrastruture and probably shouldn't be 5595: &logthis(sprintf("%-20s is %s",'%badServerCache',scalar(%badServerCache))); 5596: #converted 5597: &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache))); 5598: &logthis(sprintf("%-20s is %s",'%homecache',scalar(%homecache))); 5599: &logthis(sprintf("%-20s is %s",'%titlecache',scalar(%titlecache))); 5600: &logthis(sprintf("%-20s is %s",'%courseresdatacache',scalar(%courseresdatacache))); 5601: #1.1 only 5602: &logthis(sprintf("%-20s is %s",'%userresdatacache',scalar(%userresdatacache))); 5603: &logthis(sprintf("%-20s is %s",'%getsectioncache',scalar(%getsectioncache))); 5604: &logthis(sprintf("%-20s is %s",'%courseresversioncache',scalar(%courseresversioncache))); 5605: &logthis(sprintf("%-20s is %s",'%resversioncache',scalar(%resversioncache))); 5606: &flushcourselogs(); 5607: &logthis("Shutting down"); 5608: return DONE; 5609: } 5610: 5611: BEGIN { 5612: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf 5613: unless ($readit) { 5614: { 5615: # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block 5616: open(my $config,"</etc/httpd/conf/loncapa.conf"); 5617: 5618: while (my $configline=<$config>) { 5619: if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) { 5620: my ($dummy,$varname,$varvalue)=split(/\s+/,$configline); 5621: chomp($varvalue); 5622: $perlvar{$varname}=$varvalue; 5623: } 5624: } 5625: close($config); 5626: } 5627: { 5628: open(my $config,"</etc/httpd/conf/loncapa_apache.conf"); 5629: 5630: while (my $configline=<$config>) { 5631: if ($configline =~ /^[^\#]*PerlSetVar/) { 5632: my ($dummy,$varname,$varvalue)=split(/\s+/,$configline); 5633: chomp($varvalue); 5634: $perlvar{$varname}=$varvalue; 5635: } 5636: } 5637: close($config); 5638: } 5639: 5640: # ------------------------------------------------------------ Read domain file 5641: { 5642: %domaindescription = (); 5643: %domain_auth_def = (); 5644: %domain_auth_arg_def = (); 5645: my $fh; 5646: if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) { 5647: while (<$fh>) { 5648: next if (/^(\#|\s*$)/); 5649: # next if /^\#/; 5650: chomp; 5651: my ($domain, $domain_description, $def_auth, $def_auth_arg, 5652: $def_lang, $city, $longi, $lati) = split(/:/,$_); 5653: $domain_auth_def{$domain}=$def_auth; 5654: $domain_auth_arg_def{$domain}=$def_auth_arg; 5655: $domaindescription{$domain}=$domain_description; 5656: $domain_lang_def{$domain}=$def_lang; 5657: $domain_city{$domain}=$city; 5658: $domain_longi{$domain}=$longi; 5659: $domain_lati{$domain}=$lati; 5660: 5661: # &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}"); 5662: # &logthis("Domain.tab: $domain ".$domaindescription{$domain} ); 5663: } 5664: } 5665: close ($fh); 5666: } 5667: 5668: 5669: # ------------------------------------------------------------- Read hosts file 5670: { 5671: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab"); 5672: 5673: while (my $configline=<$config>) { 5674: next if ($configline =~ /^(\#|\s*$)/); 5675: chomp($configline); 5676: my ($id,$domain,$role,$name,$ip,$domdescr)=split(/:/,$configline); 5677: if ($id && $domain && $role && $name && $ip) { 5678: $hostname{$id}=$name; 5679: $hostdom{$id}=$domain; 5680: $hostip{$id}=$ip; 5681: $iphost{$ip}=$id; 5682: if ($role eq 'library') { $libserv{$id}=$name; } 5683: } 5684: } 5685: close($config); 5686: } 5687: 5688: # ------------------------------------------------------ Read spare server file 5689: { 5690: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab"); 5691: 5692: while (my $configline=<$config>) { 5693: chomp($configline); 5694: if ($configline) { 5695: $spareid{$configline}=1; 5696: } 5697: } 5698: close($config); 5699: } 5700: # ------------------------------------------------------------ Read permissions 5701: { 5702: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab"); 5703: 5704: while (my $configline=<$config>) { 5705: chomp($configline); 5706: if ($configline) { 5707: my ($role,$perm)=split(/ /,$configline); 5708: if ($perm ne '') { $pr{$role}=$perm; } 5709: } 5710: } 5711: close($config); 5712: } 5713: 5714: # -------------------------------------------- Read plain texts for permissions 5715: { 5716: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab"); 5717: 5718: while (my $configline=<$config>) { 5719: chomp($configline); 5720: if ($configline) { 5721: my ($short,$plain)=split(/:/,$configline); 5722: if ($plain ne '') { $prp{$short}=$plain; } 5723: } 5724: } 5725: close($config); 5726: } 5727: 5728: # ---------------------------------------------------------- Read package table 5729: { 5730: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab"); 5731: 5732: while (my $configline=<$config>) { 5733: if ($configline !~ /\S/ || $configline=~/^#/) { next; } 5734: chomp($configline); 5735: my ($short,$plain)=split(/:/,$configline); 5736: my ($pack,$name)=split(/\&/,$short); 5737: if ($plain ne '') { 5738: $packagetab{$pack.'&'.$name.'&name'}=$name; 5739: $packagetab{$short}=$plain; 5740: } 5741: } 5742: close($config); 5743: } 5744: 5745: # ------------- set up temporary directory 5746: { 5747: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/'; 5748: 5749: } 5750: 5751: %metacache=(); 5752: 5753: $processmarker='_'.time.'_'.$perlvar{'lonHostID'}; 5754: $dumpcount=0; 5755: 5756: &logtouch(); 5757: &logthis('<font color=yellow>INFO: Read configuration</font>'); 5758: $readit=1; 5759: { 5760: use integer; 5761: my $test=(2**32)+1; 5762: if ($test != 0) { $_64bit=1; } else { $_64bit=0; } 5763: &logthis(" Detected 64bit platform ($_64bit)"); 5764: } 5765: } 5766: } 5767: 5768: 1; 5769: __END__ 5770: 5771: =pod 5772: 5773: =head1 NAME 5774: 5775: Apache::lonnet - Subroutines to ask questions about things in the network. 5776: 5777: =head1 SYNOPSIS 5778: 5779: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network. 5780: 5781: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS); 5782: 5783: Common parameters: 5784: 5785: =over 4 5786: 5787: =item * 5788: 5789: $uname : an internal username (if $cname expecting a course Id specifically) 5790: 5791: =item * 5792: 5793: $udom : a domain (if $cdom expecting a course's domain specifically) 5794: 5795: =item * 5796: 5797: $symb : a resource instance identifier 5798: 5799: =item * 5800: 5801: $namespace : the name of a .db file that contains the data needed or 5802: being set. 5803: 5804: =back 5805: 5806: =head1 OVERVIEW 5807: 5808: lonnet provides subroutines which interact with the 5809: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask 5810: about classes, users, and resources. 5811: 5812: For many of these objects you can also use this to store data about 5813: them or modify them in various ways. 5814: 5815: =head2 Symbs 5816: 5817: To identify a specific instance of a resource, LON-CAPA uses symbols 5818: or "symbs"X<symb>. These identifiers are built from the URL of the 5819: map, the resource number of the resource in the map, and the URL of 5820: the resource itself. The latter is somewhat redundant, but might help 5821: if maps change. 5822: 5823: An example is 5824: 5825: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem 5826: 5827: The respective map entry is 5828: 5829: <resource id="19" src="/res/msu/korte/tests/part12.problem" 5830: title="Problem 2"> 5831: </resource> 5832: 5833: Symbs are used by the random number generator, as well as to store and 5834: restore data specific to a certain instance of for example a problem. 5835: 5836: =head2 Storing And Retrieving Data 5837: 5838: X<store()>X<cstore()>X<restore()>Three of the most important functions 5839: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>, 5840: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which 5841: is is the non-critical message twin of cstore. These functions are for 5842: handlers to store a perl hash to a user's permanent data space in an 5843: easy manner, and to retrieve it again on another call. It is expected 5844: that a handler would use this once at the beginning to retrieve data, 5845: and then again once at the end to send only the new data back. 5846: 5847: The data is stored in the user's data directory on the user's 5848: homeserver under the ID of the course. 5849: 5850: The hash that is returned by restore will have all of the previous 5851: value for all of the elements of the hash. 5852: 5853: Example: 5854: 5855: #creating a hash 5856: my %hash; 5857: $hash{'foo'}='bar'; 5858: 5859: #storing it 5860: &Apache::lonnet::cstore(\%hash); 5861: 5862: #changing a value 5863: $hash{'foo'}='notbar'; 5864: 5865: #adding a new value 5866: $hash{'bar'}='foo'; 5867: &Apache::lonnet::cstore(\%hash); 5868: 5869: #retrieving the hash 5870: my %history=&Apache::lonnet::restore(); 5871: 5872: #print the hash 5873: foreach my $key (sort(keys(%history))) { 5874: print("\%history{$key} = $history{$key}"); 5875: } 5876: 5877: Will print out: 5878: 5879: %history{1:foo} = bar 5880: %history{1:keys} = foo:timestamp 5881: %history{1:timestamp} = 990455579 5882: %history{2:bar} = foo 5883: %history{2:foo} = notbar 5884: %history{2:keys} = foo:bar:timestamp 5885: %history{2:timestamp} = 990455580 5886: %history{bar} = foo 5887: %history{foo} = notbar 5888: %history{timestamp} = 990455580 5889: %history{version} = 2 5890: 5891: Note that the special hash entries C<keys>, C<version> and 5892: C<timestamp> were added to the hash. C<version> will be equal to the 5893: total number of versions of the data that have been stored. The 5894: C<timestamp> attribute will be the UNIX time the hash was 5895: stored. C<keys> is available in every historical section to list which 5896: keys were added or changed at a specific historical revision of a 5897: hash. 5898: 5899: B<Warning>: do not store the hash that restore returns directly. This 5900: will cause a mess since it will restore the historical keys as if the 5901: were new keys. I.E. 1:foo will become 1:1:foo etc. 5902: 5903: Calling convention: 5904: 5905: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home); 5906: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home); 5907: 5908: For more detailed information, see lonnet specific documentation. 5909: 5910: =head1 RETURN MESSAGES 5911: 5912: =over 4 5913: 5914: =item * B<con_lost>: unable to contact remote host 5915: 5916: =item * B<con_delayed>: unable to contact remote host, message will be delivered 5917: when the connection is brought back up 5918: 5919: =item * B<con_failed>: unable to contact remote host and unable to save message 5920: for later delivery 5921: 5922: =item * B<error:>: an error a occured, a description of the error follows the : 5923: 5924: =item * B<no_such_host>: unable to fund a host associated with the user/domain 5925: that was requested 5926: 5927: =back 5928: 5929: =head1 PUBLIC SUBROUTINES 5930: 5931: =head2 Session Environment Functions 5932: 5933: =over 4 5934: 5935: =item * 5936: X<appenv()> 5937: B<appenv(%hash)>: the value of %hash is written to 5938: the user envirnoment file, and will be restored for each access this 5939: user makes during this session, also modifies the %ENV for the current 5940: process 5941: 5942: =item * 5943: X<delenv()> 5944: B<delenv($regexp)>: removes all items from the session 5945: environment file that matches the regular expression in $regexp. The 5946: values are also delted from the current processes %ENV. 5947: 5948: =back 5949: 5950: =head2 User Information 5951: 5952: =over 4 5953: 5954: =item * 5955: X<queryauthenticate()> 5956: B<queryauthenticate($uname,$udom)>: try to determine user's current 5957: authentication scheme 5958: 5959: =item * 5960: X<authenticate()> 5961: B<authenticate($uname,$upass,$udom)>: try to 5962: authenticate user from domain's lib servers (first use the current 5963: one). C<$upass> should be the users password. 5964: 5965: =item * 5966: X<homeserver()> 5967: B<homeserver($uname,$udom)>: find the server which has 5968: the user's directory and files (there must be only one), this caches 5969: the answer, and also caches if there is a borken connection. 5970: 5971: =item * 5972: X<idget()> 5973: B<idget($udom,@ids)>: find the usernames behind a list of IDs 5974: (IDs are a unique resource in a domain, there must be only 1 ID per 5975: username, and only 1 username per ID in a specific domain) (returns 5976: hash: id=>name,id=>name) 5977: 5978: =item * 5979: X<idrget()> 5980: B<idrget($udom,@unames)>: find the IDs behind a list of 5981: usernames (returns hash: name=>id,name=>id) 5982: 5983: =item * 5984: X<idput()> 5985: B<idput($udom,%ids)>: store away a list of names and associated IDs 5986: 5987: =item * 5988: X<rolesinit()> 5989: B<rolesinit($udom,$username,$authhost)>: get user privileges 5990: 5991: =item * 5992: X<getsection()> 5993: B<getsection($udom,$uname,$cname)>: finds the section of student in the 5994: course $cname, return section name/number or '' for "not in course" 5995: and '-1' for "no section" 5996: 5997: =item * 5998: X<userenvironment()> 5999: B<userenvironment($udom,$uname,@what)>: gets the values of the keys 6000: passed in @what from the requested user's environment, returns a hash 6001: 6002: =back 6003: 6004: =head2 User Roles 6005: 6006: =over 4 6007: 6008: =item * 6009: 6010: allowed($priv,$uri) : check for a user privilege; returns codes for allowed 6011: actions 6012: F: full access 6013: U,I,K: authentication modes (cxx only) 6014: '': forbidden 6015: 1: user needs to choose course 6016: 2: browse allowed 6017: 6018: =item * 6019: 6020: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom 6021: role rolename set privileges in format of lonTabs/roles.tab for system, domain, 6022: and course level 6023: 6024: =item * 6025: 6026: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text 6027: explanation of a user role term 6028: 6029: =back 6030: 6031: =head2 User Modification 6032: 6033: =over 4 6034: 6035: =item * 6036: 6037: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a 6038: user for the level given by URL. Optional start and end dates (leave empty 6039: string or zero for "no date") 6040: 6041: =item * 6042: 6043: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to 6044: change a users, password, possible return values are: ok, 6045: pwchange_failure, non_authorized, auth_mode_error, unknown_user, 6046: refused 6047: 6048: =item * 6049: 6050: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication 6051: 6052: =item * 6053: 6054: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 6055: modify user 6056: 6057: =item * 6058: 6059: modifystudent 6060: 6061: modify a students enrollment and identification information. 6062: The course id is resolved based on the current users environment. 6063: This means the envoking user must be a course coordinator or otherwise 6064: associated with a course. 6065: 6066: This call is essentially a wrapper for lonnet::modifyuser and 6067: lonnet::modify_student_enrollment 6068: 6069: Inputs: 6070: 6071: =over 4 6072: 6073: =item B<$udom> Students loncapa domain 6074: 6075: =item B<$uname> Students loncapa login name 6076: 6077: =item B<$uid> Students id/student number 6078: 6079: =item B<$umode> Students authentication mode 6080: 6081: =item B<$upass> Students password 6082: 6083: =item B<$first> Students first name 6084: 6085: =item B<$middle> Students middle name 6086: 6087: =item B<$last> Students last name 6088: 6089: =item B<$gene> Students generation 6090: 6091: =item B<$usec> Students section in course 6092: 6093: =item B<$end> Unix time of the roles expiration 6094: 6095: =item B<$start> Unix time of the roles start date 6096: 6097: =item B<$forceid> If defined, allow $uid to be changed 6098: 6099: =item B<$desiredhome> server to use as home server for student 6100: 6101: =back 6102: 6103: =item * 6104: 6105: modify_student_enrollment 6106: 6107: Change a students enrollment status in a class. The environment variable 6108: 'role.request.course' must be defined for this function to proceed. 6109: 6110: Inputs: 6111: 6112: =over 4 6113: 6114: =item $udom, students domain 6115: 6116: =item $uname, students name 6117: 6118: =item $uid, students user id 6119: 6120: =item $first, students first name 6121: 6122: =item $middle 6123: 6124: =item $last 6125: 6126: =item $gene 6127: 6128: =item $usec 6129: 6130: =item $end 6131: 6132: =item $start 6133: 6134: =back 6135: 6136: 6137: =item * 6138: 6139: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign 6140: custom role; give a custom role to a user for the level given by URL. Specify 6141: name and domain of role author, and role name 6142: 6143: =item * 6144: 6145: revokerole($udom,$uname,$url,$role) : revoke a role for url 6146: 6147: =item * 6148: 6149: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role 6150: 6151: =back 6152: 6153: =head2 Course Infomation 6154: 6155: =over 4 6156: 6157: =item * 6158: 6159: coursedescription($courseid) : course description 6160: 6161: =item * 6162: 6163: courseresdata($coursenum,$coursedomain,@which) : request for current 6164: parameter setting for a specific course, @what should be a list of 6165: parameters to ask about. This routine caches answers for 5 minutes. 6166: 6167: =back 6168: 6169: =head2 Course Modification 6170: 6171: =over 4 6172: 6173: =item * 6174: 6175: writecoursepref($courseid,%prefs) : write preferences (environment 6176: database) for a course 6177: 6178: =item * 6179: 6180: createcourse($udom,$description,$url) : make/modify course 6181: 6182: =back 6183: 6184: =head2 Resource Subroutines 6185: 6186: =over 4 6187: 6188: =item * 6189: 6190: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead) 6191: 6192: =item * 6193: 6194: repcopy($filename) : subscribes to the requested file, and attempts to 6195: replicate from the owning library server, Might return 6196: HTTP_SERVICE_UNAVAILABLE, HTTP_NOT_FOUND, FORBIDDEN, OK, or 6197: HTTP_BAD_REQUEST, also attempts to grab the metadata for the 6198: resource. Expects the local filesystem pathname 6199: (/home/httpd/html/res/....) 6200: 6201: =back 6202: 6203: =head2 Resource Information 6204: 6205: =over 4 6206: 6207: =item * 6208: 6209: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of 6210: a vairety of different possible values, $varname should be a request 6211: string, and the other parameters can be used to specify who and what 6212: one is asking about. 6213: 6214: Possible values for $varname are environment.lastname (or other item 6215: from the envirnment hash), user.name (or someother aspect about the 6216: user), resource.0.maxtries (or some other part and parameter of a 6217: resource) 6218: 6219: =item * 6220: 6221: directcondval($number) : get current value of a condition; reads from a state 6222: string 6223: 6224: =item * 6225: 6226: condval($condidx) : value of condition index based on state 6227: 6228: =item * 6229: 6230: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a 6231: resource's metadata, $what should be either a specific key, or either 6232: 'keys' (to get a list of possible keys) or 'packages' to get a list of 6233: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata. 6234: 6235: this function automatically caches all requests 6236: 6237: =item * 6238: 6239: metadata_query($query,$custom,$customshow) : make a metadata query against the 6240: network of library servers; returns file handle of where SQL and regex results 6241: will be stored for query 6242: 6243: =item * 6244: 6245: symbread($filename) : return symbolic list entry (filename argument optional); 6246: returns the data handle 6247: 6248: =item * 6249: 6250: symbverify($symb,$thisfn) : verifies that $symb actually exists and is 6251: a possible symb for the URL in $thisfn, and if is an encryypted 6252: resource that the user accessed using /enc/ returns a 1 on success, 0 6253: on failure, user must be in a course, as it assumes the existance of 6254: the course initial hash, and uses $ENV('request.course.id'} 6255: 6256: 6257: =item * 6258: 6259: symbclean($symb) : removes versions numbers from a symb, returns the 6260: cleaned symb 6261: 6262: =item * 6263: 6264: is_on_map($uri) : checks if the $uri is somewhere on the current 6265: course map, user must be in a course for it to work. 6266: 6267: =item * 6268: 6269: numval($salt) : return random seed value (addend for rndseed) 6270: 6271: =item * 6272: 6273: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns 6274: a random seed, all arguments are optional, if they aren't sent it uses the 6275: environment to derive them. Note: if symb isn't sent and it can't get one 6276: from &symbread it will use the current time as its return value 6277: 6278: =item * 6279: 6280: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique, 6281: unfakeable, receipt 6282: 6283: =item * 6284: 6285: receipt() : API to ireceipt working off of ENV values; given out to users 6286: 6287: =item * 6288: 6289: countacc($url) : count the number of accesses to a given URL 6290: 6291: =item * 6292: 6293: checkout($symb,$tuname,$tudom,$tcrsid) : creates a record of a user having looked at an item, most likely printed out or otherwise using a resource 6294: 6295: =item * 6296: 6297: checkin($token) : updates that a resource has beeen returned (a hard copy version for instance) and returns the data that $token was Checkout with ($symb, $tuname, $tudom, and $tcrsid) 6298: 6299: =item * 6300: 6301: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet 6302: 6303: =item * 6304: 6305: devalidate($symb) : devalidate temporary spreadsheet calculations, 6306: forcing spreadsheet to reevaluate the resource scores next time. 6307: 6308: =back 6309: 6310: =head2 Storing/Retreiving Data 6311: 6312: =over 4 6313: 6314: =item * 6315: 6316: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently 6317: for this url; hashref needs to be given and should be a \%hashname; the 6318: remaining args aren't required and if they aren't passed or are '' they will 6319: be derived from the ENV 6320: 6321: =item * 6322: 6323: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but 6324: uses critical subroutine 6325: 6326: =item * 6327: 6328: restore($symb,$namespace,$udom,$uname) : returns hash for this symb; 6329: all args are optional 6330: 6331: =item * 6332: 6333: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that 6334: works very similar to store/cstore, but all data is stored in a 6335: temporary location and can be reset using tmpreset, $storehash should 6336: be a hash reference, returns nothing on success 6337: 6338: =item * 6339: 6340: tmprestore($symb,$namespace,$udom,$uname) : storage that works very 6341: similar to restore, but all data is stored in a temporary location and 6342: can be reset using tmpreset. Returns a hash of values on success, 6343: error string otherwise. 6344: 6345: =item * 6346: 6347: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset, 6348: deltes all keys for $symb form the temporary storage hash. 6349: 6350: =item * 6351: 6352: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array 6353: reference filled in from namesp ($udom and $uname are optional) 6354: 6355: =item * 6356: 6357: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from 6358: namesp ($udom and $uname are optional) 6359: 6360: =item * 6361: 6362: dump($namespace,$udom,$uname,$regexp) : 6363: dumps the complete (or key matching regexp) namespace into a hash 6364: ($udom, $uname and $regexp are optional) 6365: 6366: =item * 6367: 6368: inc($namespace,$store,$udom,$uname) : increments $store in $namespace. 6369: $store can be a scalar, an array reference, or if the amount to be 6370: incremented is > 1, a hash reference. 6371: 6372: ($udom and $uname are optional) 6373: 6374: =item * 6375: 6376: put($namespace,$storehash,$udom,$uname) : stores hash in namesp 6377: ($udom and $uname are optional) 6378: 6379: =item * 6380: 6381: putstore($namespace,$storehash,$udomain,$uname) : stores hash in namesp 6382: keys used in storehash include version information (e.g., 1:$symb:message etc.) as 6383: used in records written by &store and retrieved by &restore. This function 6384: was created for use in editing discussion posts, without incrementing the 6385: version number included in the key for a particular post. The colon 6386: separated list of attribute names (e.g., the value associated with the key 6387: 1:keys:$symb) is also generated and passed in the ampersand separated 6388: items sent to lonnet::reply(). 6389: 6390: =item * 6391: 6392: cput($namespace,$storehash,$udom,$uname) : critical put 6393: ($udom and $uname are optional) 6394: 6395: =item * 6396: 6397: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array 6398: reference filled in from namesp (encrypts the return communication) 6399: ($udom and $uname are optional) 6400: 6401: =item * 6402: 6403: log($udom,$name,$home,$message) : write to permanent log for user; use 6404: critical subroutine 6405: 6406: =back 6407: 6408: =head2 Network Status Functions 6409: 6410: =over 4 6411: 6412: =item * 6413: 6414: dirlist($uri) : return directory list based on URI 6415: 6416: =item * 6417: 6418: spareserver() : find server with least workload from spare.tab 6419: 6420: =back 6421: 6422: =head2 Apache Request 6423: 6424: =over 4 6425: 6426: =item * 6427: 6428: ssi($url,%hash) : server side include, does a complete request cycle on url to 6429: localhost, posts hash 6430: 6431: =back 6432: 6433: =head2 Data to String to Data 6434: 6435: =over 4 6436: 6437: =item * 6438: 6439: hash2str(%hash) : convert a hash into a string complete with escaping and '=' 6440: and '&' separators, supports elements that are arrayrefs and hashrefs 6441: 6442: =item * 6443: 6444: hashref2str($hashref) : convert a hashref into a string complete with 6445: escaping and '=' and '&' separators, supports elements that are 6446: arrayrefs and hashrefs 6447: 6448: =item * 6449: 6450: arrayref2str($arrayref) : convert an arrayref into a string complete 6451: with escaping and '&' separators, supports elements that are arrayrefs 6452: and hashrefs 6453: 6454: =item * 6455: 6456: str2hash($string) : convert string to hash using unescaping and 6457: splitting on '=' and '&', supports elements that are arrayrefs and 6458: hashrefs 6459: 6460: =item * 6461: 6462: str2array($string) : convert string to hash using unescaping and 6463: splitting on '&', supports elements that are arrayrefs and hashrefs 6464: 6465: =back 6466: 6467: =head2 Logging Routines 6468: 6469: =over 4 6470: 6471: These routines allow one to make log messages in the lonnet.log and 6472: lonnet.perm logfiles. 6473: 6474: =item * 6475: 6476: logtouch() : make sure the logfile, lonnet.log, exists 6477: 6478: =item * 6479: 6480: logthis() : append message to the normal lonnet.log file, it gets 6481: preiodically rolled over and deleted. 6482: 6483: =item * 6484: 6485: logperm() : append a permanent message to lonnet.perm.log, this log 6486: file never gets deleted by any automated portion of the system, only 6487: messages of critical importance should go in here. 6488: 6489: =back 6490: 6491: =head2 General File Helper Routines 6492: 6493: =over 4 6494: 6495: =item * 6496: 6497: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded. 6498: (a) files in /uploaded 6499: (i) If a local copy of the file exists - 6500: compares modification date of local copy with last-modified date for 6501: definitive version stored on home server for course. If local copy is 6502: stale, requests a new version from the home server and stores it. 6503: If the original has been removed from the home server, then local copy 6504: is unlinked. 6505: (ii) If local copy does not exist - 6506: requests the file from the home server and stores it. 6507: 6508: If $caller is 'uploadrep': 6509: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase) 6510: for request for files originally uploaded via DOCS. 6511: - returns 'ok' if fresh local copy now available, -1 otherwise. 6512: 6513: Otherwise: 6514: This indicates a call from the content generation phase of the request. 6515: - returns the entire contents of the file or -1. 6516: 6517: (b) files in /res 6518: - returns the entire contents of a file or -1; 6519: it properly subscribes to and replicates the file if neccessary. 6520: 6521: =item * 6522: 6523: filelocation($dir,$file) : returns file system location of a file 6524: based on URI; meant to be "fairly clean" absolute reference, $dir is a 6525: directory that relative $file lookups are to looked in ($dir of /a/dir 6526: and a file of ../bob will become /a/bob) 6527: 6528: =item * 6529: 6530: hreflocation($dir,$file) : returns file system location or a URL; same as 6531: filelocation except for hrefs 6532: 6533: =item * 6534: 6535: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc) 6536: 6537: =back 6538: 6539: =head2 HTTP Helper Routines 6540: 6541: =over 4 6542: 6543: =item * 6544: 6545: escape() : unpack non-word characters into CGI-compatible hex codes 6546: 6547: =item * 6548: 6549: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character 6550: 6551: =back 6552: 6553: =head1 PRIVATE SUBROUTINES 6554: 6555: =head2 Underlying communication routines (Shouldn't call) 6556: 6557: =over 4 6558: 6559: =item * 6560: 6561: subreply() : tries to pass a message to lonc, returns con_lost if incapable 6562: 6563: =item * 6564: 6565: reply() : uses subreply to send a message to remote machine, logs all failures 6566: 6567: =item * 6568: 6569: critical() : passes a critical message to another server; if cannot 6570: get through then place message in connection buffer directory and 6571: returns con_delayed, if incapable of saving message, returns 6572: con_failed 6573: 6574: =item * 6575: 6576: reconlonc() : tries to reconnect lonc client processes. 6577: 6578: =back 6579: 6580: =head2 Resource Access Logging 6581: 6582: =over 4 6583: 6584: =item * 6585: 6586: flushcourselogs() : flush (save) buffer logs and access logs 6587: 6588: =item * 6589: 6590: courselog($what) : save message for course in hash 6591: 6592: =item * 6593: 6594: courseacclog($what) : save message for course using &courselog(). Perform 6595: special processing for specific resource types (problems, exams, quizzes, etc). 6596: 6597: =item * 6598: 6599: goodbye() : flush course logs and log shutting down; it is called in srm.conf 6600: as a PerlChildExitHandler 6601: 6602: =back 6603: 6604: =head2 Other 6605: 6606: =over 4 6607: 6608: =item * 6609: 6610: symblist($mapname,%newhash) : update symbolic storage links 6611: 6612: =back 6613: 6614: =cut